xref: /netbsd-src/lib/libc/gen/opendir.c (revision 53cf9ce3bea11ecdca40251e09047d445b4a85d7)
1 /*	$NetBSD: opendir.c,v 1.36 2010/09/16 02:38:50 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 #if 0
35 static char sccsid[] = "@(#)opendir.c	8.7 (Berkeley) 12/10/94";
36 #else
37 __RCSID("$NetBSD: opendir.c,v 1.36 2010/09/16 02:38:50 yamt Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
40 
41 #include "namespace.h"
42 #include "reentrant.h"
43 #include "extern.h"
44 
45 #include <sys/param.h>
46 #include <sys/mount.h>
47 #include <sys/stat.h>
48 
49 #include <assert.h>
50 #include <dirent.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "dirent_private.h"
58 
59 #define	MAXITERATIONS	100
60 
61 static DIR	*__opendir_common(int, const char *, int);
62 
63 __weak_alias(fdopendir,_fdopendir)
64 
65 /*
66  * Open a directory.
67  */
68 DIR *
69 opendir(const char *name)
70 {
71 
72 	_DIAGASSERT(name != NULL);
73 
74 	return (__opendir2(name, DTF_HIDEW|DTF_NODUP));
75 }
76 
77 DIR *
78 __opendir2(const char *name, int flags)
79 {
80 	int fd;
81 
82 	if ((fd = open(name, O_RDONLY | O_NONBLOCK)) == -1)
83 		return NULL;
84 	return __opendir_common(fd, name, flags);
85 }
86 
87 #ifndef __LIBC12_SOURCE__
88 DIR *
89 _fdopendir(int fd)
90 {
91 
92 	return __opendir_common(fd, NULL, DTF_HIDEW|DTF_NODUP);
93 }
94 #endif
95 
96 static DIR *
97 __opendir_common(int fd, const char *name, int flags)
98 {
99 	DIR *dirp = NULL;
100 	int serrno;
101 	struct stat sb;
102 	int pagesz;
103 	int incr;
104 	int unionstack, nfsdir;
105 	struct statvfs sfb;
106 
107 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
108 		goto error;
109 	if (fstat(fd, &sb) || !S_ISDIR(sb.st_mode)) {
110 		errno = ENOTDIR;
111 		goto error;
112 	}
113 	if ((dirp = (DIR *)malloc(sizeof(DIR))) == NULL)
114 		goto error;
115 	dirp->dd_buf = NULL;
116 
117 	/*
118 	 * If the machine's page size is an exact multiple of DIRBLKSIZ,
119 	 * use a buffer that is cluster boundary aligned.
120 	 * Hopefully this can be a big win someday by allowing page trades
121 	 * to user space to be done by getdents()
122 	 */
123 	if (((pagesz = getpagesize()) % DIRBLKSIZ) == 0)
124 		incr = pagesz;
125 	else
126 		incr = DIRBLKSIZ;
127 
128 	/*
129 	 * Determine whether this directory is the top of a union stack.
130 	 */
131 
132 	if (fstatvfs1(fd, &sfb, ST_NOWAIT) < 0)
133 		goto error;
134 
135 	if (flags & DTF_NODUP)
136 		unionstack = !(strncmp(sfb.f_fstypename, MOUNT_UNION,
137 		    sizeof(sfb.f_fstypename))) || (sfb.f_flag & MNT_UNION);
138 	else
139 		unionstack = 0;
140 
141 	nfsdir = !(strncmp(sfb.f_fstypename, MOUNT_NFS,
142 	    sizeof(sfb.f_fstypename)));
143 
144 	if (unionstack || nfsdir) {
145 		size_t len;
146 		size_t space;
147 		char *buf, *nbuf;
148 		char *ddptr;
149 		char *ddeptr;
150 		int n;
151 		struct dirent **dpv;
152 		int i;
153 
154 		/*
155 		 * The strategy here for directories on top of a union stack
156 		 * is to read all the directory entries into a buffer, sort
157 		 * the buffer, and remove duplicate entries by setting the
158 		 * inode number to zero.
159 		 *
160 		 * For directories on an NFS mounted filesystem, we try
161 	 	 * to get a consistent snapshot by trying until we have
162 		 * successfully read all of the directory without errors
163 		 * (i.e. 'bad cookie' errors from the server because
164 		 * the directory was modified). These errors should not
165 		 * happen often, but need to be dealt with.
166 		 */
167 		i = 0;
168 retry:
169 		len = 0;
170 		space = 0;
171 		buf = 0;
172 		ddptr = 0;
173 
174 		do {
175 			/*
176 			 * Always make at least DIRBLKSIZ bytes
177 			 * available to getdents
178 			 */
179 			if (space < DIRBLKSIZ) {
180 				space += incr;
181 				len += incr;
182 				nbuf = realloc(buf, len);
183 				if (nbuf == NULL) {
184 					dirp->dd_buf = buf;
185 					goto error;
186 				}
187 				buf = nbuf;
188 				ddptr = buf + (len - space);
189 			}
190 
191 			dirp->dd_seek = lseek(fd, (off_t)0, SEEK_CUR);
192 			n = getdents(fd, ddptr, space);
193 			/*
194 			 * For NFS: EINVAL means a bad cookie error
195 			 * from the server. Keep trying to get a
196 			 * consistent view, in this case this means
197 			 * starting all over again.
198 			 */
199 			if (n == -1 && errno == EINVAL && nfsdir) {
200 				free(buf);
201 				lseek(fd, (off_t)0, SEEK_SET);
202 				if (++i > MAXITERATIONS)
203 					goto error;
204 				goto retry;
205 			}
206 			if (n > 0) {
207 				ddptr += n;
208 				space -= n;
209 			}
210 		} while (n > 0);
211 
212 		ddeptr = ddptr;
213 		flags |= __DTF_READALL;
214 
215 		/*
216 		 * Re-open the directory.
217 		 * This has the effect of rewinding back to the
218 		 * top of the union stack and is needed by
219 		 * programs which plan to fchdir to a descriptor
220 		 * which has also been read -- see fts.c.
221 		 */
222 		if (flags & DTF_REWIND) {
223 			(void) close(fd);
224 			if ((fd = open(name, O_RDONLY)) == -1 ||
225 			    fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
226 				dirp->dd_buf = buf;
227 				goto error;
228 			}
229 		}
230 
231 		/*
232 		 * There is now a buffer full of (possibly) duplicate
233 		 * names.
234 		 */
235 		dirp->dd_buf = buf;
236 
237 		/*
238 		 * Go round this loop twice...
239 		 *
240 		 * Scan through the buffer, counting entries.
241 		 * On the second pass, save pointers to each one.
242 		 * Then sort the pointers and remove duplicate names.
243 		 */
244 		if (!nfsdir) {
245 			for (dpv = 0;;) {
246 				for (n = 0, ddptr = buf; ddptr < ddeptr;) {
247 					struct dirent *dp;
248 
249 					dp = (struct dirent *)(void *)ddptr;
250 					if ((long)dp & _DIRENT_ALIGN(dp))
251 						break;
252 					/*
253 					 * d_reclen is unsigned,
254 					 * so no need to compare <= 0
255 					 */
256 					if (dp->d_reclen > (ddeptr + 1 - ddptr))
257 						break;
258 					ddptr += dp->d_reclen;
259 					if (dp->d_fileno) {
260 						if (dpv)
261 							dpv[n] = dp;
262 						n++;
263 					}
264 				}
265 
266 				if (dpv) {
267 					struct dirent *xp;
268 
269 					/*
270 					 * This sort must be stable.
271 					 */
272 					mergesort(dpv, (size_t)n, sizeof(*dpv),
273 					    alphasort);
274 
275 					dpv[n] = NULL;
276 					xp = NULL;
277 
278 					/*
279 					 * Scan through the buffer in sort
280 					 * order, zapping the inode number
281 					 * of any duplicate names.
282 					 */
283 					for (n = 0; dpv[n]; n++) {
284 						struct dirent *dp = dpv[n];
285 
286 						if ((xp == NULL) ||
287 						    strcmp(dp->d_name,
288 						      xp->d_name))
289 							xp = dp;
290 						else
291 							dp->d_fileno = 0;
292 						if (dp->d_type == DT_WHT &&
293 						    (flags & DTF_HIDEW))
294 							dp->d_fileno = 0;
295 					}
296 
297 					free(dpv);
298 					break;
299 				} else {
300 					dpv = malloc((n + 1) *
301 					    sizeof(struct dirent *));
302 					if (dpv == NULL)
303 						break;
304 				}
305 			}
306 		}
307 
308 		dirp->dd_len = len;
309 		dirp->dd_size = ddptr - dirp->dd_buf;
310 	} else {
311 		dirp->dd_len = incr;
312 		dirp->dd_buf = malloc((size_t)dirp->dd_len);
313 		if (dirp->dd_buf == NULL)
314 			goto error;
315 		dirp->dd_seek = 0;
316 		flags &= ~DTF_REWIND;
317 	}
318 
319 	dirp->dd_loc = 0;
320 	dirp->dd_fd = fd;
321 	dirp->dd_flags = flags;
322 
323 	/*
324 	 * Set up seek point for rewinddir.
325 	 */
326 #ifdef _REENTRANT
327 	if (__isthreaded) {
328 		if ((dirp->dd_lock = malloc(sizeof(mutex_t))) == NULL)
329 			goto error;
330 		mutex_init((mutex_t *)dirp->dd_lock, NULL);
331 	}
332 #endif
333 	dirp->dd_internal = NULL;
334 	(void)_telldir_unlocked(dirp);
335 	return (dirp);
336 error:
337 	serrno = errno;
338 	if (dirp && dirp->dd_buf)
339 		free(dirp->dd_buf);
340 	if (dirp)
341 		free(dirp);
342 	if (fd != -1)
343 		(void)close(fd);
344 	errno = serrno;
345 	return NULL;
346 }
347