xref: /illumos-gate/usr/src/lib/libc/port/gen/fdopendir.c (revision 9b9d39d2a32ff806d2431dbcc50968ef1e6d46b2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * fdopendir, dirfd -- C library extension routines
29  *
30  * We use lmalloc()/lfree() rather than malloc()/free() in
31  * order to allow opendir()/readdir()/closedir() to be called
32  * while holding internal libc locks.
33  */
34 
35 #pragma weak _fdopendir = fdopendir
36 
37 #include "lint.h"
38 #include <mtlib.h>
39 #include <dirent.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <stdlib.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #include "libc.h"
46 
47 DIR *
48 fdopendir(int fd)
49 {
50 	private_DIR *pdirp = lmalloc(sizeof (*pdirp));
51 	DIR *dirp = (DIR *)pdirp;
52 	void *buf = lmalloc(DIRBUF);
53 	int error = 0;
54 	struct stat64 sbuf;
55 
56 	if (pdirp == NULL || buf == NULL)
57 		goto fail;
58 	/*
59 	 * POSIX mandated behavior
60 	 * close on exec if using file descriptor
61 	 */
62 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
63 		goto fail;
64 	if (fstat64(fd, &sbuf) < 0)
65 		goto fail;
66 	if ((sbuf.st_mode & S_IFMT) != S_IFDIR) {
67 		error = ENOTDIR;
68 		goto fail;
69 	}
70 	dirp->dd_buf = buf;
71 	dirp->dd_fd = fd;
72 	dirp->dd_loc = 0;
73 	dirp->dd_size = 0;
74 	(void) mutex_init(&pdirp->dd_lock, USYNC_THREAD, NULL);
75 	return (dirp);
76 
77 fail:
78 	if (pdirp != NULL)
79 		lfree(pdirp, sizeof (*pdirp));
80 	if (buf != NULL)
81 		lfree(buf, DIRBUF);
82 	if (error)
83 		errno = error;
84 	return (NULL);
85 }
86 
87 int
88 dirfd(DIR *dirp)
89 {
90 	return (dirp->dd_fd);
91 }
92