X-Git-Url: http://nsz.repo.hu/git/?a=blobdiff_plain;f=src%2Fmisc%2Frealpath.c;h=183351462519b99912265da7a87a11489dd8f1b9;hb=31a55f233b313030a787240b76c06f2d08cde29f;hp=f6b55495781b4dbefaba09b4d33393ac476e0688;hpb=0b44a0315b47dd8eced9f3b7f31580cf14bbfc01;p=musl diff --git a/src/misc/realpath.c b/src/misc/realpath.c index f6b55495..18335146 100644 --- a/src/misc/realpath.c +++ b/src/misc/realpath.c @@ -1,6 +1,49 @@ #include +#include +#include +#include +#include +#include +#include -char *realpath(const char *filename, char *resolved) +char *realpath(const char *restrict filename, char *restrict 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; + } + + fd = open(filename, O_RDONLY|O_NONBLOCK|O_CLOEXEC); + if (fd < 0) return 0; + snprintf(buf, sizeof buf, "/proc/self/fd/%d", fd); + + if (!resolved) { + alloc = 1; + resolved = malloc(PATH_MAX); + if (!resolved) return 0; + } + + 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; }