getcwd.c revision 1.22 1 /* $NetBSD: getcwd.c,v 1.22 1999/09/16 11:44:58 lukem 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.22 1999/09/16 11:44:58 lukem 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 <assert.h>
53 #include <dirent.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60
61 #include "extern.h"
62
63 #ifdef __weak_alias
64 __weak_alias(getcwd,_getcwd);
65 __weak_alias(realpath,_realpath);
66 #endif
67
68 #define ISDOT(dp) \
69 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
70 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
71
72
73 #if defined(__SVR4) || defined(__svr4__)
74 #define d_fileno d_ino
75 #endif
76
77 /*
78 * char *realpath(const char *path, char resolved_path[MAXPATHLEN]);
79 *
80 * Find the real name of path, by removing all ".", ".." and symlink
81 * components. Returns (resolved) on success, or (NULL) on failure,
82 * in which case the path which caused trouble is left in (resolved).
83 */
84 char *
85 realpath(path, resolved)
86 const char *path;
87 char *resolved;
88 {
89 struct stat sb;
90 int fd, n, rootd, serrno, nlnk = 0;
91 char *p, *q, wbuf[MAXPATHLEN];
92
93 _DIAGASSERT(path != NULL);
94 _DIAGASSERT(resolved != NULL);
95 #ifdef _DIAGNOSTIC
96 if (path == NULL || *path == '\0') {
97 errno = ENOENT;
98 return (NULL);
99 }
100 if (resolved == NULL) {
101 errno = EINVAL;
102 return (NULL);
103 }
104 #endif
105
106 /* Save the starting point. */
107 if ((fd = open(".", O_RDONLY)) < 0) {
108 (void)strcpy(resolved, ".");
109 return (NULL);
110 }
111
112 /*
113 * Find the dirname and basename from the path to be resolved.
114 * Change directory to the dirname component.
115 * lstat the basename part.
116 * if it is a symlink, read in the value and loop.
117 * if it is a directory, then change to that directory.
118 * get the current directory name and append the basename.
119 */
120 (void)strncpy(resolved, path, MAXPATHLEN - 1);
121 resolved[MAXPATHLEN - 1] = '\0';
122 loop:
123 q = strrchr(resolved, '/');
124 if (q != NULL) {
125 p = q + 1;
126 if (q == resolved)
127 q = "/";
128 else {
129 do {
130 --q;
131 } while (q > resolved && *q == '/');
132 q[1] = '\0';
133 q = resolved;
134 }
135 if (chdir(q) < 0)
136 goto err1;
137 } else
138 p = resolved;
139
140 /* Deal with the last component. */
141 if (lstat(p, &sb) == 0) {
142 if (S_ISLNK(sb.st_mode)) {
143 if (nlnk++ >= MAXSYMLINKS) {
144 errno = ELOOP;
145 goto err1;
146 }
147 n = readlink(p, resolved, MAXPATHLEN);
148 if (n < 0)
149 goto err1;
150 resolved[n] = '\0';
151 goto loop;
152 }
153 if (S_ISDIR(sb.st_mode)) {
154 if (chdir(p) < 0)
155 goto err1;
156 p = "";
157 }
158 }
159
160 /*
161 * Save the last component name and get the full pathname of
162 * the current directory.
163 */
164 (void)strncpy(wbuf, p, (sizeof(wbuf) - 1));
165
166 /*
167 * Call the inernal internal version of getcwd which
168 * does a physical search rather than using the $PWD short-cut
169 */
170 if (getcwd(resolved, MAXPATHLEN) == 0)
171 goto err1;
172
173 /*
174 * Join the two strings together, ensuring that the right thing
175 * happens if the last component is empty, or the dirname is root.
176 */
177 if (resolved[0] == '/' && resolved[1] == '\0')
178 rootd = 1;
179 else
180 rootd = 0;
181
182 if (*wbuf) {
183 if (strlen(resolved) + strlen(wbuf) + rootd + 1 > MAXPATHLEN) {
184 errno = ENAMETOOLONG;
185 goto err1;
186 }
187 if (rootd == 0)
188 (void)strcat(resolved, "/"); /* XXX: strcat is safe */
189 (void)strcat(resolved, wbuf); /* XXX: strcat is safe */
190 }
191
192 /* Go back to where we came from. */
193 if (fchdir(fd) < 0) {
194 serrno = errno;
195 goto err2;
196 }
197
198 /* It's okay if the close fails, what's an fd more or less? */
199 (void)close(fd);
200 return (resolved);
201
202 err1: serrno = errno;
203 (void)fchdir(fd);
204 err2: (void)close(fd);
205 errno = serrno;
206 return (NULL);
207 }
208
209 #ifdef OLD_GETCWD
210
211 char *
212 getcwd(pt, size)
213 char *pt;
214 size_t size;
215 {
216 struct dirent *dp;
217 DIR *dir;
218 dev_t dev;
219 ino_t ino;
220 int first;
221 char *bpt, *bup;
222 struct stat s;
223 dev_t root_dev;
224 ino_t root_ino;
225 size_t ptsize, upsize;
226 int save_errno;
227 char *ept, *eup, *up;
228 size_t dlen;
229
230 /*
231 * If no buffer specified by the user, allocate one as necessary.
232 * If a buffer is specified, the size has to be non-zero. The path
233 * is built from the end of the buffer backwards.
234 */
235 if (pt) {
236 ptsize = 0;
237 if (!size) {
238 errno = EINVAL;
239 return (NULL);
240 }
241 ept = pt + size;
242 } else {
243 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
244 return (NULL);
245 ept = pt + ptsize;
246 }
247 bpt = ept - 1;
248 *bpt = '\0';
249
250 /*
251 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
252 * Should always be enough (it's 340 levels). If it's not, allocate
253 * as necessary. Special case the first stat, it's ".", not "..".
254 */
255 if ((up = malloc(upsize = 1024 - 4)) == NULL)
256 goto err;
257 eup = up + MAXPATHLEN;
258 bup = up;
259 up[0] = '.';
260 up[1] = '\0';
261
262 /* Save root values, so know when to stop. */
263 if (stat("/", &s))
264 goto err;
265 root_dev = s.st_dev;
266 root_ino = s.st_ino;
267
268 errno = 0; /* XXX readdir has no error return. */
269
270 for (first = 1;; first = 0) {
271 /* Stat the current level. */
272 if (lstat(up, &s))
273 goto err;
274
275 /* Save current node values. */
276 ino = s.st_ino;
277 dev = s.st_dev;
278
279 /* Check for reaching root. */
280 if (root_dev == dev && root_ino == ino) {
281 *--bpt = '/';
282 /*
283 * It's unclear that it's a requirement to copy the
284 * path to the beginning of the buffer, but it's always
285 * been that way and stuff would probably break.
286 */
287 memmove(pt, bpt, (size_t)(ept - bpt));
288 free(up);
289 return (pt);
290 }
291
292 /*
293 * Build pointer to the parent directory, allocating memory
294 * as necessary. Max length is 3 for "../", the largest
295 * possible component name, plus a trailing NULL.
296 */
297 if (bup + 3 + MAXNAMLEN + 1 >= eup) {
298 if ((up = realloc(up, upsize *= 2)) == NULL)
299 goto err;
300 bup = up;
301 eup = up + upsize;
302 }
303 *bup++ = '.';
304 *bup++ = '.';
305 *bup = '\0';
306
307 /* Open and stat parent directory. */
308 if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
309 goto err;
310
311 /* Add trailing slash for next directory. */
312 *bup++ = '/';
313
314 /*
315 * If it's a mount point, have to stat each element because
316 * the inode number in the directory is for the entry in the
317 * parent directory, not the inode number of the mounted file.
318 */
319 save_errno = 0;
320 if (s.st_dev == dev) {
321 for (;;) {
322 if (!(dp = readdir(dir)))
323 goto notfound;
324 if (dp->d_fileno == ino) {
325 #if defined(__SVR4) || defined(__svr4__) || defined(__linux__)
326 dlen = strlen(dp->d_name);
327 #else
328 dlen = dp->d_namlen;
329 #endif
330 break;
331 }
332 }
333 } else
334 for (;;) {
335 if (!(dp = readdir(dir)))
336 goto notfound;
337 if (ISDOT(dp))
338 continue;
339 #if defined(__SVR4) || defined(__svr4__) || defined(__linux__)
340 dlen = strlen(dp->d_name);
341 #else
342 dlen = dp->d_namlen;
343 #endif
344 memmove(bup, dp->d_name, dlen + 1);
345
346 /* Save the first error for later. */
347 if (lstat(up, &s)) {
348 if (!save_errno)
349 save_errno = errno;
350 errno = 0;
351 continue;
352 }
353 if (s.st_dev == dev && s.st_ino == ino)
354 break;
355 }
356
357 /*
358 * Check for length of the current name, preceding slash,
359 * leading slash.
360 */
361 if (bpt - pt <= dlen + (first ? 1 : 2)) {
362 size_t len, off;
363
364 if (!ptsize) {
365 errno = ERANGE;
366 goto err;
367 }
368 off = bpt - pt;
369 len = ept - bpt;
370 if ((pt = realloc(pt, ptsize *= 2)) == NULL)
371 goto err;
372 bpt = pt + off;
373 ept = pt + ptsize;
374 memmove(ept - len, bpt, len);
375 bpt = ept - len;
376 }
377 if (!first)
378 *--bpt = '/';
379 bpt -= dlen;
380 memmove(bpt, dp->d_name, dlen);
381 (void)closedir(dir);
382
383 /* Truncate any file name. */
384 *bup = '\0';
385 }
386
387 notfound:
388 /*
389 * If readdir set errno, use it, not any saved error; otherwise,
390 * didn't find the current directory in its parent directory, set
391 * errno to ENOENT.
392 */
393 if (!errno)
394 errno = save_errno ? save_errno : ENOENT;
395 /* FALLTHROUGH */
396 err:
397 if (ptsize)
398 free(pt);
399 free(up);
400 return (NULL);
401 }
402
403 #else /* New getcwd */
404
405 char *
406 getcwd(pt, size)
407 char *pt;
408 size_t size;
409 {
410 size_t ptsize, bufsize;
411 int len;
412
413 /*
414 * If no buffer specified by the user, allocate one as necessary.
415 * If a buffer is specified, the size has to be non-zero. The path
416 * is built from the end of the buffer backwards.
417 */
418 if (pt) {
419 ptsize = 0;
420 if (!size) {
421 errno = EINVAL;
422 return (NULL);
423 }
424 bufsize = size;
425 } else {
426 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
427 return (NULL);
428 bufsize = ptsize;
429 }
430 for (;;) {
431 len = __getcwd(pt, bufsize);
432 if ((len < 0) && (size == 0) && (errno == ERANGE)) {
433 if (ptsize > (MAXPATHLEN*4))
434 return NULL;
435 if ((pt = realloc(pt, ptsize *= 2)) == NULL)
436 return NULL;
437 bufsize = ptsize;
438 continue;
439 }
440 break;
441 }
442 if (len < 0)
443 return NULL;
444 else
445 return pt;
446 }
447
448 #endif
449