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
|
use core::fmt;
use std::{net::SocketAddr, pin::Pin, sync::Arc};
use caller::HttpRequest;
use http_body_util::{BodyExt, Full};
use hyper::{
HeaderMap, Request, Response, StatusCode,
body::{Bytes, Incoming},
server::conn::http1,
service::Service,
};
use hyper_util::rt::TokioIo;
use settings::{Script, Settings};
use stats::Stats;
use tokio::{net::TcpListener, runtime::Runtime};
use util::owned_header;
mod caller;
mod settings;
mod stats;
mod util;
fn main() {
let settings = Settings::get();
let stats = Stats::new(&settings.stats_path);
stats.create_tables();
let rt = Runtime::new().unwrap();
rt.block_on(async { run(settings, stats).await });
}
// We have tokio::main at home :)
async fn run(settings: Settings, stats: Stats) {
let addr = SocketAddr::from(([0, 0, 0, 0], settings.port));
let listen = TcpListener::bind(addr).await.unwrap();
let svc = Svc {
settings,
stats: Arc::new(stats),
client_addr: addr,
};
loop {
let (stream, caddr) = listen.accept().await.unwrap();
let io = TokioIo::new(stream);
let mut svc_clone = svc.clone();
svc_clone.client_addr = caddr;
tokio::task::spawn(
async move { http1::Builder::new().serve_connection(io, svc_clone).await },
);
}
}
#[derive(Clone, Debug)]
struct Svc {
settings: Settings,
stats: Arc<Stats>,
client_addr: SocketAddr,
}
impl Service<Request<Incoming>> for Svc {
type Response = Response<Full<Bytes>>;
type Error = hyper::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, req: Request<Incoming>) -> Self::Future {
let settings = self.settings.clone();
let caddr = self.client_addr;
let stats = self.stats.clone();
Box::pin(async move { Ok(Self::handle(settings, stats, caddr, req).await) })
}
}
impl Svc {
async fn handle(
settings: Settings,
stats: Arc<Stats>,
caddr: SocketAddr,
req: Request<Incoming>,
) -> Response<Full<Bytes>> {
match Self::handle_fallible(settings, stats, caddr, req).await {
Err(re) => re.into_response(),
Ok(response) => response,
}
}
async fn handle_fallible(
settings: Settings,
stats: Arc<Stats>,
caddr: SocketAddr,
req: Request<Incoming>,
) -> Result<Response<Full<Bytes>>, RuntimeError> {
// Collect things we need from the request before we eat it's body
let method = req.method().as_str().to_ascii_uppercase();
let version = req.version();
let path = util::url_decode(req.uri().path(), false)?;
let query = req
.uri()
.query()
.map(|s| util::url_decode(s, false))
.transpose()?
.unwrap_or_default();
let script = Self::select_script(&settings, &path).ok_or(RuntimeError::NoScript)?;
// Clone the headers and extract what we need
let headers = req.headers().clone();
let content_type = owned_header(headers.get("content-type")).unwrap_or_default();
let uagent = owned_header(headers.get("user-agent")).unwrap_or_default();
// Find the client address
let client_addr = {
let x_forward = util::parse_from_header(headers.get("x-forwarded-for"));
let forward = util::parse_from_header(headers.get("forwarded-for"));
forward.unwrap_or(x_forward.unwrap_or(caddr.ip()))
};
// Finally, get the body which consumes the request
let body = req.into_body().collect().await.unwrap().to_bytes().to_vec();
let content_length = body.len();
let server_name = headers
.get("Host")
.expect("no http host header set")
.to_str()
.expect("failed to decode http host as string");
let http_request = HttpRequest {
content_type,
path_info: path.clone(),
query_string: query,
remote_addr: client_addr,
request_method: method,
script_name: script.filename.to_owned(),
server_name: server_name.to_owned(),
server_port: settings.port,
server_protocol: format!("{:?}", version),
http_headers: Self::build_http_vec(headers),
body: if content_length > 0 { Some(body) } else { None },
};
let cgi_response = caller::call_and_parse_cgi(script.clone(), http_request).await;
let status = StatusCode::from_u16(cgi_response.status).unwrap();
let mut response = Response::builder().status(status);
for (key, value) in cgi_response.headers {
response = response.header(key, value);
}
let db_req = stats::Request {
agent: &uagent,
ip_address: &client_addr,
script: &script.name,
path: &path,
};
println!(
"served to [{client_addr}]\n\tscript: {}\n\tpath: {path}\n\tUA: {uagent}",
&script.name
);
stats.log_request(db_req);
let response_body = cgi_response
.body
.map(|v| Bytes::from(v))
.unwrap_or(Bytes::new());
Ok(response.body(Full::new(response_body)).unwrap())
}
fn select_script<'s>(settings: &'s Settings, path: &str) -> Option<&'s Script> {
for script in &settings.scripts {
if let Some(regex) = script.regex.as_ref() {
if regex.is_match(path) {
return Some(script);
}
} else {
return Some(script);
}
}
None
}
fn build_http_vec(headers: HeaderMap) -> Vec<(String, String)> {
let mut ret = vec![];
for (key, value) in headers.iter() {
let key_str = key.as_str();
let mut key_upper = String::with_capacity(key_str.len() + 5);
key_upper.push_str("HTTP_");
for ch in key_str.chars() {
match ch {
_ if ch as u8 > 0x60 && ch as u8 <= 0x7A => {
key_upper.push((ch as u8 - 0x20) as char);
}
'-' => key_upper.push('_'),
ch => key_upper.push(ch),
}
}
match value.to_str() {
Ok(val_str) => {
ret.push((key_upper, val_str.to_owned()));
}
Err(err) => {
eprintln!("value for header {key_str} is not a string: {err}")
}
}
}
ret
}
}
fn status_page<D: fmt::Display>(status: u16, msg: D) -> Response<Full<Bytes>> {
let body_str = format!(
"<html>\n\
\t<head><title>{status}</title></head>\n\
\t<body style='width: 20rem; padding: 0px; margin: 2rem;'>\n\
\t\t<h1>{status}</h1>\n\
\t\t<hr/>\n\
\t\t<p>{msg}</p>\n\
\t</body>\n\
</html>"
);
Response::builder()
.status(status)
.header("Content-Type", "text/html")
.body(Full::new(body_str.into()))
.unwrap()
}
enum RuntimeError {
MalformedRequest,
NoScript,
}
impl RuntimeError {
pub fn into_response(&self) -> Response<Full<Bytes>> {
match self {
Self::MalformedRequest => status_page(400, "bad request"),
Self::NoScript => status_page(404, "failed to route request"),
}
}
}
|