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