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