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