- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.c
More file actions
Latest commit
68 lines (62 loc) · 1.49 KB
/
Copy pathurl.c
File metadata and controls
68 lines (62 loc) · 1.49 KB
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
#include"url.h"
#include<assert.h>
#include<ctype.h>
//takes character 0-9 | a-f | A-F and returns corresponding hex value
staticintdecode_hex_char(charc) {
if('0' <= c&&c <= '9') returnc-'0';
if('A' <= c&&c <= 'F') returnc-'A'+10;
if('A' <= c&&c <= 'f') returnc-'a'+10;
return-1;
}
//percent decodes string in place, returns -1 on invalid encoding
intpercent_decode(char*str, int*len) {
assert(str);
assert(len);
char*spos=str, *dpos=str;
inthas_null=0;
while(*spos) {
//found beginning of percent encoded character
if(*spos=='%') {
//check that encoding is valid
if(!(isxdigit(spos[1]) &&isxdigit(spos[2]))) {
return-1;
}
*dpos= (char)((decode_hex_char(spos[1]) << 4) +decode_hex_char(spos[2]));
//check for percent encoded null bytes
if(!*dpos) {
has_null=1;
}
++dpos;
spos+=3;
} else {
*dpos++=*spos++;
}
}
*dpos='\0';
*len= (int)(dpos-str);
returnhas_null;
}
intsafe_path(constchar*path) {
assert(path);
constchar*pos=path;
if(*path=='/') {
return0;
}
while(*pos) {
if(pos[0] =='.'&&pos[1] =='.') {
//check for patterns:
//"<start of string>..\0" => path = ".."
//"<start of string>../" => path starts with "../"
//"/..\0" => path ends with "/.."
//"/../" => path contains
if((pos==path||*(pos-1) =='/') &&
(pos[2] =='/'||pos[2] =='\0')) {
return0;
}
} elseif(pos[0] =='/'&&pos[1] =='/') {
return0;
}
++pos;
}
return1;
}