xref: /openbsd-src/lib/libc/stdlib/realpath.c (revision 7350f337b9e3eb4461d99580e625c7ef148d107c)
1 /*	$OpenBSD: realpath.c,v 1.26 2019/06/17 03:13:17 deraadt Exp $ */
2 /*
3  * Copyright (c) 2019 Bob Beck <beck@openbsd.org>
4  * Copyright (c) 2019 Theo de Raadt <deraadt@openbsd.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
13  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
15  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
16  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <limits.h>
24 #include <syslog.h>
25 #include <stdarg.h>
26 
27 int __realpath(const char *pathname, char *resolved);
28 PROTO_NORMAL(__realpath);
29 
30 /*
31  * wrapper for kernel __realpath
32  */
33 
34 char *
35 realpath(const char *path, char *resolved)
36 {
37 	char rbuf[PATH_MAX];
38 
39 	if (__realpath(path, rbuf) == -1) {
40 		/*
41 		 * XXX XXX XXX
42 		 *
43 		 * The old userland implementation strips trailing slashes.
44 		 * According to Dr. POSIX, realpathing "/bsd" should be fine,
45 		 * realpathing "/bsd/" should return ENOTDIR.
46 		 *
47 		 * Similar, but *different* to the above, The old userland
48 		 * implementation allows for realpathing "/nonexistent" but
49 		 * not "/nonexistent/", Both those should return ENOENT
50 		 * according to POSIX.
51 		 *
52 		 * This hack should go away once we decide to match POSIX.
53 		 * which we should as soon as is convenient.
54 		 */
55 		if (errno == ENOTDIR) {
56 			char pbuf[PATH_MAX];
57 			ssize_t i;
58 
59 			if (strlcpy(pbuf, path, sizeof(pbuf)) >= sizeof(pbuf)) {
60 				errno = ENAMETOOLONG;
61 				return NULL;
62 			}
63 			/* Try again without the trailing slashes. */
64 			for (i = strlen(pbuf); i > 1 && pbuf[i - 1] == '/'; i--)
65 				pbuf[i - 1] = '\0';
66 			if (__realpath(pbuf, rbuf) == -1)
67 				return NULL;
68 		} else
69 			return NULL;
70 	}
71 
72 	if (resolved == NULL)
73 		return (strdup(rbuf));
74 	strlcpy(resolved, rbuf, PATH_MAX);
75 	return (resolved);
76 }
77