forked from ish-app/ish
-
Notifications
You must be signed in to change notification settings - Fork 12
/
path.c
85 lines (78 loc) · 2.7 KB
/
path.c
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
#include <string.h>
#include "sys/calls.h"
#include "fs/path.h"
int path_normalize(const char *path, char *out, bool follow_links) {
const char *p = path;
char *o = out;
*o = '\0';
int n = MAX_PATH - 1;
// start with root or cwd, depending on whether it starts with a slash
if (*p == '/') {
strcpy(o, current->root);
n -= strlen(current->root);
o += strlen(current->root);
// if it does start with a slash, make sure to skip all the slashes
while (*p == '/')
p++;
} else {
strcpy(o, current->pwd);
n -= strlen(current->pwd);
o += strlen(current->pwd);
}
while (*p != '\0') {
if (p[0] == '.') {
if (p[1] == '\0' || p[1] == '/') {
// single dot path component, ignore
p++;
while (*p == '/')
p++;
continue;
} else if (p[1] == '.' && (p[2] == '\0' || p[2] == '/')) {
// double dot path component, delete the last component
do {
o--;
n++;
} while (*o != '/');
p += 2;
while (*p == '/')
p++;
continue;
}
}
// output a slash
*o++ = '/'; n--;
char *c = o;
// copy up to a slash or null
while (*p != '/' && *p != '\0' && --n > 0)
*o++ = *p++;
// eat any slashes
while (*p == '/')
p++;
if (n == 0)
return _ENAMETOOLONG;
if (follow_links || *p != '\0') {
// this buffer is used to store the path that we're readlinking, then
// if it turns out to point to a symlink it's reused as the buffer
// passed to the next path_normalize call
char possible_symlink[MAX_PATH];
strcpy(possible_symlink, out);
possible_symlink[o - out] = '\0';
struct mount *mount = find_mount_and_trim_path(possible_symlink);
int res = mount->fs->readlink(mount, possible_symlink, c, MAX_PATH - (c - out));
if (res >= 0) {
// readlink does not null terminate
c[res] = '\0';
// if we should restart from the root, copy down
if (*c == '/')
memmove(out, c, strlen(c) + 1);
char *expanded_path = possible_symlink;
strcpy(expanded_path, out);
strcat(expanded_path, "/");
strcat(expanded_path, p);
return path_normalize(expanded_path, out, follow_links);
}
}
}
*o = '\0';
return 0;
}