xref: /freebsd/lib/libc/gen/opendir.c (revision 9a14aa017b21c292740c00ee098195cd46642730)
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 	DIR *dir;
79 	int saved_errno;
80 
81 	/*
82 	 * stat() before _open() because opening of special files may be
83 	 * harmful.
84 	 */
85 	if (stat(name, &statb) != 0)
86 		return (NULL);
87 	if (!S_ISDIR(statb.st_mode)) {
88 		errno = ENOTDIR;
89 		return (NULL);
90 	}
91 	if ((fd = _open(name, O_RDONLY | O_NONBLOCK | O_DIRECTORY)) == -1)
92 		return (NULL);
93 
94 	dir = __opendir_common(fd, name, flags);
95 	if (dir == NULL) {
96 		saved_errno = errno;
97 		_close(fd);
98 		errno = saved_errno;
99 	}
100 	return (dir);
101 }
102 
103 static int
104 opendir_compar(const void *p1, const void *p2)
105 {
106 
107 	return (strcmp((*(const struct dirent **)p1)->d_name,
108 	    (*(const struct dirent **)p2)->d_name));
109 }
110 
111 /*
112  * Common routine for opendir(3), __opendir2(3) and fdopendir(3).
113  */
114 static DIR *
115 __opendir_common(int fd, const char *name, int flags)
116 {
117 	DIR *dirp;
118 	int incr;
119 	int saved_errno;
120 	int unionstack;
121 	int fd2;
122 	struct stat statb;
123 
124 	dirp = NULL;
125 	/* _fstat() the open handler because the file may have changed.  */
126 	if (_fstat(fd, &statb) != 0)
127 		goto fail;
128 	if (!S_ISDIR(statb.st_mode)) {
129 		errno = ENOTDIR;
130 		goto fail;
131 	}
132 	if (_fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 ||
133 	    (dirp = malloc(sizeof(DIR) + sizeof(struct _telldir))) == NULL)
134 		goto fail;
135 
136 	dirp->dd_td = (struct _telldir *)((char *)dirp + sizeof(DIR));
137 	LIST_INIT(&dirp->dd_td->td_locq);
138 	dirp->dd_td->td_loccnt = 0;
139 
140 	/*
141 	 * Use the system page size if that is a multiple of DIRBLKSIZ.
142 	 * Hopefully this can be a big win someday by allowing page
143 	 * trades to user space to be done by _getdirentries().
144 	 */
145 	incr = getpagesize();
146 	if ((incr % DIRBLKSIZ) != 0)
147 		incr = DIRBLKSIZ;
148 
149 	/*
150 	 * Determine whether this directory is the top of a union stack.
151 	 */
152 	if (flags & DTF_NODUP) {
153 		struct statfs sfb;
154 
155 		if (_fstatfs(fd, &sfb) < 0)
156 			goto fail;
157 		unionstack = !strcmp(sfb.f_fstypename, "unionfs")
158 		    || (sfb.f_flags & MNT_UNION);
159 	} else {
160 		unionstack = 0;
161 	}
162 
163 	if (unionstack) {
164 		int len = 0;
165 		int space = 0;
166 		char *buf = 0;
167 		char *ddptr = 0;
168 		char *ddeptr;
169 		int n;
170 		struct dirent **dpv;
171 
172 		/*
173 		 * The strategy here is to read all the directory
174 		 * entries into a buffer, sort the buffer, and
175 		 * remove duplicate entries by setting the inode
176 		 * number to zero.
177 		 */
178 
179 		do {
180 			/*
181 			 * Always make at least DIRBLKSIZ bytes
182 			 * available to _getdirentries
183 			 */
184 			if (space < DIRBLKSIZ) {
185 				space += incr;
186 				len += incr;
187 				buf = reallocf(buf, len);
188 				if (buf == NULL)
189 					goto fail;
190 				ddptr = buf + (len - space);
191 			}
192 
193 			n = _getdirentries(fd, ddptr, space, &dirp->dd_seek);
194 			if (n > 0) {
195 				ddptr += n;
196 				space -= n;
197 			}
198 		} while (n > 0);
199 
200 		ddeptr = ddptr;
201 		flags |= __DTF_READALL;
202 
203 		/*
204 		 * Re-open the directory.
205 		 * This has the effect of rewinding back to the
206 		 * top of the union stack and is needed by
207 		 * programs which plan to fchdir to a descriptor
208 		 * which has also been read -- see fts.c.
209 		 */
210 		if (flags & DTF_REWIND) {
211 			if ((fd2 = _open(name, O_RDONLY | O_DIRECTORY)) == -1) {
212 				saved_errno = errno;
213 				free(buf);
214 				free(dirp);
215 				errno = saved_errno;
216 				return (NULL);
217 			}
218 			(void)_dup2(fd2, fd);
219 			_close(fd2);
220 		}
221 
222 		/*
223 		 * There is now a buffer full of (possibly) duplicate
224 		 * names.
225 		 */
226 		dirp->dd_buf = buf;
227 
228 		/*
229 		 * Go round this loop twice...
230 		 *
231 		 * Scan through the buffer, counting entries.
232 		 * On the second pass, save pointers to each one.
233 		 * Then sort the pointers and remove duplicate names.
234 		 */
235 		for (dpv = 0;;) {
236 			n = 0;
237 			ddptr = buf;
238 			while (ddptr < ddeptr) {
239 				struct dirent *dp;
240 
241 				dp = (struct dirent *) ddptr;
242 				if ((long)dp & 03L)
243 					break;
244 				if ((dp->d_reclen <= 0) ||
245 				    (dp->d_reclen > (ddeptr + 1 - ddptr)))
246 					break;
247 				ddptr += dp->d_reclen;
248 				if (dp->d_fileno) {
249 					if (dpv)
250 						dpv[n] = dp;
251 					n++;
252 				}
253 			}
254 
255 			if (dpv) {
256 				struct dirent *xp;
257 
258 				/*
259 				 * This sort must be stable.
260 				 */
261 				mergesort(dpv, n, sizeof(*dpv),
262 				    opendir_compar);
263 
264 				dpv[n] = NULL;
265 				xp = NULL;
266 
267 				/*
268 				 * Scan through the buffer in sort order,
269 				 * zapping the inode number of any
270 				 * duplicate names.
271 				 */
272 				for (n = 0; dpv[n]; n++) {
273 					struct dirent *dp = dpv[n];
274 
275 					if ((xp == NULL) ||
276 					    strcmp(dp->d_name, xp->d_name)) {
277 						xp = dp;
278 					} else {
279 						dp->d_fileno = 0;
280 					}
281 					if (dp->d_type == DT_WHT &&
282 					    (flags & DTF_HIDEW))
283 						dp->d_fileno = 0;
284 				}
285 
286 				free(dpv);
287 				break;
288 			} else {
289 				dpv = malloc((n+1) * sizeof(struct dirent *));
290 				if (dpv == NULL)
291 					break;
292 			}
293 		}
294 
295 		dirp->dd_len = len;
296 		dirp->dd_size = ddptr - dirp->dd_buf;
297 	} else {
298 		dirp->dd_len = incr;
299 		dirp->dd_size = 0;
300 		dirp->dd_buf = malloc(dirp->dd_len);
301 		if (dirp->dd_buf == NULL)
302 			goto fail;
303 		dirp->dd_seek = 0;
304 		flags &= ~DTF_REWIND;
305 	}
306 
307 	dirp->dd_loc = 0;
308 	dirp->dd_fd = fd;
309 	dirp->dd_flags = flags;
310 	dirp->dd_lock = NULL;
311 
312 	/*
313 	 * Set up seek point for rewinddir.
314 	 */
315 	dirp->dd_rewind = telldir(dirp);
316 
317 	return (dirp);
318 
319 fail:
320 	saved_errno = errno;
321 	free(dirp);
322 	errno = saved_errno;
323 	return (NULL);
324 }
325