]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/mdocml/compat_fts.c
Revert r312765 for now, since it causes assertions when building
[FreeBSD/FreeBSD.git] / contrib / mdocml / compat_fts.c
1 #include "config.h"
2
3 #if HAVE_FTS
4
5 int dummy;
6
7 #else
8
9 /*      $Id: compat_fts.c,v 1.12 2016/10/18 23:58:12 schwarze Exp $     */
10 /*      $OpenBSD: fts.c,v 1.56 2016/09/21 04:38:56 guenther Exp $       */
11
12 /*-
13  * Copyright (c) 1990, 1993, 1994
14  *      The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #include <sys/stat.h>
42 #include <sys/types.h>
43
44 #include <dirent.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <limits.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include "compat_fts.h"
52
53 #define MAXIMUM(a, b)   (((a) > (b)) ? (a) : (b))
54
55 static FTSENT   *fts_alloc(FTS *, const char *, size_t);
56 static FTSENT   *fts_build(FTS *);
57 static void      fts_lfree(FTSENT *);
58 static void      fts_load(FTS *, FTSENT *);
59 static size_t    fts_maxarglen(char * const *);
60 static void      fts_padjust(FTS *, FTSENT *);
61 static int       fts_palloc(FTS *, size_t);
62 static FTSENT   *fts_sort(FTS *, FTSENT *, int);
63 static unsigned short    fts_stat(FTS *, FTSENT *);
64
65 #define ISDOT(a)        (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
66 #ifndef O_DIRECTORY
67 #define O_DIRECTORY     0
68 #endif
69 #ifndef O_CLOEXEC
70 #define O_CLOEXEC       0
71 #endif
72 #ifndef PATH_MAX
73 #define PATH_MAX        4096
74 #endif
75
76 #define CLR(opt)        (sp->fts_options &= ~(opt))
77 #define ISSET(opt)      (sp->fts_options & (opt))
78 #define SET(opt)        (sp->fts_options |= (opt))
79
80 FTS *
81 fts_open(char * const *argv, int options,
82     int (*compar)(const FTSENT **, const FTSENT **))
83 {
84         FTS *sp;
85         FTSENT *p, *root;
86         int nitems;
87         FTSENT *parent, *tmp;
88
89         /* Options check. */
90         if (options & ~FTS_OPTIONMASK) {
91                 errno = EINVAL;
92                 return (NULL);
93         }
94
95         /* At least one path must be specified. */
96         if (*argv == NULL) {
97                 errno = EINVAL;
98                 return (NULL);
99         }
100
101         /* Allocate/initialize the stream */
102         if ((sp = calloc(1, sizeof(FTS))) == NULL)
103                 return (NULL);
104         sp->fts_compar = compar;
105         sp->fts_options = options;
106
107         /*
108          * Start out with 1K of path space, and enough, in any case,
109          * to hold the user's paths.
110          */
111         if (fts_palloc(sp, MAXIMUM(fts_maxarglen(argv), PATH_MAX)))
112                 goto mem1;
113
114         /* Allocate/initialize root's parent. */
115         if ((parent = fts_alloc(sp, "", 0)) == NULL)
116                 goto mem2;
117         parent->fts_level = FTS_ROOTPARENTLEVEL;
118
119         /* Allocate/initialize root(s). */
120         for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
121                 if ((p = fts_alloc(sp, *argv, strlen(*argv))) == NULL)
122                         goto mem3;
123                 p->fts_level = FTS_ROOTLEVEL;
124                 p->fts_parent = parent;
125                 p->fts_accpath = p->fts_name;
126                 p->fts_info = fts_stat(sp, p);
127
128                 /* Command-line "." and ".." are real directories. */
129                 if (p->fts_info == FTS_DOT)
130                         p->fts_info = FTS_D;
131
132                 /*
133                  * If comparison routine supplied, traverse in sorted
134                  * order; otherwise traverse in the order specified.
135                  */
136                 if (compar) {
137                         p->fts_link = root;
138                         root = p;
139                 } else {
140                         p->fts_link = NULL;
141                         if (root == NULL)
142                                 tmp = root = p;
143                         else {
144                                 tmp->fts_link = p;
145                                 tmp = p;
146                         }
147                 }
148         }
149         if (compar && nitems > 1)
150                 root = fts_sort(sp, root, nitems);
151
152         /*
153          * Allocate a dummy pointer and make fts_read think that we've just
154          * finished the node before the root(s); set p->fts_info to FTS_INIT
155          * so that everything about the "current" node is ignored.
156          */
157         if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
158                 goto mem3;
159         sp->fts_cur->fts_link = root;
160         sp->fts_cur->fts_info = FTS_INIT;
161
162         if (nitems == 0)
163                 free(parent);
164
165         return (sp);
166
167 mem3:   fts_lfree(root);
168         free(parent);
169 mem2:   free(sp->fts_path);
170 mem1:   free(sp);
171         return (NULL);
172 }
173
174 static void
175 fts_load(FTS *sp, FTSENT *p)
176 {
177         size_t len;
178         char *cp;
179
180         /*
181          * Load the stream structure for the next traversal.  Since we don't
182          * actually enter the directory until after the preorder visit, set
183          * the fts_accpath field specially so the chdir gets done to the right
184          * place and the user can access the first node.  From fts_open it's
185          * known that the path will fit.
186          */
187         len = p->fts_pathlen = p->fts_namelen;
188         memmove(sp->fts_path, p->fts_name, len + 1);
189         if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
190                 len = strlen(++cp);
191                 memmove(p->fts_name, cp, len + 1);
192                 p->fts_namelen = len;
193         }
194         p->fts_accpath = p->fts_path = sp->fts_path;
195         sp->fts_dev = p->fts_dev;
196 }
197
198 int
199 fts_close(FTS *sp)
200 {
201         FTSENT *freep, *p;
202
203         /*
204          * This still works if we haven't read anything -- the dummy structure
205          * points to the root list, so we step through to the end of the root
206          * list which has a valid parent pointer.
207          */
208         if (sp->fts_cur) {
209                 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
210                         freep = p;
211                         p = p->fts_link ? p->fts_link : p->fts_parent;
212                         free(freep);
213                 }
214                 free(p);
215         }
216
217         /* Free up child linked list, sort array, path buffer, stream ptr.*/
218         if (sp->fts_child)
219                 fts_lfree(sp->fts_child);
220         free(sp->fts_array);
221         free(sp->fts_path);
222         free(sp);
223
224         return (0);
225 }
226
227 /*
228  * Special case of "/" at the end of the path so that slashes aren't
229  * appended which would cause paths to be written as "....//foo".
230  */
231 #define NAPPEND(p)                                                      \
232         (p->fts_path[p->fts_pathlen - 1] == '/'                         \
233             ? p->fts_pathlen - 1 : p->fts_pathlen)
234
235 FTSENT *
236 fts_read(FTS *sp)
237 {
238         FTSENT *p, *tmp;
239         int instr;
240         char *t;
241
242         /* If finished or unrecoverable error, return NULL. */
243         if (sp->fts_cur == NULL || ISSET(FTS_STOP))
244                 return (NULL);
245
246         /* Set current node pointer. */
247         p = sp->fts_cur;
248
249         /* Save and zero out user instructions. */
250         instr = p->fts_instr;
251         p->fts_instr = FTS_NOINSTR;
252
253         /* Directory in pre-order. */
254         if (p->fts_info == FTS_D) {
255                 /* If skipped or crossed mount point, do post-order visit. */
256                 if (instr == FTS_SKIP ||
257                     (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
258                         if (sp->fts_child) {
259                                 fts_lfree(sp->fts_child);
260                                 sp->fts_child = NULL;
261                         }
262                         p->fts_info = FTS_DP;
263                         return (p);
264                 }
265
266                 /*
267                  * If haven't read do so.  If the read fails, fts_build sets
268                  * FTS_STOP or the fts_info field of the node.
269                  */
270                 if (sp->fts_child) {
271                         /* nothing */
272                 } else if ((sp->fts_child = fts_build(sp)) == NULL) {
273                         if (ISSET(FTS_STOP))
274                                 return (NULL);
275                         return (p);
276                 }
277                 p = sp->fts_child;
278                 sp->fts_child = NULL;
279                 goto name;
280         }
281
282         /* Move to the next node on this level. */
283 next:   tmp = p;
284         if ((p = p->fts_link)) {
285                 free(tmp);
286
287                 /*
288                  * If reached the top, return to the original directory (or
289                  * the root of the tree), and load the paths for the next root.
290                  */
291                 if (p->fts_level == FTS_ROOTLEVEL) {
292                         fts_load(sp, p);
293                         return (sp->fts_cur = p);
294                 }
295
296                 /*
297                  * User may have called fts_set on the node.  If skipped,
298                  * ignore.  If followed, get a file descriptor so we can
299                  * get back if necessary.
300                  */
301                 if (p->fts_instr == FTS_SKIP)
302                         goto next;
303
304 name:           t = sp->fts_path + NAPPEND(p->fts_parent);
305                 *t++ = '/';
306                 memmove(t, p->fts_name, p->fts_namelen + 1);
307                 return (sp->fts_cur = p);
308         }
309
310         /* Move up to the parent node. */
311         p = tmp->fts_parent;
312         free(tmp);
313
314         if (p->fts_level == FTS_ROOTPARENTLEVEL) {
315                 /*
316                  * Done; free everything up and set errno to 0 so the user
317                  * can distinguish between error and EOF.
318                  */
319                 free(p);
320                 errno = 0;
321                 return (sp->fts_cur = NULL);
322         }
323
324         /* NUL terminate the pathname. */
325         sp->fts_path[p->fts_pathlen] = '\0';
326
327         p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
328         return (sp->fts_cur = p);
329 }
330
331 /*
332  * Fts_set takes the stream as an argument although it's not used in this
333  * implementation; it would be necessary if anyone wanted to add global
334  * semantics to fts using fts_set.  An error return is allowed for similar
335  * reasons.
336  */
337 int
338 fts_set(FTS *sp, FTSENT *p, int instr)
339 {
340         if (instr && instr != FTS_NOINSTR && instr != FTS_SKIP) {
341                 errno = EINVAL;
342                 return (1);
343         }
344         p->fts_instr = instr;
345         return (0);
346 }
347
348 /*
349  * This is the tricky part -- do not casually change *anything* in here.  The
350  * idea is to build the linked list of entries that are used by fts_children
351  * and fts_read.  There are lots of special cases.
352  *
353  * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
354  * set and it's a physical walk (so that symbolic links can't be directories),
355  * we can do things quickly.  First, if it's a 4.4BSD file system, the type
356  * of the file is in the directory entry.  Otherwise, we assume that the number
357  * of subdirectories in a node is equal to the number of links to the parent.
358  * The former skips all stat calls.  The latter skips stat calls in any leaf
359  * directories and for any files after the subdirectories in the directory have
360  * been found, cutting the stat calls by about 2/3.
361  */
362 static FTSENT *
363 fts_build(FTS *sp)
364 {
365         struct dirent *dp;
366         FTSENT *p, *head;
367         FTSENT *cur, *tail;
368         DIR *dirp;
369         void *oldaddr;
370         size_t dlen, len, maxlen;
371         int nitems, level, doadjust;
372         int saved_errno;
373         char *cp;
374
375         /* Set current node pointer. */
376         cur = sp->fts_cur;
377
378         /*
379          * Open the directory for reading.  If this fails, we're done.
380          * If being called from fts_read, set the fts_info field.
381          */
382         if ((dirp = opendir(cur->fts_accpath)) == NULL) {
383                 cur->fts_info = FTS_DNR;
384                 cur->fts_errno = errno;
385                 return (NULL);
386         }
387
388         /*
389          * Figure out the max file name length that can be stored in the
390          * current path -- the inner loop allocates more path as necessary.
391          * We really wouldn't have to do the maxlen calculations here, we
392          * could do them in fts_read before returning the path, but it's a
393          * lot easier here since the length is part of the dirent structure.
394          *
395          * If not changing directories set a pointer so that can just append
396          * each new name into the path.
397          */
398         len = NAPPEND(cur);
399         cp = sp->fts_path + len;
400         *cp++ = '/';
401         len++;
402         maxlen = sp->fts_pathlen - len;
403
404         /*
405          * fts_level is signed so we must prevent it from wrapping
406          * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
407          */
408         level = cur->fts_level;
409         if (level < FTS_MAXLEVEL)
410             level++;
411
412         /* Read the directory, attaching each entry to the `link' pointer. */
413         doadjust = 0;
414         for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
415                 if (ISDOT(dp->d_name))
416                         continue;
417
418 #if HAVE_DIRENT_NAMLEN
419                 dlen = dp->d_namlen;
420 #else
421                 dlen = strlen(dp->d_name);
422 #endif
423
424                 if (!(p = fts_alloc(sp, dp->d_name, dlen)))
425                         goto mem1;
426                 if (dlen >= maxlen) {   /* include space for NUL */
427                         oldaddr = sp->fts_path;
428                         if (fts_palloc(sp, dlen + len + 1)) {
429                                 /*
430                                  * No more memory for path or structures.  Save
431                                  * errno, free up the current structure and the
432                                  * structures already allocated.
433                                  */
434 mem1:                           saved_errno = errno;
435                                 free(p);
436                                 fts_lfree(head);
437                                 (void)closedir(dirp);
438                                 cur->fts_info = FTS_ERR;
439                                 SET(FTS_STOP);
440                                 errno = saved_errno;
441                                 return (NULL);
442                         }
443                         /* Did realloc() change the pointer? */
444                         if (oldaddr != sp->fts_path) {
445                                 doadjust = 1;
446                                 cp = sp->fts_path + len;
447                         }
448                         maxlen = sp->fts_pathlen - len;
449                 }
450
451                 p->fts_level = level;
452                 p->fts_parent = sp->fts_cur;
453                 p->fts_pathlen = len + dlen;
454                 if (p->fts_pathlen < len) {
455                         /*
456                          * If we wrap, free up the current structure and
457                          * the structures already allocated, then error
458                          * out with ENAMETOOLONG.
459                          */
460                         free(p);
461                         fts_lfree(head);
462                         (void)closedir(dirp);
463                         cur->fts_info = FTS_ERR;
464                         SET(FTS_STOP);
465                         errno = ENAMETOOLONG;
466                         return (NULL);
467                 }
468
469                 /* Build a file name for fts_stat to stat. */
470                 p->fts_accpath = p->fts_path;
471                 memmove(cp, p->fts_name, p->fts_namelen + 1);
472                 /* Stat it. */
473                 p->fts_info = fts_stat(sp, p);
474
475                 /* We walk in directory order so "ls -f" doesn't get upset. */
476                 p->fts_link = NULL;
477                 if (head == NULL)
478                         head = tail = p;
479                 else {
480                         tail->fts_link = p;
481                         tail = p;
482                 }
483                 ++nitems;
484         }
485         if (dirp)
486                 (void)closedir(dirp);
487
488         /*
489          * If realloc() changed the address of the path, adjust the
490          * addresses for the rest of the tree and the dir list.
491          */
492         if (doadjust)
493                 fts_padjust(sp, head);
494
495         /*
496          * If not changing directories, reset the path back to original
497          * state.
498          */
499         if (len == sp->fts_pathlen || nitems == 0)
500                 --cp;
501         *cp = '\0';
502
503         /* If didn't find anything, return NULL. */
504         if (!nitems) {
505                 cur->fts_info = FTS_DP;
506                 return (NULL);
507         }
508
509         /* Sort the entries. */
510         if (sp->fts_compar && nitems > 1)
511                 head = fts_sort(sp, head, nitems);
512         return (head);
513 }
514
515 static unsigned short
516 fts_stat(FTS *sp, FTSENT *p)
517 {
518         FTSENT *t;
519         dev_t dev;
520         ino_t ino;
521         struct stat *sbp;
522
523         /* If user needs stat info, stat buffer already allocated. */
524         sbp = p->fts_statp;
525
526         if (lstat(p->fts_accpath, sbp)) {
527                 p->fts_errno = errno;
528                 memset(sbp, 0, sizeof(struct stat));
529                 return (FTS_NS);
530         }
531
532         if (S_ISDIR(sbp->st_mode)) {
533                 /*
534                  * Set the device/inode.  Used to find cycles and check for
535                  * crossing mount points.  Also remember the link count, used
536                  * in fts_build to limit the number of stat calls.  It is
537                  * understood that these fields are only referenced if fts_info
538                  * is set to FTS_D.
539                  */
540                 dev = p->fts_dev = sbp->st_dev;
541                 ino = p->fts_ino = sbp->st_ino;
542                 p->fts_nlink = sbp->st_nlink;
543
544                 if (ISDOT(p->fts_name))
545                         return (FTS_DOT);
546
547                 /*
548                  * Cycle detection is done by brute force when the directory
549                  * is first encountered.  If the tree gets deep enough or the
550                  * number of symbolic links to directories is high enough,
551                  * something faster might be worthwhile.
552                  */
553                 for (t = p->fts_parent;
554                     t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
555                         if (ino == t->fts_ino && dev == t->fts_dev) {
556                                 p->fts_cycle = t;
557                                 return (FTS_DC);
558                         }
559                 return (FTS_D);
560         }
561         if (S_ISLNK(sbp->st_mode))
562                 return (FTS_SL);
563         if (S_ISREG(sbp->st_mode))
564                 return (FTS_F);
565         return (FTS_DEFAULT);
566 }
567
568 static FTSENT *
569 fts_sort(FTS *sp, FTSENT *head, int nitems)
570 {
571         FTSENT **ap, *p;
572
573         /*
574          * Construct an array of pointers to the structures and call qsort(3).
575          * Reassemble the array in the order returned by qsort.  If unable to
576          * sort for memory reasons, return the directory entries in their
577          * current order.  Allocate enough space for the current needs plus
578          * 40 so don't realloc one entry at a time.
579          */
580         if (nitems > sp->fts_nitems) {
581                 struct _ftsent **a;
582
583                 sp->fts_nitems = nitems + 40;
584                 if ((a = reallocarray(sp->fts_array,
585                     sp->fts_nitems, sizeof(FTSENT *))) == NULL) {
586                         free(sp->fts_array);
587                         sp->fts_array = NULL;
588                         sp->fts_nitems = 0;
589                         return (head);
590                 }
591                 sp->fts_array = a;
592         }
593         for (ap = sp->fts_array, p = head; p; p = p->fts_link)
594                 *ap++ = p;
595         qsort(sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
596         for (head = *(ap = sp->fts_array); --nitems; ++ap)
597                 ap[0]->fts_link = ap[1];
598         ap[0]->fts_link = NULL;
599         return (head);
600 }
601
602 static FTSENT *
603 fts_alloc(FTS *sp, const char *name, size_t namelen)
604 {
605         FTSENT *p;
606         size_t len;
607
608         len = sizeof(FTSENT) + namelen;
609         if ((p = calloc(1, len)) == NULL)
610                 return (NULL);
611
612         p->fts_path = sp->fts_path;
613         p->fts_namelen = namelen;
614         p->fts_instr = FTS_NOINSTR;
615         p->fts_statp = malloc(sizeof(struct stat));
616         if (p->fts_statp == NULL) {
617                 free(p);
618                 return (NULL);
619         }
620         memcpy(p->fts_name, name, namelen);
621
622         return (p);
623 }
624
625 static void
626 fts_lfree(FTSENT *head)
627 {
628         FTSENT *p;
629
630         /* Free a linked list of structures. */
631         while ((p = head)) {
632                 head = head->fts_link;
633                 free(p);
634         }
635 }
636
637 /*
638  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
639  * Most systems will allow creation of paths much longer than PATH_MAX, even
640  * though the kernel won't resolve them.  Add the size (not just what's needed)
641  * plus 256 bytes so don't realloc the path 2 bytes at a time.
642  */
643 static int
644 fts_palloc(FTS *sp, size_t more)
645 {
646         char *p;
647
648         /*
649          * Check for possible wraparound.
650          */
651         more += 256;
652         if (sp->fts_pathlen + more < sp->fts_pathlen) {
653                 free(sp->fts_path);
654                 sp->fts_path = NULL;
655                 errno = ENAMETOOLONG;
656                 return (1);
657         }
658         sp->fts_pathlen += more;
659         p = realloc(sp->fts_path, sp->fts_pathlen);
660         if (p == NULL) {
661                 free(sp->fts_path);
662                 sp->fts_path = NULL;
663                 return (1);
664         }
665         sp->fts_path = p;
666         return (0);
667 }
668
669 /*
670  * When the path is realloc'd, have to fix all of the pointers in structures
671  * already returned.
672  */
673 static void
674 fts_padjust(FTS *sp, FTSENT *head)
675 {
676         FTSENT *p;
677         char *addr = sp->fts_path;
678
679 #define ADJUST(p) {                                                     \
680         if ((p)->fts_accpath != (p)->fts_name) {                        \
681                 (p)->fts_accpath =                                      \
682                     (char *)addr + ((p)->fts_accpath - (p)->fts_path);  \
683         }                                                               \
684         (p)->fts_path = addr;                                           \
685 }
686         /* Adjust the current set of children. */
687         for (p = sp->fts_child; p; p = p->fts_link)
688                 ADJUST(p);
689
690         /* Adjust the rest of the tree, including the current level. */
691         for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
692                 ADJUST(p);
693                 p = p->fts_link ? p->fts_link : p->fts_parent;
694         }
695 }
696
697 static size_t
698 fts_maxarglen(char * const *argv)
699 {
700         size_t len, max;
701
702         for (max = 0; *argv; ++argv)
703                 if ((len = strlen(*argv)) > max)
704                         max = len;
705         return (max + 1);
706 }
707
708 #endif