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