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