]> git.cameronkatri.com Git - mandoc.git/blob - compat_fts.c
Remove the ENDBODY_NOSPACE flag, simplifying the code.
[mandoc.git] / 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.13 2017/02/15 15:58:46 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, *prev;
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 = prev = 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 root = p;
143 else
144 prev->fts_link = p;
145 prev = p;
146 }
147 }
148 if (compar && nitems > 1)
149 root = fts_sort(sp, root, nitems);
150
151 /*
152 * Allocate a dummy pointer and make fts_read think that we've just
153 * finished the node before the root(s); set p->fts_info to FTS_INIT
154 * so that everything about the "current" node is ignored.
155 */
156 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
157 goto mem3;
158 sp->fts_cur->fts_link = root;
159 sp->fts_cur->fts_info = FTS_INIT;
160
161 if (nitems == 0)
162 free(parent);
163
164 return (sp);
165
166 mem3: fts_lfree(root);
167 free(parent);
168 mem2: free(sp->fts_path);
169 mem1: free(sp);
170 return (NULL);
171 }
172
173 static void
174 fts_load(FTS *sp, FTSENT *p)
175 {
176 size_t len;
177 char *cp;
178
179 /*
180 * Load the stream structure for the next traversal. Since we don't
181 * actually enter the directory until after the preorder visit, set
182 * the fts_accpath field specially so the chdir gets done to the right
183 * place and the user can access the first node. From fts_open it's
184 * known that the path will fit.
185 */
186 len = p->fts_pathlen = p->fts_namelen;
187 memmove(sp->fts_path, p->fts_name, len + 1);
188 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
189 len = strlen(++cp);
190 memmove(p->fts_name, cp, len + 1);
191 p->fts_namelen = len;
192 }
193 p->fts_accpath = p->fts_path = sp->fts_path;
194 sp->fts_dev = p->fts_dev;
195 }
196
197 int
198 fts_close(FTS *sp)
199 {
200 FTSENT *freep, *p;
201
202 /*
203 * This still works if we haven't read anything -- the dummy structure
204 * points to the root list, so we step through to the end of the root
205 * list which has a valid parent pointer.
206 */
207 if (sp->fts_cur) {
208 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
209 freep = p;
210 p = p->fts_link ? p->fts_link : p->fts_parent;
211 free(freep);
212 }
213 free(p);
214 }
215
216 /* Free up child linked list, sort array, path buffer, stream ptr.*/
217 if (sp->fts_child)
218 fts_lfree(sp->fts_child);
219 free(sp->fts_array);
220 free(sp->fts_path);
221 free(sp);
222
223 return (0);
224 }
225
226 /*
227 * Special case of "/" at the end of the path so that slashes aren't
228 * appended which would cause paths to be written as "....//foo".
229 */
230 #define NAPPEND(p) \
231 (p->fts_path[p->fts_pathlen - 1] == '/' \
232 ? p->fts_pathlen - 1 : p->fts_pathlen)
233
234 FTSENT *
235 fts_read(FTS *sp)
236 {
237 FTSENT *p, *tmp;
238 int instr;
239 char *t;
240
241 /* If finished or unrecoverable error, return NULL. */
242 if (sp->fts_cur == NULL || ISSET(FTS_STOP))
243 return (NULL);
244
245 /* Set current node pointer. */
246 p = sp->fts_cur;
247
248 /* Save and zero out user instructions. */
249 instr = p->fts_instr;
250 p->fts_instr = FTS_NOINSTR;
251
252 /* Directory in pre-order. */
253 if (p->fts_info == FTS_D) {
254 /* If skipped or crossed mount point, do post-order visit. */
255 if (instr == FTS_SKIP ||
256 (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
257 if (sp->fts_child) {
258 fts_lfree(sp->fts_child);
259 sp->fts_child = NULL;
260 }
261 p->fts_info = FTS_DP;
262 return (p);
263 }
264
265 /*
266 * If haven't read do so. If the read fails, fts_build sets
267 * FTS_STOP or the fts_info field of the node.
268 */
269 if (sp->fts_child) {
270 /* nothing */
271 } else if ((sp->fts_child = fts_build(sp)) == NULL) {
272 if (ISSET(FTS_STOP))
273 return (NULL);
274 return (p);
275 }
276 p = sp->fts_child;
277 sp->fts_child = NULL;
278 goto name;
279 }
280
281 /* Move to the next node on this level. */
282 next: tmp = p;
283 if ((p = p->fts_link)) {
284 free(tmp);
285
286 /*
287 * If reached the top, return to the original directory (or
288 * the root of the tree), and load the paths for the next root.
289 */
290 if (p->fts_level == FTS_ROOTLEVEL) {
291 fts_load(sp, p);
292 return (sp->fts_cur = p);
293 }
294
295 /*
296 * User may have called fts_set on the node. If skipped,
297 * ignore. If followed, get a file descriptor so we can
298 * get back if necessary.
299 */
300 if (p->fts_instr == FTS_SKIP)
301 goto next;
302
303 name: t = sp->fts_path + NAPPEND(p->fts_parent);
304 *t++ = '/';
305 memmove(t, p->fts_name, p->fts_namelen + 1);
306 return (sp->fts_cur = p);
307 }
308
309 /* Move up to the parent node. */
310 p = tmp->fts_parent;
311 free(tmp);
312
313 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
314 /*
315 * Done; free everything up and set errno to 0 so the user
316 * can distinguish between error and EOF.
317 */
318 free(p);
319 errno = 0;
320 return (sp->fts_cur = NULL);
321 }
322
323 /* NUL terminate the pathname. */
324 sp->fts_path[p->fts_pathlen] = '\0';
325
326 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
327 return (sp->fts_cur = p);
328 }
329
330 /*
331 * Fts_set takes the stream as an argument although it's not used in this
332 * implementation; it would be necessary if anyone wanted to add global
333 * semantics to fts using fts_set. An error return is allowed for similar
334 * reasons.
335 */
336 int
337 fts_set(FTS *sp, FTSENT *p, int instr)
338 {
339 if (instr && instr != FTS_NOINSTR && instr != FTS_SKIP) {
340 errno = EINVAL;
341 return (1);
342 }
343 p->fts_instr = instr;
344 return (0);
345 }
346
347 /*
348 * This is the tricky part -- do not casually change *anything* in here. The
349 * idea is to build the linked list of entries that are used by fts_children
350 * and fts_read. There are lots of special cases.
351 *
352 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
353 * set and it's a physical walk (so that symbolic links can't be directories),
354 * we can do things quickly. First, if it's a 4.4BSD file system, the type
355 * of the file is in the directory entry. Otherwise, we assume that the number
356 * of subdirectories in a node is equal to the number of links to the parent.
357 * The former skips all stat calls. The latter skips stat calls in any leaf
358 * directories and for any files after the subdirectories in the directory have
359 * been found, cutting the stat calls by about 2/3.
360 */
361 static FTSENT *
362 fts_build(FTS *sp)
363 {
364 struct dirent *dp;
365 FTSENT *p, *head;
366 FTSENT *cur, *tail;
367 DIR *dirp;
368 void *oldaddr;
369 size_t dlen, len, maxlen;
370 int nitems, level, doadjust;
371 int saved_errno;
372 char *cp;
373
374 /* Set current node pointer. */
375 cur = sp->fts_cur;
376
377 /*
378 * Open the directory for reading. If this fails, we're done.
379 * If being called from fts_read, set the fts_info field.
380 */
381 if ((dirp = opendir(cur->fts_accpath)) == NULL) {
382 cur->fts_info = FTS_DNR;
383 cur->fts_errno = errno;
384 return (NULL);
385 }
386
387 /*
388 * Figure out the max file name length that can be stored in the
389 * current path -- the inner loop allocates more path as necessary.
390 * We really wouldn't have to do the maxlen calculations here, we
391 * could do them in fts_read before returning the path, but it's a
392 * lot easier here since the length is part of the dirent structure.
393 *
394 * If not changing directories set a pointer so that can just append
395 * each new name into the path.
396 */
397 len = NAPPEND(cur);
398 cp = sp->fts_path + len;
399 *cp++ = '/';
400 len++;
401 maxlen = sp->fts_pathlen - len;
402
403 /*
404 * fts_level is signed so we must prevent it from wrapping
405 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
406 */
407 level = cur->fts_level;
408 if (level < FTS_MAXLEVEL)
409 level++;
410
411 /* Read the directory, attaching each entry to the `link' pointer. */
412 doadjust = 0;
413 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
414 if (ISDOT(dp->d_name))
415 continue;
416
417 #if HAVE_DIRENT_NAMLEN
418 dlen = dp->d_namlen;
419 #else
420 dlen = strlen(dp->d_name);
421 #endif
422
423 if (!(p = fts_alloc(sp, dp->d_name, dlen)))
424 goto mem1;
425 if (dlen >= maxlen) { /* include space for NUL */
426 oldaddr = sp->fts_path;
427 if (fts_palloc(sp, dlen + len + 1)) {
428 /*
429 * No more memory for path or structures. Save
430 * errno, free up the current structure and the
431 * structures already allocated.
432 */
433 mem1: saved_errno = errno;
434 free(p);
435 fts_lfree(head);
436 (void)closedir(dirp);
437 cur->fts_info = FTS_ERR;
438 SET(FTS_STOP);
439 errno = saved_errno;
440 return (NULL);
441 }
442 /* Did realloc() change the pointer? */
443 if (oldaddr != sp->fts_path) {
444 doadjust = 1;
445 cp = sp->fts_path + len;
446 }
447 maxlen = sp->fts_pathlen - len;
448 }
449
450 p->fts_level = level;
451 p->fts_parent = sp->fts_cur;
452 p->fts_pathlen = len + dlen;
453 if (p->fts_pathlen < len) {
454 /*
455 * If we wrap, free up the current structure and
456 * the structures already allocated, then error
457 * out with ENAMETOOLONG.
458 */
459 free(p);
460 fts_lfree(head);
461 (void)closedir(dirp);
462 cur->fts_info = FTS_ERR;
463 SET(FTS_STOP);
464 errno = ENAMETOOLONG;
465 return (NULL);
466 }
467
468 /* Build a file name for fts_stat to stat. */
469 p->fts_accpath = p->fts_path;
470 memmove(cp, p->fts_name, p->fts_namelen + 1);
471 /* Stat it. */
472 p->fts_info = fts_stat(sp, p);
473
474 /* We walk in directory order so "ls -f" doesn't get upset. */
475 p->fts_link = NULL;
476 if (head == NULL)
477 head = tail = p;
478 else {
479 tail->fts_link = p;
480 tail = p;
481 }
482 ++nitems;
483 }
484 if (dirp)
485 (void)closedir(dirp);
486
487 /*
488 * If realloc() changed the address of the path, adjust the
489 * addresses for the rest of the tree and the dir list.
490 */
491 if (doadjust)
492 fts_padjust(sp, head);
493
494 /*
495 * If not changing directories, reset the path back to original
496 * state.
497 */
498 if (len == sp->fts_pathlen || nitems == 0)
499 --cp;
500 *cp = '\0';
501
502 /* If didn't find anything, return NULL. */
503 if (!nitems) {
504 cur->fts_info = FTS_DP;
505 return (NULL);
506 }
507
508 /* Sort the entries. */
509 if (sp->fts_compar && nitems > 1)
510 head = fts_sort(sp, head, nitems);
511 return (head);
512 }
513
514 static unsigned short
515 fts_stat(FTS *sp, FTSENT *p)
516 {
517 FTSENT *t;
518 dev_t dev;
519 ino_t ino;
520 struct stat *sbp;
521
522 /* If user needs stat info, stat buffer already allocated. */
523 sbp = p->fts_statp;
524
525 if (lstat(p->fts_accpath, sbp)) {
526 p->fts_errno = errno;
527 memset(sbp, 0, sizeof(struct stat));
528 return (FTS_NS);
529 }
530
531 if (S_ISDIR(sbp->st_mode)) {
532 /*
533 * Set the device/inode. Used to find cycles and check for
534 * crossing mount points. Also remember the link count, used
535 * in fts_build to limit the number of stat calls. It is
536 * understood that these fields are only referenced if fts_info
537 * is set to FTS_D.
538 */
539 dev = p->fts_dev = sbp->st_dev;
540 ino = p->fts_ino = sbp->st_ino;
541 p->fts_nlink = sbp->st_nlink;
542
543 if (ISDOT(p->fts_name))
544 return (FTS_DOT);
545
546 /*
547 * Cycle detection is done by brute force when the directory
548 * is first encountered. If the tree gets deep enough or the
549 * number of symbolic links to directories is high enough,
550 * something faster might be worthwhile.
551 */
552 for (t = p->fts_parent;
553 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
554 if (ino == t->fts_ino && dev == t->fts_dev) {
555 p->fts_cycle = t;
556 return (FTS_DC);
557 }
558 return (FTS_D);
559 }
560 if (S_ISLNK(sbp->st_mode))
561 return (FTS_SL);
562 if (S_ISREG(sbp->st_mode))
563 return (FTS_F);
564 return (FTS_DEFAULT);
565 }
566
567 static FTSENT *
568 fts_sort(FTS *sp, FTSENT *head, int nitems)
569 {
570 FTSENT **ap, *p;
571
572 /*
573 * Construct an array of pointers to the structures and call qsort(3).
574 * Reassemble the array in the order returned by qsort. If unable to
575 * sort for memory reasons, return the directory entries in their
576 * current order. Allocate enough space for the current needs plus
577 * 40 so don't realloc one entry at a time.
578 */
579 if (nitems > sp->fts_nitems) {
580 struct _ftsent **a;
581
582 sp->fts_nitems = nitems + 40;
583 if ((a = reallocarray(sp->fts_array,
584 sp->fts_nitems, sizeof(FTSENT *))) == NULL) {
585 free(sp->fts_array);
586 sp->fts_array = NULL;
587 sp->fts_nitems = 0;
588 return (head);
589 }
590 sp->fts_array = a;
591 }
592 for (ap = sp->fts_array, p = head; p; p = p->fts_link)
593 *ap++ = p;
594 qsort(sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
595 for (head = *(ap = sp->fts_array); --nitems; ++ap)
596 ap[0]->fts_link = ap[1];
597 ap[0]->fts_link = NULL;
598 return (head);
599 }
600
601 static FTSENT *
602 fts_alloc(FTS *sp, const char *name, size_t namelen)
603 {
604 FTSENT *p;
605 size_t len;
606
607 len = sizeof(FTSENT) + namelen;
608 if ((p = calloc(1, len)) == NULL)
609 return (NULL);
610
611 p->fts_path = sp->fts_path;
612 p->fts_namelen = namelen;
613 p->fts_instr = FTS_NOINSTR;
614 p->fts_statp = malloc(sizeof(struct stat));
615 if (p->fts_statp == NULL) {
616 free(p);
617 return (NULL);
618 }
619 memcpy(p->fts_name, name, namelen);
620
621 return (p);
622 }
623
624 static void
625 fts_lfree(FTSENT *head)
626 {
627 FTSENT *p;
628
629 /* Free a linked list of structures. */
630 while ((p = head)) {
631 head = head->fts_link;
632 free(p);
633 }
634 }
635
636 /*
637 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
638 * Most systems will allow creation of paths much longer than PATH_MAX, even
639 * though the kernel won't resolve them. Add the size (not just what's needed)
640 * plus 256 bytes so don't realloc the path 2 bytes at a time.
641 */
642 static int
643 fts_palloc(FTS *sp, size_t more)
644 {
645 char *p;
646
647 /*
648 * Check for possible wraparound.
649 */
650 more += 256;
651 if (sp->fts_pathlen + more < sp->fts_pathlen) {
652 free(sp->fts_path);
653 sp->fts_path = NULL;
654 errno = ENAMETOOLONG;
655 return (1);
656 }
657 sp->fts_pathlen += more;
658 p = realloc(sp->fts_path, sp->fts_pathlen);
659 if (p == NULL) {
660 free(sp->fts_path);
661 sp->fts_path = NULL;
662 return (1);
663 }
664 sp->fts_path = p;
665 return (0);
666 }
667
668 /*
669 * When the path is realloc'd, have to fix all of the pointers in structures
670 * already returned.
671 */
672 static void
673 fts_padjust(FTS *sp, FTSENT *head)
674 {
675 FTSENT *p;
676 char *addr = sp->fts_path;
677
678 #define ADJUST(p) { \
679 if ((p)->fts_accpath != (p)->fts_name) { \
680 (p)->fts_accpath = \
681 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
682 } \
683 (p)->fts_path = addr; \
684 }
685 /* Adjust the current set of children. */
686 for (p = sp->fts_child; p; p = p->fts_link)
687 ADJUST(p);
688
689 /* Adjust the rest of the tree, including the current level. */
690 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
691 ADJUST(p);
692 p = p->fts_link ? p->fts_link : p->fts_parent;
693 }
694 }
695
696 static size_t
697 fts_maxarglen(char * const *argv)
698 {
699 size_t len, max;
700
701 for (max = 0; *argv; ++argv)
702 if ((len = strlen(*argv)) > max)
703 max = len;
704 return (max + 1);
705 }
706
707 #endif