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