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