xref: /freebsd/lib/libc/gen/getcwd.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
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 #define	ISDOT(dp) \
50 	(dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
51 	    (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
52 
53 extern int __getcwd(char *, size_t);
54 
55 char *
56 getcwd(pt, size)
57 	char *pt;
58 	size_t size;
59 {
60 	struct dirent *dp;
61 	DIR *dir = NULL;
62 	dev_t dev;
63 	ino_t ino;
64 	int first;
65 	char *bpt, *bup;
66 	struct stat s;
67 	dev_t root_dev;
68 	ino_t root_ino;
69 	size_t ptsize, upsize;
70 	int save_errno;
71 	char *ept, *eup, *up, c;
72 
73 	/*
74 	 * If no buffer specified by the user, allocate one as necessary.
75 	 * If a buffer is specified, the size has to be non-zero.  The path
76 	 * is built from the end of the buffer backwards.
77 	 */
78 	if (pt) {
79 		ptsize = 0;
80 		if (!size) {
81 			errno = EINVAL;
82 			return (NULL);
83 		}
84 		if (size == 1) {
85 			errno = ERANGE;
86 			return (NULL);
87 		}
88 		ept = pt + size;
89 	} else {
90 		if ((pt = malloc(ptsize = PATH_MAX)) == NULL)
91 			return (NULL);
92 		ept = pt + ptsize;
93 	}
94 	if (__getcwd(pt, ept - pt) == 0) {
95 		if (*pt != '/') {
96 			bpt = pt;
97 			ept = pt + strlen(pt) - 1;
98 			while (bpt < ept) {
99 				c = *bpt;
100 				*bpt++ = *ept;
101 				*ept-- = c;
102 			}
103 		}
104 		return (pt);
105 	}
106 	bpt = ept - 1;
107 	*bpt = '\0';
108 
109 	/*
110 	 * Allocate 1024 bytes for the string of "../"'s.
111 	 * Should always be enough.  If it's not, allocate
112 	 * as necessary.  Special case the first stat, it's ".", not "..".
113 	 */
114 	if ((up = malloc(upsize = 1024)) == NULL)
115 		goto err;
116 	eup = up + upsize;
117 	bup = up;
118 	up[0] = '.';
119 	up[1] = '\0';
120 
121 	/* Save root values, so know when to stop. */
122 	if (stat("/", &s))
123 		goto err;
124 	root_dev = s.st_dev;
125 	root_ino = s.st_ino;
126 
127 	errno = 0;			/* XXX readdir has no error return. */
128 
129 	for (first = 1;; first = 0) {
130 		/* Stat the current level. */
131 		if (lstat(up, &s))
132 			goto err;
133 
134 		/* Save current node values. */
135 		ino = s.st_ino;
136 		dev = s.st_dev;
137 
138 		/* Check for reaching root. */
139 		if (root_dev == dev && root_ino == ino) {
140 			*--bpt = '/';
141 			/*
142 			 * It's unclear that it's a requirement to copy the
143 			 * path to the beginning of the buffer, but it's always
144 			 * been that way and stuff would probably break.
145 			 */
146 			bcopy(bpt, pt, ept - bpt);
147 			free(up);
148 			return (pt);
149 		}
150 
151 		/*
152 		 * Build pointer to the parent directory, allocating memory
153 		 * as necessary.  Max length is 3 for "../", the largest
154 		 * possible component name, plus a trailing NUL.
155 		 */
156 		while (bup + 3  + MAXNAMLEN + 1 >= eup) {
157 			if ((up = reallocf(up, upsize *= 2)) == NULL)
158 				goto err;
159 			bup = up;
160 			eup = up + upsize;
161 		}
162 		*bup++ = '.';
163 		*bup++ = '.';
164 		*bup = '\0';
165 
166 		/* Open and stat parent directory. */
167 		if (!(dir = opendir(up)) || _fstat(dirfd(dir), &s))
168 			goto err;
169 
170 		/* Add trailing slash for next directory. */
171 		*bup++ = '/';
172 		*bup = '\0';
173 
174 		/*
175 		 * If it's a mount point, have to stat each element because
176 		 * the inode number in the directory is for the entry in the
177 		 * parent directory, not the inode number of the mounted file.
178 		 */
179 		save_errno = 0;
180 		if (s.st_dev == dev) {
181 			for (;;) {
182 				if (!(dp = readdir(dir)))
183 					goto notfound;
184 				if (dp->d_fileno == ino)
185 					break;
186 			}
187 		} else
188 			for (;;) {
189 				if (!(dp = readdir(dir)))
190 					goto notfound;
191 				if (ISDOT(dp))
192 					continue;
193 				bcopy(dp->d_name, bup, dp->d_namlen + 1);
194 
195 				/* Save the first error for later. */
196 				if (lstat(up, &s)) {
197 					if (!save_errno)
198 						save_errno = errno;
199 					errno = 0;
200 					continue;
201 				}
202 				if (s.st_dev == dev && s.st_ino == ino)
203 					break;
204 			}
205 
206 		/*
207 		 * Check for length of the current name, preceding slash,
208 		 * leading slash.
209 		 */
210 		while (bpt - pt < dp->d_namlen + (first ? 1 : 2)) {
211 			size_t len, off;
212 
213 			if (!ptsize) {
214 				errno = ERANGE;
215 				goto err;
216 			}
217 			off = bpt - pt;
218 			len = ept - bpt;
219 			if ((pt = reallocf(pt, ptsize *= 2)) == NULL)
220 				goto err;
221 			bpt = pt + off;
222 			ept = pt + ptsize;
223 			bcopy(bpt, ept - len, len);
224 			bpt = ept - len;
225 		}
226 		if (!first)
227 			*--bpt = '/';
228 		bpt -= dp->d_namlen;
229 		bcopy(dp->d_name, bpt, dp->d_namlen);
230 		(void) closedir(dir);
231 		dir = NULL;
232 
233 		/* Truncate any file name. */
234 		*bup = '\0';
235 	}
236 
237 notfound:
238 	/*
239 	 * If readdir set errno, use it, not any saved error; otherwise,
240 	 * didn't find the current directory in its parent directory, set
241 	 * errno to ENOENT.
242 	 */
243 	if (!errno)
244 		errno = save_errno ? save_errno : ENOENT;
245 	/* FALLTHROUGH */
246 err:
247 	save_errno = errno;
248 
249 	if (ptsize)
250 		free(pt);
251 	if (dir)
252 		(void) closedir(dir);
253 	free(up);
254 
255 	errno = save_errno;
256 	return (NULL);
257 }
258