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