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