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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
|
use camino::{Utf8Path, Utf8PathBuf};
use std::{fmt, io, ops::Deref, path::Display, str::FromStr};
use crate::RuntimeError;
/// Webpath is the path we get from HTTP requests. It's garunteed to not fall
/// below the webroot and will never start or end with a slash.
#[derive(Clone, Debug, PartialEq)]
pub struct Webpath {
pub webcanon: Utf8PathBuf,
is_dir: bool,
}
impl FromStr for Webpath {
type Err = RuntimeError;
fn from_str(raw: &str) -> Result<Self, Self::Err> {
let is_dir = raw.trim_end().ends_with('/');
let mut curr = Utf8PathBuf::new();
for component in raw.split('/') {
match component {
"." => continue,
".." => {
if !curr.pop() {
return Err(RuntimeError::PathTooLow {
path: raw.to_owned(),
});
}
}
comp => curr.push(comp),
}
}
Ok(Self {
webcanon: curr,
is_dir,
})
}
}
impl Webpath {
/// Return whether or not this Webpath is empty which would indicate it's
/// the homepage.
pub fn is_index(&self) -> bool {
self.webcanon == ""
}
/// Whether or not this Webpath points to a directory (has a trailing slash)
pub fn is_dir(&self) -> bool {
self.is_dir
}
/// Return a String that interprets this Webpath as a directory, adding a
/// trailing slash
pub fn as_dir(&self) -> String {
format!("/{}/", self.webcanon)
}
/// Returns the first directory of the Webpath. Assumes the path is a
/// directory if it ends in a `/`, otherwise pops the last component.
pub fn first_dir(&self) -> String {
if self.is_dir {
self.webcanon.to_string()
} else {
let mut dir = self.webcanon.clone();
dir.pop();
dir.to_string()
}
}
}
impl Deref for Webpath {
type Target = Utf8Path;
fn deref(&self) -> &Self::Target {
&self.webcanon
}
}
impl AsRef<Utf8Path> for Webpath {
fn as_ref(&self) -> &Utf8Path {
&self.webcanon
}
}
impl PartialEq<str> for Webpath {
fn eq(&self, other: &str) -> bool {
self.webcanon.eq(other)
}
}
impl fmt::Display for Webpath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "/{}", self.webcanon)
}
}
const ROOT_INDEX: &str = "home.html";
const DIRFILE_EXT: &str = "html";
pub struct PathResolution {
pub filepath: Utf8PathBuf,
pub is_dirfile: bool,
}
impl Deref for PathResolution {
type Target = Utf8Path;
fn deref(&self) -> &Self::Target {
self.filepath.as_path()
}
}
impl fmt::Display for PathResolution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", *self)
}
}
#[derive(Clone, Debug)]
pub struct Filesystem {
webroot: Utf8PathBuf,
}
impl Filesystem {
pub fn new<P: Into<Utf8PathBuf>>(root: P) -> Self {
Self {
webroot: root.into(),
}
}
pub fn resolve(&self, webpath: &Webpath) -> Result<PathResolution, RuntimeError> {
if webpath.is_index() || webpath == ROOT_INDEX {
return Ok(PathResolution {
filepath: self.webroot.join(ROOT_INDEX),
is_dirfile: false,
});
}
let path = self.webroot.join(webpath);
let metadata = Self::metadata(&path)?;
// If it's a file then return the path immediatly
if metadata.is_file() {
Ok(PathResolution {
filepath: path,
is_dirfile: false,
})
} else {
// we check this above. but still..
//TODO: gen- probably don't unwrap
let filename = path.file_name().unwrap();
let dirfile = path.join(format!("{filename}.{DIRFILE_EXT}"));
if dirfile.exists() {
Ok(PathResolution {
filepath: dirfile,
is_dirfile: true,
})
} else {
Err(RuntimeError::NotFound {
source: io::ErrorKind::NotFound.into(),
path: dirfile,
})
}
}
}
/// Resolve a file system path to a webpath.
///
/// Paths are not checked to see if they exist and are not checked to be within the webroot.
///
/// Paths attempt to resolve to the simplest form. For example, if the path is [`ROOT_INDEX`]
/// it will come out as `/` and if it is a dirfile, it will come out as a directory.
///
/// **FOOTGUN** currently assumes every path is a file...
pub fn reverse_resolve<P: AsRef<Utf8Path>>(&self, path: P) -> Result<Webpath, RuntimeError> {
let path = path.as_ref();
let relpath = match path.strip_prefix(&self.webroot) {
Ok(relpath) => relpath,
Err(_e) => {
if path.is_relative() {
path
} else {
//FIXME: gen- This error is not strictly correct, but it'll do for now.
// 2024-10-12
return Err(RuntimeError::PathTooLow {
path: path.to_string(),
});
}
}
};
if relpath == "" || relpath == ROOT_INDEX {
return Ok(Webpath {
webcanon: Utf8PathBuf::new(),
is_dir: true,
});
}
todo!();
Ok(Webpath {
webcanon: relpath.into(),
is_dir: false,
})
}
pub fn metadata<P: AsRef<Utf8Path>>(path: P) -> Result<std::fs::Metadata, RuntimeError> {
path.as_ref()
.metadata()
.map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned()))
}
pub async fn open<P: AsRef<Utf8Path>>(path: P) -> Result<tokio::fs::File, RuntimeError> {
tokio::fs::File::open(path.as_ref())
.await
.map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned()))
}
pub async fn read<P: AsRef<Utf8Path>>(path: P) -> Result<Vec<u8>, RuntimeError> {
tokio::fs::read(path.as_ref())
.await
.map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned()))
}
pub async fn read_to_string<P: AsRef<Utf8Path>>(path: P) -> Result<String, RuntimeError> {
tracing::trace!("read_to_string {}", path.as_ref());
tokio::fs::read_to_string(path.as_ref())
.await
.map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned()))
}
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use crate::fs::{Webpath, ROOT_INDEX};
use super::Filesystem;
macro_rules! webpath {
($location:expr) => {
Webpath::from_str($location).unwrap()
};
}
#[test]
fn webpath_finds_too_low() {
assert!(Webpath::from_str("/..").is_err());
assert!(Webpath::from_str("/one/..").is_ok());
assert!(Webpath::from_str("/one/../..").is_err());
assert!(Webpath::from_str("/one/../two").is_ok())
}
#[test]
fn webpath_path_correct() {
assert_eq!(Webpath::from_str("/one").unwrap().webcanon, "one");
assert_eq!(Webpath::from_str("/one/..").unwrap().webcanon, "");
assert_eq!(Webpath::from_str("/one/two/..").unwrap().webcanon, "one");
assert_eq!(Webpath::from_str("/one/../two").unwrap().webcanon, "two");
assert_eq!(
Webpath::from_str("/one/two/three/..").unwrap().webcanon,
"one/two"
);
assert_eq!(
Webpath::from_str("/one/../home.html").unwrap().webcanon,
"home.html"
);
}
const TESTROOT: &str = "test/serve";
#[test]
fn filesystem_resolves_index() {
let fs = Filesystem::new(TESTROOT);
assert_eq!(
fs.resolve(&webpath!("/")).unwrap().filepath,
format!("{TESTROOT}/{ROOT_INDEX}")
);
assert_eq!(
fs.resolve(&webpath!("/one/..")).unwrap().filepath,
format!("{TESTROOT}/{ROOT_INDEX}")
);
}
#[test]
fn filesystem_resolves_dirfile() {
let fs = Filesystem::new(TESTROOT);
assert_eq!(
fs.resolve(&webpath!("/one")).unwrap().filepath,
format!("{TESTROOT}/one/one.html")
);
assert_eq!(
fs.resolve(&webpath!("/one/eleven/")).unwrap().filepath,
format!("{TESTROOT}/one/eleven/eleven.html")
);
assert_eq!(
fs.resolve(&webpath!("/one/eleven/..")).unwrap().filepath,
format!("{TESTROOT}/one/one.html")
);
}
#[test]
fn filesystem_reverse_resolves_index() {
let fs = Filesystem::new(TESTROOT);
assert_eq!(fs.reverse_resolve(TESTROOT).unwrap(), webpath!("/"));
assert_eq!(
fs.reverse_resolve(format!("{TESTROOT}/{ROOT_INDEX}"))
.unwrap(),
webpath!("/")
)
}
#[test]
fn filesystem_reverse_resolves_directories() {
let fs = Filesystem::new(TESTROOT);
assert_eq!(fs.reverse_resolve("test/").unwrap(), webpath!("test/"))
}
}
|