1 /* $OpenBSD: fts.c,v 1.40 2007/11/06 10:14:53 chl 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 return (NULL); 520 (void)close(fd); 521 return (sp->fts_child); 522 } 523 524 /* 525 * This is the tricky part -- do not casually change *anything* in here. The 526 * idea is to build the linked list of entries that are used by fts_children 527 * and fts_read. There are lots of special cases. 528 * 529 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is 530 * set and it's a physical walk (so that symbolic links can't be directories), 531 * we can do things quickly. First, if it's a 4.4BSD file system, the type 532 * of the file is in the directory entry. Otherwise, we assume that the number 533 * of subdirectories in a node is equal to the number of links to the parent. 534 * The former skips all stat calls. The latter skips stat calls in any leaf 535 * directories and for any files after the subdirectories in the directory have 536 * been found, cutting the stat calls by about 2/3. 537 */ 538 static FTSENT * 539 fts_build(FTS *sp, int type) 540 { 541 struct dirent *dp; 542 FTSENT *p, *head; 543 FTSENT *cur, *tail; 544 DIR *dirp; 545 void *oldaddr; 546 size_t len, maxlen; 547 int nitems, cderrno, descend, level, nlinks, nostat, doadjust; 548 int saved_errno; 549 char *cp; 550 551 /* Set current node pointer. */ 552 cur = sp->fts_cur; 553 554 /* 555 * Open the directory for reading. If this fails, we're done. 556 * If being called from fts_read, set the fts_info field. 557 */ 558 if ((dirp = opendir(cur->fts_accpath)) == NULL) { 559 if (type == BREAD) { 560 cur->fts_info = FTS_DNR; 561 cur->fts_errno = errno; 562 } 563 return (NULL); 564 } 565 566 /* 567 * Nlinks is the number of possible entries of type directory in the 568 * directory if we're cheating on stat calls, 0 if we're not doing 569 * any stat calls at all, -1 if we're doing stats on everything. 570 */ 571 if (type == BNAMES) 572 nlinks = 0; 573 else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) { 574 nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2); 575 nostat = 1; 576 } else { 577 nlinks = -1; 578 nostat = 0; 579 } 580 581 #ifdef notdef 582 (void)printf("nlinks == %d (cur: %u)\n", nlinks, cur->fts_nlink); 583 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n", 584 ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT)); 585 #endif 586 /* 587 * If we're going to need to stat anything or we want to descend 588 * and stay in the directory, chdir. If this fails we keep going, 589 * but set a flag so we don't chdir after the post-order visit. 590 * We won't be able to stat anything, but we can still return the 591 * names themselves. Note, that since fts_read won't be able to 592 * chdir into the directory, it will have to return different path 593 * names than before, i.e. "a/b" instead of "b". Since the node 594 * has already been visited in pre-order, have to wait until the 595 * post-order visit to return the error. There is a special case 596 * here, if there was nothing to stat then it's not an error to 597 * not be able to stat. This is all fairly nasty. If a program 598 * needed sorted entries or stat information, they had better be 599 * checking FTS_NS on the returned nodes. 600 */ 601 cderrno = 0; 602 if (nlinks || type == BREAD) { 603 if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) { 604 if (nlinks && type == BREAD) 605 cur->fts_errno = errno; 606 cur->fts_flags |= FTS_DONTCHDIR; 607 descend = 0; 608 cderrno = errno; 609 (void)closedir(dirp); 610 dirp = NULL; 611 } else 612 descend = 1; 613 } else 614 descend = 0; 615 616 /* 617 * Figure out the max file name length that can be stored in the 618 * current path -- the inner loop allocates more path as necessary. 619 * We really wouldn't have to do the maxlen calculations here, we 620 * could do them in fts_read before returning the path, but it's a 621 * lot easier here since the length is part of the dirent structure. 622 * 623 * If not changing directories set a pointer so that can just append 624 * each new name into the path. 625 */ 626 len = NAPPEND(cur); 627 if (ISSET(FTS_NOCHDIR)) { 628 cp = sp->fts_path + len; 629 *cp++ = '/'; 630 } 631 len++; 632 maxlen = sp->fts_pathlen - len; 633 634 level = cur->fts_level + 1; 635 636 /* Read the directory, attaching each entry to the `link' pointer. */ 637 doadjust = 0; 638 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) { 639 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name)) 640 continue; 641 642 if (!(p = fts_alloc(sp, dp->d_name, (size_t)dp->d_namlen))) 643 goto mem1; 644 if (dp->d_namlen >= maxlen) { /* include space for NUL */ 645 oldaddr = sp->fts_path; 646 if (fts_palloc(sp, dp->d_namlen +len + 1)) { 647 /* 648 * No more memory for path or structures. Save 649 * errno, free up the current structure and the 650 * structures already allocated. 651 */ 652 mem1: saved_errno = errno; 653 if (p) 654 free(p); 655 fts_lfree(head); 656 (void)closedir(dirp); 657 cur->fts_info = FTS_ERR; 658 SET(FTS_STOP); 659 errno = saved_errno; 660 return (NULL); 661 } 662 /* Did realloc() change the pointer? */ 663 if (oldaddr != sp->fts_path) { 664 doadjust = 1; 665 if (ISSET(FTS_NOCHDIR)) 666 cp = sp->fts_path + len; 667 } 668 maxlen = sp->fts_pathlen - len; 669 } 670 671 p->fts_level = level; 672 p->fts_parent = sp->fts_cur; 673 p->fts_pathlen = len + dp->d_namlen; 674 if (p->fts_pathlen < len) { 675 /* 676 * If we wrap, free up the current structure and 677 * the structures already allocated, then error 678 * out with ENAMETOOLONG. 679 */ 680 free(p); 681 fts_lfree(head); 682 (void)closedir(dirp); 683 cur->fts_info = FTS_ERR; 684 SET(FTS_STOP); 685 errno = ENAMETOOLONG; 686 return (NULL); 687 } 688 689 if (cderrno) { 690 if (nlinks) { 691 p->fts_info = FTS_NS; 692 p->fts_errno = cderrno; 693 } else 694 p->fts_info = FTS_NSOK; 695 p->fts_accpath = cur->fts_accpath; 696 } else if (nlinks == 0 697 #ifdef DT_DIR 698 || (nostat && 699 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN) 700 #endif 701 ) { 702 p->fts_accpath = 703 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name; 704 p->fts_info = FTS_NSOK; 705 } else { 706 /* Build a file name for fts_stat to stat. */ 707 if (ISSET(FTS_NOCHDIR)) { 708 p->fts_accpath = p->fts_path; 709 memmove(cp, p->fts_name, p->fts_namelen + 1); 710 } else 711 p->fts_accpath = p->fts_name; 712 /* Stat it. */ 713 p->fts_info = fts_stat(sp, p, 0); 714 715 /* Decrement link count if applicable. */ 716 if (nlinks > 0 && (p->fts_info == FTS_D || 717 p->fts_info == FTS_DC || p->fts_info == FTS_DOT)) 718 --nlinks; 719 } 720 721 /* We walk in directory order so "ls -f" doesn't get upset. */ 722 p->fts_link = NULL; 723 if (head == NULL) 724 head = tail = p; 725 else { 726 tail->fts_link = p; 727 tail = p; 728 } 729 ++nitems; 730 } 731 if (dirp) 732 (void)closedir(dirp); 733 734 /* 735 * If realloc() changed the address of the path, adjust the 736 * addresses for the rest of the tree and the dir list. 737 */ 738 if (doadjust) 739 fts_padjust(sp, head); 740 741 /* 742 * If not changing directories, reset the path back to original 743 * state. 744 */ 745 if (ISSET(FTS_NOCHDIR)) { 746 if (len == sp->fts_pathlen || nitems == 0) 747 --cp; 748 *cp = '\0'; 749 } 750 751 /* 752 * If descended after called from fts_children or after called from 753 * fts_read and nothing found, get back. At the root level we use 754 * the saved fd; if one of fts_open()'s arguments is a relative path 755 * to an empty directory, we wind up here with no other way back. If 756 * can't get back, we're done. 757 */ 758 if (descend && (type == BCHILD || !nitems) && 759 (cur->fts_level == FTS_ROOTLEVEL ? FCHDIR(sp, sp->fts_rfd) : 760 fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) { 761 cur->fts_info = FTS_ERR; 762 SET(FTS_STOP); 763 return (NULL); 764 } 765 766 /* If didn't find anything, return NULL. */ 767 if (!nitems) { 768 if (type == BREAD) 769 cur->fts_info = FTS_DP; 770 return (NULL); 771 } 772 773 /* Sort the entries. */ 774 if (sp->fts_compar && nitems > 1) 775 head = fts_sort(sp, head, nitems); 776 return (head); 777 } 778 779 static u_short 780 fts_stat(FTS *sp, FTSENT *p, int follow) 781 { 782 FTSENT *t; 783 dev_t dev; 784 ino_t ino; 785 struct stat *sbp, sb; 786 int saved_errno; 787 788 /* If user needs stat info, stat buffer already allocated. */ 789 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp; 790 791 /* 792 * If doing a logical walk, or application requested FTS_FOLLOW, do 793 * a stat(2). If that fails, check for a non-existent symlink. If 794 * fail, set the errno from the stat call. 795 */ 796 if (ISSET(FTS_LOGICAL) || follow) { 797 if (stat(p->fts_accpath, sbp)) { 798 saved_errno = errno; 799 if (!lstat(p->fts_accpath, sbp)) { 800 errno = 0; 801 return (FTS_SLNONE); 802 } 803 p->fts_errno = saved_errno; 804 goto err; 805 } 806 } else if (lstat(p->fts_accpath, sbp)) { 807 p->fts_errno = errno; 808 err: memset(sbp, 0, sizeof(struct stat)); 809 return (FTS_NS); 810 } 811 812 if (S_ISDIR(sbp->st_mode)) { 813 /* 814 * Set the device/inode. Used to find cycles and check for 815 * crossing mount points. Also remember the link count, used 816 * in fts_build to limit the number of stat calls. It is 817 * understood that these fields are only referenced if fts_info 818 * is set to FTS_D. 819 */ 820 dev = p->fts_dev = sbp->st_dev; 821 ino = p->fts_ino = sbp->st_ino; 822 p->fts_nlink = sbp->st_nlink; 823 824 if (ISDOT(p->fts_name)) 825 return (FTS_DOT); 826 827 /* 828 * Cycle detection is done by brute force when the directory 829 * is first encountered. If the tree gets deep enough or the 830 * number of symbolic links to directories is high enough, 831 * something faster might be worthwhile. 832 */ 833 for (t = p->fts_parent; 834 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) 835 if (ino == t->fts_ino && dev == t->fts_dev) { 836 p->fts_cycle = t; 837 return (FTS_DC); 838 } 839 return (FTS_D); 840 } 841 if (S_ISLNK(sbp->st_mode)) 842 return (FTS_SL); 843 if (S_ISREG(sbp->st_mode)) 844 return (FTS_F); 845 return (FTS_DEFAULT); 846 } 847 848 static FTSENT * 849 fts_sort(FTS *sp, FTSENT *head, int nitems) 850 { 851 FTSENT **ap, *p; 852 853 /* 854 * Construct an array of pointers to the structures and call qsort(3). 855 * Reassemble the array in the order returned by qsort. If unable to 856 * sort for memory reasons, return the directory entries in their 857 * current order. Allocate enough space for the current needs plus 858 * 40 so don't realloc one entry at a time. 859 */ 860 if (nitems > sp->fts_nitems) { 861 struct _ftsent **a; 862 863 sp->fts_nitems = nitems + 40; 864 if ((a = realloc(sp->fts_array, 865 sp->fts_nitems * sizeof(FTSENT *))) == NULL) { 866 if (sp->fts_array) 867 free(sp->fts_array); 868 sp->fts_array = NULL; 869 sp->fts_nitems = 0; 870 return (head); 871 } 872 sp->fts_array = a; 873 } 874 for (ap = sp->fts_array, p = head; p; p = p->fts_link) 875 *ap++ = p; 876 qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar); 877 for (head = *(ap = sp->fts_array); --nitems; ++ap) 878 ap[0]->fts_link = ap[1]; 879 ap[0]->fts_link = NULL; 880 return (head); 881 } 882 883 static FTSENT * 884 fts_alloc(FTS *sp, char *name, size_t namelen) 885 { 886 FTSENT *p; 887 size_t len; 888 889 /* 890 * The file name is a variable length array and no stat structure is 891 * necessary if the user has set the nostat bit. Allocate the FTSENT 892 * structure, the file name and the stat structure in one chunk, but 893 * be careful that the stat structure is reasonably aligned. Since the 894 * fts_name field is declared to be of size 1, the fts_name pointer is 895 * namelen + 2 before the first possible address of the stat structure. 896 */ 897 len = sizeof(FTSENT) + namelen; 898 if (!ISSET(FTS_NOSTAT)) 899 len += sizeof(struct stat) + ALIGNBYTES; 900 if ((p = malloc(len)) == NULL) 901 return (NULL); 902 903 memset(p, 0, len); 904 p->fts_path = sp->fts_path; 905 p->fts_namelen = namelen; 906 p->fts_instr = FTS_NOINSTR; 907 if (!ISSET(FTS_NOSTAT)) 908 p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2); 909 memcpy(p->fts_name, name, namelen); 910 911 return (p); 912 } 913 914 static void 915 fts_lfree(FTSENT *head) 916 { 917 FTSENT *p; 918 919 /* Free a linked list of structures. */ 920 while ((p = head)) { 921 head = head->fts_link; 922 free(p); 923 } 924 } 925 926 /* 927 * Allow essentially unlimited paths; find, rm, ls should all work on any tree. 928 * Most systems will allow creation of paths much longer than MAXPATHLEN, even 929 * though the kernel won't resolve them. Add the size (not just what's needed) 930 * plus 256 bytes so don't realloc the path 2 bytes at a time. 931 */ 932 static int 933 fts_palloc(FTS *sp, size_t more) 934 { 935 char *p; 936 937 /* 938 * Check for possible wraparound. 939 */ 940 more += 256; 941 if (sp->fts_pathlen + more < sp->fts_pathlen) { 942 if (sp->fts_path) 943 free(sp->fts_path); 944 sp->fts_path = NULL; 945 errno = ENAMETOOLONG; 946 return (1); 947 } 948 sp->fts_pathlen += more; 949 p = realloc(sp->fts_path, sp->fts_pathlen); 950 if (p == NULL) { 951 if (sp->fts_path) 952 free(sp->fts_path); 953 sp->fts_path = NULL; 954 return (1); 955 } 956 sp->fts_path = p; 957 return (0); 958 } 959 960 /* 961 * When the path is realloc'd, have to fix all of the pointers in structures 962 * already returned. 963 */ 964 static void 965 fts_padjust(FTS *sp, FTSENT *head) 966 { 967 FTSENT *p; 968 char *addr = sp->fts_path; 969 970 #define ADJUST(p) { \ 971 if ((p)->fts_accpath != (p)->fts_name) { \ 972 (p)->fts_accpath = \ 973 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \ 974 } \ 975 (p)->fts_path = addr; \ 976 } 977 /* Adjust the current set of children. */ 978 for (p = sp->fts_child; p; p = p->fts_link) 979 ADJUST(p); 980 981 /* Adjust the rest of the tree, including the current level. */ 982 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) { 983 ADJUST(p); 984 p = p->fts_link ? p->fts_link : p->fts_parent; 985 } 986 } 987 988 static size_t 989 fts_maxarglen(char * const *argv) 990 { 991 size_t len, max; 992 993 for (max = 0; *argv; ++argv) 994 if ((len = strlen(*argv)) > max) 995 max = len; 996 return (max + 1); 997 } 998 999 /* 1000 * Change to dir specified by fd or p->fts_accpath without getting 1001 * tricked by someone changing the world out from underneath us. 1002 * Assumes p->fts_dev and p->fts_ino are filled in. 1003 */ 1004 static int 1005 fts_safe_changedir(FTS *sp, FTSENT *p, int fd, char *path) 1006 { 1007 int ret, oerrno, newfd; 1008 struct stat sb; 1009 1010 newfd = fd; 1011 if (ISSET(FTS_NOCHDIR)) 1012 return (0); 1013 if (fd < 0 && (newfd = open(path, O_RDONLY, 0)) < 0) 1014 return (-1); 1015 if (fstat(newfd, &sb)) { 1016 ret = -1; 1017 goto bail; 1018 } 1019 if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) { 1020 errno = ENOENT; /* disinformation */ 1021 ret = -1; 1022 goto bail; 1023 } 1024 ret = fchdir(newfd); 1025 bail: 1026 oerrno = errno; 1027 if (fd < 0) 1028 (void)close(newfd); 1029 errno = oerrno; 1030 return (ret); 1031 } 1032