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