fts.c 30 KB

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