about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorRich Felker <dalias@aerifal.cx>2011-04-17 17:32:36 -0400
committerRich Felker <dalias@aerifal.cx>2011-04-17 17:32:36 -0400
commite98bdca9df8df791fe93ec8eec920fa8d14da1f5 (patch)
treea3cd1fc61d5f51911a2f67981dbd552ce42e73c9 /src
parent2afed79f15a32e9616a27f9d327cef0cefbbaab1 (diff)
downloadmusl-e98bdca9df8df791fe93ec8eec920fa8d14da1f5.tar.gz
musl-e98bdca9df8df791fe93ec8eec920fa8d14da1f5.tar.xz
musl-e98bdca9df8df791fe93ec8eec920fa8d14da1f5.zip
minimal realpath implementation using /proc
clean and simple, but fails when the caller does not have permissions
to open the file for reading or when /proc is not available. i may
replace this with a full implementation later, possibly leaving this
version as an optimization to use when it works.
Diffstat (limited to 'src')
-rw-r--r--src/misc/realpath.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/misc/realpath.c b/src/misc/realpath.c
index f6b55495..8dcf5ec9 100644
--- a/src/misc/realpath.c
+++ b/src/misc/realpath.c
@@ -1,6 +1,49 @@
 #include <stdlib.h>
+#include <stdio.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <unistd.h>
 
 char *realpath(const char *filename, char *resolved)
 {
+	int fd;
+	ssize_t r;
+	struct stat st1, st2;
+	char buf[15+3*sizeof(int)];
+	int alloc = 0;
+
+	if (!filename) {
+		errno = EINVAL;
+		return 0;
+	}
+
+	if (!resolved) {
+		alloc = 1;
+		resolved = malloc(PATH_MAX);
+		if (!resolved) return 0;
+	}
+
+	fd = open(filename, O_RDONLY|O_NONBLOCK);
+	if (fd < 0) return 0;
+	snprintf(buf, sizeof buf, "/proc/self/fd/%d", fd);
+
+	r = readlink(buf, resolved, PATH_MAX-1);
+	if (r < 0) goto err;
+	resolved[r] = 0;
+
+	fstat(fd, &st1);
+	r = stat(resolved, &st2);
+	if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
+		if (!r) errno = ELOOP;
+		goto err;
+	}
+
+	close(fd);
+	return resolved;
+err:
+	if (alloc) free(resolved);
+	close(fd);
 	return 0;
 }