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
|
#![allow(dead_code)]
use std::{
ffi::OsString,
os::unix::ffi::OsStringExt,
path::{Component, Path, PathBuf},
process::ExitCode,
};
use mlua::{Function, Lua, Table};
use tokio::{
io::{self, BufReader, BufWriter},
net::{TcpListener, TcpStream},
};
use crate::{
client::Client,
handler::{Handle, Handler},
request::Request,
response::{Response, Status},
};
mod client;
mod handler;
mod request;
mod response;
macro_rules! exit {
($fmt:literal, $($s:expr),*) => {
{
eprintln!($fmt, $($s),*);
return ::std::process::ExitCode::FAILURE
}
}
}
#[derive(Debug, thiserror::Error)]
enum HandleError {
#[error("error reading handler function: {0}")]
Function(mlua::Error),
#[error("error calling handler: {0}")]
InvokeHandler(mlua::Error),
#[error("handler error: {0}")]
Handler(#[from] handler::Error),
}
#[derive(Debug, thiserror::Error)]
enum ResponseError {
#[error("error reading request: {0}")]
Request(request::Error),
#[error("error sending response: {0}")]
Response(io::Error),
}
#[derive(Debug, thiserror::Error)]
enum InitLuaError {
#[error("failed to create variable: {0}")]
CreateTable(mlua::Error),
#[error("failed to create helper function: {0}")]
Function(mlua::Error),
#[error("failed to set variable {1}: {0}")]
SetVar(mlua::Error, String),
#[error("failed to load variable {1}: {0}")]
LoadVar(mlua::Error, String),
#[error("failed to load config: {0}")]
LoadConfig(std::io::Error),
#[error("failed to eval config: {0}")]
EvalConfig(mlua::Error),
}
async fn handle(handlers: Table, request: Request) -> Result<Response, HandleError> {
let method = request.method().to_string();
let function = handlers
.get::<Function>(method.as_str())
.map_err(HandleError::Function)?;
let handler = function
.call::<Handler>(request.clone())
.map_err(HandleError::InvokeHandler)?;
match handler {
Handler::StaticFile(staticfile) => Ok(staticfile.handle(request).await?),
Handler::Lua(lua_response) => Ok(lua_response.handle(request).await?),
}
}
async fn response(handlers: Table, stream: TcpStream) -> Result<(), ResponseError> {
let mut client = {
let (r, w) = stream.into_split();
Client::new(BufReader::new(r), BufWriter::new(w))
};
while let Some(request) = client
.read_request()
.await
.map_err(ResponseError::Request)?
{
let response = match handle(handlers.clone(), request).await {
Ok(response) => response,
Err(e) => {
eprintln!("failed to handle request: {e:?}");
Response::builder()
.status(Status::InternalServerError)
.body(response::Body::Empty)
}
};
client
.send_response(response)
.await
.map_err(ResponseError::Response)?;
}
Ok(())
}
fn join_path(root: &Path, rest: &Path) -> Result<PathBuf, std::io::Error> {
root.components()
.chain(
rest.components()
.filter(|p| !matches!(p, Component::RootDir)),
)
.filter(|p| !matches!(p, Component::CurDir | Component::ParentDir))
.collect::<PathBuf>()
.canonicalize()
}
fn init_lua(lua: Lua) -> Result<(), InitLuaError> {
let http = lua.create_table().map_err(InitLuaError::CreateTable)?;
lua.globals()
.set("http", http.clone())
.map_err(|e| InitLuaError::SetVar(e, "http".to_string()))?;
http.set(
"join_paths",
lua.create_function(|_, (root, rest): (mlua::String, mlua::String)| {
let a = PathBuf::from(OsString::from_vec(root.as_bytes().to_vec()));
let b = PathBuf::from(OsString::from_vec(rest.as_bytes().to_vec()));
join_path(&a, &b).map_err(|e| mlua::Error::runtime(format!("failed to join path: {e}")))
})
.map_err(InitLuaError::Function)?,
)
.map_err(|e| InitLuaError::SetVar(e, "http.join_paths".to_string()))?;
let chunk = lua.load(std::fs::read_to_string("config.lua").map_err(InitLuaError::LoadConfig)?);
chunk.eval::<()>().map_err(InitLuaError::EvalConfig)?;
Ok(())
}
#[allow(unexpected_cfgs)]
#[tokio::main(flavor = "local")]
async fn main() -> ExitCode {
let lua = Lua::new();
if let Err(e) = init_lua(lua.clone()) {
exit!("failed to init lua: {}", e);
}
let http = match lua.globals().get::<Table>("http") {
Ok(http) => http,
Err(e) => exit!("failed to load table 'http': {}", e),
};
let bind = match http.get::<String>("bind") {
Ok(bind) => bind,
Err(e) => exit!("failed to load string 'http.bind': {}", e),
};
let handlers = match http.get::<Table>("handlers") {
Ok(handlers) => handlers,
Err(e) => exit!("failed to load 'http.handlers': {}", e),
};
let listener = match TcpListener::bind(&bind).await {
Ok(listener) => listener,
Err(e) => exit!("failed to bind to {}: {}", bind, e),
};
loop {
let (stream, addr) = match listener.accept().await {
Ok((stream, addr)) => (stream, addr),
Err(e) => {
eprintln!("failed to accept connection: {e}");
continue;
}
};
eprintln!("accepted connection from {addr}");
let future = response(handlers.clone(), stream);
tokio::task::spawn_local(async {
if let Err(e) = future.await {
eprintln!("response failure: {e:?}");
}
});
}
}
|