]> git.saurik.com Git - apple/libc.git/blob - gen/fts.c
Libc-763.12.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 = NULL;
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 /*
460 * If reached the top, return to the original directory, and
461 * load the paths for the next root.
462 */
463 if (p->fts_level == FTS_ROOTLEVEL) {
464 if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
465 SET(FTS_STOP);
466 return (NULL);
467 }
468 fts_load(sp, p);
469 free(tmp);
470 return (sp->fts_cur = p);
471 }
472
473 /*
474 * User may have called fts_set on the node. If skipped,
475 * ignore. If followed, get a file descriptor so we can
476 * get back if necessary.
477 */
478 if (p->fts_instr == FTS_SKIP) {
479 free(tmp);
480 goto next;
481 }
482 if (p->fts_instr == FTS_FOLLOW) {
483 p->fts_info = fts_stat(sp, p, 1);
484 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR))
485 if ((p->fts_symfd =
486 open(".", O_RDONLY, 0)) < 0) {
487 p->fts_errno = errno;
488 p->fts_info = FTS_ERR;
489 } else
490 p->fts_flags |= FTS_SYMFOLLOW;
491 p->fts_instr = FTS_NOINSTR;
492 }
493
494 free(tmp);
495 name: t = sp->fts_path + NAPPEND(p->fts_parent);
496 *t++ = '/';
497 memmove(t, p->fts_name, p->fts_namelen + 1);
498 return (sp->fts_cur = p);
499 }
500
501 /* Move up to the parent node. */
502 p = tmp->fts_parent;
503 free(tmp);
504
505 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
506 /*
507 * Done; free everything up and set errno to 0 so the user
508 * can distinguish between error and EOF.
509 */
510 free(p);
511 errno = 0;
512 return (sp->fts_cur = NULL);
513 }
514
515 /* Nul terminate the pathname. */
516 sp->fts_path[p->fts_pathlen] = '\0';
517
518 /*
519 * Return to the parent directory. If at a root node or came through
520 * a symlink, go back through the file descriptor. Otherwise, cd up
521 * one directory.
522 */
523 if (p->fts_level == FTS_ROOTLEVEL) {
524 if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
525 SET(FTS_STOP);
526 return (NULL);
527 }
528 } else if (p->fts_flags & FTS_SYMFOLLOW) {
529 if (FCHDIR(sp, p->fts_symfd)) {
530 saved_errno = errno;
531 (void)close(p->fts_symfd);
532 errno = saved_errno;
533 SET(FTS_STOP);
534 return (NULL);
535 }
536 (void)close(p->fts_symfd);
537 } else if (!(p->fts_flags & FTS_DONTCHDIR)) {
538 if (CHDIR(sp, "..")) {
539 SET(FTS_STOP);
540 return (NULL);
541 }
542 }
543 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
544 return (sp->fts_cur = p);
545 }
546
547 /*
548 * Fts_set takes the stream as an argument although it's not used in this
549 * implementation; it would be necessary if anyone wanted to add global
550 * semantics to fts using fts_set. An error return is allowed for similar
551 * reasons.
552 */
553 /* ARGSUSED */
554 int
555 fts_set(sp, p, instr)
556 FTS *sp;
557 FTSENT *p;
558 int instr;
559 {
560 if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
561 instr != FTS_NOINSTR && instr != FTS_SKIP) {
562 errno = EINVAL;
563 return (1);
564 }
565 p->fts_instr = instr;
566 return (0);
567 }
568
569 FTSENT *
570 fts_children(sp, instr)
571 register FTS *sp;
572 int instr;
573 {
574 register FTSENT *p;
575 int fd;
576
577 if (instr && instr != FTS_NAMEONLY) {
578 errno = EINVAL;
579 return (NULL);
580 }
581
582 /* Set current node pointer. */
583 p = sp->fts_cur;
584
585 /*
586 * Errno set to 0 so user can distinguish empty directory from
587 * an error.
588 */
589 errno = 0;
590
591 /* Fatal errors stop here. */
592 if (ISSET(FTS_STOP))
593 return (NULL);
594
595 /* Return logical hierarchy of user's arguments. */
596 if (p->fts_info == FTS_INIT)
597 return (p->fts_link);
598
599 /*
600 * If not a directory being visited in pre-order, stop here. Could
601 * allow FTS_DNR, assuming the user has fixed the problem, but the
602 * same effect is available with FTS_AGAIN.
603 */
604 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
605 return (NULL);
606
607 /* Free up any previous child list. */
608 if (sp->fts_child)
609 fts_lfree(sp->fts_child);
610
611 if (instr == FTS_NAMEONLY) {
612 sp->fts_options |= FTS_NAMEONLY;
613 instr = BNAMES;
614 } else
615 instr = BCHILD;
616
617 /*
618 * If using chdir on a relative path and called BEFORE fts_read does
619 * its chdir to the root of a traversal, we can lose -- we need to
620 * chdir into the subdirectory, and we don't know where the current
621 * directory is, so we can't get back so that the upcoming chdir by
622 * fts_read will work.
623 */
624 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
625 ISSET(FTS_NOCHDIR))
626 return (sp->fts_child = fts_build(sp, instr));
627
628 if ((fd = open(".", O_RDONLY, 0)) < 0)
629 return (NULL);
630 sp->fts_child = fts_build(sp, instr);
631 if (fchdir(fd))
632 return (NULL);
633 (void)close(fd);
634 return (sp->fts_child);
635 }
636
637 /*
638 * This is the tricky part -- do not casually change *anything* in here. The
639 * idea is to build the linked list of entries that are used by fts_children
640 * and fts_read. There are lots of special cases.
641 *
642 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
643 * set, we can use d_type to determine if the entry is a directory (or for
644 * logical walks, a directory or symlink) and not call stat for other file
645 * types. This cuts the number of stat calls significantly.
646 */
647 static FTSENT *
648 fts_build(sp, type)
649 register FTS *sp;
650 int type;
651 {
652 register struct dirent *dp;
653 register FTSENT *p, *head;
654 register int nitems;
655 FTSENT *cur, *tail;
656 DIR *dirp;
657 void *adjaddr;
658 int cderrno, descend, len, level, maxlen, dostat, oflag, saved_errno;
659 char *cp = NULL;
660
661 /* Set current node pointer. */
662 cur = sp->fts_cur;
663
664 /*
665 * Open the directory for reading. If this fails, we're done.
666 * If being called from fts_read, set the fts_info field.
667 */
668 #ifdef FTS_WHITEOUT
669 if (ISSET(FTS_WHITEOUT))
670 oflag = DTF_NODUP|DTF_REWIND;
671 else
672 oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
673 #else
674 #define __opendir2(path, flag) opendir(path)
675 #endif
676 if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
677 if (type == BREAD) {
678 cur->fts_info = FTS_DNR;
679 cur->fts_errno = errno;
680 }
681 return (NULL);
682 }
683
684 if (type == BNAMES)
685 dostat = F_NOSTAT;
686 else if (ISSET(FTS_NOSTAT))
687 dostat = ISSET(FTS_PHYSICAL) ? F_STATDIR : F_STATDIRSYM;
688 else
689 dostat = F_ALWAYSSTAT;
690
691 #ifdef notdef
692 (void)printf("dostat == %d\n", dostat);
693 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
694 ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
695 #endif
696 /*
697 * If we're going to need to stat anything or we want to descend
698 * and stay in the directory, chdir. If this fails we keep going,
699 * but set a flag so we don't chdir after the post-order visit.
700 * We won't be able to stat anything, but we can still return the
701 * names themselves. Note, that since fts_read won't be able to
702 * chdir into the directory, it will have to return different path
703 * names than before, i.e. "a/b" instead of "b". Since the node
704 * has already been visited in pre-order, have to wait until the
705 * post-order visit to return the error. There is a special case
706 * here, if there was nothing to stat then it's not an error to
707 * not be able to stat. This is all fairly nasty. If a program
708 * needed sorted entries or stat information, they had better be
709 * checking FTS_NS on the returned nodes.
710 */
711 cderrno = 0;
712 if (dostat || type == BREAD)
713 if (FCHDIR(sp, dirfd(dirp))) {
714 if (dostat && type == BREAD)
715 cur->fts_errno = errno;
716 cur->fts_flags |= FTS_DONTCHDIR;
717 descend = 0;
718 cderrno = errno;
719 } else
720 descend = 1;
721 else
722 descend = 0;
723
724 /*
725 * Figure out the max file name length that can be stored in the
726 * current path -- the inner loop allocates more path as necessary.
727 * We really wouldn't have to do the maxlen calculations here, we
728 * could do them in fts_read before returning the path, but it's a
729 * lot easier here since the length is part of the dirent structure.
730 *
731 * If not changing directories set a pointer so that can just append
732 * each new name into the path.
733 */
734 maxlen = sp->fts_pathlen - cur->fts_pathlen - 1;
735 len = NAPPEND(cur);
736 if (ISSET(FTS_NOCHDIR)) {
737 cp = sp->fts_path + len;
738 *cp++ = '/';
739 }
740
741 level = cur->fts_level + 1;
742
743 /* Read the directory, attaching each entry to the `link' pointer. */
744 adjaddr = NULL;
745 for (head = tail = NULL, nitems = 0; dp = readdir(dirp);) {
746 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
747 continue;
748
749 if ((p = fts_alloc(sp, dp->d_name, (int)dp->d_namlen)) == NULL)
750 goto mem1;
751 if (dp->d_namlen > maxlen) {
752 if (fts_palloc(sp, (size_t)dp->d_namlen)) {
753 /*
754 * No more memory for path or structures. Save
755 * errno, free up the current structure and the
756 * structures already allocated.
757 */
758 mem1: saved_errno = errno;
759 if (p)
760 free(p);
761 fts_lfree(head);
762 (void)closedir(dirp);
763 errno = saved_errno;
764 cur->fts_info = FTS_ERR;
765 SET(FTS_STOP);
766 return (NULL);
767 }
768 adjaddr = sp->fts_path;
769 maxlen = sp->fts_pathlen - sp->fts_cur->fts_pathlen - 1;
770 }
771
772 p->fts_pathlen = len + dp->d_namlen + 1;
773 p->fts_parent = sp->fts_cur;
774 p->fts_level = level;
775
776 #ifdef FTS_WHITEOUT
777 if (dp->d_type == DT_WHT)
778 p->fts_flags |= FTS_ISW;
779 #endif
780
781 if (cderrno) {
782 if (dostat) {
783 p->fts_info = FTS_NS;
784 p->fts_errno = cderrno;
785 } else
786 p->fts_info = FTS_NSOK;
787 p->fts_accpath = cur->fts_accpath;
788 } else {
789 /*
790 * We need to know all file types values that d_type may
791 * be set to. So if that changes, the following needs
792 * to be modified appropriately.
793 */
794 switch(dostat | dp->d_type) {
795 case (F_STATDIR | DT_UNKNOWN):
796 case (F_STATDIR | DT_DIR):
797 case (F_STATDIRSYM | DT_UNKNOWN):
798 case (F_STATDIRSYM | DT_DIR):
799 case (F_STATDIRSYM | DT_LNK):
800 case (F_ALWAYSSTAT | DT_UNKNOWN):
801 case (F_ALWAYSSTAT | DT_FIFO):
802 case (F_ALWAYSSTAT | DT_CHR):
803 case (F_ALWAYSSTAT | DT_DIR):
804 case (F_ALWAYSSTAT | DT_BLK):
805 case (F_ALWAYSSTAT | DT_REG):
806 case (F_ALWAYSSTAT | DT_LNK):
807 case (F_ALWAYSSTAT | DT_SOCK):
808 case (F_ALWAYSSTAT | DT_WHT):
809 /* Build a file name for fts_stat to stat. */
810 if (ISSET(FTS_NOCHDIR)) {
811 p->fts_accpath = p->fts_path;
812 memmove(cp, p->fts_name, p->fts_namelen + 1);
813 } else
814 p->fts_accpath = p->fts_name;
815 /* Stat it. */
816 p->fts_info = fts_stat(sp, p, 0);
817 break;
818 default:
819 /* No stat necessary */
820 p->fts_accpath =
821 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
822 p->fts_info = FTS_NSOK;
823 break;
824 }
825 }
826
827 /* We walk in directory order so "ls -f" doesn't get upset. */
828 p->fts_link = NULL;
829 if (head == NULL)
830 head = tail = p;
831 else {
832 tail->fts_link = p;
833 tail = p;
834 }
835 ++nitems;
836 }
837 (void)closedir(dirp);
838
839 /*
840 * If had to realloc the path, adjust the addresses for the rest
841 * of the tree.
842 */
843 if (adjaddr)
844 fts_padjust(sp, adjaddr);
845
846 /*
847 * If not changing directories, reset the path back to original
848 * state.
849 */
850 if (ISSET(FTS_NOCHDIR)) {
851 if (cp - 1 > sp->fts_path)
852 --cp;
853 *cp = '\0';
854 }
855
856 /*
857 * If descended after called from fts_children or after called from
858 * fts_read and nothing found, get back. At the root level we use
859 * the saved fd; if one of fts_open()'s arguments is a relative path
860 * to an empty directory, we wind up here with no other way back. If
861 * can't get back, we're done.
862 */
863 if (descend && (type == BCHILD || !nitems) &&
864 (cur->fts_level == FTS_ROOTLEVEL ?
865 FCHDIR(sp, sp->fts_rfd) : CHDIR(sp, ".."))) {
866 cur->fts_info = FTS_ERR;
867 SET(FTS_STOP);
868 return (NULL);
869 }
870
871 /* If didn't find anything, return NULL. */
872 if (!nitems) {
873 if (type == BREAD)
874 cur->fts_info = FTS_DP;
875 return (NULL);
876 }
877
878 /* Sort the entries. */
879 if (sp->fts_compar && nitems > 1)
880 head = fts_sort(sp, head, nitems);
881 return (head);
882 }
883
884 static u_short
885 fts_stat(sp, p, follow)
886 FTS *sp;
887 register FTSENT *p;
888 int follow;
889 {
890 register FTSENT *t;
891 register dev_t dev;
892 register ino_t ino;
893 struct stat *sbp, sb;
894 int saved_errno;
895
896 /* If user needs stat info, stat buffer already allocated. */
897 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
898
899 #ifdef FTS_WHITEOUT
900 /* check for whiteout */
901 if (p->fts_flags & FTS_ISW) {
902 if (sbp != &sb) {
903 memset(sbp, '\0', sizeof (*sbp));
904 sbp->st_mode = S_IFWHT;
905 }
906 return (FTS_W);
907 }
908 #endif
909
910 /*
911 * If doing a logical walk, or application requested FTS_FOLLOW, do
912 * a stat(2). If that fails, check for a non-existent symlink. If
913 * fail, set the errno from the stat call.
914 */
915 if (ISSET(FTS_LOGICAL) || follow) {
916 if (stat(p->fts_accpath, sbp)) {
917 saved_errno = errno;
918 if (!lstat(p->fts_accpath, sbp)) {
919 if (saved_errno == ELOOP)
920 p->fts_errno = ELOOP;
921 errno = 0;
922 return (FTS_SLNONE);
923 }
924 p->fts_errno = saved_errno;
925 goto err;
926 }
927 /*
928 * For FTS_COMFOLLOWDIR, drop back to lstat unless we have
929 * a directory
930 */
931 if (follow == -1 && !S_ISDIR(sbp->st_mode)) {
932 if (lstat(p->fts_accpath, sbp)) {
933 p->fts_errno = errno;
934 goto err;
935 }
936 }
937 } else if (lstat(p->fts_accpath, sbp)) {
938 p->fts_errno = errno;
939 err: memset(sbp, 0, sizeof(struct stat));
940 return (FTS_NS);
941 }
942
943 if (S_ISDIR(sbp->st_mode)) {
944 /*
945 * Set the device/inode. Used to find cycles and check for
946 * crossing mount points. Also remember the link count, used
947 * in fts_build to limit the number of stat calls. It is
948 * understood that these fields are only referenced if fts_info
949 * is set to FTS_D.
950 */
951 dev = p->fts_dev = sbp->st_dev;
952 ino = p->fts_ino = sbp->st_ino;
953 p->fts_nlink = sbp->st_nlink;
954
955 if (ISDOT(p->fts_name))
956 return (FTS_DOT);
957
958 /*
959 * Cycle detection is done by brute force when the directory
960 * is first encountered. If the tree gets deep enough or the
961 * number of symbolic links to directories is high enough,
962 * something faster might be worthwhile.
963 */
964 for (t = p->fts_parent;
965 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
966 if (ino == t->fts_ino && dev == t->fts_dev) {
967 p->fts_cycle = t;
968 return (FTS_DC);
969 }
970 return (FTS_D);
971 }
972 if (S_ISLNK(sbp->st_mode))
973 return (FTS_SL);
974 if (S_ISREG(sbp->st_mode))
975 return (FTS_F);
976 return (FTS_DEFAULT);
977 }
978
979 static FTSENT *
980 fts_sort(sp, head, nitems)
981 FTS *sp;
982 FTSENT *head;
983 register int nitems;
984 {
985 register FTSENT **ap, *p;
986
987 /*
988 * Construct an array of pointers to the structures and call qsort(3).
989 * Reassemble the array in the order returned by qsort. If unable to
990 * sort for memory reasons, return the directory entries in their
991 * current order. Allocate enough space for the current needs plus
992 * 40 so don't realloc one entry at a time.
993 */
994 if (nitems > sp->fts_nitems) {
995 sp->fts_nitems = nitems + 40;
996 if ((sp->fts_array = realloc(sp->fts_array,
997 (size_t)(sp->fts_nitems * sizeof(FTSENT *)))) == NULL) {
998 sp->fts_nitems = 0;
999 return (head);
1000 }
1001 }
1002 for (ap = sp->fts_array, p = head; p; p = p->fts_link)
1003 *ap++ = p;
1004 #ifdef __BLOCKS__
1005 if (ISSET(FTS_BLOCK_COMPAR))
1006 qsort_b((void *)sp->fts_array, nitems, sizeof(FTSENT *), (int (^)(const void *, const void *))sp->fts_compar_b);
1007 else
1008 #endif /* __BLOCKS__ */
1009 qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
1010 for (head = *(ap = sp->fts_array); --nitems; ++ap)
1011 ap[0]->fts_link = ap[1];
1012 ap[0]->fts_link = NULL;
1013 return (head);
1014 }
1015
1016 static FTSENT *
1017 fts_alloc(sp, name, namelen)
1018 FTS *sp;
1019 char *name;
1020 register int namelen;
1021 {
1022 register FTSENT *p;
1023 size_t len;
1024
1025 /*
1026 * The file name is a variable length array and no stat structure is
1027 * necessary if the user has set the nostat bit. Allocate the FTSENT
1028 * structure, the file name and the stat structure in one chunk, but
1029 * be careful that the stat structure is reasonably aligned. Since the
1030 * fts_name field is declared to be of size 1, the fts_name pointer is
1031 * namelen + 2 before the first possible address of the stat structure.
1032 */
1033 len = sizeof(FTSENT) + namelen;
1034 if (!ISSET(FTS_NOSTAT))
1035 len += sizeof(struct stat) + ALIGNBYTES;
1036 if ((p = malloc(len)) == NULL)
1037 return (NULL);
1038
1039 /* Copy the name plus the trailing NULL. */
1040 memmove(p->fts_name, name, namelen + 1);
1041
1042 if (!ISSET(FTS_NOSTAT))
1043 p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
1044 p->fts_namelen = namelen;
1045 p->fts_path = sp->fts_path;
1046 p->fts_errno = 0;
1047 p->fts_flags = 0;
1048 p->fts_instr = FTS_NOINSTR;
1049 p->fts_number = 0;
1050 p->fts_pointer = NULL;
1051 return (p);
1052 }
1053
1054 static void
1055 fts_lfree(head)
1056 register FTSENT *head;
1057 {
1058 register FTSENT *p;
1059
1060 /* Free a linked list of structures. */
1061 while (p = head) {
1062 head = head->fts_link;
1063 free(p);
1064 }
1065 }
1066
1067 /*
1068 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
1069 * Most systems will allow creation of paths much longer than MAXPATHLEN, even
1070 * though the kernel won't resolve them. Add the size (not just what's needed)
1071 * plus 256 bytes so don't realloc the path 2 bytes at a time.
1072 */
1073 static int
1074 fts_palloc(sp, more)
1075 FTS *sp;
1076 size_t more;
1077 {
1078 sp->fts_pathlen += more + 256;
1079 sp->fts_path = realloc(sp->fts_path, (size_t)sp->fts_pathlen);
1080 return (sp->fts_path == NULL);
1081 }
1082
1083 /*
1084 * When the path is realloc'd, have to fix all of the pointers in structures
1085 * already returned.
1086 */
1087 static void
1088 fts_padjust(sp, addr)
1089 FTS *sp;
1090 void *addr;
1091 {
1092 FTSENT *p;
1093
1094 #define ADJUST(p) { \
1095 (p)->fts_accpath = \
1096 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
1097 (p)->fts_path = addr; \
1098 }
1099 /* Adjust the current set of children. */
1100 for (p = sp->fts_child; p; p = p->fts_link)
1101 ADJUST(p);
1102
1103 /* Adjust the rest of the tree. */
1104 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
1105 ADJUST(p);
1106 p = p->fts_link ? p->fts_link : p->fts_parent;
1107 }
1108 }
1109
1110 static size_t
1111 fts_maxarglen(argv)
1112 char * const *argv;
1113 {
1114 size_t len, max;
1115
1116 for (max = 0; *argv; ++argv)
1117 if ((len = strlen(*argv)) > max)
1118 max = len;
1119 return (max);
1120 }