xref: /freebsd/lib/libc/gen/opendir.c (revision 1670a1c2a47d10ecccd001970b859caf93cd3b6e)
1 /*-
2  * Copyright (c) 1983, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if defined(LIBC_SCCS) && !defined(lint)
31 static char sccsid[] = "@(#)opendir.c	8.8 (Berkeley) 5/1/95";
32 #endif /* LIBC_SCCS and not lint */
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "namespace.h"
37 #include <sys/param.h>
38 #include <sys/mount.h>
39 #include <sys/stat.h>
40 
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include "un-namespace.h"
48 
49 #include "telldir.h"
50 
51 static DIR * __opendir_common(int, const char *, int);
52 
53 /*
54  * Open a directory.
55  */
56 DIR *
57 opendir(const char *name)
58 {
59 
60 	return (__opendir2(name, DTF_HIDEW|DTF_NODUP));
61 }
62 
63 /*
64  * Open a directory with existing file descriptor.
65  */
66 DIR *
67 fdopendir(int fd)
68 {
69 
70 	return (__opendir_common(fd, NULL, DTF_HIDEW|DTF_NODUP));
71 }
72 
73 DIR *
74 __opendir2(const char *name, int flags)
75 {
76 	int fd;
77 	struct stat statb;
78 
79 	/*
80 	 * stat() before _open() because opening of special files may be
81 	 * harmful.
82 	 */
83 	if (stat(name, &statb) != 0)
84 		return (NULL);
85 	if (!S_ISDIR(statb.st_mode)) {
86 		errno = ENOTDIR;
87 		return (NULL);
88 	}
89 	if ((fd = _open(name, O_RDONLY | O_NONBLOCK | O_DIRECTORY)) == -1)
90 		return (NULL);
91 
92 	return __opendir_common(fd, name, flags);
93 }
94 
95 static int
96 opendir_compar(const void *p1, const void *p2)
97 {
98 
99 	return (strcmp((*(const struct dirent **)p1)->d_name,
100 	    (*(const struct dirent **)p2)->d_name));
101 }
102 
103 /*
104  * Common routine for opendir(3), __opendir2(3) and fdopendir(3).
105  */
106 static DIR *
107 __opendir_common(int fd, const char *name, int flags)
108 {
109 	DIR *dirp;
110 	int incr;
111 	int saved_errno;
112 	int unionstack;
113 	struct stat statb;
114 
115 	dirp = NULL;
116 	/* _fstat() the open handler because the file may have changed.  */
117 	if (_fstat(fd, &statb) != 0)
118 		goto fail;
119 	if (!S_ISDIR(statb.st_mode)) {
120 		errno = ENOTDIR;
121 		goto fail;
122 	}
123 	if (_fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 ||
124 	    (dirp = malloc(sizeof(DIR) + sizeof(struct _telldir))) == NULL)
125 		goto fail;
126 
127 	dirp->dd_td = (struct _telldir *)((char *)dirp + sizeof(DIR));
128 	LIST_INIT(&dirp->dd_td->td_locq);
129 	dirp->dd_td->td_loccnt = 0;
130 
131 	/*
132 	 * Use the system page size if that is a multiple of DIRBLKSIZ.
133 	 * Hopefully this can be a big win someday by allowing page
134 	 * trades to user space to be done by _getdirentries().
135 	 */
136 	incr = getpagesize();
137 	if ((incr % DIRBLKSIZ) != 0)
138 		incr = DIRBLKSIZ;
139 
140 	/*
141 	 * Determine whether this directory is the top of a union stack.
142 	 */
143 	if (flags & DTF_NODUP) {
144 		struct statfs sfb;
145 
146 		if (_fstatfs(fd, &sfb) < 0)
147 			goto fail;
148 		unionstack = !strcmp(sfb.f_fstypename, "unionfs")
149 		    || (sfb.f_flags & MNT_UNION);
150 	} else {
151 		unionstack = 0;
152 	}
153 
154 	if (unionstack) {
155 		int len = 0;
156 		int space = 0;
157 		char *buf = 0;
158 		char *ddptr = 0;
159 		char *ddeptr;
160 		int n;
161 		struct dirent **dpv;
162 
163 		/*
164 		 * The strategy here is to read all the directory
165 		 * entries into a buffer, sort the buffer, and
166 		 * remove duplicate entries by setting the inode
167 		 * number to zero.
168 		 */
169 
170 		do {
171 			/*
172 			 * Always make at least DIRBLKSIZ bytes
173 			 * available to _getdirentries
174 			 */
175 			if (space < DIRBLKSIZ) {
176 				space += incr;
177 				len += incr;
178 				buf = reallocf(buf, len);
179 				if (buf == NULL)
180 					goto fail;
181 				ddptr = buf + (len - space);
182 			}
183 
184 			n = _getdirentries(fd, ddptr, space, &dirp->dd_seek);
185 			if (n > 0) {
186 				ddptr += n;
187 				space -= n;
188 			}
189 		} while (n > 0);
190 
191 		ddeptr = ddptr;
192 		flags |= __DTF_READALL;
193 
194 		/*
195 		 * Re-open the directory.
196 		 * This has the effect of rewinding back to the
197 		 * top of the union stack and is needed by
198 		 * programs which plan to fchdir to a descriptor
199 		 * which has also been read -- see fts.c.
200 		 */
201 		if (flags & DTF_REWIND) {
202 			(void)_close(fd);
203 			if ((fd = _open(name, O_RDONLY | O_DIRECTORY)) == -1) {
204 				saved_errno = errno;
205 				free(buf);
206 				free(dirp);
207 				errno = saved_errno;
208 				return (NULL);
209 			}
210 		}
211 
212 		/*
213 		 * There is now a buffer full of (possibly) duplicate
214 		 * names.
215 		 */
216 		dirp->dd_buf = buf;
217 
218 		/*
219 		 * Go round this loop twice...
220 		 *
221 		 * Scan through the buffer, counting entries.
222 		 * On the second pass, save pointers to each one.
223 		 * Then sort the pointers and remove duplicate names.
224 		 */
225 		for (dpv = 0;;) {
226 			n = 0;
227 			ddptr = buf;
228 			while (ddptr < ddeptr) {
229 				struct dirent *dp;
230 
231 				dp = (struct dirent *) ddptr;
232 				if ((long)dp & 03L)
233 					break;
234 				if ((dp->d_reclen <= 0) ||
235 				    (dp->d_reclen > (ddeptr + 1 - ddptr)))
236 					break;
237 				ddptr += dp->d_reclen;
238 				if (dp->d_fileno) {
239 					if (dpv)
240 						dpv[n] = dp;
241 					n++;
242 				}
243 			}
244 
245 			if (dpv) {
246 				struct dirent *xp;
247 
248 				/*
249 				 * This sort must be stable.
250 				 */
251 				mergesort(dpv, n, sizeof(*dpv),
252 				    opendir_compar);
253 
254 				dpv[n] = NULL;
255 				xp = NULL;
256 
257 				/*
258 				 * Scan through the buffer in sort order,
259 				 * zapping the inode number of any
260 				 * duplicate names.
261 				 */
262 				for (n = 0; dpv[n]; n++) {
263 					struct dirent *dp = dpv[n];
264 
265 					if ((xp == NULL) ||
266 					    strcmp(dp->d_name, xp->d_name)) {
267 						xp = dp;
268 					} else {
269 						dp->d_fileno = 0;
270 					}
271 					if (dp->d_type == DT_WHT &&
272 					    (flags & DTF_HIDEW))
273 						dp->d_fileno = 0;
274 				}
275 
276 				free(dpv);
277 				break;
278 			} else {
279 				dpv = malloc((n+1) * sizeof(struct dirent *));
280 				if (dpv == NULL)
281 					break;
282 			}
283 		}
284 
285 		dirp->dd_len = len;
286 		dirp->dd_size = ddptr - dirp->dd_buf;
287 	} else {
288 		dirp->dd_len = incr;
289 		dirp->dd_size = 0;
290 		dirp->dd_buf = malloc(dirp->dd_len);
291 		if (dirp->dd_buf == NULL)
292 			goto fail;
293 		dirp->dd_seek = 0;
294 		flags &= ~DTF_REWIND;
295 	}
296 
297 	dirp->dd_loc = 0;
298 	dirp->dd_fd = fd;
299 	dirp->dd_flags = flags;
300 	dirp->dd_lock = NULL;
301 
302 	/*
303 	 * Set up seek point for rewinddir.
304 	 */
305 	dirp->dd_rewind = telldir(dirp);
306 
307 	return (dirp);
308 
309 fail:
310 	saved_errno = errno;
311 	free(dirp);
312 	(void)_close(fd);
313 	errno = saved_errno;
314 	return (NULL);
315 }
316