1 /* $OpenBSD: fts.c,v 1.60 2021/01/08 16:06:30 tb Exp $ */
2
3 /*-
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/param.h> /* ALIGN */
33 #include <sys/stat.h>
34
35 #include <dirent.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <fts.h>
39 #include <limits.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43
44 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
45
46 static FTSENT *fts_alloc(FTS *, const char *, size_t);
47 static FTSENT *fts_build(FTS *, int);
48 static void fts_lfree(FTSENT *);
49 static void fts_load(FTS *, FTSENT *);
50 static size_t fts_maxarglen(char * const *);
51 static void fts_padjust(FTS *, FTSENT *);
52 static int fts_palloc(FTS *, size_t);
53 static FTSENT *fts_sort(FTS *, FTSENT *, int);
54 static u_short fts_stat(FTS *, FTSENT *, int, int);
55 static int fts_safe_changedir(FTS *, FTSENT *, int, const char *);
56
57 /* Android: OpenBSD source compatibility workarounds. */
58 #include "private/bsd_sys_param.h"
59 #define DEF_WEAK(s) /* nothing */
60 void* recallocarray(void*, size_t, size_t, size_t);
61
62 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
63
64 #define CLR(opt) (sp->fts_options &= ~(opt))
65 #define ISSET(opt) (sp->fts_options & (opt))
66 #define SET(opt) (sp->fts_options |= (opt))
67
68 #define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && fchdir(fd))
69
70 /* fts_build flags */
71 #define BCHILD 1 /* fts_children */
72 #define BNAMES 2 /* fts_children, names only */
73 #define BREAD 3 /* fts_read */
74
75 FTS *
__fts_open(char * const * argv,int options,int (* compar)(const FTSENT **,const FTSENT **))76 __fts_open(char * const *argv, int options,
77 int (*compar)(const FTSENT **, const FTSENT **))
78 {
79 FTS *sp;
80 FTSENT *p, *root;
81 int nitems;
82 FTSENT *parent, *prev;
83
84 /* Android: options check moved to __fts_open() for ftw(). */
85
86 /* At least one path must be specified. */
87 if (*argv == NULL) {
88 errno = EINVAL;
89 return (NULL);
90 }
91
92 /* Allocate/initialize the stream */
93 if ((sp = calloc(1, sizeof(FTS))) == NULL)
94 return (NULL);
95 sp->fts_compar = compar;
96 sp->fts_options = options;
97
98 /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
99 if (ISSET(FTS_LOGICAL))
100 SET(FTS_NOCHDIR);
101
102 /*
103 * Start out with 1K of path space, and enough, in any case,
104 * to hold the user's paths.
105 */
106 if (fts_palloc(sp, MAXIMUM(fts_maxarglen(argv), PATH_MAX)))
107 goto mem1;
108
109 /* Allocate/initialize root's parent. */
110 if ((parent = fts_alloc(sp, "", 0)) == NULL)
111 goto mem2;
112 parent->fts_level = FTS_ROOTPARENTLEVEL;
113
114 /* Allocate/initialize root(s). */
115 for (root = prev = NULL, nitems = 0; *argv; ++argv, ++nitems) {
116 if ((p = fts_alloc(sp, *argv, strlen(*argv))) == NULL)
117 goto mem3;
118 p->fts_level = FTS_ROOTLEVEL;
119 p->fts_parent = parent;
120 p->fts_accpath = p->fts_name;
121 p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW), -1);
122
123 // Android: for ftw/nftw we need to fail early: http://b/31152735
124 if ((options & FTS_FOR_FTW) != 0 && p->fts_info == FTS_NS) goto mem3;
125
126 /* Command-line "." and ".." are real directories. */
127 if (p->fts_info == FTS_DOT)
128 p->fts_info = FTS_D;
129
130 /*
131 * If comparison routine supplied, traverse in sorted
132 * order; otherwise traverse in the order specified.
133 */
134 if (compar) {
135 p->fts_link = root;
136 root = p;
137 } else {
138 p->fts_link = NULL;
139 if (root == NULL)
140 root = p;
141 else
142 prev->fts_link = p;
143 prev = p;
144 }
145 }
146 if (compar && nitems > 1)
147 root = fts_sort(sp, root, nitems);
148
149 /*
150 * Allocate a dummy pointer and make fts_read think that we've just
151 * finished the node before the root(s); set p->fts_info to FTS_INIT
152 * so that everything about the "current" node is ignored.
153 */
154 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
155 goto mem3;
156 sp->fts_cur->fts_link = root;
157 sp->fts_cur->fts_info = FTS_INIT;
158
159 /*
160 * If using chdir(2), grab a file descriptor pointing to dot to ensure
161 * that we can get back here; this could be avoided for some paths,
162 * but almost certainly not worth the effort. Slashes, symbolic links,
163 * and ".." are all fairly nasty problems. Note, if we can't get the
164 * descriptor we run anyway, just more slowly.
165 */
166 if (!ISSET(FTS_NOCHDIR) &&
167 (sp->fts_rfd = open(".", O_RDONLY | O_CLOEXEC)) == -1)
168 SET(FTS_NOCHDIR);
169
170 if (nitems == 0)
171 free(parent);
172
173 return (sp);
174
175 mem3: fts_lfree(root);
176 free(parent);
177 mem2: free(sp->fts_path);
178 mem1: free(sp);
179 return (NULL);
180 }
181 DEF_WEAK(fts_open);
182
183 static void
fts_load(FTS * sp,FTSENT * p)184 fts_load(FTS *sp, FTSENT *p)
185 {
186 size_t len;
187 char *cp;
188
189 /*
190 * Load the stream structure for the next traversal. Since we don't
191 * actually enter the directory until after the preorder visit, set
192 * the fts_accpath field specially so the chdir gets done to the right
193 * place and the user can access the first node. From fts_open it's
194 * known that the path will fit.
195 */
196 len = p->fts_pathlen = p->fts_namelen;
197 memmove(sp->fts_path, p->fts_name, len + 1);
198 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
199 len = strlen(++cp);
200 memmove(p->fts_name, cp, len + 1);
201 p->fts_namelen = len;
202 }
203 p->fts_accpath = p->fts_path = sp->fts_path;
204 sp->fts_dev = p->fts_dev;
205 }
206
207 int
fts_close(FTS * sp)208 fts_close(FTS *sp)
209 {
210 FTSENT *freep, *p;
211 int rfd, error = 0;
212
213 /*
214 * This still works if we haven't read anything -- the dummy structure
215 * points to the root list, so we step through to the end of the root
216 * list which has a valid parent pointer.
217 */
218 if (sp->fts_cur) {
219 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
220 freep = p;
221 p = p->fts_link ? p->fts_link : p->fts_parent;
222 free(freep);
223 }
224 free(p);
225 }
226
227 /* Stash the original directory fd if needed. */
228 rfd = ISSET(FTS_NOCHDIR) ? -1 : sp->fts_rfd;
229
230 /* Free up child linked list, sort array, path buffer, stream ptr.*/
231 if (sp->fts_child)
232 fts_lfree(sp->fts_child);
233 free(sp->fts_array);
234 free(sp->fts_path);
235 free(sp);
236
237 /* Return to original directory, checking for error. */
238 if (rfd != -1) {
239 int saved_errno;
240 error = fchdir(rfd);
241 saved_errno = errno;
242 (void)close(rfd);
243 errno = saved_errno;
244 }
245
246 return (error);
247 }
248 DEF_WEAK(fts_close);
249
250 /*
251 * Special case of "/" at the end of the path so that slashes aren't
252 * appended which would cause paths to be written as "....//foo".
253 */
254 #define NAPPEND(p) \
255 (p->fts_path[p->fts_pathlen - 1] == '/' \
256 ? p->fts_pathlen - 1 : p->fts_pathlen)
257
258 FTSENT *
fts_read(FTS * sp)259 fts_read(FTS *sp)
260 {
261 FTSENT *p, *tmp;
262 int instr;
263 char *t;
264 int saved_errno;
265
266 /* If finished or unrecoverable error, return NULL. */
267 if (sp->fts_cur == NULL || ISSET(FTS_STOP))
268 return (NULL);
269
270 /* Set current node pointer. */
271 p = sp->fts_cur;
272
273 /* Save and zero out user instructions. */
274 instr = p->fts_instr;
275 p->fts_instr = FTS_NOINSTR;
276
277 /* Any type of file may be re-visited; re-stat and re-turn. */
278 if (instr == FTS_AGAIN) {
279 p->fts_info = fts_stat(sp, p, 0, -1);
280 return (p);
281 }
282
283 /*
284 * Following a symlink -- SLNONE test allows application to see
285 * SLNONE and recover. If indirecting through a symlink, have
286 * keep a pointer to current location. If unable to get that
287 * pointer, follow fails.
288 */
289 if (instr == FTS_FOLLOW &&
290 (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
291 p->fts_info = fts_stat(sp, p, 1, -1);
292 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
293 if ((p->fts_symfd =
294 open(".", O_RDONLY | O_CLOEXEC)) == -1) {
295 p->fts_errno = errno;
296 p->fts_info = FTS_ERR;
297 } else
298 p->fts_flags |= FTS_SYMFOLLOW;
299 }
300 return (p);
301 }
302
303 /* Directory in pre-order. */
304 if (p->fts_info == FTS_D) {
305 /* If skipped or crossed mount point, do post-order visit. */
306 if (instr == FTS_SKIP ||
307 (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
308 if (p->fts_flags & FTS_SYMFOLLOW)
309 (void)close(p->fts_symfd);
310 if (sp->fts_child) {
311 fts_lfree(sp->fts_child);
312 sp->fts_child = NULL;
313 }
314 p->fts_info = FTS_DP;
315 return (p);
316 }
317
318 /* Rebuild if only read the names and now traversing. */
319 if (sp->fts_child && ISSET(FTS_NAMEONLY)) {
320 CLR(FTS_NAMEONLY);
321 fts_lfree(sp->fts_child);
322 sp->fts_child = NULL;
323 }
324
325 /*
326 * Cd to the subdirectory.
327 *
328 * If have already read and now fail to chdir, whack the list
329 * to make the names come out right, and set the parent errno
330 * so the application will eventually get an error condition.
331 * Set the FTS_DONTCHDIR flag so that when we logically change
332 * directories back to the parent we don't do a chdir.
333 *
334 * If haven't read do so. If the read fails, fts_build sets
335 * FTS_STOP or the fts_info field of the node.
336 */
337 if (sp->fts_child) {
338 if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
339 p->fts_errno = errno;
340 p->fts_flags |= FTS_DONTCHDIR;
341 for (p = sp->fts_child; p; p = p->fts_link)
342 p->fts_accpath =
343 p->fts_parent->fts_accpath;
344 }
345 } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
346 if (ISSET(FTS_STOP))
347 return (NULL);
348 return (p);
349 }
350 p = sp->fts_child;
351 sp->fts_child = NULL;
352 goto name;
353 }
354
355 /* Move to the next node on this level. */
356 next: tmp = p;
357 if ((p = p->fts_link)) {
358 free(tmp);
359
360 /*
361 * If reached the top, return to the original directory (or
362 * the root of the tree), and load the paths for the next root.
363 */
364 if (p->fts_level == FTS_ROOTLEVEL) {
365 if (FCHDIR(sp, sp->fts_rfd)) {
366 SET(FTS_STOP);
367 return (NULL);
368 }
369 fts_load(sp, p);
370 return (sp->fts_cur = p);
371 }
372
373 /*
374 * User may have called fts_set on the node. If skipped,
375 * ignore. If followed, get a file descriptor so we can
376 * get back if necessary.
377 */
378 if (p->fts_instr == FTS_SKIP)
379 goto next;
380 if (p->fts_instr == FTS_FOLLOW) {
381 p->fts_info = fts_stat(sp, p, 1, -1);
382 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
383 if ((p->fts_symfd =
384 open(".", O_RDONLY | O_CLOEXEC)) == -1) {
385 p->fts_errno = errno;
386 p->fts_info = FTS_ERR;
387 } else
388 p->fts_flags |= FTS_SYMFOLLOW;
389 }
390 p->fts_instr = FTS_NOINSTR;
391 }
392
393 name: t = sp->fts_path + NAPPEND(p->fts_parent);
394 *t++ = '/';
395 memmove(t, p->fts_name, p->fts_namelen + 1);
396 return (sp->fts_cur = p);
397 }
398
399 /* Move up to the parent node. */
400 p = tmp->fts_parent;
401 free(tmp);
402
403 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
404 /*
405 * Done; free everything up and set errno to 0 so the user
406 * can distinguish between error and EOF.
407 */
408 free(p);
409 errno = 0;
410 return (sp->fts_cur = NULL);
411 }
412
413 /* NUL terminate the pathname. */
414 sp->fts_path[p->fts_pathlen] = '\0';
415
416 /*
417 * Return to the parent directory. If at a root node or came through
418 * a symlink, go back through the file descriptor. Otherwise, cd up
419 * one directory.
420 */
421 if (p->fts_level == FTS_ROOTLEVEL) {
422 if (FCHDIR(sp, sp->fts_rfd)) {
423 SET(FTS_STOP);
424 sp->fts_cur = p;
425 return (NULL);
426 }
427 } else if (p->fts_flags & FTS_SYMFOLLOW) {
428 if (FCHDIR(sp, p->fts_symfd)) {
429 saved_errno = errno;
430 (void)close(p->fts_symfd);
431 errno = saved_errno;
432 SET(FTS_STOP);
433 sp->fts_cur = p;
434 return (NULL);
435 }
436 (void)close(p->fts_symfd);
437 } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
438 fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
439 SET(FTS_STOP);
440 sp->fts_cur = p;
441 return (NULL);
442 }
443 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
444 return (sp->fts_cur = p);
445 }
446 DEF_WEAK(fts_read);
447
448 /*
449 * Fts_set takes the stream as an argument although it's not used in this
450 * implementation; it would be necessary if anyone wanted to add global
451 * semantics to fts using fts_set. An error return is allowed for similar
452 * reasons.
453 */
454 int
fts_set(FTS * sp __unused,FTSENT * p,int instr)455 fts_set(FTS *sp __unused, FTSENT *p, int instr)
456 {
457 if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
458 instr != FTS_NOINSTR && instr != FTS_SKIP) {
459 errno = EINVAL;
460 return (1);
461 }
462 p->fts_instr = instr;
463 return (0);
464 }
465 DEF_WEAK(fts_set);
466
467 FTSENT *
fts_children(FTS * sp,int instr)468 fts_children(FTS *sp, int instr)
469 {
470 FTSENT *p;
471 int fd;
472
473 if (instr && instr != FTS_NAMEONLY) {
474 errno = EINVAL;
475 return (NULL);
476 }
477
478 /* Set current node pointer. */
479 p = sp->fts_cur;
480
481 /*
482 * Errno set to 0 so user can distinguish empty directory from
483 * an error.
484 */
485 errno = 0;
486
487 /* Fatal errors stop here. */
488 if (ISSET(FTS_STOP))
489 return (NULL);
490
491 /* Return logical hierarchy of user's arguments. */
492 if (p->fts_info == FTS_INIT)
493 return (p->fts_link);
494
495 /*
496 * If not a directory being visited in pre-order, stop here. Could
497 * allow FTS_DNR, assuming the user has fixed the problem, but the
498 * same effect is available with FTS_AGAIN.
499 */
500 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
501 return (NULL);
502
503 /* Free up any previous child list. */
504 if (sp->fts_child)
505 fts_lfree(sp->fts_child);
506
507 if (instr == FTS_NAMEONLY) {
508 SET(FTS_NAMEONLY);
509 instr = BNAMES;
510 } else
511 instr = BCHILD;
512
513 /*
514 * If using chdir on a relative path and called BEFORE fts_read does
515 * its chdir to the root of a traversal, we can lose -- we need to
516 * chdir into the subdirectory, and we don't know where the current
517 * directory is, so we can't get back so that the upcoming chdir by
518 * fts_read will work.
519 */
520 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
521 ISSET(FTS_NOCHDIR))
522 return (sp->fts_child = fts_build(sp, instr));
523
524 if ((fd = open(".", O_RDONLY | O_CLOEXEC)) == -1)
525 return (NULL);
526 sp->fts_child = fts_build(sp, instr);
527 if (fchdir(fd)) {
528 (void)close(fd);
529 return (NULL);
530 }
531 (void)close(fd);
532 return (sp->fts_child);
533 }
534 DEF_WEAK(fts_children);
535
536 /*
537 * This is the tricky part -- do not casually change *anything* in here. The
538 * idea is to build the linked list of entries that are used by fts_children
539 * and fts_read. There are lots of special cases.
540 *
541 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
542 * set and it's a physical walk (so that symbolic links can't be directories),
543 * we can do things quickly. First, if it's a 4.4BSD file system, the type
544 * of the file is in the directory entry. Otherwise, we assume that the number
545 * of subdirectories in a node is equal to the number of links to the parent.
546 * The former skips all stat calls. The latter skips stat calls in any leaf
547 * directories and for any files after the subdirectories in the directory have
548 * been found, cutting the stat calls by about 2/3.
549 */
550 static FTSENT *
fts_build(FTS * sp,int type)551 fts_build(FTS *sp, int type)
552 {
553 struct dirent *dp;
554 FTSENT *p, *head;
555 FTSENT *cur, *tail;
556 DIR *dirp;
557 void *oldaddr;
558 size_t len, maxlen;
559 int nitems, cderrno, descend, level, nlinks, nostat, doadjust;
560 int saved_errno;
561 char *cp;
562
563 /* Set current node pointer. */
564 cur = sp->fts_cur;
565
566 /*
567 * Open the directory for reading. If this fails, we're done.
568 * If being called from fts_read, set the fts_info field.
569 */
570 if ((dirp = opendir(cur->fts_accpath)) == NULL) {
571 if (type == BREAD) {
572 cur->fts_info = FTS_DNR;
573 cur->fts_errno = errno;
574 }
575 return (NULL);
576 }
577
578 /*
579 * Nlinks is the number of possible entries of type directory in the
580 * directory if we're cheating on stat calls, 0 if we're not doing
581 * any stat calls at all, -1 if we're doing stats on everything.
582 */
583 if (type == BNAMES)
584 nlinks = 0;
585 else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
586 nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
587 nostat = 1;
588 } else {
589 nlinks = -1;
590 nostat = 0;
591 }
592
593 #ifdef notdef
594 (void)printf("nlinks == %d (cur: %u)\n", nlinks, cur->fts_nlink);
595 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
596 ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
597 #endif
598 /*
599 * If we're going to need to stat anything or we want to descend
600 * and stay in the directory, chdir. If this fails we keep going,
601 * but set a flag so we don't chdir after the post-order visit.
602 * We won't be able to stat anything, but we can still return the
603 * names themselves. Note, that since fts_read won't be able to
604 * chdir into the directory, it will have to return different path
605 * names than before, i.e. "a/b" instead of "b". Since the node
606 * has already been visited in pre-order, have to wait until the
607 * post-order visit to return the error. There is a special case
608 * here, if there was nothing to stat then it's not an error to
609 * not be able to stat. This is all fairly nasty. If a program
610 * needed sorted entries or stat information, they had better be
611 * checking FTS_NS on the returned nodes.
612 */
613 cderrno = 0;
614 if (nlinks || type == BREAD) {
615 if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
616 if (nlinks && type == BREAD)
617 cur->fts_errno = errno;
618 cur->fts_flags |= FTS_DONTCHDIR;
619 descend = 0;
620 cderrno = errno;
621 (void)closedir(dirp);
622 dirp = NULL;
623 } else
624 descend = 1;
625 } else
626 descend = 0;
627
628 /*
629 * Figure out the max file name length that can be stored in the
630 * current path -- the inner loop allocates more path as necessary.
631 * We really wouldn't have to do the maxlen calculations here, we
632 * could do them in fts_read before returning the path, but it's a
633 * lot easier here since the length is part of the dirent structure.
634 *
635 * If not changing directories set a pointer so that can just append
636 * each new name into the path.
637 */
638 len = NAPPEND(cur);
639 if (ISSET(FTS_NOCHDIR)) {
640 cp = sp->fts_path + len;
641 *cp++ = '/';
642 }
643 len++;
644 maxlen = sp->fts_pathlen - len;
645
646 /*
647 * fts_level is signed so we must prevent it from wrapping
648 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
649 */
650 level = cur->fts_level;
651 if (level < FTS_MAXLEVEL)
652 level++;
653
654 /* Read the directory, attaching each entry to the `link' pointer. */
655 doadjust = 0;
656 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
657 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
658 continue;
659
660 if (!(p = fts_alloc(sp, dp->d_name, strlen(dp->d_name))))
661 goto mem1;
662 if (strlen(dp->d_name) >= maxlen) { /* include space for NUL */
663 oldaddr = sp->fts_path;
664 if (fts_palloc(sp, strlen(dp->d_name) +len + 1)) {
665 /*
666 * No more memory for path or structures. Save
667 * errno, free up the current structure and the
668 * structures already allocated.
669 */
670 mem1: saved_errno = errno;
671 free(p);
672 fts_lfree(head);
673 (void)closedir(dirp);
674 cur->fts_info = FTS_ERR;
675 SET(FTS_STOP);
676 errno = saved_errno;
677 return (NULL);
678 }
679 /* Did realloc() change the pointer? */
680 if (oldaddr != sp->fts_path) {
681 doadjust = 1;
682 if (ISSET(FTS_NOCHDIR))
683 cp = sp->fts_path + len;
684 }
685 maxlen = sp->fts_pathlen - len;
686 }
687
688 p->fts_level = level;
689 p->fts_parent = sp->fts_cur;
690 p->fts_pathlen = len + strlen(dp->d_name);
691 if (p->fts_pathlen < len) {
692 /*
693 * If we wrap, free up the current structure and
694 * the structures already allocated, then error
695 * out with ENAMETOOLONG.
696 */
697 free(p);
698 fts_lfree(head);
699 (void)closedir(dirp);
700 cur->fts_info = FTS_ERR;
701 SET(FTS_STOP);
702 errno = ENAMETOOLONG;
703 return (NULL);
704 }
705
706 if (cderrno) {
707 if (nlinks) {
708 p->fts_info = FTS_NS;
709 p->fts_errno = cderrno;
710 } else
711 p->fts_info = FTS_NSOK;
712 p->fts_accpath = cur->fts_accpath;
713 } else if (nlinks == 0
714 #ifdef DT_DIR
715 || (nostat &&
716 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
717 #endif
718 ) {
719 p->fts_accpath =
720 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
721 p->fts_info = FTS_NSOK;
722 } else {
723 /* Build a file name for fts_stat to stat. */
724 if (ISSET(FTS_NOCHDIR)) {
725 p->fts_accpath = p->fts_path;
726 memmove(cp, p->fts_name, p->fts_namelen + 1);
727 p->fts_info = fts_stat(sp, p, 0, dirfd(dirp));
728 } else {
729 p->fts_accpath = p->fts_name;
730 p->fts_info = fts_stat(sp, p, 0, -1);
731 }
732
733 /* Decrement link count if applicable. */
734 if (nlinks > 0 && (p->fts_info == FTS_D ||
735 p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
736 --nlinks;
737 }
738
739 /* We walk in directory order so "ls -f" doesn't get upset. */
740 p->fts_link = NULL;
741 if (head == NULL)
742 head = tail = p;
743 else {
744 tail->fts_link = p;
745 tail = p;
746 }
747 ++nitems;
748 }
749 if (dirp)
750 (void)closedir(dirp);
751
752 /*
753 * If realloc() changed the address of the path, adjust the
754 * addresses for the rest of the tree and the dir list.
755 */
756 if (doadjust)
757 fts_padjust(sp, head);
758
759 /*
760 * If not changing directories, reset the path back to original
761 * state.
762 */
763 if (ISSET(FTS_NOCHDIR)) {
764 if (len == sp->fts_pathlen || nitems == 0)
765 --cp;
766 *cp = '\0';
767 }
768
769 /*
770 * If descended after called from fts_children or after called from
771 * fts_read and nothing found, get back. At the root level we use
772 * the saved fd; if one of fts_open()'s arguments is a relative path
773 * to an empty directory, we wind up here with no other way back. If
774 * can't get back, we're done.
775 */
776 if (descend && (type == BCHILD || !nitems) &&
777 (cur->fts_level == FTS_ROOTLEVEL ? FCHDIR(sp, sp->fts_rfd) :
778 fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
779 cur->fts_info = FTS_ERR;
780 SET(FTS_STOP);
781 return (NULL);
782 }
783
784 /* If didn't find anything, return NULL. */
785 if (!nitems) {
786 if (type == BREAD)
787 cur->fts_info = FTS_DP;
788 return (NULL);
789 }
790
791 /* Sort the entries. */
792 if (sp->fts_compar && nitems > 1)
793 head = fts_sort(sp, head, nitems);
794 return (head);
795 }
796
797 static u_short
fts_stat(FTS * sp,FTSENT * p,int follow,int dfd)798 fts_stat(FTS *sp, FTSENT *p, int follow, int dfd)
799 {
800 FTSENT *t;
801 dev_t dev;
802 ino_t ino;
803 struct stat *sbp, sb;
804 int saved_errno;
805 const char *path;
806
807 if (dfd == -1) {
808 path = p->fts_accpath;
809 dfd = AT_FDCWD;
810 } else
811 path = p->fts_name;
812
813 /* If user needs stat info, stat buffer already allocated. */
814 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
815
816 /*
817 * If doing a logical walk, or application requested FTS_FOLLOW, do
818 * a stat(2). If that fails, check for a non-existent symlink. If
819 * fail, set the errno from the stat call.
820 */
821 if (ISSET(FTS_LOGICAL) || follow) {
822 if (fstatat(dfd, path, sbp, 0)) {
823 saved_errno = errno;
824 if (!fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) {
825 errno = 0;
826 return (FTS_SLNONE);
827 }
828 p->fts_errno = saved_errno;
829 goto err;
830 }
831 } else if (fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) {
832 p->fts_errno = errno;
833 err: memset(sbp, 0, sizeof(struct stat));
834 return (FTS_NS);
835 }
836
837 if (S_ISDIR(sbp->st_mode)) {
838 /*
839 * Set the device/inode. Used to find cycles and check for
840 * crossing mount points. Also remember the link count, used
841 * in fts_build to limit the number of stat calls. It is
842 * understood that these fields are only referenced if fts_info
843 * is set to FTS_D.
844 */
845 dev = p->fts_dev = sbp->st_dev;
846 ino = p->fts_ino = sbp->st_ino;
847 p->fts_nlink = sbp->st_nlink;
848
849 if (ISDOT(p->fts_name))
850 return (FTS_DOT);
851
852 /*
853 * Cycle detection is done by brute force when the directory
854 * is first encountered. If the tree gets deep enough or the
855 * number of symbolic links to directories is high enough,
856 * something faster might be worthwhile.
857 */
858 for (t = p->fts_parent;
859 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
860 if (ino == t->fts_ino && dev == t->fts_dev) {
861 p->fts_cycle = t;
862 return (FTS_DC);
863 }
864 return (FTS_D);
865 }
866 if (S_ISLNK(sbp->st_mode))
867 return (FTS_SL);
868 if (S_ISREG(sbp->st_mode))
869 return (FTS_F);
870 return (FTS_DEFAULT);
871 }
872
873 static FTSENT *
fts_sort(FTS * sp,FTSENT * head,int nitems)874 fts_sort(FTS *sp, FTSENT *head, int nitems)
875 {
876 FTSENT **ap, *p;
877
878 /*
879 * Construct an array of pointers to the structures and call qsort(3).
880 * Reassemble the array in the order returned by qsort. If unable to
881 * sort for memory reasons, return the directory entries in their
882 * current order. Allocate enough space for the current needs plus
883 * 40 so don't realloc one entry at a time.
884 */
885 if (nitems > sp->fts_nitems) {
886 struct _ftsent **a;
887
888 if ((a = reallocarray(sp->fts_array,
889 nitems + 40, sizeof(FTSENT *))) == NULL) {
890 free(sp->fts_array);
891 sp->fts_array = NULL;
892 sp->fts_nitems = 0;
893 return (head);
894 }
895 sp->fts_nitems = nitems + 40;
896 sp->fts_array = a;
897 }
898 for (ap = sp->fts_array, p = head; p; p = p->fts_link)
899 *ap++ = p;
900 qsort(sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
901 for (head = *(ap = sp->fts_array); --nitems; ++ap)
902 ap[0]->fts_link = ap[1];
903 ap[0]->fts_link = NULL;
904 return (head);
905 }
906
907 static FTSENT *
fts_alloc(FTS * sp,const char * name,size_t namelen)908 fts_alloc(FTS *sp, const char *name, size_t namelen)
909 {
910 FTSENT *p;
911 size_t len;
912
913 /*
914 * The file name is a variable length array and no stat structure is
915 * necessary if the user has set the nostat bit. Allocate the FTSENT
916 * structure, the file name and the stat structure in one chunk, but
917 * be careful that the stat structure is reasonably aligned. Since the
918 * fts_name field is declared to be of size 1, the fts_name pointer is
919 * namelen + 2 before the first possible address of the stat structure.
920 */
921 len = sizeof(FTSENT) + namelen;
922 if (!ISSET(FTS_NOSTAT))
923 len += sizeof(struct stat) + ALIGNBYTES;
924 if ((p = calloc(1, len)) == NULL)
925 return (NULL);
926
927 p->fts_path = sp->fts_path;
928 p->fts_namelen = namelen;
929 p->fts_instr = FTS_NOINSTR;
930 if (!ISSET(FTS_NOSTAT))
931 p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
932 memcpy(p->fts_name, name, namelen);
933
934 return (p);
935 }
936
937 static void
fts_lfree(FTSENT * head)938 fts_lfree(FTSENT *head)
939 {
940 FTSENT *p;
941
942 /* Free a linked list of structures. */
943 while ((p = head)) {
944 head = head->fts_link;
945 free(p);
946 }
947 }
948
949 /*
950 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
951 * Most systems will allow creation of paths much longer than PATH_MAX, even
952 * though the kernel won't resolve them. Add the size (not just what's needed)
953 * plus 256 bytes so don't realloc the path 2 bytes at a time.
954 */
955 static int
fts_palloc(FTS * sp,size_t more)956 fts_palloc(FTS *sp, size_t more)
957 {
958 char *p;
959
960 /*
961 * Check for possible wraparound.
962 */
963 more += 256;
964 if (sp->fts_pathlen + more < sp->fts_pathlen) {
965 free(sp->fts_path);
966 sp->fts_path = NULL;
967 errno = ENAMETOOLONG;
968 return (1);
969 }
970 p = recallocarray(sp->fts_path, sp->fts_pathlen,
971 sp->fts_pathlen + more, 1);
972 if (p == NULL) {
973 free(sp->fts_path);
974 sp->fts_path = NULL;
975 return (1);
976 }
977 sp->fts_pathlen += more;
978 sp->fts_path = p;
979 return (0);
980 }
981
982 /*
983 * When the path is realloc'd, have to fix all of the pointers in structures
984 * already returned.
985 */
986 static void
fts_padjust(FTS * sp,FTSENT * head)987 fts_padjust(FTS *sp, FTSENT *head)
988 {
989 FTSENT *p;
990 char *addr = sp->fts_path;
991
992 #define ADJUST(p) { \
993 if ((p)->fts_accpath != (p)->fts_name) { \
994 (p)->fts_accpath = \
995 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
996 } \
997 (p)->fts_path = addr; \
998 }
999 /* Adjust the current set of children. */
1000 for (p = sp->fts_child; p; p = p->fts_link)
1001 ADJUST(p);
1002
1003 /* Adjust the rest of the tree, including the current level. */
1004 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1005 ADJUST(p);
1006 p = p->fts_link ? p->fts_link : p->fts_parent;
1007 }
1008 }
1009
1010 static size_t
fts_maxarglen(char * const * argv)1011 fts_maxarglen(char * const *argv)
1012 {
1013 size_t len, max;
1014
1015 for (max = 0; *argv; ++argv)
1016 if ((len = strlen(*argv)) > max)
1017 max = len;
1018 return (max + 1);
1019 }
1020
1021 /*
1022 * Change to dir specified by fd or p->fts_accpath without getting
1023 * tricked by someone changing the world out from underneath us.
1024 * Assumes p->fts_dev and p->fts_ino are filled in.
1025 */
1026 static int
fts_safe_changedir(FTS * sp,FTSENT * p,int fd,const char * path)1027 fts_safe_changedir(FTS *sp, FTSENT *p, int fd, const char *path)
1028 {
1029 int ret, oerrno, newfd;
1030 struct stat sb;
1031
1032 newfd = fd;
1033 if (ISSET(FTS_NOCHDIR))
1034 return (0);
1035 if (fd == -1 && (newfd = open(path, O_RDONLY|O_DIRECTORY|O_CLOEXEC)) == -1)
1036 return (-1);
1037 if (fstat(newfd, &sb) == -1) {
1038 ret = -1;
1039 goto bail;
1040 }
1041 if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
1042 errno = ENOENT; /* disinformation */
1043 ret = -1;
1044 goto bail;
1045 }
1046 ret = fchdir(newfd);
1047 bail:
1048 oerrno = errno;
1049 if (fd == -1)
1050 (void)close(newfd);
1051 errno = oerrno;
1052 return (ret);
1053 }
1054
1055 FTS *
fts_open(char * const * argv,int options,int (* compar)(const FTSENT **,const FTSENT **))1056 fts_open(char * const *argv, int options,
1057 int (*compar)(const FTSENT **, const FTSENT **))
1058 {
1059 // Android needs to an __fts_open() that doesn't make this check
1060 // so that FTS_FOR_FTW works.
1061 if (options & ~FTS_OPTIONMASK) {
1062 errno = EINVAL;
1063 return (NULL);
1064 }
1065 return __fts_open(argv, options, compar);
1066 }
1067