Imported Upstream version 4.5.10
[platform/upstream/findutils.git] / find / defs.h
1 /* defs.h -- data types and declarations.
2    Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2004, 2005, 2006,
3    2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
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 3 of the License, or
8    (at your option) any later version.
9
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.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 #ifndef INC_DEFS_H
21 #define INC_DEFS_H 1
22
23 #if !defined(ALREADY_INCLUDED_CONFIG_H)
24 /*
25  * Savannah bug #20128: if we include some system header and it
26  * includes some othersecond system header, the second system header
27  * may in fact turn out to be a file provided by gnulib.  For that
28  * situation, we need to have already included <config.h> so that the
29  * Gnulib files have access to the information probed by their
30  * configure script fragments.  So <config.h> should be the first
31  * thing included.
32  */
33 #error "<config.h> should be #included before defs.h, and indeed before any other header"
34 Please stop compiling the program now
35 #endif
36
37
38 #include <sys/types.h>
39
40 /* XXX: some of these includes probably don't belong in a common header file */
41 #include <sys/stat.h>
42 #include <stdio.h>              /* for FILE* */
43 #include <string.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <time.h>
47 #include <limits.h>             /* for CHAR_BIT */
48 #include <stdbool.h>            /* for bool */
49 #include <stdint.h>             /* for uintmax_t */
50 #include <sys/stat.h> /* S_ISUID etc. */
51 #include <selinux/selinux.h>
52
53
54
55 #ifndef CHAR_BIT
56 # define CHAR_BIT 8
57 #endif
58
59 # include <inttypes.h>
60
61 #include "regex.h"
62 #include "timespec.h"
63 #include "buildcmd.h"
64 #include "quotearg.h"
65 #include "sharefile.h"
66
67 #ifndef ATTRIBUTE_NORETURN
68 # if HAVE_ATTRIBUTE_NORETURN
69 #  define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
70 # else
71 #  define ATTRIBUTE_NORETURN /* nothing */
72 # endif
73 #endif
74
75 int optionl_stat (const char *name, struct stat *p);
76 int optionp_stat (const char *name, struct stat *p);
77 int optionh_stat (const char *name, struct stat *p);
78 int debug_stat   (const char *file, struct stat *bufp);
79
80 void set_stat_placeholders (struct stat *p);
81 int get_statinfo (const char *pathname, const char *name, struct stat *p);
82
83
84 #define MODE_WXUSR      (S_IWUSR | S_IXUSR)
85 #define MODE_R          (S_IRUSR | S_IRGRP | S_IROTH)
86 #define MODE_RW         (S_IWUSR | S_IWGRP | S_IWOTH | MODE_R)
87 #define MODE_RWX        (S_IXUSR | S_IXGRP | S_IXOTH | MODE_RW)
88 #define MODE_ALL        (S_ISUID | S_ISGID | S_ISVTX | MODE_RWX)
89
90
91 struct predicate;
92 struct options;
93
94 /* Pointer to a predicate function. */
95 typedef bool (*PRED_FUNC)(const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr);
96
97 /* The number of seconds in a day. */
98 #define         DAYSECS     86400
99
100 /* Argument structures for predicates. */
101
102 enum comparison_type
103 {
104   COMP_GT,
105   COMP_LT,
106   COMP_EQ
107 };
108
109 enum permissions_type
110 {
111   PERM_AT_LEAST,
112   PERM_ANY,
113   PERM_EXACT
114 };
115
116 enum predicate_type
117 {
118   NO_TYPE,
119   PRIMARY_TYPE,
120   UNI_OP,
121   BI_OP,
122   OPEN_PAREN,
123   CLOSE_PAREN
124 };
125
126 enum predicate_precedence
127 {
128   NO_PREC,
129   COMMA_PREC,
130   OR_PREC,
131   AND_PREC,
132   NEGATE_PREC,
133   MAX_PREC
134 };
135
136 struct long_val
137 {
138   enum comparison_type kind;
139   bool negative;         /* Defined only when representing time_t.  */
140   uintmax_t l_val;
141 };
142
143 struct perm_val
144 {
145   enum permissions_type kind;
146   mode_t val[2];
147 };
148
149 /* dir_id is used to support loop detection in find.c
150  */
151 struct dir_id
152 {
153   ino_t ino;
154   dev_t dev;
155 };
156
157 /* samefile_file_id is used to support the -samefile test.
158  */
159 struct samefile_file_id
160 {
161   ino_t ino;
162   dev_t dev;
163   int   fd;
164 };
165
166 struct size_val
167 {
168   enum comparison_type kind;
169   int blocksize;
170   uintmax_t size;
171 };
172
173
174 enum xval
175   {
176     XVAL_ATIME, XVAL_BIRTHTIME, XVAL_CTIME, XVAL_MTIME, XVAL_TIME
177   };
178
179 struct time_val
180 {
181   enum xval            xval;
182   enum comparison_type kind;
183   struct timespec      ts;
184 };
185
186
187 struct exec_val
188 {
189   bool multiple;                /* -exec {} \+ denotes multiple argument. */
190   struct buildcmd_control ctl;
191   struct buildcmd_state   state;
192   char **replace_vec;           /* Command arguments (for ";" style) */
193   int num_args;
194   bool close_stdin;             /* If true, close stdin in the child. */
195   struct saved_cwd *wd_for_exec; /* What directory to perform the exec in. */
196   int last_child_status;        /* Status of the most recent child. */
197 };
198
199 /* The format string for a -printf or -fprintf is chopped into one or
200    more `struct segment', linked together into a list.
201    Each stretch of plain text is a segment, and
202    each \c and `%' conversion is a segment. */
203
204 /* Special values for the `kind' field of `struct segment'. */
205 enum SegmentKind
206   {
207     KIND_PLAIN=0,               /* Segment containing just plain text. */
208     KIND_STOP=1,                /* \c -- stop printing and flush output. */
209     KIND_FORMAT,                /* Regular format */
210   };
211
212 struct segment
213 {
214   enum SegmentKind segkind;     /* KIND_FORMAT, KIND_PLAIN, KIND_STOP */
215   char format_char[2];          /* Format chars if kind is KIND_FORMAT */
216   char *text;                   /* Plain text or `%' format string. */
217   int text_len;                 /* Length of `text'. */
218   struct segment *next;         /* Next segment for this predicate. */
219 };
220
221 struct format_val
222 {
223   struct segment *segment;      /* Linked list of segments. */
224   FILE *stream;                 /* Output stream to print on. */
225   const char *filename;         /* We need the filename for error messages. */
226   bool dest_is_tty;             /* True if the destination is a terminal. */
227   struct quoting_options *quote_opts;
228 };
229
230 /* Profiling information for a predicate */
231 struct predicate_performance_info
232 {
233   unsigned long visits;
234   unsigned long successes;
235 };
236
237 /* evaluation cost of a predicate */
238 enum EvaluationCost
239 {
240   NeedsNothing,
241   NeedsInodeNumber,
242   NeedsType,
243   NeedsStatInfo,
244   NeedsLinkName,
245   NeedsAccessInfo,
246   NeedsSyncDiskHit,
247   NeedsEventualExec,
248   NeedsImmediateExec,
249   NeedsUserInteraction,
250   NeedsUnknown,
251   NumEvaluationCosts
252 };
253
254 struct predicate
255 {
256   /* Pointer to the function that implements this predicate.  */
257   PRED_FUNC pred_func;
258
259   /* Only used for debugging, but defined unconditionally so individual
260      modules can be compiled with -DDEBUG.  */
261   char *p_name;
262
263   /* The type of this node.  There are two kinds.  The first is real
264      predicates ("primaries") such as -perm, -print, or -exec.  The
265      other kind is operators for combining predicates. */
266   enum predicate_type p_type;
267
268   /* The precedence of this node.  Only has meaning for operators. */
269   enum predicate_precedence p_prec;
270
271   /* True if this predicate node produces side effects.
272      If side_effects are produced
273      then optimization will not be performed */
274   bool side_effects;
275
276   /* True if this predicate node requires default print be turned off. */
277   bool no_default_print;
278
279   /* True if this predicate node requires a stat system call to execute. */
280   bool need_stat;
281
282   /* True if this predicate node requires knowledge of the file type. */
283   bool need_type;
284
285   /* True if this predicate node requires knowledge of the inode number. */
286   bool need_inum;
287
288   enum EvaluationCost p_cost;
289
290   /* est_success_rate is a number between 0.0 and 1.0 */
291   float est_success_rate;
292
293   /* True if this predicate should display control characters literally */
294   bool literal_control_chars;
295
296   /* True if this predicate didn't originate from the user. */
297   bool artificial;
298
299   /* The raw text of the argument of this predicate. */
300   const char *arg_text;
301
302   /* Information needed by the predicate processor.
303      Next to each member are listed the predicates that use it. */
304   union
305   {
306     const char *str;            /* fstype [i]lname [i]name [i]path */
307     struct re_pattern_buffer *regex; /* regex */
308     struct exec_val exec_vec;   /* exec ok */
309     struct long_val numinfo;    /* gid inum links  uid */
310     struct size_val size;       /* size */
311     uid_t uid;                  /* user */
312     gid_t gid;                  /* group */
313     struct time_val reftime;    /* newer newerXY anewer cnewer mtime atime ctime mmin amin cmin */
314     struct perm_val perm;       /* perm */
315     struct samefile_file_id samefileid; /* samefile */
316     mode_t type;                /* type */
317     struct format_val printf_vec; /* printf fprintf fprint ls fls print0 fprint0 print */
318     security_context_t scontext; /* security context */
319   } args;
320
321   /* The next predicate in the user input sequence,
322      which represents the order in which the user supplied the
323      predicates on the command line. */
324   struct predicate *pred_next;
325
326   /* The right and left branches from this node in the expression
327      tree, which represents the order in which the nodes should be
328      processed. */
329   struct predicate *pred_left;
330   struct predicate *pred_right;
331
332   struct predicate_performance_info perf;
333
334   const struct parser_table* parser_entry;
335 };
336
337 /* find.c, ftsfind.c */
338 bool is_fts_enabled(int *ftsoptions);
339
340 /* find library function declarations.  */
341
342 /* find global function declarations.  */
343
344 /* find.c */
345 /* SymlinkOption represents the choice of
346  * -P, -L or -P (default) on the command line.
347  */
348 enum SymlinkOption
349   {
350     SYMLINK_NEVER_DEREF,        /* Option -P */
351     SYMLINK_ALWAYS_DEREF,       /* Option -L */
352     SYMLINK_DEREF_ARGSONLY      /* Option -H */
353   };
354 extern enum SymlinkOption symlink_handling; /* defined in find.c. */
355
356 void set_follow_state (enum SymlinkOption opt);
357 void cleanup(void);
358
359 /* fstype.c */
360 char *filesystem_type (const struct stat *statp, const char *path);
361 char * get_mounted_filesystems (void);
362 dev_t * get_mounted_devices (size_t *);
363
364
365
366 enum arg_type
367   {
368     ARG_OPTION,                 /* regular options like -maxdepth */
369     ARG_NOOP,                   /* does nothing, returns true, internal use only */
370     ARG_POSITIONAL_OPTION,      /* options whose position is important (-follow) */
371     ARG_TEST,                   /* a like -name */
372     ARG_SPECIAL_PARSE,          /* complex to parse, don't eat the test name before calling parse_xx(). */
373     ARG_PUNCTUATION,            /* like -o or ( */
374     ARG_ACTION                  /* like -print */
375   };
376
377
378 struct parser_table;
379 /* Pointer to a parser function. */
380 typedef bool (*PARSE_FUNC)(const struct parser_table *p,
381                            char *argv[], int *arg_ptr);
382 struct parser_table
383 {
384   enum arg_type type;
385   char *parser_name;
386   PARSE_FUNC parser_func;
387   PRED_FUNC    pred_func;
388 };
389
390 /* parser.c */
391 const struct parser_table* find_parser (char *search_name);
392 bool parse_print (const struct parser_table*, char *argv[], int *arg_ptr);
393 void pred_sanity_check (const struct predicate *predicates);
394 void check_option_combinations (const struct predicate *p);
395 void parse_begin_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates);
396 void parse_end_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates);
397 bool parse_openparen  (const struct parser_table* entry, char *argv[], int *arg_ptr);
398 bool parse_closeparen (const struct parser_table* entry, char *argv[], int *arg_ptr);
399
400 /* pred.c */
401
402 typedef bool PREDICATEFUNCTION(const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr);
403 PREDICATEFUNCTION pred_amin;
404 PREDICATEFUNCTION pred_and;
405 PREDICATEFUNCTION pred_anewer;
406 PREDICATEFUNCTION pred_atime;
407 PREDICATEFUNCTION pred_closeparen;
408 PREDICATEFUNCTION pred_cmin;
409 PREDICATEFUNCTION pred_cnewer;
410 PREDICATEFUNCTION pred_comma;
411 PREDICATEFUNCTION pred_ctime;
412 PREDICATEFUNCTION pred_delete;
413 PREDICATEFUNCTION pred_empty;
414 PREDICATEFUNCTION pred_exec;
415 PREDICATEFUNCTION pred_execdir;
416 PREDICATEFUNCTION pred_executable;
417 PREDICATEFUNCTION pred_false;
418 PREDICATEFUNCTION pred_fls;
419 PREDICATEFUNCTION pred_fprint;
420 PREDICATEFUNCTION pred_fprint0;
421 PREDICATEFUNCTION pred_fprintf;
422 PREDICATEFUNCTION pred_fstype;
423 PREDICATEFUNCTION pred_gid;
424 PREDICATEFUNCTION pred_group;
425 PREDICATEFUNCTION pred_ilname;
426 PREDICATEFUNCTION pred_iname;
427 PREDICATEFUNCTION pred_inum;
428 PREDICATEFUNCTION pred_ipath;
429 PREDICATEFUNCTION pred_links;
430 PREDICATEFUNCTION pred_lname;
431 PREDICATEFUNCTION pred_ls;
432 PREDICATEFUNCTION pred_mmin;
433 PREDICATEFUNCTION pred_mtime;
434 PREDICATEFUNCTION pred_name;
435 PREDICATEFUNCTION pred_negate;
436 PREDICATEFUNCTION pred_newer;
437 PREDICATEFUNCTION pred_newerXY;
438 PREDICATEFUNCTION pred_nogroup;
439 PREDICATEFUNCTION pred_nouser;
440 PREDICATEFUNCTION pred_ok;
441 PREDICATEFUNCTION pred_okdir;
442 PREDICATEFUNCTION pred_openparen;
443 PREDICATEFUNCTION pred_or;
444 PREDICATEFUNCTION pred_path;
445 PREDICATEFUNCTION pred_perm;
446 PREDICATEFUNCTION pred_print;
447 PREDICATEFUNCTION pred_print0;
448 PREDICATEFUNCTION pred_prune;
449 PREDICATEFUNCTION pred_quit;
450 PREDICATEFUNCTION pred_readable;
451 PREDICATEFUNCTION pred_regex;
452 PREDICATEFUNCTION pred_samefile;
453 PREDICATEFUNCTION pred_size;
454 PREDICATEFUNCTION pred_true;
455 PREDICATEFUNCTION pred_type;
456 PREDICATEFUNCTION pred_uid;
457 PREDICATEFUNCTION pred_used;
458 PREDICATEFUNCTION pred_user;
459 PREDICATEFUNCTION pred_writable;
460 PREDICATEFUNCTION pred_xtype;
461 PREDICATEFUNCTION pred_context;
462
463
464
465 int launch (struct buildcmd_control *ctl, void *usercontext, int argc, char **argv);
466
467
468 char *find_pred_name (PRED_FUNC pred_func);
469
470
471
472 void print_predicate (FILE *fp, const struct predicate *p);
473 void print_tree (FILE*, struct predicate *node, int indent);
474 void print_list (FILE*, struct predicate *node);
475 void print_optlist (FILE *fp, const struct predicate *node);
476 void show_success_rates(const struct predicate *node);
477
478
479 /* tree.c */
480 bool matches_start_point(const char * glob, bool foldcase);
481 struct predicate * build_expression_tree (int argc, char *argv[], int end_of_leading_options);
482 struct predicate * get_eval_tree (void);
483 struct predicate *get_new_pred_noarg (const struct parser_table *entry);
484 struct predicate *get_new_pred (const struct parser_table *entry);
485 struct predicate *get_new_pred_chk_op (const struct parser_table *entry,
486                                               const char *arg);
487 float  calculate_derived_rates (struct predicate *p);
488
489 /* util.c */
490 bool fd_leak_check_is_enabled (void);
491 struct predicate *insert_primary (const struct parser_table *entry, const char *arg);
492 struct predicate *insert_primary_noarg (const struct parser_table *entry);
493 struct predicate *insert_primary_withpred (const struct parser_table *entry, PRED_FUNC fptr, const char *arg);
494 void usage (FILE *fp, int status, char *msg);
495 extern bool check_nofollow(void);
496 void complete_pending_execs(struct predicate *p);
497 void complete_pending_execdirs (void);
498 const char *safely_quote_err_filename (int n, char const *arg);
499 void record_initial_cwd (void);
500 bool is_exec_in_local_dir(const PRED_FUNC pred_func);
501
502 void fatal_target_file_error (int errno_value, const char *name) ATTRIBUTE_NORETURN;
503 void fatal_nontarget_file_error (int errno_value, const char *name) ATTRIBUTE_NORETURN;
504 void nonfatal_target_file_error (int errno_value, const char *name);
505 void nonfatal_nontarget_file_error (int errno_value, const char *name);
506
507
508 int process_leading_options (int argc, char *argv[]);
509 void set_option_defaults (struct options *p);
510 void error_severity (int level);
511
512 #if 0
513 #define apply_predicate(pathname, stat_buf_ptr, node)   \
514   (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
515 #else
516 bool apply_predicate(const char *pathname, struct stat *stat_buf, struct predicate *p);
517 #endif
518
519 #define pred_is(node, fn) ( ((node)->pred_func) == (fn) )
520
521
522 /* find.c. */
523 int get_info (const char *pathname, struct stat *p, struct predicate *pred_ptr);
524 bool following_links (void);
525 bool digest_mode (mode_t *mode, const char *pathname, const char *name, struct stat *pstat, bool leaf);
526 bool default_prints (struct predicate *pred);
527 bool looks_like_expression (const char *arg, bool leading);
528
529
530 enum DebugOption
531   {
532     DebugNone             = 0,
533     DebugExpressionTree   = 1,
534     DebugStat             = 2,
535     DebugSearch           = 4,
536     DebugTreeOpt          = 8,
537     DebugHelp             = 16,
538     DebugExec             = 32,
539     DebugSuccessRates     = 64
540   };
541
542 struct options
543 {
544   /* If true, process directory before contents.  True unless -depth given. */
545   bool do_dir_first;
546   /* If true, -depth was EXPLICITLY set (as opposed to having been turned
547    * on by -delete, for example).
548    */
549    bool explicit_depth;
550
551   /* If >=0, don't descend more than this many levels of subdirectories. */
552   int maxdepth;
553
554   /* If >=0, don't process files above this level. */
555   int mindepth;
556
557   /* If true, do not assume that files in directories with nlink == 2
558      are non-directories. */
559   bool no_leaf_check;
560
561   /* If true, don't cross filesystem boundaries. */
562   bool stay_on_filesystem;
563
564   /* If true, we ignore the problem where we find that a directory entry
565    * no longer exists by the time we get around to processing it.
566    */
567   bool ignore_readdir_race;
568
569   /* If true, pass control characters through.  If false, escape them
570    * or turn them into harmless things.
571    */
572   bool literal_control_chars;
573
574   /* If true, we issue warning messages
575    */
576   bool warnings;
577
578   /* If true, avoid POSIX-incompatible behaviours
579    * (this functionality is currently incomplete
580    * and at the moment affects mainly warning messages).
581    */
582   bool posixly_correct;
583
584   struct timespec      start_time;              /* Time at start of execution.  */
585
586   /* Either one day before now (the default), or the start of today (if -daystart is given). */
587   struct timespec      cur_day_start;
588
589   /* If true, cur_day_start has been adjusted to the start of the day. */
590   bool full_days;
591
592   int output_block_size;        /* Output block size.  */
593
594   /* bitmask for debug options */
595   unsigned long debug_options;
596
597   enum SymlinkOption symlink_handling;
598
599
600   /* Pointer to the function used to stat files. */
601   int (*xstat) (const char *name, struct stat *statbuf);
602
603
604   /* Indicate if we can implement safely_chdir() using the O_NOFOLLOW
605    * flag to open(2).
606    */
607   bool open_nofollow_available;
608
609   /* The variety of regular expression that we support.
610    * The default is POSIX Basic Regular Expressions, but this
611    * can be changed with the positional option, -regextype.
612    */
613   int regex_options;
614
615   /* function used to get file context */
616   int (*x_getfilecon) (int, const char *, security_context_t *);
617
618   /* Optimisation level.  One is the default.
619    */
620   unsigned short optimisation_level;
621
622
623   /* How should we quote filenames in error messages and so forth?
624    */
625   enum quoting_style err_quoting_style;
626 };
627 extern struct options options;
628
629
630 struct state
631 {
632   /* Current depth; 0 means current path is a command line arg. */
633   int curdepth;
634
635   /* If true, we have called stat on the current path. */
636   bool have_stat;
637
638   /* If true, we know the type of the current path. */
639   bool have_type;
640   mode_t type;                  /* this is the actual type */
641
642   /* The file being operated on, relative to the current directory.
643      Used for stat, readlink, remove, and opendir.  */
644   char *rel_pathname;
645   /* The directory fd to which rel_pathname is relative.  Thsi is relevant
646    * when we're navigating the hierarchy with fts() and using FTS_CWDFD.
647    */
648   int cwd_dir_fd;
649
650   /* Length of starting path. */
651   int starting_path_length;
652
653   /* If true, don't descend past current directory.
654      Can be set by -prune, -maxdepth, and -xdev/-mount. */
655   bool stop_at_current_level;
656
657   /* Status value to return to system. */
658   int exit_status;
659
660   /* True if there are any execdirs.  This saves us a pair of fchdir()
661    * calls for every directory we leave if it is false.  This is just
662    * an optimisation.  Set to true if you want to be conservative.
663    */
664   bool execdirs_outstanding;
665
666   /* Shared files, opened via the interface in sharefile.h. */
667   sharefile_handle shared_files;
668
669   /* Avoid multiple error messages for the same file. */
670   bool already_issued_stat_error_msg;
671 };
672
673 /* finddata.c */
674 extern struct options options;
675 extern struct state state;
676 extern struct saved_cwd *initial_wd;
677
678 #endif