xref: /dragonfly/lib/libc/gen/getcwd.c (revision 1de703da)
1 /*
2  * Copyright (c) 1989, 1991, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libc/gen/getcwd.c,v 1.18 1999/09/28 13:24:13 marcel Exp $
34  * $DragonFly: src/lib/libc/gen/getcwd.c,v 1.2 2003/06/17 04:26:42 dillon Exp $
35  *
36  * @(#)getcwd.c	8.5 (Berkeley) 2/7/95
37  */
38 
39 #include <sys/param.h>
40 #include <sys/stat.h>
41 
42 #include <dirent.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <signal.h>
50 
51 #define	ISDOT(dp) \
52 	(dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
53 	    (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
54 
55 static int have__getcwd = 1;	/* 0 = no, 1 = perhaps, 2 = yes */
56 
57 char *
58 getcwd(pt, size)
59 	char *pt;
60 	size_t size;
61 {
62 	register struct dirent *dp;
63 	register DIR *dir = NULL;
64 	register dev_t dev;
65 	register ino_t ino;
66 	register int first;
67 	register char *bpt, *bup;
68 	struct stat s;
69 	dev_t root_dev;
70 	ino_t root_ino;
71 	size_t ptsize, upsize;
72 	int save_errno;
73 	char *ept, *eup, *up, c;
74 
75 	/*
76 	 * If no buffer specified by the user, allocate one as necessary.
77 	 * If a buffer is specified, the size has to be non-zero.  The path
78 	 * is built from the end of the buffer backwards.
79 	 */
80 	if (pt) {
81 		ptsize = 0;
82 		if (!size) {
83 			errno = EINVAL;
84 			return (NULL);
85 		}
86 		if (size == 1) {
87 			errno = ERANGE;
88 			return (NULL);
89 		}
90 		ept = pt + size;
91 	} else {
92 		if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
93 			return (NULL);
94 		ept = pt + ptsize;
95 	}
96 #if	defined(__NETBSD_SYSCALLS)
97 	have__getcwd = 0;
98 #else
99 	if (have__getcwd) {
100 		struct sigaction sa, osa;
101 		int sigsys_installed = 0;
102 		int ret;
103 
104 		if (have__getcwd == 1) {	/* unsure? */
105 			sigemptyset(&sa.sa_mask);
106 			sa.sa_flags = 0;
107 			sa.sa_handler = SIG_IGN;
108 			if (sigaction(SIGSYS, &sa, &osa) >= 0)
109 				sigsys_installed = 1;
110 		}
111 		ret = __getcwd(pt, ept - pt);
112 		if (sigsys_installed == 1) {
113 			int oerrno = errno;
114 			sigaction(SIGSYS, &osa, NULL);
115 			errno = oerrno;
116 		}
117 		/* XXX a bogus syscall seems to return EINVAL(!) */
118 		if (ret < 0 && (errno == ENOSYS || errno == EINVAL))
119 			have__getcwd = 0;
120 		else if (have__getcwd == 1)
121 			have__getcwd = 2;	/* yep, remember we have it */
122 		if (ret == 0) {
123 			if (*pt != '/') {
124 				bpt = pt;
125 				ept = pt + strlen(pt) - 1;
126 				while (bpt < ept) {
127 					c = *bpt;
128 					*bpt++ = *ept;
129 					*ept-- = c;
130 				}
131 			}
132 			return (pt);
133 		}
134 	}
135 #endif
136 	bpt = ept - 1;
137 	*bpt = '\0';
138 
139 	/*
140 	 * Allocate bytes (1024 - malloc space) for the string of "../"'s.
141 	 * Should always be enough (it's 340 levels).  If it's not, allocate
142 	 * as necessary.  Special case the first stat, it's ".", not "..".
143 	 */
144 	if ((up = malloc(upsize = 1024 - 4)) == NULL)
145 		goto err;
146 	eup = up + MAXPATHLEN;
147 	bup = up;
148 	up[0] = '.';
149 	up[1] = '\0';
150 
151 	/* Save root values, so know when to stop. */
152 	if (stat("/", &s))
153 		goto err;
154 	root_dev = s.st_dev;
155 	root_ino = s.st_ino;
156 
157 	errno = 0;			/* XXX readdir has no error return. */
158 
159 	for (first = 1;; first = 0) {
160 		/* Stat the current level. */
161 		if (lstat(up, &s))
162 			goto err;
163 
164 		/* Save current node values. */
165 		ino = s.st_ino;
166 		dev = s.st_dev;
167 
168 		/* Check for reaching root. */
169 		if (root_dev == dev && root_ino == ino) {
170 			*--bpt = '/';
171 			/*
172 			 * It's unclear that it's a requirement to copy the
173 			 * path to the beginning of the buffer, but it's always
174 			 * been that way and stuff would probably break.
175 			 */
176 			bcopy(bpt, pt, ept - bpt);
177 			free(up);
178 			return (pt);
179 		}
180 
181 		/*
182 		 * Build pointer to the parent directory, allocating memory
183 		 * as necessary.  Max length is 3 for "../", the largest
184 		 * possible component name, plus a trailing NULL.
185 		 */
186 		if (bup + 3  + MAXNAMLEN + 1 >= eup) {
187 			if ((up = reallocf(up, upsize *= 2)) == NULL)
188 				goto err;
189 			bup = up;
190 			eup = up + upsize;
191 		}
192 		*bup++ = '.';
193 		*bup++ = '.';
194 		*bup = '\0';
195 
196 		/* Open and stat parent directory. */
197 		if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
198 			goto err;
199 
200 		/* Add trailing slash for next directory. */
201 		*bup++ = '/';
202 		*bup = '\0';
203 
204 		/*
205 		 * If it's a mount point, have to stat each element because
206 		 * the inode number in the directory is for the entry in the
207 		 * parent directory, not the inode number of the mounted file.
208 		 */
209 		save_errno = 0;
210 		if (s.st_dev == dev) {
211 			for (;;) {
212 				if (!(dp = readdir(dir)))
213 					goto notfound;
214 				if (dp->d_fileno == ino)
215 					break;
216 			}
217 		} else
218 			for (;;) {
219 				if (!(dp = readdir(dir)))
220 					goto notfound;
221 				if (ISDOT(dp))
222 					continue;
223 				bcopy(dp->d_name, bup, dp->d_namlen + 1);
224 
225 				/* Save the first error for later. */
226 				if (lstat(up, &s)) {
227 					if (!save_errno)
228 						save_errno = errno;
229 					errno = 0;
230 					continue;
231 				}
232 				if (s.st_dev == dev && s.st_ino == ino)
233 					break;
234 			}
235 
236 		/*
237 		 * Check for length of the current name, preceding slash,
238 		 * leading slash.
239 		 */
240 		if (bpt - pt < dp->d_namlen + (first ? 1 : 2)) {
241 			size_t len, off;
242 
243 			if (!ptsize) {
244 				errno = ERANGE;
245 				goto err;
246 			}
247 			off = bpt - pt;
248 			len = ept - bpt;
249 			if ((pt = realloc(pt, ptsize *= 2)) == NULL)
250 				goto err;
251 			bpt = pt + off;
252 			ept = pt + ptsize;
253 			bcopy(bpt, ept - len, len);
254 			bpt = ept - len;
255 		}
256 		if (!first)
257 			*--bpt = '/';
258 		bpt -= dp->d_namlen;
259 		bcopy(dp->d_name, bpt, dp->d_namlen);
260 		(void) closedir(dir);
261 		dir = NULL;
262 
263 		/* Truncate any file name. */
264 		*bup = '\0';
265 	}
266 
267 notfound:
268 	/*
269 	 * If readdir set errno, use it, not any saved error; otherwise,
270 	 * didn't find the current directory in its parent directory, set
271 	 * errno to ENOENT.
272 	 */
273 	if (!errno)
274 		errno = save_errno ? save_errno : ENOENT;
275 	/* FALLTHROUGH */
276 err:
277 	save_errno = errno;
278 
279 	if (ptsize)
280 		free(pt);
281 	if (dir)
282 		(void) closedir(dir);
283 	free(up);
284 
285 	errno = save_errno;
286 	return (NULL);
287 }
288