1 /* $OpenBSD: fts.c,v 1.43 2009/08/27 16:19:27 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. 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 /* 637 * fts_level is a short so we must prevent it from wrapping 638 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL. 639 */ 640 level = cur->fts_level; 641 if (level < FTS_MAXLEVEL) 642 level++; 643 644 /* Read the directory, attaching each entry to the `link' pointer. */ 645 doadjust = 0; 646 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) { 647 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name)) 648 continue; 649 650 if (!(p = fts_alloc(sp, dp->d_name, (size_t)dp->d_namlen))) 651 goto mem1; 652 if (dp->d_namlen >= maxlen) { /* include space for NUL */ 653 oldaddr = sp->fts_path; 654 if (fts_palloc(sp, dp->d_namlen +len + 1)) { 655 /* 656 * No more memory for path or structures. Save 657 * errno, free up the current structure and the 658 * structures already allocated. 659 */ 660 mem1: saved_errno = errno; 661 if (p) 662 free(p); 663 fts_lfree(head); 664 (void)closedir(dirp); 665 cur->fts_info = FTS_ERR; 666 SET(FTS_STOP); 667 errno = saved_errno; 668 return (NULL); 669 } 670 /* Did realloc() change the pointer? */ 671 if (oldaddr != sp->fts_path) { 672 doadjust = 1; 673 if (ISSET(FTS_NOCHDIR)) 674 cp = sp->fts_path + len; 675 } 676 maxlen = sp->fts_pathlen - len; 677 } 678 679 p->fts_level = level; 680 p->fts_parent = sp->fts_cur; 681 p->fts_pathlen = len + dp->d_namlen; 682 if (p->fts_pathlen < len) { 683 /* 684 * If we wrap, free up the current structure and 685 * the structures already allocated, then error 686 * out with ENAMETOOLONG. 687 */ 688 free(p); 689 fts_lfree(head); 690 (void)closedir(dirp); 691 cur->fts_info = FTS_ERR; 692 SET(FTS_STOP); 693 errno = ENAMETOOLONG; 694 return (NULL); 695 } 696 697 if (cderrno) { 698 if (nlinks) { 699 p->fts_info = FTS_NS; 700 p->fts_errno = cderrno; 701 } else 702 p->fts_info = FTS_NSOK; 703 p->fts_accpath = cur->fts_accpath; 704 } else if (nlinks == 0 705 #ifdef DT_DIR 706 || (nostat && 707 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN) 708 #endif 709 ) { 710 p->fts_accpath = 711 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name; 712 p->fts_info = FTS_NSOK; 713 } else { 714 /* Build a file name for fts_stat to stat. */ 715 if (ISSET(FTS_NOCHDIR)) { 716 p->fts_accpath = p->fts_path; 717 memmove(cp, p->fts_name, p->fts_namelen + 1); 718 } else 719 p->fts_accpath = p->fts_name; 720 /* Stat it. */ 721 p->fts_info = fts_stat(sp, p, 0); 722 723 /* Decrement link count if applicable. */ 724 if (nlinks > 0 && (p->fts_info == FTS_D || 725 p->fts_info == FTS_DC || p->fts_info == FTS_DOT)) 726 --nlinks; 727 } 728 729 /* We walk in directory order so "ls -f" doesn't get upset. */ 730 p->fts_link = NULL; 731 if (head == NULL) 732 head = tail = p; 733 else { 734 tail->fts_link = p; 735 tail = p; 736 } 737 ++nitems; 738 } 739 if (dirp) 740 (void)closedir(dirp); 741 742 /* 743 * If realloc() changed the address of the path, adjust the 744 * addresses for the rest of the tree and the dir list. 745 */ 746 if (doadjust) 747 fts_padjust(sp, head); 748 749 /* 750 * If not changing directories, reset the path back to original 751 * state. 752 */ 753 if (ISSET(FTS_NOCHDIR)) { 754 if (len == sp->fts_pathlen || nitems == 0) 755 --cp; 756 *cp = '\0'; 757 } 758 759 /* 760 * If descended after called from fts_children or after called from 761 * fts_read and nothing found, get back. At the root level we use 762 * the saved fd; if one of fts_open()'s arguments is a relative path 763 * to an empty directory, we wind up here with no other way back. If 764 * can't get back, we're done. 765 */ 766 if (descend && (type == BCHILD || !nitems) && 767 (cur->fts_level == FTS_ROOTLEVEL ? FCHDIR(sp, sp->fts_rfd) : 768 fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) { 769 cur->fts_info = FTS_ERR; 770 SET(FTS_STOP); 771 return (NULL); 772 } 773 774 /* If didn't find anything, return NULL. */ 775 if (!nitems) { 776 if (type == BREAD) 777 cur->fts_info = FTS_DP; 778 return (NULL); 779 } 780 781 /* Sort the entries. */ 782 if (sp->fts_compar && nitems > 1) 783 head = fts_sort(sp, head, nitems); 784 return (head); 785 } 786 787 static u_short 788 fts_stat(FTS *sp, FTSENT *p, int follow) 789 { 790 FTSENT *t; 791 dev_t dev; 792 ino_t ino; 793 struct stat *sbp, sb; 794 int saved_errno; 795 796 /* If user needs stat info, stat buffer already allocated. */ 797 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp; 798 799 /* 800 * If doing a logical walk, or application requested FTS_FOLLOW, do 801 * a stat(2). If that fails, check for a non-existent symlink. If 802 * fail, set the errno from the stat call. 803 */ 804 if (ISSET(FTS_LOGICAL) || follow) { 805 if (stat(p->fts_accpath, sbp)) { 806 saved_errno = errno; 807 if (!lstat(p->fts_accpath, sbp)) { 808 errno = 0; 809 return (FTS_SLNONE); 810 } 811 p->fts_errno = saved_errno; 812 goto err; 813 } 814 } else if (lstat(p->fts_accpath, sbp)) { 815 p->fts_errno = errno; 816 err: memset(sbp, 0, sizeof(struct stat)); 817 return (FTS_NS); 818 } 819 820 if (S_ISDIR(sbp->st_mode)) { 821 /* 822 * Set the device/inode. Used to find cycles and check for 823 * crossing mount points. Also remember the link count, used 824 * in fts_build to limit the number of stat calls. It is 825 * understood that these fields are only referenced if fts_info 826 * is set to FTS_D. 827 */ 828 dev = p->fts_dev = sbp->st_dev; 829 ino = p->fts_ino = sbp->st_ino; 830 p->fts_nlink = sbp->st_nlink; 831 832 if (ISDOT(p->fts_name)) 833 return (FTS_DOT); 834 835 /* 836 * Cycle detection is done by brute force when the directory 837 * is first encountered. If the tree gets deep enough or the 838 * number of symbolic links to directories is high enough, 839 * something faster might be worthwhile. 840 */ 841 for (t = p->fts_parent; 842 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) 843 if (ino == t->fts_ino && dev == t->fts_dev) { 844 p->fts_cycle = t; 845 return (FTS_DC); 846 } 847 return (FTS_D); 848 } 849 if (S_ISLNK(sbp->st_mode)) 850 return (FTS_SL); 851 if (S_ISREG(sbp->st_mode)) 852 return (FTS_F); 853 return (FTS_DEFAULT); 854 } 855 856 static FTSENT * 857 fts_sort(FTS *sp, FTSENT *head, int nitems) 858 { 859 FTSENT **ap, *p; 860 861 /* 862 * Construct an array of pointers to the structures and call qsort(3). 863 * Reassemble the array in the order returned by qsort. If unable to 864 * sort for memory reasons, return the directory entries in their 865 * current order. Allocate enough space for the current needs plus 866 * 40 so don't realloc one entry at a time. 867 */ 868 if (nitems > sp->fts_nitems) { 869 struct _ftsent **a; 870 871 sp->fts_nitems = nitems + 40; 872 if ((a = realloc(sp->fts_array, 873 sp->fts_nitems * sizeof(FTSENT *))) == NULL) { 874 if (sp->fts_array) 875 free(sp->fts_array); 876 sp->fts_array = NULL; 877 sp->fts_nitems = 0; 878 return (head); 879 } 880 sp->fts_array = a; 881 } 882 for (ap = sp->fts_array, p = head; p; p = p->fts_link) 883 *ap++ = p; 884 qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar); 885 for (head = *(ap = sp->fts_array); --nitems; ++ap) 886 ap[0]->fts_link = ap[1]; 887 ap[0]->fts_link = NULL; 888 return (head); 889 } 890 891 static FTSENT * 892 fts_alloc(FTS *sp, char *name, size_t namelen) 893 { 894 FTSENT *p; 895 size_t len; 896 897 /* 898 * The file name is a variable length array and no stat structure is 899 * necessary if the user has set the nostat bit. Allocate the FTSENT 900 * structure, the file name and the stat structure in one chunk, but 901 * be careful that the stat structure is reasonably aligned. Since the 902 * fts_name field is declared to be of size 1, the fts_name pointer is 903 * namelen + 2 before the first possible address of the stat structure. 904 */ 905 len = sizeof(FTSENT) + namelen; 906 if (!ISSET(FTS_NOSTAT)) 907 len += sizeof(struct stat) + ALIGNBYTES; 908 if ((p = malloc(len)) == NULL) 909 return (NULL); 910 911 memset(p, 0, len); 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 MAXPATHLEN, 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