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