fts.c 30 KB

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