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