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