Debian Codegraph @

src/fts.c

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