aboutsummaryrefslogtreecommitdiffstats
path: root/readmagiclink.c
blob: 160dd96f1743fe95eeedc025ccebcd2432ade910 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


char *
libsimple_readmagiclink(const char *path)
{
	int fd;
	struct stat st;
	char *target1;
	char *target2;

	fd = open(path, O_PATH | O_NOFOLLOW);
	if (fd < 0)
		return NULL;

	target1 = libsimple_efreadlink(fd);
	if (!strends(target1, " (deleted)")) {
		close(fd);
		return target1;
	}

	if (fstat(fd, &st)) {
		free(target1);
		close(fd);
		return NULL;
	}

	target2 = libsimple_efreadlink(fd);
	if (!strends(target2, " (deleted)")) {
		free(target1);
		close(fd);
		return target2;
	}

	close(fd);

	if (strcmp(target1, target2)) {
		free(target2);
		return target1;
	} else {
		free(target1);
		if (st.st_nlink)
			return target2;
		target2[strlen(target2) - (sizeof(" (deleted)") - 1U)] = '\0';
		return target2;
	}
}


#else
#include "test.h"

int
main(void) /* TODO test */
{
	return 0;
}

#endif