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