Debian Codegraph @

debian/musl-fts/fts.c

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