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