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