xref: /minix3/lib/libc/gen/initdir.c (revision f14fb602092e015ff630df58e17c2a9cd57d29b3)
1 /*	$NetBSD: initdir.c,v 1.3 2012/03/13 21:13:36 christos 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 __RCSID("$NetBSD: initdir.c,v 1.3 2012/03/13 21:13:36 christos Exp $");
35 #endif /* LIBC_SCCS and not lint */
36 
37 #include "namespace.h"
38 
39 #ifdef __minix
40 /* NetBSD BUG on !_REENTRANT */
41 #include <sys/cdefs.h>
42 #include <sys/featuretest.h>
43 #include <sys/types.h>
44 
45 #if !defined(O_CLOEXEC)
46 #define O_CLOEXEC 0
47 #endif
48 
49 #endif
50 
51 #include "reentrant.h"
52 #include "extern.h"
53 
54 #include <sys/param.h>
55 
56 #include <assert.h>
57 #include <dirent.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #include "dirent_private.h"
65 
66 #define	MAXITERATIONS	100
67 
68 int
69 _initdir(DIR *dirp, int fd, const char *name)
70 {
71 	int flags = dirp->dd_flags;
72 	int pagesz;
73 	int incr;
74 
75 	/*
76 	 * If the machine's page size is an exact multiple of DIRBLKSIZ,
77 	 * use a buffer that is cluster boundary aligned.
78 	 * Hopefully this can be a big win someday by allowing page trades
79 	 * to user space to be done by getdents()
80 	 */
81 	if (((pagesz = getpagesize()) % DIRBLKSIZ) == 0)
82 		incr = pagesz;
83 	else
84 		incr = DIRBLKSIZ;
85 
86 	if ((flags & DTF_REWIND) && name == NULL) {
87 		return EINVAL;
88 	}
89 	if ((flags & __DTF_READALL) != 0) {
90 		size_t len;
91 		size_t space;
92 		char *buf, *nbuf;
93 		char *ddptr;
94 		char *ddeptr;
95 		int n;
96 		struct dirent **dpv;
97 		int i;
98 
99 		/*
100 		 * The strategy here for directories on top of a union stack
101 		 * is to read all the directory entries into a buffer, sort
102 		 * the buffer, and remove duplicate entries by setting the
103 		 * inode number to zero.
104 		 *
105 		 * For directories on an NFS mounted filesystem, we try
106 	 	 * to get a consistent snapshot by trying until we have
107 		 * successfully read all of the directory without errors
108 		 * (i.e. 'bad cookie' errors from the server because
109 		 * the directory was modified). These errors should not
110 		 * happen often, but need to be dealt with.
111 		 */
112 		i = 0;
113 retry:
114 		len = 0;
115 		space = 0;
116 		buf = 0;
117 		ddptr = 0;
118 
119 		do {
120 			/*
121 			 * Always make at least DIRBLKSIZ bytes
122 			 * available to getdents
123 			 */
124 			if (space < DIRBLKSIZ) {
125 				space += incr;
126 				len += incr;
127 				nbuf = realloc(buf, len);
128 				if (nbuf == NULL) {
129 					dirp->dd_buf = buf;
130 					return errno;
131 				}
132 				buf = nbuf;
133 				ddptr = buf + (len - space);
134 			}
135 
136 			dirp->dd_seek = lseek(fd, (off_t)0, SEEK_CUR);
137 			n = getdents(fd, ddptr, space);
138 			/*
139 			 * For NFS: EINVAL means a bad cookie error
140 			 * from the server. Keep trying to get a
141 			 * consistent view, in this case this means
142 			 * starting all over again.
143 			 */
144 			if (n == -1 && errno == EINVAL &&
145 			    (flags & __DTF_RETRY_ON_BADCOOKIE) != 0) {
146 				free(buf);
147 				lseek(fd, (off_t)0, SEEK_SET);
148 				if (++i > MAXITERATIONS)
149 					return EINVAL;
150 				goto retry;
151 			}
152 			if (n > 0) {
153 				ddptr += n;
154 				space -= n;
155 			}
156 		} while (n > 0);
157 
158 		ddeptr = ddptr;
159 
160 		/*
161 		 * Re-open the directory.
162 		 * This has the effect of rewinding back to the
163 		 * top of the union stack and is needed by
164 		 * programs which plan to fchdir to a descriptor
165 		 * which has also been read -- see fts.c.
166 		 */
167 		if (flags & DTF_REWIND) {
168 			(void) close(fd);
169 			if ((fd = open(name, O_RDONLY | O_CLOEXEC)) == -1) {
170 				dirp->dd_buf = buf;
171 				return errno;
172 			}
173 		}
174 
175 		/*
176 		 * There is now a buffer full of (possibly) duplicate
177 		 * names.
178 		 */
179 		dirp->dd_buf = buf;
180 
181 		/*
182 		 * Go round this loop twice...
183 		 *
184 		 * Scan through the buffer, counting entries.
185 		 * On the second pass, save pointers to each one.
186 		 * Then sort the pointers and remove duplicate names.
187 		 */
188 		if ((flags & DTF_NODUP) != 0) {
189 			for (dpv = 0;;) {
190 				for (n = 0, ddptr = buf; ddptr < ddeptr;) {
191 					struct dirent *dp;
192 
193 					dp = (struct dirent *)(void *)ddptr;
194 					if ((long)dp & _DIRENT_ALIGN(dp))
195 						break;
196 					/*
197 					 * d_reclen is unsigned,
198 					 * so no need to compare <= 0
199 					 */
200 					if (dp->d_reclen > (ddeptr + 1 - ddptr))
201 						break;
202 					ddptr += dp->d_reclen;
203 					if (dp->d_fileno) {
204 						if (dpv)
205 							dpv[n] = dp;
206 						n++;
207 					}
208 				}
209 
210 				if (dpv) {
211 					struct dirent *xp;
212 
213 					/*
214 					 * This sort must be stable.
215 					 */
216 					mergesort(dpv, (size_t)n, sizeof(*dpv),
217 					    alphasort);
218 
219 					dpv[n] = NULL;
220 					xp = NULL;
221 
222 					/*
223 					 * Scan through the buffer in sort
224 					 * order, zapping the inode number
225 					 * of any duplicate names.
226 					 */
227 					for (n = 0; dpv[n]; n++) {
228 						struct dirent *dp = dpv[n];
229 
230 						if ((xp == NULL) ||
231 						    strcmp(dp->d_name,
232 						      xp->d_name))
233 							xp = dp;
234 						else
235 							dp->d_fileno = 0;
236 #ifndef __minix
237 						if (dp->d_type == DT_WHT &&
238 						    (flags & DTF_HIDEW))
239 							dp->d_fileno = 0;
240 #endif
241 					}
242 
243 					free(dpv);
244 					break;
245 				} else {
246 					dpv = malloc((n + 1) *
247 					    sizeof(struct dirent *));
248 					if (dpv == NULL)
249 						break;
250 				}
251 			}
252 		}
253 
254 		_DIAGASSERT(__type_fit(int, len));
255 		dirp->dd_len = (int)len;
256 		dirp->dd_size = ddptr - dirp->dd_buf;
257 	} else {
258 		dirp->dd_len = incr;
259 		dirp->dd_buf = malloc((size_t)dirp->dd_len);
260 		if (dirp->dd_buf == NULL)
261 			return errno;
262 		dirp->dd_seek = 0;
263 		flags &= ~DTF_REWIND;
264 	}
265 	dirp->dd_loc = 0;
266 	dirp->dd_fd = fd;
267 	dirp->dd_flags = flags;
268 	/*
269 	 * Set up seek point for rewinddir.
270 	 */
271 	(void)_telldir_unlocked(dirp);
272 	return 0;
273 }
274 
275 void
276 _finidir(DIR *dirp)
277 {
278 	struct dirpos *poslist;
279 
280 	free(dirp->dd_buf);
281 
282 	/* free seekdir/telldir storage */
283 	for (poslist = dirp->dd_internal; poslist; ) {
284 		struct dirpos *nextpos = poslist->dp_next;
285 		free(poslist);
286 		poslist = nextpos;
287 	}
288 	dirp->dd_internal = NULL;
289 }
290