2011-02-12 00:22:29 -05:00
|
|
|
#include <stdlib.h>
|
2011-04-17 17:32:36 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <limits.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <unistd.h>
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2012-09-06 22:44:55 -04:00
|
|
|
char *realpath(const char *restrict filename, char *restrict resolved)
|
2011-02-12 00:22:29 -05:00
|
|
|
{
|
2011-04-17 17:32:36 -04:00
|
|
|
int fd;
|
|
|
|
ssize_t r;
|
|
|
|
struct stat st1, st2;
|
|
|
|
char buf[15+3*sizeof(int)];
|
|
|
|
int alloc = 0;
|
|
|
|
|
|
|
|
if (!filename) {
|
|
|
|
errno = EINVAL;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2012-09-29 17:59:50 -04:00
|
|
|
fd = open(filename, O_RDONLY|O_NONBLOCK|O_CLOEXEC);
|
2011-06-18 07:41:14 -04:00
|
|
|
if (fd < 0) return 0;
|
|
|
|
snprintf(buf, sizeof buf, "/proc/self/fd/%d", fd);
|
|
|
|
|
2011-04-17 17:32:36 -04:00
|
|
|
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);
|
2011-02-12 00:22:29 -05:00
|
|
|
return 0;
|
|
|
|
}
|