xref: /original-bsd/lib/libc/gen/telldir.c (revision 21439bbc)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)telldir.c	5.9 (Berkeley) 02/23/91";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/param.h>
13 #include <dirent.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 
17 /*
18  * The option SINGLEUSE may be defined to say that a telldir
19  * cookie may be used only once before it is freed. This option
20  * is used to avoid having memory usage grow without bound.
21  */
22 #define SINGLEUSE
23 
24 /*
25  * One of these structures is malloced to describe the current directory
26  * position each time telldir is called. It records the current magic
27  * cookie returned by getdirentries and the offset within the buffer
28  * associated with that return value.
29  */
30 struct ddloc {
31 	struct	ddloc *loc_next;/* next structure in list */
32 	long	loc_index;	/* key associated with structure */
33 	long	loc_seek;	/* magic cookie returned by getdirentries */
34 	long	loc_loc;	/* offset of entry in buffer */
35 };
36 
37 #define	NDIRHASH	32	/* Num of hash lists, must be a power of 2 */
38 #define	LOCHASH(i)	((i)&(NDIRHASH-1))
39 
40 static long	dd_loccnt;	/* Index of entry for sequential readdir's */
41 static struct	ddloc *dd_hash[NDIRHASH];   /* Hash list heads for ddlocs */
42 
43 /*
44  * return a pointer into a directory
45  */
46 long
47 telldir(dirp)
48 	const DIR *dirp;
49 {
50 	register int index;
51 	register struct ddloc *lp;
52 
53 	if ((lp = (struct ddloc *)malloc(sizeof(struct ddloc))) == NULL)
54 		return (-1);
55 	index = dd_loccnt++;
56 	lp->loc_index = index;
57 	lp->loc_seek = dirp->dd_seek;
58 	lp->loc_loc = dirp->dd_loc;
59 	lp->loc_next = dd_hash[LOCHASH(index)];
60 	dd_hash[LOCHASH(index)] = lp;
61 	return (index);
62 }
63 
64 /*
65  * seek to an entry in a directory.
66  * Only values returned by "telldir" should be passed to seekdir.
67  */
68 void
69 _seekdir(dirp, loc)
70 	register DIR *dirp;
71 	long loc;
72 {
73 	register struct ddloc *lp;
74 	register struct ddloc **prevlp;
75 	struct dirent *dp;
76 	extern long lseek();
77 
78 	prevlp = &dd_hash[LOCHASH(loc)];
79 	lp = *prevlp;
80 	while (lp != NULL) {
81 		if (lp->loc_index == loc)
82 			break;
83 		prevlp = &lp->loc_next;
84 		lp = lp->loc_next;
85 	}
86 	if (lp == NULL)
87 		return;
88 	if (lp->loc_loc == dirp->dd_loc && lp->loc_seek == dirp->dd_seek)
89 		goto found;
90 	(void) lseek(dirp->dd_fd, lp->loc_seek, 0);
91 	dirp->dd_seek = lp->loc_seek;
92 	dirp->dd_loc = 0;
93 	while (dirp->dd_loc < lp->loc_loc) {
94 		dp = readdir(dirp);
95 		if (dp == NULL)
96 			break;
97 	}
98 found:
99 #ifdef SINGLEUSE
100 	*prevlp = lp->loc_next;
101 	free((caddr_t)lp);
102 #endif
103 }
104