summaryrefslogtreecommitdiff
path: root/src/misc/realpath.c
blob: d2708e59da426b8d7210cd540f6a786e11c3e6f2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "syscall.h"

char *realpath(const char *restrict filename, char *restrict resolved)
{
	int fd;
	ssize_t r;
	struct stat st1, st2;
	char buf[15+3*sizeof(int)];
	char tmp[PATH_MAX];

	if (!filename) {
		errno = EINVAL;
		return 0;
	}

	fd = sys_open(filename, O_PATH|O_NONBLOCK|O_CLOEXEC);
	if (fd < 0) return 0;
	__procfdname(buf, fd);

	r = readlink(buf, tmp, sizeof tmp - 1);
	if (r < 0) goto err;
	tmp[r] = 0;

	fstat(fd, &st1);
	r = stat(tmp, &st2);
	if (r<0 || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) {
		if (!r) errno = ELOOP;
		goto err;
	}

	__syscall(SYS_close, fd);
	return resolved ? strcpy(resolved, tmp) : strdup(tmp);
err:
	__syscall(SYS_close, fd);
	return 0;
}