Welcome to mirror list, hosted at ThFree Co, Russian Federation.

realpath.c « linux « sys « libc « newlib - cygwin.com/git/newlib-cygwin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8aa5eb445fca813a2e21b67cc9ba35523620d31f (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* realpath.c - Return the canonicalized absolute pathname */

/* Written 2000 by Werner Almesberger */


#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <sys/stat.h>


/* FIXME: buffer overrun possible, loops forever on cyclic symlinks */


/*
 * Canonical name: never ends with a slash
 */

static int resolve_path(char *path,char *result,char *pos)
{
    if (*path == '/') {
	*result = '/';
	pos = result+1;
	path++;
    }
    *pos = 0;
    if (!*path) return 0;
    while (1) {
	char *slash;
	struct stat st;

	slash = *path ? strchr(path,'/') : NULL;
	if (slash) *slash = 0;
	if (!path[0] || (path[0] == '.' &&
	  (!path[1] || (path[1] == '.' && !path[2])))) {
	    pos--;
	    if (pos != result && path[0] && path[1])
		while (*--pos != '/');
	}
	else {
	    strcpy(pos,path);
	    if (lstat(result,&st) < 0) return -1;
	    if (S_ISLNK(st.st_mode)) {
		char buf[PATH_MAX];

		if (readlink(result,buf,sizeof(buf)) < 0) return -1;
		*pos = 0;
		if (slash) {
		    *slash = '/';
		    strcat(buf,slash);
		}
		strcpy(path,buf);
		if (*path == '/') result[1] = 0;
		pos = strchr(result,0);
		continue;
	    }
	    pos = strchr(result,0);
	}
	if (slash) {
	    *pos++ = '/';
	    path = slash+1;
	}
	*pos = 0;
	if (!slash) break;
    }
    return 0;
}


char *realpath(const char *path,char *resolved_path)
{
    char cwd[PATH_MAX];
    char *path_copy;
    int res;

    if (!*path) {
	errno = ENOENT; /* SUSv2 */
	return NULL;
    }
    if (!getcwd(cwd,sizeof(cwd))) return NULL;
    strcpy(resolved_path,"/");
    if (resolve_path(cwd,resolved_path,resolved_path)) return NULL;
    strcat(resolved_path,"/");
    path_copy = strdup(path);
    if (!path_copy) return NULL;
    res = resolve_path(path_copy,resolved_path,strchr(resolved_path,0));
    free(path_copy);
    if (res) return NULL;
    return resolved_path;
}