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