xref: /freebsd/lib/libc/gen/getcwd.c (revision b1f9167f94059fd55c630891d359bcff987bd7eb)
1 /*
2  * Copyright (c) 1989, 1991, 1993, 1995
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[] = "@(#)getcwd.c	8.5 (Berkeley) 2/7/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/stat.h>
39 
40 #include <dirent.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include "un-namespace.h"
48 
49 #include "gen-private.h"
50 
51 #define	ISDOT(dp) \
52 	(dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
53 	    (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
54 
55 extern int __getcwd(char *, size_t);
56 
57 char *
58 getcwd(pt, size)
59 	char *pt;
60 	size_t size;
61 {
62 	struct dirent *dp;
63 	DIR *dir = NULL;
64 	dev_t dev;
65 	ino_t ino;
66 	int first;
67 	char *bpt;
68 	struct stat s;
69 	dev_t root_dev;
70 	ino_t root_ino;
71 	size_t ptsize;
72 	int save_errno;
73 	char *ept, c;
74 	int fd;
75 
76 	/*
77 	 * If no buffer specified by the user, allocate one as necessary.
78 	 * If a buffer is specified, the size has to be non-zero.  The path
79 	 * is built from the end of the buffer backwards.
80 	 */
81 	if (pt) {
82 		ptsize = 0;
83 		if (!size) {
84 			errno = EINVAL;
85 			return (NULL);
86 		}
87 		if (size == 1) {
88 			errno = ERANGE;
89 			return (NULL);
90 		}
91 		ept = pt + size;
92 	} else {
93 		if ((pt = malloc(ptsize = PATH_MAX)) == NULL)
94 			return (NULL);
95 		ept = pt + ptsize;
96 	}
97 	if (__getcwd(pt, ept - pt) == 0) {
98 		if (*pt != '/') {
99 			bpt = pt;
100 			ept = pt + strlen(pt) - 1;
101 			while (bpt < ept) {
102 				c = *bpt;
103 				*bpt++ = *ept;
104 				*ept-- = c;
105 			}
106 		}
107 		return (pt);
108 	}
109 	bpt = ept - 1;
110 	*bpt = '\0';
111 
112 	/* Save root values, so know when to stop. */
113 	if (stat("/", &s))
114 		goto err;
115 	root_dev = s.st_dev;
116 	root_ino = s.st_ino;
117 
118 	errno = 0;			/* XXX readdir has no error return. */
119 
120 	for (first = 1;; first = 0) {
121 		/* Stat the current level. */
122 		if (dir != NULL ? _fstat(_dirfd(dir), &s) : lstat(".", &s))
123 			goto err;
124 
125 		/* Save current node values. */
126 		ino = s.st_ino;
127 		dev = s.st_dev;
128 
129 		/* Check for reaching root. */
130 		if (root_dev == dev && root_ino == ino) {
131 			*--bpt = '/';
132 			/*
133 			 * It's unclear that it's a requirement to copy the
134 			 * path to the beginning of the buffer, but it's always
135 			 * been that way and stuff would probably break.
136 			 */
137 			bcopy(bpt, pt, ept - bpt);
138 			if (dir)
139 				(void) closedir(dir);
140 			return (pt);
141 		}
142 
143 		/* Open and stat parent directory. */
144 		fd = _openat(dir != NULL ? _dirfd(dir) : AT_FDCWD,
145 				"..", O_RDONLY | O_CLOEXEC);
146 		if (fd == -1)
147 			goto err;
148 		if (dir)
149 			(void) closedir(dir);
150 		if (!(dir = fdopendir(fd)) || _fstat(_dirfd(dir), &s)) {
151 			_close(fd);
152 			goto err;
153 		}
154 
155 		/*
156 		 * If it's a mount point, have to stat each element because
157 		 * the inode number in the directory is for the entry in the
158 		 * parent directory, not the inode number of the mounted file.
159 		 */
160 		save_errno = 0;
161 		if (s.st_dev == dev) {
162 			for (;;) {
163 				if (!(dp = readdir(dir)))
164 					goto notfound;
165 				if (dp->d_fileno == ino)
166 					break;
167 			}
168 		} else
169 			for (;;) {
170 				if (!(dp = readdir(dir)))
171 					goto notfound;
172 				if (ISDOT(dp))
173 					continue;
174 
175 				/* Save the first error for later. */
176 				if (fstatat(_dirfd(dir), dp->d_name, &s,
177 				    AT_SYMLINK_NOFOLLOW)) {
178 					if (!save_errno)
179 						save_errno = errno;
180 					errno = 0;
181 					continue;
182 				}
183 				if (s.st_dev == dev && s.st_ino == ino)
184 					break;
185 			}
186 
187 		/*
188 		 * Check for length of the current name, preceding slash,
189 		 * leading slash.
190 		 */
191 		while (bpt - pt < dp->d_namlen + (first ? 1 : 2)) {
192 			size_t len, off;
193 
194 			if (!ptsize) {
195 				errno = ERANGE;
196 				goto err;
197 			}
198 			off = bpt - pt;
199 			len = ept - bpt;
200 			if ((pt = reallocf(pt, ptsize *= 2)) == NULL)
201 				goto err;
202 			bpt = pt + off;
203 			ept = pt + ptsize;
204 			bcopy(bpt, ept - len, len);
205 			bpt = ept - len;
206 		}
207 		if (!first)
208 			*--bpt = '/';
209 		bpt -= dp->d_namlen;
210 		bcopy(dp->d_name, bpt, dp->d_namlen);
211 	}
212 
213 notfound:
214 	/*
215 	 * If readdir set errno, use it, not any saved error; otherwise,
216 	 * didn't find the current directory in its parent directory, set
217 	 * errno to ENOENT.
218 	 */
219 	if (!errno)
220 		errno = save_errno ? save_errno : ENOENT;
221 	/* FALLTHROUGH */
222 err:
223 	save_errno = errno;
224 
225 	if (ptsize)
226 		free(pt);
227 	if (dir)
228 		(void) closedir(dir);
229 
230 	errno = save_errno;
231 	return (NULL);
232 }
233