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