getcwd.c revision 1.15 1 /* $NetBSD: getcwd.c,v 1.15 1998/11/06 19:43:23 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.15 1998/11/06 19:43:23 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 #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 char *
190 getcwd(pt, size)
191 char *pt;
192 size_t size;
193 {
194 struct dirent *dp;
195 DIR *dir;
196 dev_t dev;
197 ino_t ino;
198 int first;
199 char *bpt, *bup;
200 struct stat s;
201 dev_t root_dev;
202 ino_t root_ino;
203 size_t ptsize, upsize;
204 int save_errno;
205 char *ept, *eup, *up;
206 size_t dlen;
207
208 /*
209 * If no buffer specified by the user, allocate one as necessary.
210 * If a buffer is specified, the size has to be non-zero. The path
211 * is built from the end of the buffer backwards.
212 */
213 if (pt) {
214 ptsize = 0;
215 if (!size) {
216 errno = EINVAL;
217 return (NULL);
218 }
219 ept = pt + size;
220 } else {
221 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
222 return (NULL);
223 ept = pt + ptsize;
224 }
225 bpt = ept - 1;
226 *bpt = '\0';
227
228 /*
229 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
230 * Should always be enough (it's 340 levels). If it's not, allocate
231 * as necessary. Special case the first stat, it's ".", not "..".
232 */
233 if ((up = malloc(upsize = 1024 - 4)) == NULL)
234 goto err;
235 eup = up + MAXPATHLEN;
236 bup = up;
237 up[0] = '.';
238 up[1] = '\0';
239
240 /* Save root values, so know when to stop. */
241 if (stat("/", &s))
242 goto err;
243 root_dev = s.st_dev;
244 root_ino = s.st_ino;
245
246 errno = 0; /* XXX readdir has no error return. */
247
248 for (first = 1;; first = 0) {
249 /* Stat the current level. */
250 if (lstat(up, &s))
251 goto err;
252
253 /* Save current node values. */
254 ino = s.st_ino;
255 dev = s.st_dev;
256
257 /* Check for reaching root. */
258 if (root_dev == dev && root_ino == ino) {
259 *--bpt = '/';
260 /*
261 * It's unclear that it's a requirement to copy the
262 * path to the beginning of the buffer, but it's always
263 * been that way and stuff would probably break.
264 */
265 memmove(pt, bpt, (size_t)(ept - bpt));
266 free(up);
267 return (pt);
268 }
269
270 /*
271 * Build pointer to the parent directory, allocating memory
272 * as necessary. Max length is 3 for "../", the largest
273 * possible component name, plus a trailing NULL.
274 */
275 if (bup + 3 + MAXNAMLEN + 1 >= eup) {
276 if ((up = realloc(up, upsize *= 2)) == NULL)
277 goto err;
278 bup = up;
279 eup = up + upsize;
280 }
281 *bup++ = '.';
282 *bup++ = '.';
283 *bup = '\0';
284
285 /* Open and stat parent directory. */
286 if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
287 goto err;
288
289 /* Add trailing slash for next directory. */
290 *bup++ = '/';
291
292 /*
293 * If it's a mount point, have to stat each element because
294 * the inode number in the directory is for the entry in the
295 * parent directory, not the inode number of the mounted file.
296 */
297 save_errno = 0;
298 if (s.st_dev == dev) {
299 for (;;) {
300 if (!(dp = readdir(dir)))
301 goto notfound;
302 if (dp->d_fileno == ino) {
303 #if defined(__SVR4) || defined(__svr4__)
304 dlen = strlen(dp->d_name);
305 #else
306 dlen = dp->d_namlen;
307 #endif
308 break;
309 }
310 }
311 } else
312 for (;;) {
313 if (!(dp = readdir(dir)))
314 goto notfound;
315 if (ISDOT(dp))
316 continue;
317 #if defined(__SVR4) || defined(__svr4__)
318 dlen = strlen(dp->d_name);
319 #else
320 dlen = dp->d_namlen;
321 #endif
322 memmove(bup, dp->d_name, dlen + 1);
323
324 /* Save the first error for later. */
325 if (lstat(up, &s)) {
326 if (!save_errno)
327 save_errno = errno;
328 errno = 0;
329 continue;
330 }
331 if (s.st_dev == dev && s.st_ino == ino)
332 break;
333 }
334
335 /*
336 * Check for length of the current name, preceding slash,
337 * leading slash.
338 */
339 if (bpt - pt <= dlen + (first ? 1 : 2)) {
340 size_t len, off;
341
342 if (!ptsize) {
343 errno = ERANGE;
344 goto err;
345 }
346 off = bpt - pt;
347 len = ept - bpt;
348 if ((pt = realloc(pt, ptsize *= 2)) == NULL)
349 goto err;
350 bpt = pt + off;
351 ept = pt + ptsize;
352 memmove(ept - len, bpt, len);
353 bpt = ept - len;
354 }
355 if (!first)
356 *--bpt = '/';
357 bpt -= dlen;
358 memmove(bpt, dp->d_name, dlen);
359 (void)closedir(dir);
360
361 /* Truncate any file name. */
362 *bup = '\0';
363 }
364
365 notfound:
366 /*
367 * If readdir set errno, use it, not any saved error; otherwise,
368 * didn't find the current directory in its parent directory, set
369 * errno to ENOENT.
370 */
371 if (!errno)
372 errno = save_errno ? save_errno : ENOENT;
373 /* FALLTHROUGH */
374 err:
375 if (ptsize)
376 free(pt);
377 free(up);
378 return (NULL);
379 }
380