xref: /netbsd-src/lib/libc/gen/getcwd.c (revision daf6c4152fcddc27c445489775ed1f66ab4ea9a9)
1 /*	$NetBSD: getcwd.c,v 1.49 2011/02/16 20:20:25 tron 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.49 2011/02/16 20:20:25 tron 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,_sys_getcwd)
58 __weak_alias(_getcwd,_sys_getcwd)
59 __weak_alias(realpath,_realpath)
60 
61 #if !defined(lint)
62 #undef getcwd
63 #define getcwd _sys_getcwd
64 #if !defined(_FORTIFY_SOURCE)
65 char *_sys_getcwd(char *, size_t);
66 #endif
67 
68 #endif
69 #endif
70 
71 /*
72  * char *realpath(const char *path, char resolved[MAXPATHLEN]);
73  *
74  * Find the real name of path, by removing all ".", ".." and symlink
75  * components.  Returns (resolved) on success, or (NULL) on failure,
76  * in which case the path which caused trouble is left in (resolved).
77  */
78 char *
79 realpath(const char *path, char *resolved)
80 {
81 	struct stat sb;
82 	int idx = 0, n, nlnk = 0;
83 	const char *q;
84 	char *p, wbuf[2][MAXPATHLEN];
85 	size_t len;
86 
87 	_DIAGASSERT(resolved != NULL);
88 
89 	/* POSIX sez we must test for this */
90 	if (path == NULL) {
91 		errno = EINVAL;
92 		return NULL;
93 	}
94 
95 	/*
96 	 * Build real path one by one with paying an attention to .,
97 	 * .. and symbolic link.
98 	 */
99 
100 	/*
101 	 * `p' is where we'll put a new component with prepending
102 	 * a delimiter.
103 	 */
104 	p = resolved;
105 
106 	if (*path == 0) {
107 		*p = 0;
108 		errno = ENOENT;
109 		return (NULL);
110 	}
111 
112 	/* If relative path, start from current working directory. */
113 	if (*path != '/') {
114 		/* check for resolved pointer to appease coverity */
115 		if (resolved && getcwd(resolved, MAXPATHLEN) == NULL) {
116 			p[0] = '.';
117 			p[1] = 0;
118 			return (NULL);
119 		}
120 		len = strlen(resolved);
121 		if (len > 1)
122 			p += len;
123 	}
124 
125 loop:
126 	/* Skip any slash. */
127 	while (*path == '/')
128 		path++;
129 
130 	if (*path == 0) {
131 		if (p == resolved)
132 			*p++ = '/';
133 		*p = 0;
134 		return (resolved);
135 	}
136 
137 	/* Find the end of this component. */
138 	q = path;
139 	do
140 		q++;
141 	while (*q != '/' && *q != 0);
142 
143 	/* Test . or .. */
144 	if (path[0] == '.') {
145 		if (q - path == 1) {
146 			path = q;
147 			goto loop;
148 		}
149 		if (path[1] == '.' && q - path == 2) {
150 			/* Trim the last component. */
151 			if (p != resolved)
152 				while (*--p != '/')
153 					;
154 			path = q;
155 			goto loop;
156 		}
157 	}
158 
159 	/* Append this component. */
160 	if (p - resolved + 1 + q - path + 1 > MAXPATHLEN) {
161 		errno = ENAMETOOLONG;
162 		if (p == resolved)
163 			*p++ = '/';
164 		*p = 0;
165 		return (NULL);
166 	}
167 	p[0] = '/';
168 	memcpy(&p[1], path,
169 	    /* LINTED We know q > path. */
170 	    q - path);
171 	p[1 + q - path] = 0;
172 
173 	/*
174 	 * If this component is a symlink, toss it and prepend link
175 	 * target to unresolved path.
176 	 */
177 	if (lstat(resolved, &sb) == -1) {
178 		return (NULL);
179 	}
180 	if (S_ISLNK(sb.st_mode)) {
181 		if (nlnk++ >= MAXSYMLINKS) {
182 			errno = ELOOP;
183 			return (NULL);
184 		}
185 		n = readlink(resolved, wbuf[idx], sizeof(wbuf[0]) - 1);
186 		if (n < 0)
187 			return (NULL);
188 		if (n == 0) {
189 			errno = ENOENT;
190 			return (NULL);
191 		}
192 
193 		/* Append unresolved path to link target and switch to it. */
194 		if (n + (len = strlen(q)) + 1 > sizeof(wbuf[0])) {
195 			errno = ENAMETOOLONG;
196 			return (NULL);
197 		}
198 		memcpy(&wbuf[idx][n], q, len + 1);
199 		path = wbuf[idx];
200 		idx ^= 1;
201 
202 		/* If absolute symlink, start from root. */
203 		if (*path == '/')
204 			p = resolved;
205 		goto loop;
206 	}
207 	if (*q == '/' && !S_ISDIR(sb.st_mode)) {
208 		errno = ENOTDIR;
209 		return (NULL);
210 	}
211 
212 	/* Advance both resolved and unresolved path. */
213 	p += 1 + q - path;
214 	path = q;
215 	goto loop;
216 }
217 
218 char *
219 getcwd(char *pt, size_t size)
220 {
221 	char *npt;
222 
223 	/*
224 	 * If a buffer is specified, the size has to be non-zero.
225 	 */
226 	if (pt != NULL) {
227 		if (size == 0) {
228 			/* __getcwd(pt, 0) results ERANGE. */
229 			errno = EINVAL;
230 			return (NULL);
231 		}
232 		if (__getcwd(pt, size) >= 0)
233 			return (pt);
234 		return (NULL);
235 	}
236 
237 	/*
238 	 * If no buffer specified by the user, allocate one as necessary.
239 	 */
240 	size = 1024 >> 1;
241 	do {
242 		if ((npt = realloc(pt, size <<= 1)) == NULL)
243 			break;
244 		pt = npt;
245 		if (__getcwd(pt, size) >= 0)
246 			return (pt);
247 	} while (size <= MAXPATHLEN * 4 && errno == ERANGE);
248 
249 	free(pt);
250 	return (NULL);
251 }
252