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