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