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

use crate::http::Response;
use crate::into::IntoResponse;

use tokio::{io, fs};

use http::body::BodyWithTimeout;

use std::path::{ Path, PathBuf };
use std::convert::AsRef;
use std::str::Utf8Error;
use std::fmt;

use percent_encoding::percent_decode_str;

mod file;
pub use file::File;

mod partial_file;
pub use partial_file::{PartialFile, Range};

pub mod caching;
pub use caching::Caching;

pub mod static_files;
pub use static_files::{StaticFilesRoute, StaticFileRoute, serve_file};

/// returns io::Error not found if path is directory
pub async fn with_file<P>(path: P) -> io::Result<Response>
where P: AsRef<Path> {
	File::open(path).await
		.map(|f| f.into_response())
}

/// returns io::Error not found if path is directory
pub async fn with_partial_file<P>(path: P, range: Range) -> io::Result<Response>
where P: AsRef<Path> {
	PartialFile::open(path, range).await
		.map(|pf| pf.into_response())
}

/// Static get handler which servers/returns a file.
/// 
/// ## Example
/// ```
/// # use fire_http as fire;
/// use fire::get_with_file;
/// 
/// type Data = ();
/// 
/// get_with_file! { Index, "/" => "./www/index.html" }
/// ```
#[macro_export]
macro_rules! get_with_file {
	($name:ident, $($tt:tt)*) => (
		$crate::get_with_file!($name<Data>, $($tt)*);
	);
	($name:ident<$data_ty:ty>, $uri:expr => $path:expr) => (
		$crate::get!(
			$name<$data_ty>,
			$uri,
			|_r| -> $crate::Result<$crate::http::Response> {
				$crate::fs::with_file($path).await
					.map_err($crate::Error::from_client_io)
			}
		);
	)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntoPathBufError {
	TraversalAttack,
	InvalidCharacter,
	Utf8(Utf8Error)
}

impl fmt::Display for IntoPathBufError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(self, f)
	}
}

impl std::error::Error for IntoPathBufError {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		match self {
			Self::Utf8(u) => Some(u),
			_ => None
		}
	}
}

impl From<Utf8Error> for IntoPathBufError {
	fn from(e: Utf8Error) -> Self {
		Self::Utf8(e)
	}
}

pub trait IntoPathBuf {
	fn into_path_buf(self) -> Result<PathBuf, IntoPathBufError>;
}

impl IntoPathBuf for &str {
	fn into_path_buf(self) -> Result<PathBuf, IntoPathBufError> {

		let mut path_buf = PathBuf::new();

		for (i, part) in self.split('/').enumerate() {
			match (i, part) {
				(0, "") => continue,
				(_, "..") => { path_buf.pop(); },
				(_, ".") => continue,
				(_, p) => {

					let dec = percent_decode_str(p)
						.decode_utf8()?;

					if dec.contains('\\') ||
						dec.contains('/') ||
						dec.starts_with('.') {
						return Err(IntoPathBufError::InvalidCharacter)
					}

					path_buf.push(dec.as_ref());

				}
			}
		}

		Ok(path_buf)
	}
}


// TODO maybe return crate::Result
// because file::create should be a server Error
pub async fn write_body_to_file<P>(
	body: BodyWithTimeout,
	path: P
) -> io::Result<()>
where P: AsRef<Path> {
	let mut file = fs::File::create(path).await?;
	body.copy_to_async_write(&mut file).await
}