xref: /minix3/lib/libc/gen/initdir.c (revision 6b8821515da8851628dd9dcd785dacf07085019b)
1 /*	$NetBSD: initdir.c,v 1.1 2010/09/26 02:26:59 yamt Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 __RCSID("$NetBSD: initdir.c,v 1.1 2010/09/26 02:26:59 yamt Exp $");
35 #endif /* LIBC_SCCS and not lint */
36 
37 #include "namespace.h"
38 
39 #ifdef __minix
40 /* NetBSD BUG on !_REENTRANT */
41 #include <sys/cdefs.h>
42 #include <sys/featuretest.h>
43 #include <sys/types.h>
44 #endif
45 
46 #include "reentrant.h"
47 #include "extern.h"
48 
49 #include <sys/param.h>
50 
51 #include <assert.h>
52 #include <dirent.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 
59 #include "dirent_private.h"
60 
61 #define	MAXITERATIONS	100
62 
63 int
64 _initdir(DIR *dirp, int fd, const char *name)
65 {
66 	int flags = dirp->dd_flags;
67 	int pagesz;
68 	int incr;
69 
70 	/*
71 	 * If the machine's page size is an exact multiple of DIRBLKSIZ,
72 	 * use a buffer that is cluster boundary aligned.
73 	 * Hopefully this can be a big win someday by allowing page trades
74 	 * to user space to be done by getdents()
75 	 */
76 	if (((pagesz = getpagesize()) % DIRBLKSIZ) == 0)
77 		incr = pagesz;
78 	else
79 		incr = DIRBLKSIZ;
80 
81 	if ((flags & DTF_REWIND) && name == NULL) {
82 		return EINVAL;
83 	}
84 	if ((flags & __DTF_READALL) != 0) {
85 		size_t len;
86 		size_t space;
87 		char *buf, *nbuf;
88 		char *ddptr;
89 		char *ddeptr;
90 		int n;
91 		struct dirent **dpv;
92 		int i;
93 
94 		/*
95 		 * The strategy here for directories on top of a union stack
96 		 * is to read all the directory entries into a buffer, sort
97 		 * the buffer, and remove duplicate entries by setting the
98 		 * inode number to zero.
99 		 *
100 		 * For directories on an NFS mounted filesystem, we try
101 	 	 * to get a consistent snapshot by trying until we have
102 		 * successfully read all of the directory without errors
103 		 * (i.e. 'bad cookie' errors from the server because
104 		 * the directory was modified). These errors should not
105 		 * happen often, but need to be dealt with.
106 		 */
107 		i = 0;
108 retry:
109 		len = 0;
110 		space = 0;
111 		buf = 0;
112 		ddptr = 0;
113 
114 		do {
115 			/*
116 			 * Always make at least DIRBLKSIZ bytes
117 			 * available to getdents
118 			 */
119 			if (space < DIRBLKSIZ) {
120 				space += incr;
121 				len += incr;
122 				nbuf = realloc(buf, len);
123 				if (nbuf == NULL) {
124 					dirp->dd_buf = buf;
125 					return errno;
126 				}
127 				buf = nbuf;
128 				ddptr = buf + (len - space);
129 			}
130 
131 			dirp->dd_seek = lseek(fd, (off_t)0, SEEK_CUR);
132 			n = getdents(fd, ddptr, space);
133 			/*
134 			 * For NFS: EINVAL means a bad cookie error
135 			 * from the server. Keep trying to get a
136 			 * consistent view, in this case this means
137 			 * starting all over again.
138 			 */
139 			if (n == -1 && errno == EINVAL &&
140 			    (flags & __DTF_RETRY_ON_BADCOOKIE) != 0) {
141 				free(buf);
142 				lseek(fd, (off_t)0, SEEK_SET);
143 				if (++i > MAXITERATIONS)
144 					return EINVAL;
145 				goto retry;
146 			}
147 			if (n > 0) {
148 				ddptr += n;
149 				space -= n;
150 			}
151 		} while (n > 0);
152 
153 		ddeptr = ddptr;
154 
155 		/*
156 		 * Re-open the directory.
157 		 * This has the effect of rewinding back to the
158 		 * top of the union stack and is needed by
159 		 * programs which plan to fchdir to a descriptor
160 		 * which has also been read -- see fts.c.
161 		 */
162 		if (flags & DTF_REWIND) {
163 			(void) close(fd);
164 			if ((fd = open(name, O_RDONLY)) == -1 ||
165 			    fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
166 				dirp->dd_buf = buf;
167 				return errno;
168 			}
169 		}
170 
171 		/*
172 		 * There is now a buffer full of (possibly) duplicate
173 		 * names.
174 		 */
175 		dirp->dd_buf = buf;
176 
177 		/*
178 		 * Go round this loop twice...
179 		 *
180 		 * Scan through the buffer, counting entries.
181 		 * On the second pass, save pointers to each one.
182 		 * Then sort the pointers and remove duplicate names.
183 		 */
184 		if ((flags & DTF_NODUP) != 0) {
185 			for (dpv = 0;;) {
186 				for (n = 0, ddptr = buf; ddptr < ddeptr;) {
187 					struct dirent *dp;
188 
189 					dp = (struct dirent *)(void *)ddptr;
190 					if ((long)dp & _DIRENT_ALIGN(dp))
191 						break;
192 					/*
193 					 * d_reclen is unsigned,
194 					 * so no need to compare <= 0
195 					 */
196 					if (dp->d_reclen > (ddeptr + 1 - ddptr))
197 						break;
198 					ddptr += dp->d_reclen;
199 					if (dp->d_fileno) {
200 						if (dpv)
201 							dpv[n] = dp;
202 						n++;
203 					}
204 				}
205 
206 				if (dpv) {
207 					struct dirent *xp;
208 
209 					/*
210 					 * This sort must be stable.
211 					 */
212 					mergesort(dpv, (size_t)n, sizeof(*dpv),
213 					    alphasort);
214 
215 					dpv[n] = NULL;
216 					xp = NULL;
217 
218 					/*
219 					 * Scan through the buffer in sort
220 					 * order, zapping the inode number
221 					 * of any duplicate names.
222 					 */
223 					for (n = 0; dpv[n]; n++) {
224 						struct dirent *dp = dpv[n];
225 
226 						if ((xp == NULL) ||
227 						    strcmp(dp->d_name,
228 						      xp->d_name))
229 							xp = dp;
230 						else
231 							dp->d_fileno = 0;
232 #ifndef __minix
233 						if (dp->d_type == DT_WHT &&
234 						    (flags & DTF_HIDEW))
235 							dp->d_fileno = 0;
236 #endif
237 					}
238 
239 					free(dpv);
240 					break;
241 				} else {
242 					dpv = malloc((n + 1) *
243 					    sizeof(struct dirent *));
244 					if (dpv == NULL)
245 						break;
246 				}
247 			}
248 		}
249 
250 		dirp->dd_len = len;
251 		dirp->dd_size = ddptr - dirp->dd_buf;
252 	} else {
253 		dirp->dd_len = incr;
254 		dirp->dd_buf = malloc((size_t)dirp->dd_len);
255 		if (dirp->dd_buf == NULL)
256 			return errno;
257 		dirp->dd_seek = 0;
258 		flags &= ~DTF_REWIND;
259 	}
260 	dirp->dd_loc = 0;
261 	dirp->dd_fd = fd;
262 	dirp->dd_flags = flags;
263 	/*
264 	 * Set up seek point for rewinddir.
265 	 */
266 	(void)_telldir_unlocked(dirp);
267 	return 0;
268 }
269 
270 void
271 _finidir(DIR *dirp)
272 {
273 	struct dirpos *poslist;
274 
275 	free(dirp->dd_buf);
276 
277 	/* free seekdir/telldir storage */
278 	for (poslist = dirp->dd_internal; poslist; ) {
279 		struct dirpos *nextpos = poslist->dp_next;
280 		free(poslist);
281 		poslist = nextpos;
282 	}
283 	dirp->dd_internal = NULL;
284 }
285