Home | History | Annotate | Line # | Download | only in gen
opendir.c revision 1.18
      1 /*	$NetBSD: opendir.c,v 1.18 1999/09/16 11:45:02 lukem 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.18 1999/09/16 11:45:02 lukem 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 #ifdef _DIAGNOSTIC
     72 	if (name == NULL || *name == '\0') {
     73 		errno = ENOENT;
     74 		return (NULL);
     75 	}
     76 #endif
     77 
     78 	return (__opendir2(name, DTF_HIDEW|DTF_NODUP));
     79 }
     80 
     81 DIR *
     82 __opendir2(name, flags)
     83 	const char *name;
     84 	int flags;
     85 {
     86 	DIR *dirp;
     87 	int fd;
     88 	struct stat sb;
     89 	int pagesz;
     90 	int incr;
     91 	int unionstack, nfsdir;
     92 	struct statfs sfb;
     93 
     94 	_DIAGASSERT(name != NULL);
     95 #ifdef _DIAGNOSTIC
     96 	if (name == NULL || *name == '\0')
     97 		return (NULL);
     98 #endif
     99 
    100 	if ((fd = open(name, O_RDONLY | O_NONBLOCK)) == -1)
    101 		return (NULL);
    102 	if (fstat(fd, &sb) || !S_ISDIR(sb.st_mode)) {
    103 		errno = ENOTDIR;
    104 		close(fd);
    105 		return (NULL);
    106 	}
    107 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 ||
    108 	    (dirp = (DIR *)malloc(sizeof(DIR))) == NULL) {
    109 		close(fd);
    110 		return (NULL);
    111 	}
    112 
    113 	/*
    114 	 * If the machine's page size is an exact multiple of DIRBLKSIZ,
    115 	 * use a buffer that is cluster boundary aligned.
    116 	 * Hopefully this can be a big win someday by allowing page trades
    117 	 * to user space to be done by getdirentries()
    118 	 */
    119 	if (((pagesz = getpagesize()) % DIRBLKSIZ) == 0)
    120 		incr = pagesz;
    121 	else
    122 		incr = DIRBLKSIZ;
    123 
    124 	/*
    125 	 * Determine whether this directory is the top of a union stack.
    126 	 */
    127 
    128 	if (fstatfs(fd, &sfb) < 0) {
    129 		free(dirp);
    130 		close(fd);
    131 		return (NULL);
    132 	}
    133 
    134 	if (flags & DTF_NODUP)
    135 		unionstack = !(strncmp(sfb.f_fstypename, MOUNT_UNION,
    136 		    MFSNAMELEN)) || (sfb.f_flags & MNT_UNION);
    137 	else
    138 		unionstack = 0;
    139 
    140 	nfsdir = !(strncmp(sfb.f_fstypename, MOUNT_NFS, MFSNAMELEN));
    141 
    142 	if (unionstack || nfsdir) {
    143 		size_t len;
    144 		size_t space;
    145 		char *buf;
    146 		char *ddptr;
    147 		char *ddeptr;
    148 		int n;
    149 		struct dirent **dpv;
    150 
    151 		/*
    152 		 * The strategy here for directories on top of a union stack
    153 		 * is to read all the directory entries into a buffer, sort
    154 		 * the buffer, and remove duplicate entries by setting the
    155 		 * inode number to zero.
    156 		 *
    157 		 * For directories on an NFS mounted filesystem, we try
    158 	 	 * to get a consistent snapshot by trying until we have
    159 		 * successfully read all of the directory without errors
    160 		 * (i.e. 'bad cookie' errors from the server because
    161 		 * the directory was modified). These errors should not
    162 		 * happen often, but need to be dealt with.
    163 		 */
    164 retry:
    165 		len = 0;
    166 		space = 0;
    167 		buf = 0;
    168 		ddptr = 0;
    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 = realloc(buf, len);
    179 				if (buf == NULL) {
    180 					free(dirp);
    181 					close(fd);
    182 					return (NULL);
    183 				}
    184 				ddptr = buf + (len - space);
    185 			}
    186 
    187 			dirp->dd_seek = lseek(fd, (off_t)0, SEEK_CUR);
    188 			n = getdents(fd, ddptr, space);
    189 			/*
    190 			 * For NFS: EINVAL means a bad cookie error
    191 			 * from the server. Keep trying to get a
    192 			 * consistent view, in this case this means
    193 			 * starting all over again.
    194 			 */
    195 			if (n == -1 && errno == EINVAL && nfsdir) {
    196 				free(buf);
    197 				lseek(fd, (off_t)0, SEEK_SET);
    198 				goto retry;
    199 			}
    200 			if (n > 0) {
    201 				ddptr += n;
    202 				space -= n;
    203 			}
    204 		} while (n > 0);
    205 
    206 		ddeptr = ddptr;
    207 		flags |= __DTF_READALL;
    208 
    209 		/*
    210 		 * Re-open the directory.
    211 		 * This has the effect of rewinding back to the
    212 		 * top of the union stack and is needed by
    213 		 * programs which plan to fchdir to a descriptor
    214 		 * which has also been read -- see fts.c.
    215 		 */
    216 		if (flags & DTF_REWIND) {
    217 			(void) close(fd);
    218 			if ((fd = open(name, O_RDONLY)) == -1) {
    219 				free(buf);
    220 				free(dirp);
    221 				return (NULL);
    222 			}
    223 		}
    224 
    225 		/*
    226 		 * There is now a buffer full of (possibly) duplicate
    227 		 * names.
    228 		 */
    229 		dirp->dd_buf = buf;
    230 
    231 		/*
    232 		 * Go round this loop twice...
    233 		 *
    234 		 * Scan through the buffer, counting entries.
    235 		 * On the second pass, save pointers to each one.
    236 		 * Then sort the pointers and remove duplicate names.
    237 		 */
    238 		if (!nfsdir) {
    239 			for (dpv = 0;;) {
    240 				for (n = 0, ddptr = buf; ddptr < ddeptr;) {
    241 					struct dirent *dp;
    242 
    243 					dp = (struct dirent *)(void *)ddptr;
    244 					if ((long)dp & 03)
    245 						break;
    246 					/*
    247 					 * d_reclen is unsigned,
    248 					 * so no need to compare <= 0
    249 					 */
    250 					if (dp->d_reclen > (ddeptr + 1 - ddptr))
    251 						break;
    252 					ddptr += dp->d_reclen;
    253 					if (dp->d_fileno) {
    254 						if (dpv)
    255 							dpv[n] = dp;
    256 						n++;
    257 					}
    258 				}
    259 
    260 				if (dpv) {
    261 					struct dirent *xp;
    262 
    263 					/*
    264 					 * This sort must be stable.
    265 					 */
    266 					mergesort(dpv, (size_t)n, sizeof(*dpv),
    267 					    alphasort);
    268 
    269 					dpv[n] = NULL;
    270 					xp = NULL;
    271 
    272 					/*
    273 					 * Scan through the buffer in sort
    274 					 * order, zapping the inode number
    275 					 * of any duplicate names.
    276 					 */
    277 					for (n = 0; dpv[n]; n++) {
    278 						struct dirent *dp = dpv[n];
    279 
    280 						if ((xp == NULL) ||
    281 						    strcmp(dp->d_name,
    282 						      xp->d_name))
    283 							xp = dp;
    284 						else
    285 							dp->d_fileno = 0;
    286 						if (dp->d_type == DT_WHT &&
    287 						    (flags & DTF_HIDEW))
    288 							dp->d_fileno = 0;
    289 					}
    290 
    291 					free(dpv);
    292 					break;
    293 				} else {
    294 					dpv = malloc((n+1) * sizeof(struct dirent *));
    295 					if (dpv == NULL)
    296 						break;
    297 				}
    298 			}
    299 		}
    300 
    301 		dirp->dd_len = len;
    302 		dirp->dd_size = ddptr - dirp->dd_buf;
    303 	} else {
    304 		dirp->dd_len = incr;
    305 		dirp->dd_buf = malloc((size_t)dirp->dd_len);
    306 		if (dirp->dd_buf == NULL) {
    307 			free(dirp);
    308 			close (fd);
    309 			return (NULL);
    310 		}
    311 		dirp->dd_seek = 0;
    312 		flags &= ~DTF_REWIND;
    313 	}
    314 
    315 	dirp->dd_loc = 0;
    316 	dirp->dd_fd = fd;
    317 	dirp->dd_flags = flags;
    318 
    319 	/*
    320 	 * Set up seek point for rewinddir.
    321 	 */
    322 	dirp->dd_rewind = telldir(dirp);
    323 
    324 	return (dirp);
    325 }
    326