find: fix implicit -print (sometime differed from standard)
[oweals/busybox.git] / findutils / find.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini find implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Reworked by David Douthitt <n9ubh@callsign.net> and
8  *  Matt Kraai <kraai@alumni.carnegiemellon.edu>.
9  *
10  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
11  */
12
13 /* findutils-4.1.20:
14  *
15  * # find file.txt -exec 'echo {}' '{}  {}' ';'
16  * find: echo file.txt: No such file or directory
17  * # find file.txt -exec 'echo' '{}  {}' '; '
18  * find: missing argument to `-exec'
19  * # find file.txt -exec 'echo {}' '{}  {}' ';' junk
20  * find: paths must precede expression
21  * # find file.txt -exec 'echo {}' '{}  {}' ';' junk ';'
22  * find: paths must precede expression
23  * # find file.txt -exec 'echo' '{}  {}' ';'
24  * file.txt  file.txt
25  * (strace: execve("/bin/echo", ["echo", "file.txt  file.txt"], [ 30 vars ]))
26  * # find file.txt -exec 'echo' '{}  {}' ';' -print -exec pwd ';'
27  * file.txt  file.txt
28  * file.txt
29  * /tmp
30  * # find -name '*.c' -o -name '*.h'
31  * [shows files, *.c and *.h intermixed]
32  * # find file.txt -name '*f*' -o -name '*t*'
33  * file.txt
34  * # find file.txt -name '*z*' -o -name '*t*'
35  * file.txt
36  * # find file.txt -name '*f*' -o -name '*z*'
37  * file.txt
38  *
39  * # find t z -name '*t*' -print -o -name '*z*'
40  * t
41  * # find t z t z -name '*t*' -o -name '*z*' -print
42  * z
43  * z
44  * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
45  * (no output)
46  */
47
48 #include "busybox.h"
49 #include <fnmatch.h>
50
51 USE_FEATURE_FIND_XDEV(static dev_t *xdev_dev;)
52 USE_FEATURE_FIND_XDEV(static int xdev_count;)
53
54 typedef int (*action_fp)(const char *fileName, struct stat *statbuf, void *);
55
56 typedef struct {
57         action_fp f;
58 } action;
59 #define SACT(name, arg...) typedef struct { action a; arg; } action_##name;
60 #define SFUNC(name)        static int func_##name(const char *fileName, struct stat *statbuf, action_##name* ap)
61                         SACT(print)
62                         SACT(name,  char *pattern;)
63 USE_FEATURE_FIND_PRINT0(SACT(print0))
64 USE_FEATURE_FIND_TYPE(  SACT(type,  int type_mask;))
65 USE_FEATURE_FIND_PERM(  SACT(perm,  char perm_char; int perm_mask;))
66 USE_FEATURE_FIND_MTIME( SACT(mtime, char mtime_char; int mtime_days;))
67 USE_FEATURE_FIND_MMIN(  SACT(mmin,  char mmin_char; int mmin_mins;))
68 USE_FEATURE_FIND_NEWER( SACT(newer, time_t newer_mtime;))
69 USE_FEATURE_FIND_INUM(  SACT(inum,  ino_t inode_num;))
70 USE_FEATURE_FIND_EXEC(  SACT(exec,  char **exec_argv; int *subst_count; int exec_argc;))
71 USE_DESKTOP(            SACT(paren, action ***subexpr;))
72
73 static action ***actions;
74 static int need_print = 1;
75
76 static inline int one_char(const char* str, char c)
77 {
78         return (str[0] == c && str[1] == '\0');
79 }
80
81
82 static int count_subst(const char *str)
83 {
84         int count = 0;
85         while ((str = strstr(str, "{}"))) {
86                 count++;
87                 str++;
88         }
89         return count;
90 }
91
92
93 static char* subst(const char *src, int count, const char* filename)
94 {
95         char *buf, *dst, *end;
96         int flen = strlen(filename);
97         /* we replace each '{}' with filename: growth by strlen-2 */
98         buf = dst = xmalloc(strlen(src) + count*(flen-2) + 1);
99         while ((end = strstr(src, "{}"))) {
100                 memcpy(dst, src, end - src);
101                 dst += end - src;
102                 src = end + 2;
103                 memcpy(dst, filename, flen);
104                 dst += flen;
105         }
106         strcpy(dst, src);
107         return buf;
108 }
109
110
111 static int exec_actions(action ***appp, const char *fileName, struct stat *statbuf)
112 {
113         int cur_group;
114         int cur_action;
115         int rc = TRUE;
116         action **app, *ap;
117
118         cur_group = -1;
119         while ((app = appp[++cur_group])) {
120                 cur_action = -1;
121                 do {
122                         ap = app[++cur_action];
123                 } while (ap && (rc = ap->f(fileName, statbuf, ap)));
124                 if (!ap) {
125                         /* all actions in group were successful */
126                         break;
127                 }
128         }
129         return rc;
130 }
131
132
133 SFUNC(name)
134 {
135         const char *tmp = strrchr(fileName, '/');
136         if (tmp == NULL)
137                 tmp = fileName;
138         else
139                 tmp++;
140         return fnmatch(ap->pattern, tmp, FNM_PERIOD) == 0;
141 }
142 #if ENABLE_FEATURE_FIND_TYPE
143 SFUNC(type)
144 {
145         return !((statbuf->st_mode & S_IFMT) == ap->type_mask);
146 }
147 #endif
148 #if ENABLE_FEATURE_FIND_PERM
149 SFUNC(perm)
150 {
151         return !((isdigit(ap->perm_char) && (statbuf->st_mode & 07777) == ap->perm_mask)
152                 || (ap->perm_char == '-' && (statbuf->st_mode & ap->perm_mask) == ap->perm_mask)
153                 || (ap->perm_char == '+' && (statbuf->st_mode & ap->perm_mask) != 0));
154 }
155 #endif
156 #if ENABLE_FEATURE_FIND_MTIME
157 SFUNC(mtime)
158 {
159         time_t file_age = time(NULL) - statbuf->st_mtime;
160         time_t mtime_secs = ap->mtime_days * 24 * 60 * 60;
161         return !((isdigit(ap->mtime_char) && file_age >= mtime_secs
162                                           && file_age < mtime_secs + 24 * 60 * 60)
163                 || (ap->mtime_char == '+' && file_age >= mtime_secs + 24 * 60 * 60)
164                 || (ap->mtime_char == '-' && file_age < mtime_secs));
165 }
166 #endif
167 #if ENABLE_FEATURE_FIND_MMIN
168 SFUNC(mmin)
169 {
170         time_t file_age = time(NULL) - statbuf->st_mtime;
171         time_t mmin_secs = ap->mmin_mins * 60;
172         return !((isdigit(ap->mmin_char) && file_age >= mmin_secs
173                                          && file_age < mmin_secs + 60)
174                 || (ap->mmin_char == '+' && file_age >= mmin_secs + 60)
175                 || (ap->mmin_char == '-' && file_age < mmin_secs));
176 }
177 #endif
178 #if ENABLE_FEATURE_FIND_NEWER
179 SFUNC(newer)
180 {
181         return (ap->newer_mtime >= statbuf->st_mtime);
182 }
183 #endif
184 #if ENABLE_FEATURE_FIND_INUM
185 SFUNC(inum)
186 {
187         return (statbuf->st_ino != ap->inode_num);
188 }
189 #endif
190 #if ENABLE_FEATURE_FIND_EXEC
191 SFUNC(exec)
192 {
193         int i, rc;
194         char *argv[ap->exec_argc+1];
195         for (i = 0; i < ap->exec_argc; i++)
196                 argv[i] = subst(ap->exec_argv[i], ap->subst_count[i], fileName);
197         argv[i] = NULL; /* terminate the list */
198         errno = 0;
199         rc = wait4pid(spawn(argv));
200         if (errno)
201                 bb_perror_msg("%s", argv[0]);
202         for (i = 0; i < ap->exec_argc; i++)
203                 free(argv[i]);
204         return rc == 0; /* return 1 if success */
205 }
206 #endif
207
208 #if ENABLE_FEATURE_FIND_PRINT0
209 SFUNC(print0)
210 {
211         printf("%s%c", fileName, '\0');
212         return TRUE;
213 }
214 #endif
215
216 SFUNC(print)
217 {
218         puts(fileName);
219         return TRUE;
220 }
221
222 #if ENABLE_DESKTOP
223 SFUNC(paren)
224 {
225         return exec_actions(ap->subexpr, fileName, statbuf);
226 }
227 #endif
228
229
230 static int fileAction(const char *fileName, struct stat *statbuf, void* junk, int depth)
231 {
232 #ifdef CONFIG_FEATURE_FIND_XDEV
233         if (S_ISDIR(statbuf->st_mode) && xdev_count) {
234                 int i;
235                 for (i = 0; i < xdev_count; i++) {
236                         if (xdev_dev[i] != statbuf->st_dev)
237                                 return SKIP;
238                 }
239         }
240 #endif
241         /* had no explicit -print[0] or -exec? then print */
242         if (exec_actions(actions, fileName, statbuf) && need_print)
243                 puts(fileName);
244         return TRUE;
245 }
246
247
248 #if ENABLE_FEATURE_FIND_TYPE
249 static int find_type(char *type)
250 {
251         int mask = 0;
252
253         switch (type[0]) {
254         case 'b':
255                 mask = S_IFBLK;
256                 break;
257         case 'c':
258                 mask = S_IFCHR;
259                 break;
260         case 'd':
261                 mask = S_IFDIR;
262                 break;
263         case 'p':
264                 mask = S_IFIFO;
265                 break;
266         case 'f':
267                 mask = S_IFREG;
268                 break;
269         case 'l':
270                 mask = S_IFLNK;
271                 break;
272         case 's':
273                 mask = S_IFSOCK;
274                 break;
275         }
276
277         if (mask == 0 || type[1] != '\0')
278                 bb_error_msg_and_die(bb_msg_invalid_arg, type, "-type");
279
280         return mask;
281 }
282 #endif
283
284 action*** parse_params(char **argv)
285 {
286         action*** appp;
287         int cur_group = 0;
288         int cur_action = 0;
289
290         action* alloc_action(int sizeof_struct, action_fp f)
291         {
292                 action *ap;
293                 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(*appp));
294                 appp[cur_group][cur_action++] = ap = xmalloc(sizeof_struct);
295                 appp[cur_group][cur_action] = NULL;
296                 ap->f = f;
297                 return ap;
298         }
299 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
300
301         appp = xzalloc(2 * sizeof(*appp)); /* appp[0],[1] == NULL */
302
303 // Actions have side effects and return a true or false value
304 // We implement: -print, -print0, -exec
305
306 // The rest are tests.
307
308 // Tests and actions are grouped by operators
309 // ( expr )              Force precedence
310 // ! expr                True if expr is false
311 // -not expr             Same as ! expr
312 // expr1 [-a[nd]] expr2  And; expr2 is not evaluated if expr1 is false
313 // expr1 -o[r] expr2     Or; expr2 is not evaluated if expr1 is true
314 // expr1 , expr2         List; both expr1 and expr2 are always evaluated
315 // We implement: (), -a, -o
316
317         while (*argv) {
318                 char *arg = argv[0];
319                 char *arg1 = argv[1];
320         /* --- Operators --- */
321                 if (strcmp(arg, "-a") == 0
322                     USE_DESKTOP(|| strcmp(arg, "-and") == 0)
323                 ) {
324                         /* no special handling required */
325                 }
326                 else if (strcmp(arg, "-o") == 0
327                          USE_DESKTOP(|| strcmp(arg, "-or") == 0)
328                 ) {
329                         /* start new OR group */
330                         cur_group++;
331                         appp = xrealloc(appp, (cur_group+2) * sizeof(*appp));
332                         appp[cur_group] = NULL;
333                         appp[cur_group+1] = NULL;
334                         cur_action = 0;
335                 }
336
337         /* --- Tests and actions --- */
338                 else if (strcmp(arg, "-print") == 0) {
339                         need_print = 0;
340                         (void) ALLOC_ACTION(print);
341                 }
342 #if ENABLE_FEATURE_FIND_PRINT0
343                 else if (strcmp(arg, "-print0") == 0) {
344                         need_print = 0;
345                         (void) ALLOC_ACTION(print0);
346                 }
347 #endif
348                 else if (strcmp(arg, "-name") == 0) {
349                         action_name *ap;
350                         if (!*++argv)
351                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
352                         ap = ALLOC_ACTION(name);
353                         ap->pattern = arg1;
354                 }
355 #if ENABLE_FEATURE_FIND_TYPE
356                 else if (strcmp(arg, "-type") == 0) {
357                         action_type *ap;
358                         if (!*++argv)
359                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
360                         ap = ALLOC_ACTION(type);
361                         ap->type_mask = find_type(arg1);
362                 }
363 #endif
364 #if ENABLE_FEATURE_FIND_PERM
365 /* TODO:
366  * -perm mode   File's permission bits are exactly mode (octal or symbolic).
367  *              Symbolic modes use mode 0 as a point of departure.
368  * -perm -mode  All of the permission bits mode are set for the file.
369  * -perm +mode  Any of the permission bits mode are set for the file.
370  */
371                 else if (strcmp(arg, "-perm") == 0) {
372                         action_perm *ap;
373                         if (!*++argv)
374                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
375                         ap = ALLOC_ACTION(perm);
376                         ap->perm_mask = xstrtol_range(arg1, 8, 0, 07777);
377                         ap->perm_char = arg1[0];
378                         if (ap->perm_char == '-')
379                                 ap->perm_mask = -ap->perm_mask;
380                 }
381 #endif
382 #if ENABLE_FEATURE_FIND_MTIME
383                 else if (strcmp(arg, "-mtime") == 0) {
384                         action_mtime *ap;
385                         if (!*++argv)
386                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
387                         ap = ALLOC_ACTION(mtime);
388                         ap->mtime_days = xatol(arg1);
389                         ap->mtime_char = arg1[0];
390                         if (ap->mtime_char == '-')
391                                 ap->mtime_days = -ap->mtime_days;
392                 }
393 #endif
394 #if ENABLE_FEATURE_FIND_MMIN
395                 else if (strcmp(arg, "-mmin") == 0) {
396                         action_mmin *ap;
397                         if (!*++argv)
398                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
399                         ap = ALLOC_ACTION(mmin);
400                         ap->mmin_mins = xatol(arg1);
401                         ap->mmin_char = arg1[0];
402                         if (ap->mmin_char == '-')
403                                 ap->mmin_mins = -ap->mmin_mins;
404                 }
405 #endif
406 #if ENABLE_FEATURE_FIND_NEWER
407                 else if (strcmp(arg, "-newer") == 0) {
408                         action_newer *ap;
409                         struct stat stat_newer;
410                         if (!*++argv)
411                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
412                         xstat(arg1, &stat_newer);
413                         ap = ALLOC_ACTION(newer);
414                         ap->newer_mtime = stat_newer.st_mtime;
415                 }
416 #endif
417 #if ENABLE_FEATURE_FIND_INUM
418                 else if (strcmp(arg, "-inum") == 0) {
419                         action_inum *ap;
420                         if (!*++argv)
421                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
422                         ap = ALLOC_ACTION(inum);
423                         ap->inode_num = xatoul(arg1);
424                 }
425 #endif
426 #if ENABLE_FEATURE_FIND_EXEC
427                 else if (strcmp(arg, "-exec") == 0) {
428                         int i;
429                         action_exec *ap;
430                         need_print = 0;
431                         ap = ALLOC_ACTION(exec);
432                         ap->exec_argv = ++argv; /* first arg after -exec */
433                         ap->exec_argc = 0;
434                         while (1) {
435                                 if (!*argv) /* did not see ';' till end */
436                                         bb_error_msg_and_die(bb_msg_requires_arg, arg);
437                                 if (one_char(argv[0], ';'))
438                                         break;
439                                 argv++;
440                                 ap->exec_argc++;
441                         }
442                         if (ap->exec_argc == 0)
443                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
444                         ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
445                         i = ap->exec_argc;
446                         while (i--)
447                                 ap->subst_count[i] = count_subst(ap->exec_argv[i]);
448                 }
449 #endif
450 #if ENABLE_DESKTOP
451                 else if (one_char(arg, '(')) {
452                         action_paren *ap;
453                         char **endarg;
454                         int nested = 1;
455
456                         endarg = argv;
457                         while (1) {
458                                 if (!*++endarg)
459                                         bb_error_msg_and_die("unpaired '('");
460                                 if (one_char(*endarg, '('))
461                                         nested++;
462                                 else if (one_char(*endarg, ')') && !--nested) {
463                                         *endarg = NULL;
464                                         break;
465                                 }
466                         }
467                         ap = ALLOC_ACTION(paren);
468                         ap->subexpr = parse_params(argv + 1);
469                         *endarg = ")"; /* restore NULLed parameter */
470                         argv = endarg;
471                 }
472 #endif
473                 else
474                         bb_show_usage();
475                 argv++;
476         }
477
478         return appp;
479 #undef ALLOC_ACTION
480 }
481
482
483 int find_main(int argc, char **argv)
484 {
485         int dereference = FALSE;
486         char **argp;
487         int i, firstopt, status = EXIT_SUCCESS;
488
489         for (firstopt = 1; firstopt < argc; firstopt++) {
490                 if (argv[firstopt][0] == '-')
491                         break;
492 #if ENABLE_DESKTOP
493                 if (one_char(argv[firstopt], '('))
494                         break;
495 #endif
496         }
497         if (firstopt == 1) {
498                 argv[0] = ".";
499                 argv--;
500                 firstopt++;
501         }
502
503 // All options always return true. They always take effect,
504 // rather than being processed only when their place in the
505 // expression is reached
506 // We implement: -follow, -xdev
507
508         /* Process options, and replace then with -a */
509         /* (that will be ignored by recursive parser later) */
510         argp = &argv[firstopt];
511         while (*argp) {
512                 char *arg = argp[0];
513                 if (strcmp(arg, "-follow") == 0) {
514                         dereference = TRUE;
515                         argp[0] = "-a";
516                 }
517 #if ENABLE_FEATURE_FIND_XDEV
518                 else if (strcmp(arg, "-xdev") == 0) {
519                         struct stat stbuf;
520                         if (!xdev_count) {
521                                 xdev_count = firstopt - 1;
522                                 xdev_dev = xmalloc(xdev_count * sizeof(dev_t));
523                                 for (i = 1; i < firstopt; i++) {
524                                         /* not xstat(): shouldn't bomb out on
525                                          * "find not_exist exist -xdev" */
526                                         if (stat(argv[i], &stbuf)) stbuf.st_dev = -1L;
527                                         xdev_dev[i-1] = stbuf.st_dev;
528                                 }
529                         }
530                         argp[0] = "-a";
531                 }
532                 argp++;
533         }
534 #endif
535
536         actions = parse_params(&argv[firstopt]);
537
538         for (i = 1; i < firstopt; i++) {
539                 if (!recursive_action(argv[i],
540                                 TRUE,           // recurse
541                                 dereference,    // follow links
542                                 FALSE,          // depth first
543                                 fileAction,     // file action
544                                 fileAction,     // dir action
545                                 NULL,           // user data
546                                 0))             // depth
547                         status = EXIT_FAILURE;
548         }
549         return status;
550 }