getcwd.c revision 1.11 1 /* $NetBSD: getcwd.c,v 1.11 1998/02/26 02:49:21 perry Exp $ */
2
3 /*
4 * Copyright (c) 1989, 1991, 1993, 1995
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Jan-Simon Pendry.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #if defined(LIBC_SCCS) && !defined(lint)
41 #if 0
42 static char sccsid[] = "@(#)getcwd.c 8.5 (Berkeley) 2/7/95";
43 #else
44 __RCSID("$NetBSD: getcwd.c,v 1.11 1998/02/26 02:49:21 perry Exp $");
45 #endif
46 #endif /* LIBC_SCCS and not lint */
47
48 #include "namespace.h"
49 #include <sys/param.h>
50 #include <sys/stat.h>
51
52 #include <dirent.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59
60 #ifdef __weak_alias
61 __weak_alias(getcwd,_getcwd);
62 __weak_alias(realpath,_realpath);
63 #endif
64
65 static char *getcwd_physical __P((char *, size_t));
66
67 #define ISDOT(dp) \
68 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
69 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
70
71 char *
72 getcwd(pt, size)
73 char *pt;
74 size_t size;
75 {
76 char *pwd;
77 size_t pwdlen;
78 dev_t dev;
79 ino_t ino;
80 struct stat s;
81
82 /* Check $PWD -- if it's right, it's fast. */
83 if ((pwd = getenv("PWD")) != NULL && pwd[0] == '/' && !stat(pwd, &s)) {
84 dev = s.st_dev;
85 ino = s.st_ino;
86 if (!stat(".", &s) && dev == s.st_dev && ino == s.st_ino) {
87 pwdlen = strlen(pwd);
88 if (size != 0) {
89 if (pwdlen + 1 > size) {
90 errno = ERANGE;
91 return (NULL);
92 }
93 } else if ((pt = malloc(pwdlen + 1)) == NULL)
94 return (NULL);
95 memmove(pt, pwd, pwdlen);
96 pt[pwdlen] = '\0';
97 return (pt);
98 }
99 }
100
101 return (getcwd_physical(pt, size));
102 }
103
104 /*
105 * char *realpath(const char *path, char resolved_path[MAXPATHLEN]);
106 *
107 * Find the real name of path, by removing all ".", ".." and symlink
108 * components. Returns (resolved) on success, or (NULL) on failure,
109 * in which case the path which caused trouble is left in (resolved).
110 */
111 char *
112 realpath(path, resolved)
113 const char *path;
114 char *resolved;
115 {
116 struct stat sb;
117 int fd, n, rootd, serrno;
118 char *p, *q, wbuf[MAXPATHLEN];
119
120 /* Save the starting point. */
121 if ((fd = open(".", O_RDONLY)) < 0) {
122 (void)strcpy(resolved, ".");
123 return (NULL);
124 }
125
126 /*
127 * Find the dirname and basename from the path to be resolved.
128 * Change directory to the dirname component.
129 * lstat the basename part.
130 * if it is a symlink, read in the value and loop.
131 * if it is a directory, then change to that directory.
132 * get the current directory name and append the basename.
133 */
134 (void)strncpy(resolved, path, MAXPATHLEN - 1);
135 resolved[MAXPATHLEN - 1] = '\0';
136 loop:
137 q = strrchr(resolved, '/');
138 if (q != NULL) {
139 p = q + 1;
140 if (q == resolved)
141 q = "/";
142 else {
143 do {
144 --q;
145 } while (q > resolved && *q == '/');
146 q[1] = '\0';
147 q = resolved;
148 }
149 if (chdir(q) < 0)
150 goto err1;
151 } else
152 p = resolved;
153
154 /* Deal with the last component. */
155 if (lstat(p, &sb) == 0) {
156 if (S_ISLNK(sb.st_mode)) {
157 n = readlink(p, resolved, MAXPATHLEN);
158 if (n < 0)
159 goto err1;
160 resolved[n] = '\0';
161 goto loop;
162 }
163 if (S_ISDIR(sb.st_mode)) {
164 if (chdir(p) < 0)
165 goto err1;
166 p = "";
167 }
168 }
169
170 /*
171 * Save the last component name and get the full pathname of
172 * the current directory.
173 */
174 (void)strncpy(wbuf, p, (sizeof(wbuf) - 1));
175
176 /*
177 * Call the inernal internal version of getcwd which
178 * does a physical search rather than using the $PWD short-cut
179 */
180 if (getcwd_physical(resolved, MAXPATHLEN) == 0)
181 goto err1;
182
183 /*
184 * Join the two strings together, ensuring that the right thing
185 * happens if the last component is empty, or the dirname is root.
186 */
187 if (resolved[0] == '/' && resolved[1] == '\0')
188 rootd = 1;
189 else
190 rootd = 0;
191
192 if (*wbuf) {
193 if (strlen(resolved) + strlen(wbuf) + rootd + 1 > MAXPATHLEN) {
194 errno = ENAMETOOLONG;
195 goto err1;
196 }
197 if (rootd == 0)
198 (void)strcat(resolved, "/"); /* XXX: strcat is safe */
199 (void)strcat(resolved, wbuf); /* XXX: strcat is safe */
200 }
201
202 /* Go back to where we came from. */
203 if (fchdir(fd) < 0) {
204 serrno = errno;
205 goto err2;
206 }
207
208 /* It's okay if the close fails, what's an fd more or less? */
209 (void)close(fd);
210 return (resolved);
211
212 err1: serrno = errno;
213 (void)fchdir(fd);
214 err2: (void)close(fd);
215 errno = serrno;
216 return (NULL);
217 }
218
219 static char *
220 getcwd_physical(pt, size)
221 char *pt;
222 size_t size;
223 {
224 struct dirent *dp;
225 DIR *dir;
226 dev_t dev;
227 ino_t ino;
228 int first;
229 char *bpt, *bup;
230 struct stat s;
231 dev_t root_dev;
232 ino_t root_ino;
233 size_t ptsize, upsize;
234 int save_errno;
235 char *ept, *eup, *up;
236
237 /*
238 * If no buffer specified by the user, allocate one as necessary.
239 * If a buffer is specified, the size has to be non-zero. The path
240 * is built from the end of the buffer backwards.
241 */
242 if (pt) {
243 ptsize = 0;
244 if (!size) {
245 errno = EINVAL;
246 return (NULL);
247 }
248 ept = pt + size;
249 } else {
250 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
251 return (NULL);
252 ept = pt + ptsize;
253 }
254 bpt = ept - 1;
255 *bpt = '\0';
256
257 /*
258 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
259 * Should always be enough (it's 340 levels). If it's not, allocate
260 * as necessary. Special case the first stat, it's ".", not "..".
261 */
262 if ((up = malloc(upsize = 1024 - 4)) == NULL)
263 goto err;
264 eup = up + MAXPATHLEN;
265 bup = up;
266 up[0] = '.';
267 up[1] = '\0';
268
269 /* Save root values, so know when to stop. */
270 if (stat("/", &s))
271 goto err;
272 root_dev = s.st_dev;
273 root_ino = s.st_ino;
274
275 errno = 0; /* XXX readdir has no error return. */
276
277 for (first = 1;; first = 0) {
278 /* Stat the current level. */
279 if (lstat(up, &s))
280 goto err;
281
282 /* Save current node values. */
283 ino = s.st_ino;
284 dev = s.st_dev;
285
286 /* Check for reaching root. */
287 if (root_dev == dev && root_ino == ino) {
288 *--bpt = '/';
289 /*
290 * It's unclear that it's a requirement to copy the
291 * path to the beginning of the buffer, but it's always
292 * been that way and stuff would probably break.
293 */
294 bcopy(bpt, pt, (size_t)(ept - bpt));
295 free(up);
296 return (pt);
297 }
298
299 /*
300 * Build pointer to the parent directory, allocating memory
301 * as necessary. Max length is 3 for "../", the largest
302 * possible component name, plus a trailing NULL.
303 */
304 if (bup + 3 + MAXNAMLEN + 1 >= eup) {
305 if ((up = realloc(up, upsize *= 2)) == NULL)
306 goto err;
307 bup = up;
308 eup = up + upsize;
309 }
310 *bup++ = '.';
311 *bup++ = '.';
312 *bup = '\0';
313
314 /* Open and stat parent directory. */
315 if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
316 goto err;
317
318 /* Add trailing slash for next directory. */
319 *bup++ = '/';
320
321 /*
322 * If it's a mount point, have to stat each element because
323 * the inode number in the directory is for the entry in the
324 * parent directory, not the inode number of the mounted file.
325 */
326 save_errno = 0;
327 if (s.st_dev == dev) {
328 for (;;) {
329 if (!(dp = readdir(dir)))
330 goto notfound;
331 if (dp->d_fileno == ino)
332 break;
333 }
334 } else
335 for (;;) {
336 if (!(dp = readdir(dir)))
337 goto notfound;
338 if (ISDOT(dp))
339 continue;
340 bcopy(dp->d_name, bup,
341 (size_t)(dp->d_namlen + 1));
342
343 /* Save the first error for later. */
344 if (lstat(up, &s)) {
345 if (!save_errno)
346 save_errno = errno;
347 errno = 0;
348 continue;
349 }
350 if (s.st_dev == dev && s.st_ino == ino)
351 break;
352 }
353
354 /*
355 * Check for length of the current name, preceding slash,
356 * leading slash.
357 */
358 if (bpt - pt <= dp->d_namlen + (first ? 1 : 2)) {
359 size_t len, off;
360
361 if (!ptsize) {
362 errno = ERANGE;
363 goto err;
364 }
365 off = bpt - pt;
366 len = ept - bpt;
367 if ((pt = realloc(pt, ptsize *= 2)) == NULL)
368 goto err;
369 bpt = pt + off;
370 ept = pt + ptsize;
371 bcopy(bpt, ept - len, len);
372 bpt = ept - len;
373 }
374 if (!first)
375 *--bpt = '/';
376 bpt -= dp->d_namlen;
377 bcopy(dp->d_name, bpt, (size_t)dp->d_namlen);
378 (void)closedir(dir);
379
380 /* Truncate any file name. */
381 *bup = '\0';
382 }
383
384 notfound:
385 /*
386 * If readdir set errno, use it, not any saved error; otherwise,
387 * didn't find the current directory in its parent directory, set
388 * errno to ENOENT.
389 */
390 if (!errno)
391 errno = save_errno ? save_errno : ENOENT;
392 /* FALLTHROUGH */
393 err:
394 if (ptsize)
395 free(pt);
396 free(up);
397 return (NULL);
398 }
399