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