-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathHandler.affine
More file actions
99 lines (85 loc) · 2.14 KB
/
Copy pathPathHandler.affine
File metadata and controls
99 lines (85 loc) · 2.14 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 hyperpolymath
module PathHandler;
use prelude::{Option, Some, None, Result, Ok, Err};
use string::{contains, ends_with, starts_with};
use SafePath::{is_safe, safe_join, sanitize_filename};
pub type PathError = TraversalDetected | InvalidPath | PermissionDenied | NotFound;
pub type ValidatedPath = | VP(String);
pub fn unwrap_path(p: ValidatedPath) -> String {
match p {
VP(s) => s
}
}
pub fn validate(path: String) -> Option<ValidatedPath> {
if is_safe(path) {
Some(VP(path))
} else {
None
}
}
pub fn path_join(base: ValidatedPath, components: [String]) -> Result<ValidatedPath, PathError> {
let base_str = unwrap_path(base);
match safe_join(base_str, components) {
Some(joined) => Ok(VP(joined)),
None => Err(TraversalDetected)
}
}
pub fn sanitize(filename: String) -> String {
sanitize_filename(filename)
}
pub fn is_within(path: ValidatedPath, base: ValidatedPath) -> Bool {
let path_str = unwrap_path(path);
let base_str = unwrap_path(base);
starts_with(path_str, base_str)
}
pub fn get_parent(path: ValidatedPath) -> Option<ValidatedPath> {
let s = unwrap_path(path);
let n = len(s);
let mut last_slash = 0 - 1;
let mut i = 0;
while i < n {
if char_to_int(string_get(s, i)) == 47 {
last_slash = i;
}
i = i + 1;
}
if last_slash <= 0 {
None
} else {
Some(VP(string_sub(s, 0, last_slash)))
}
}
pub fn filename(path: ValidatedPath) -> String {
let s = unwrap_path(path);
let n = len(s);
let mut last_slash = 0 - 1;
let mut i = 0;
while i < n {
if char_to_int(string_get(s, i)) == 47 {
last_slash = i;
}
i = i + 1;
}
if last_slash < 0 {
s
} else {
string_sub(s, last_slash + 1, n - last_slash - 1)
}
}
pub fn has_extension(path: ValidatedPath, ext: String) -> Bool {
let s = unwrap_path(path);
ends_with(s, ext)
}
pub fn from_trusted(path: String) -> ValidatedPath {
VP(path)
}
pub fn is_excluded(path: ValidatedPath, excludes: [String]) -> Bool {
let s = unwrap_path(path);
for excl in excludes {
if contains(s, excl) {
return true;
}
}
false
}