xref: /netbsd-src/lib/libc/gen/getcwd.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: getcwd.c,v 1.45 2007/10/26 19:48:14 christos 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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #if defined(LIBC_SCCS) && !defined(lint)
37 #if 0
38 static char sccsid[] = "@(#)getcwd.c	8.5 (Berkeley) 2/7/95";
39 #else
40 __RCSID("$NetBSD: getcwd.c,v 1.45 2007/10/26 19:48:14 christos Exp $");
41 #endif
42 #endif /* LIBC_SCCS and not lint */
43 
44 #include "namespace.h"
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 
48 #include <assert.h>
49 #include <errno.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 
54 #include "extern.h"
55 
56 #ifdef __weak_alias
57 __weak_alias(getcwd,_getcwd)
58 __weak_alias(realpath,_realpath)
59 #endif
60 
61 /*
62  * char *realpath(const char *path, char resolved[MAXPATHLEN]);
63  *
64  * Find the real name of path, by removing all ".", ".." and symlink
65  * components.  Returns (resolved) on success, or (NULL) on failure,
66  * in which case the path which caused trouble is left in (resolved).
67  */
68 char *
69 realpath(const char *path, char *resolved)
70 {
71 	struct stat sb;
72 	int idx = 0, n, nlnk = 0;
73 	const char *q;
74 	char *p, wbuf[2][MAXPATHLEN];
75 	size_t len;
76 
77 	_DIAGASSERT(path != NULL);
78 	_DIAGASSERT(resolved != NULL);
79 
80 	/*
81 	 * Build real path one by one with paying an attention to .,
82 	 * .. and symbolic link.
83 	 */
84 
85 	/*
86 	 * `p' is where we'll put a new component with prepending
87 	 * a delimiter.
88 	 */
89 	p = resolved;
90 
91 	if (*path == 0) {
92 		*p = 0;
93 		errno = ENOENT;
94 		return (NULL);
95 	}
96 
97 	/* If relative path, start from current working directory. */
98 	if (*path != '/') {
99 		/* check for resolved pointer to appease coverity */
100 		if (resolved && getcwd(resolved, MAXPATHLEN) == NULL) {
101 			p[0] = '.';
102 			p[1] = 0;
103 			return (NULL);
104 		}
105 		len = strlen(resolved);
106 		if (len > 1)
107 			p += len;
108 	}
109 
110 loop:
111 	/* Skip any slash. */
112 	while (*path == '/')
113 		path++;
114 
115 	if (*path == 0) {
116 		if (p == resolved)
117 			*p++ = '/';
118 		*p = 0;
119 		return (resolved);
120 	}
121 
122 	/* Find the end of this component. */
123 	q = path;
124 	do
125 		q++;
126 	while (*q != '/' && *q != 0);
127 
128 	/* Test . or .. */
129 	if (path[0] == '.') {
130 		if (q - path == 1) {
131 			path = q;
132 			goto loop;
133 		}
134 		if (path[1] == '.' && q - path == 2) {
135 			/* Trim the last component. */
136 			if (p != resolved)
137 				while (*--p != '/')
138 					;
139 			path = q;
140 			goto loop;
141 		}
142 	}
143 
144 	/* Append this component. */
145 	if (p - resolved + 1 + q - path + 1 > MAXPATHLEN) {
146 		errno = ENAMETOOLONG;
147 		if (p == resolved)
148 			*p++ = '/';
149 		*p = 0;
150 		return (NULL);
151 	}
152 	p[0] = '/';
153 	memcpy(&p[1], path,
154 	    /* LINTED We know q > path. */
155 	    q - path);
156 	p[1 + q - path] = 0;
157 
158 	/*
159 	 * If this component is a symlink, toss it and prepend link
160 	 * target to unresolved path.
161 	 */
162 	if (lstat(resolved, &sb) == -1) {
163 		return (NULL);
164 	}
165 	if (S_ISLNK(sb.st_mode)) {
166 		if (nlnk++ >= MAXSYMLINKS) {
167 			errno = ELOOP;
168 			return (NULL);
169 		}
170 		n = readlink(resolved, wbuf[idx], sizeof(wbuf[0]) - 1);
171 		if (n < 0)
172 			return (NULL);
173 		if (n == 0) {
174 			errno = ENOENT;
175 			return (NULL);
176 		}
177 
178 		/* Append unresolved path to link target and switch to it. */
179 		if (n + (len = strlen(q)) + 1 > sizeof(wbuf[0])) {
180 			errno = ENAMETOOLONG;
181 			return (NULL);
182 		}
183 		memcpy(&wbuf[idx][n], q, len + 1);
184 		path = wbuf[idx];
185 		idx ^= 1;
186 
187 		/* If absolute symlink, start from root. */
188 		if (*path == '/')
189 			p = resolved;
190 		goto loop;
191 	}
192 	if (*q == '/' && !S_ISDIR(sb.st_mode)) {
193 		errno = ENOTDIR;
194 		return (NULL);
195 	}
196 
197 	/* Advance both resolved and unresolved path. */
198 	p += 1 + q - path;
199 	path = q;
200 	goto loop;
201 }
202 
203 
204 #if defined(_FORTIFY_SOURCE) && !defined(__lint__)
205 #undef getcwd
206 #define getcwd _getcwd
207 #endif
208 
209 char *
210 getcwd(char *pt, size_t size)
211 {
212 	char *npt;
213 
214 	/*
215 	 * If a buffer is specified, the size has to be non-zero.
216 	 */
217 	if (pt != NULL) {
218 		if (size == 0) {
219 			/* __getcwd(pt, 0) results ERANGE. */
220 			errno = EINVAL;
221 			return (NULL);
222 		}
223 		if (__getcwd(pt, size) >= 0)
224 			return (pt);
225 		return (NULL);
226 	}
227 
228 	/*
229 	 * If no buffer specified by the user, allocate one as necessary.
230 	 */
231 	size = 1024 >> 1;
232 	do {
233 		if ((npt = realloc(pt, size <<= 1)) == NULL)
234 			break;
235 		pt = npt;
236 		if (__getcwd(pt, size) >= 0)
237 			return (pt);
238 	} while (size <= MAXPATHLEN * 4 && errno == ERANGE);
239 
240 	free(pt);
241 	return (NULL);
242 }
243