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