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