about summary refs log tree commit diff
path: root/src/fs.rs
blob: b44e4c481e1df0b510cdedf5473f65e8bbb27e66 (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
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
use camino::{Utf8Path, Utf8PathBuf};
use core::fmt;
use std::{io, ops::Deref, 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 {
	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)
	}
}

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,
}

#[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> {
		println!("resolve = {webpath}");
		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,
				})
			}
		}
	}

	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> {
		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")
		);
	}
}