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