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