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