xref: /freebsd/lib/libc/stdlib/realpath.c (revision df21a004be237a1dccd03c7b47254625eea62fa9)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2003 Constantin S. Svintsoff <kostik@iclub.nsu.ru>
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. The names of the authors may not be used to endorse or promote
15  *    products derived from this software without specific prior written
16  *    permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 #include <sys/param.h>
32 #include <sys/stat.h>
33 
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <libsys.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <ssp/ssp.h>
41 
42 /*
43  * Find the real name of path, by removing all ".", ".." and symlink
44  * components.  Returns (resolved) on success, or (NULL) on failure,
45  * in which case the path which caused trouble is left in (resolved).
46  */
47 static char * __noinline
48 realpath1(const char *path, char *resolved)
49 {
50 	struct stat sb;
51 	char *p, *q;
52 	size_t left_len, prev_len, resolved_len, next_token_len;
53 	unsigned symlinks;
54 	ssize_t slen;
55 	char left[PATH_MAX], next_token[PATH_MAX], symlink[PATH_MAX];
56 
57 	symlinks = 0;
58 	if (path[0] == '/') {
59 		resolved[0] = '/';
60 		resolved[1] = '\0';
61 		if (path[1] == '\0')
62 			return (resolved);
63 		resolved_len = 1;
64 		left_len = strlcpy(left, path + 1, sizeof(left));
65 	} else {
66 		if (getcwd(resolved, PATH_MAX) == NULL) {
67 			resolved[0] = '.';
68 			resolved[1] = '\0';
69 			return (NULL);
70 		}
71 		resolved_len = strlen(resolved);
72 		left_len = strlcpy(left, path, sizeof(left));
73 	}
74 	if (left_len >= sizeof(left) || resolved_len >= PATH_MAX) {
75 		errno = ENAMETOOLONG;
76 		return (NULL);
77 	}
78 
79 	/*
80 	 * Iterate over path components in `left'.
81 	 */
82 	while (left_len != 0) {
83 		/*
84 		 * Extract the next path component and adjust `left'
85 		 * and its length.
86 		 */
87 		p = strchr(left, '/');
88 
89 		next_token_len = p != NULL ? (size_t)(p - left) : left_len;
90 		memcpy(next_token, left, next_token_len);
91 		next_token[next_token_len] = '\0';
92 
93 		if (p != NULL) {
94 			left_len -= next_token_len + 1;
95 			memmove(left, p + 1, left_len + 1);
96 		} else {
97 			left[0] = '\0';
98 			left_len = 0;
99 		}
100 
101 		prev_len = resolved_len;
102 		if (resolved[resolved_len - 1] != '/') {
103 			if (resolved_len + 1 >= PATH_MAX) {
104 				errno = ENAMETOOLONG;
105 				return (NULL);
106 			}
107 			resolved[resolved_len++] = '/';
108 			resolved[resolved_len] = '\0';
109 		}
110 		if (next_token[0] == '\0') {
111 			/* Handle consequential slashes. */
112 			continue;
113 		} else if (strcmp(next_token, ".") == 0) {
114 			continue;
115 		} else if (strcmp(next_token, "..") == 0) {
116 			/*
117 			 * Strip the last path component except when we have
118 			 * single "/"
119 			 */
120 			if (resolved_len > 1) {
121 				resolved[resolved_len - 1] = '\0';
122 				q = strrchr(resolved, '/') + 1;
123 				*q = '\0';
124 				resolved_len = q - resolved;
125 			}
126 			continue;
127 		}
128 
129 		/*
130 		 * Append the next path component and lstat() it.
131 		 */
132 		resolved_len = strlcat(resolved, next_token, PATH_MAX);
133 		if (resolved_len >= PATH_MAX) {
134 			errno = ENAMETOOLONG;
135 			return (NULL);
136 		}
137 		if (lstat(resolved, &sb) != 0) {
138 			/*
139 			 * EACCES means the parent directory is not
140 			 * readable, while ENOTDIR means the parent
141 			 * directory is not a directory.  Rewind the path
142 			 * to correctly indicate where the error lies.
143 			 */
144 			if (errno == EACCES || errno == ENOTDIR)
145 				resolved[prev_len] = '\0';
146 			return (NULL);
147 		}
148 		if (S_ISLNK(sb.st_mode)) {
149 			if (symlinks++ > MAXSYMLINKS) {
150 				errno = ELOOP;
151 				return (NULL);
152 			}
153 			slen = readlink(resolved, symlink, sizeof(symlink));
154 			if (slen < 0)
155 				return (NULL);
156 			if (slen == 0) {
157 				errno = ENOENT;
158 				return (NULL);
159 			}
160 			if ((size_t)slen >= sizeof(symlink)) {
161 				errno = ENAMETOOLONG;
162 				return (NULL);
163 			}
164 			symlink[slen] = '\0';
165 			if (symlink[0] == '/') {
166 				resolved[1] = 0;
167 				resolved_len = 1;
168 			} else {
169 				/* Strip the last path component. */
170 				q = strrchr(resolved, '/') + 1;
171 				*q = '\0';
172 				resolved_len = q - resolved;
173 			}
174 
175 			/*
176 			 * If there are any path components left, then
177 			 * append them to symlink. The result is placed
178 			 * in `left'.
179 			 */
180 			if (p != NULL) {
181 				if (symlink[slen - 1] != '/') {
182 					if ((size_t)slen + 1 >= sizeof(symlink)) {
183 						errno = ENAMETOOLONG;
184 						return (NULL);
185 					}
186 					symlink[slen] = '/';
187 					symlink[slen + 1] = 0;
188 				}
189 				left_len = strlcat(symlink, left,
190 				    sizeof(symlink));
191 				if (left_len >= sizeof(symlink)) {
192 					errno = ENAMETOOLONG;
193 					return (NULL);
194 				}
195 			}
196 			left_len = strlcpy(left, symlink, sizeof(left));
197 		} else if (!S_ISDIR(sb.st_mode) && p != NULL) {
198 			errno = ENOTDIR;
199 			return (NULL);
200 		}
201 	}
202 
203 	/*
204 	 * Remove trailing slash except when the resolved pathname
205 	 * is a single "/".
206 	 */
207 	if (resolved_len > 1 && resolved[resolved_len - 1] == '/')
208 		resolved[resolved_len - 1] = '\0';
209 	return (resolved);
210 }
211 
212 char *
213 __ssp_real(realpath)(const char * __restrict path, char * __restrict resolved)
214 {
215 	char *m, *res;
216 
217 	if (path == NULL) {
218 		errno = EINVAL;
219 		return (NULL);
220 	}
221 	if (path[0] == '\0') {
222 		errno = ENOENT;
223 		return (NULL);
224 	}
225 	if (resolved != NULL) {
226 		m = NULL;
227 	} else {
228 		m = resolved = malloc(PATH_MAX);
229 		if (resolved == NULL)
230 			return (NULL);
231 	}
232 	if (__sys___realpathat(AT_FDCWD, path, resolved, PATH_MAX, 0) == 0) {
233 		return (resolved);
234 	}
235 	res = realpath1(path, resolved);
236 	if (res == NULL)
237 		free(m);
238 	return (res);
239 }
240