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