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