]> git.saurik.com Git - apple/libc.git/blame - gen.subproj/getcwd.c
Libc-186.tar.gz
[apple/libc.git] / gen.subproj / getcwd.c
CommitLineData
e9ce8d39
A
1/*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22/*
23 * Copyright (c) 1989, 1991, 1993
24 * The Regents of the University of California. All rights reserved.
25 *
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
28 * are met:
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * SUCH DAMAGE.
53 */
54
55
56#include <sys/param.h>
57#include <sys/stat.h>
58
59#include <dirent.h>
60#include <errno.h>
61#include <fcntl.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <unistd.h>
66
67static char *getcwd_physical __P((char *, size_t));
68
69#define ISDOT(dp) \
70 (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
71 dp->d_name[1] == '.' && dp->d_name[2] == '\0'))
72
73char *
74getcwd(pt, size)
75 char *pt;
76 size_t size;
77{
78 char *pwd;
79 size_t pwdlen;
80 dev_t dev;
81 ino_t ino;
82 struct stat s;
83
84 /* Check $PWD -- if it's right, it's fast. */
85 if ((pwd = getenv("PWD")) != NULL && pwd[0] == '/' && stat(pwd, &s) != -1) {
86 dev = s.st_dev;
87 ino = s.st_ino;
88 if (stat(".", &s) != -1 && dev == s.st_dev && ino == s.st_ino) {
89 pwdlen = strlen(pwd);
90 if (pt) {
91 if (!size) {
92 errno = EINVAL;
93 return (NULL);
94 }
95 if (pwdlen + 1 > size) {
96 errno = ERANGE;
97 return (NULL);
98 }
99 } else if ((pt = malloc(pwdlen + 1)) == NULL) {
100 errno = ENOMEM;
101 return (NULL);
102 }
103 memmove(pt, pwd, pwdlen);
104 pt[pwdlen] = '\0';
105 return (pt);
106 }
107 }
108
109 return (getcwd_physical(pt, size));
110}
111
112/*
113 * char *realpath(const char *path, char resolved_path[MAXPATHLEN]);
114 *
115 * Find the real name of path, by removing all ".", ".." and symlink
116 * components. Returns (resolved) on success, or (NULL) on failure,
117 * in which case the path which caused trouble is left in (resolved).
118 */
119char *
120realpath(path, resolved)
121 const char *path;
122 char *resolved;
123{
124 struct stat sb;
125 int fd, n, rootd, serrno;
126 char *p, *q, wbuf[MAXPATHLEN];
127 int symlinks = 0;
128
129 /* Save the starting point. */
130 if ((fd = open(".", O_RDONLY)) < 0) {
131 (void)strcpy(resolved, ".");
132 return (NULL);
133 }
134
135 /*
136 * Find the dirname and basename from the path to be resolved.
137 * Change directory to the dirname component.
138 * lstat the basename part.
139 * if it is a symlink, read in the value and loop.
140 * if it is a directory, then change to that directory.
141 * get the current directory name and append the basename.
142 */
143 (void)strncpy(resolved, path, MAXPATHLEN - 1);
144 resolved[MAXPATHLEN - 1] = '\0';
145loop:
146 q = strrchr(resolved, '/');
147 if (q != NULL) {
148 p = q + 1;
149 if (q == resolved)
150 q = "/";
151 else {
152 do {
153 --q;
154 } while (q > resolved && *q == '/');
155 q[1] = '\0';
156 q = resolved;
157 }
158 if (chdir(q) < 0)
159 goto err1;
160 } else
161 p = resolved;
162
163 /* Deal with the last component. */
164 if (lstat(p, &sb) == 0) {
165 if (S_ISLNK(sb.st_mode)) {
166 if (++symlinks > MAXSYMLINKS) {
167 errno = ELOOP;
168 goto err1;
169 }
170 n = readlink(p, resolved, MAXPATHLEN-1);
171 if (n < 0)
172 goto err1;
173 resolved[n] = '\0';
174 goto loop;
175 }
176 if (S_ISDIR(sb.st_mode)) {
177 if (chdir(p) < 0)
178 goto err1;
179 p = "";
180 }
181 }
182
183 /*
184 * Save the last component name and get the full pathname of
185 * the current directory.
186 */
187 (void)strcpy(wbuf, p);
188
189 /*
190 * Call the inernal internal version of getcwd which
191 * does a physical search rather than using the $PWD short-cut
192 */
193 if (getcwd_physical(resolved, MAXPATHLEN) == 0)
194 goto err1;
195
196 /*
197 * Join the two strings together, ensuring that the right thing
198 * happens if the last component is empty, or the dirname is root.
199 */
200 if (resolved[0] == '/' && resolved[1] == '\0')
201 rootd = 1;
202 else
203 rootd = 0;
204
205 if (*wbuf) {
206 if (strlen(resolved) + strlen(wbuf) + rootd + 1 > MAXPATHLEN) {
207 errno = ENAMETOOLONG;
208 goto err1;
209 }
210 if (rootd == 0)
211 (void)strcat(resolved, "/");
212 (void)strcat(resolved, wbuf);
213 }
214
215 /* Go back to where we came from. */
216 if (fchdir(fd) < 0) {
217 serrno = errno;
218 goto err2;
219 }
220
221 /* It's okay if the close fails, what's an fd more or less? */
222 (void)close(fd);
223 return (resolved);
224
225err1: serrno = errno;
226 (void)fchdir(fd);
227err2: (void)close(fd);
228 errno = serrno;
229 return (NULL);
230}
231
232static char *
233getcwd_physical(pt, size)
234 char *pt;
235 size_t size;
236{
237 register struct dirent *dp;
238 register DIR *dir;
239 register dev_t dev;
240 register ino_t ino;
241 register int first;
242 register char *bpt, *bup;
243 struct stat s;
244 dev_t root_dev;
245 ino_t root_ino;
246 size_t ptsize, upsize;
247 int save_errno;
248 char *ept, *eup, *up;
249
250 /*
251 * If no buffer specified by the user, allocate one as necessary.
252 * If a buffer is specified, the size has to be non-zero. The path
253 * is built from the end of the buffer backwards.
254 */
255 if (pt) {
256 ptsize = 0;
257 if (!size) {
258 errno = EINVAL;
259 return (NULL);
260 }
261 ept = pt + size;
262 } else {
263 if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
264 return (NULL);
265 ept = pt + ptsize;
266 }
267 bpt = ept - 1;
268 *bpt = '\0';
269
270 /*
271 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
272 * Should always be enough (it's 340 levels). If it's not, allocate
273 * as necessary. Special case the first stat, it's ".", not "..".
274 */
275 if ((up = malloc(upsize = 1024 - 4)) == NULL)
276 goto err;
277 eup = up + MAXPATHLEN;
278 bup = up;
279 up[0] = '.';
280 up[1] = '\0';
281
282 /* Save root values, so know when to stop. */
283 if (stat("/", &s))
284 goto err;
285 root_dev = s.st_dev;
286 root_ino = s.st_ino;
287
288 errno = 0; /* XXX readdir has no error return. */
289
290 for (first = 1;; first = 0) {
291 /* Stat the current level. */
292 if (lstat(up, &s))
293 goto err;
294
295 /* Save current node values. */
296 ino = s.st_ino;
297 dev = s.st_dev;
298
299 /* Check for reaching root. */
300 if (root_dev == dev && root_ino == ino) {
301 *--bpt = '/';
302 /*
303 * It's unclear that it's a requirement to copy the
304 * path to the beginning of the buffer, but it's always
305 * been that way and stuff would probably break.
306 */
307 (void)bcopy(bpt, pt, ept - bpt);
308 free(up);
309 return (pt);
310 }
311
312 /*
313 * Build pointer to the parent directory, allocating memory
314 * as necessary. Max length is 3 for "../", the largest
315 * possible component name, plus a trailing NULL.
316 */
317 if (bup + 3 + MAXNAMLEN + 1 >= eup) {
318 if ((up = realloc(up, upsize *= 2)) == NULL)
319 goto err;
320 bup = up;
321 eup = up + upsize;
322 }
323 *bup++ = '.';
324 *bup++ = '.';
325 *bup = '\0';
326
327 /* Open and stat parent directory. */
328 if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
329 goto err;
330
331 /* Add trailing slash for next directory. */
332 *bup++ = '/';
333
334 /*
335 * If it's a mount point, have to stat each element because
336 * the inode number in the directory is for the entry in the
337 * parent directory, not the inode number of the mounted file.
338 */
339 save_errno = 0;
340 if (s.st_dev == dev) {
341 for (;;) {
342 if (!(dp = readdir(dir)))
343 goto notfound;
344 if (dp->d_fileno == ino)
345 break;
346 }
347 } else
348 for (;;) {
349 if (!(dp = readdir(dir)))
350 goto notfound;
351 if (ISDOT(dp))
352 continue;
353 bcopy(dp->d_name, bup, dp->d_namlen + 1);
354
355 /* Save the first error for later. */
356 if (lstat(up, &s)) {
357 if (!save_errno)
358 save_errno = errno;
359 errno = 0;
360 continue;
361 }
362 if (s.st_dev == dev && s.st_ino == ino)
363 break;
364 }
365
366 /*
367 * Check for length of the current name, preceding slash,
368 * leading slash.
369 */
370 if (bpt - pt <= dp->d_namlen + (first ? 1 : 2)) {
371 size_t len, off;
372
373 if (!ptsize) {
374 errno = ERANGE;
375 goto err;
376 }
377 off = bpt - pt;
378 len = ept - bpt;
379 if ((pt = realloc(pt, ptsize *= 2)) == NULL)
380 goto err;
381 bpt = pt + off;
382 ept = pt + ptsize;
383 (void)bcopy(bpt, ept - len, len);
384 bpt = ept - len;
385 }
386 if (!first)
387 *--bpt = '/';
388 bpt -= dp->d_namlen;
389 bcopy(dp->d_name, bpt, dp->d_namlen);
390 (void)closedir(dir);
391
392 /* Truncate any file name. */
393 *bup = '\0';
394 }
395
396notfound:
397 /*
398 * If readdir set errno, use it, not any saved error; otherwise,
399 * didn't find the current directory in its parent directory, set
400 * errno to ENOENT.
401 */
402 if (!errno)
403 errno = save_errno ? save_errno : ENOENT;
404 /* FALLTHROUGH */
405err:
406 if (ptsize)
407 free(pt);
408 free(up);
409 return (NULL);
410}