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