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
|
use std::collections::HashMap;
use std::convert::Infallible;
use std::fs;
use std::net::{Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;
use hyper::service::{make_service_fn, service_fn};
use hyper::{header, Body, Request, Response, Server, StatusCode};
use miette::IntoDiagnostic;
use structopt::StructOpt;
mod utils;
use utils::HttpHandler;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(long, parse(from_os_str), default_value = "narchttpd.kdl")]
config_file: PathBuf,
}
#[derive(Debug, knuffel::Decode)]
struct HttpConfig {
#[knuffel(argument)]
enabled: bool,
#[knuffel(property(name = "port"))]
port: u16,
}
#[derive(Debug, knuffel::Decode)]
struct StaticDomain {
#[knuffel(child, unwrap(argument))]
root: PathBuf,
}
impl StaticDomain {
fn handler(self) -> Box<dyn HttpHandler> {
let Self { root } = self;
Box::new(utils::serve_static::Params::new(root))
}
}
#[derive(Debug, knuffel::Decode)]
struct ProxyChildDomain {
#[knuffel(child, unwrap(argument))]
command: String,
#[knuffel(child, unwrap(argument))]
in_dir: Option<PathBuf>,
#[knuffel(child, unwrap(argument))]
port: u16,
}
impl ProxyChildDomain {
fn handler(self) -> Box<dyn HttpHandler> {
let Self {
command,
in_dir,
port,
} = self;
Box::new(utils::proxy_child::ProxyChild::new(command, in_dir, port))
}
}
#[derive(Debug, knuffel::Decode)]
enum DomainType {
Static(StaticDomain),
ProxyChild(ProxyChildDomain),
}
impl DomainType {
fn handler(self) -> Box<dyn HttpHandler> {
match self {
Self::Static(domain) => domain.handler(),
Self::ProxyChild(domain) => domain.handler(),
}
}
}
#[derive(Debug, knuffel::Decode)]
struct DomainConfig {
#[knuffel(arguments)]
domains: Vec<String>,
#[knuffel(children)]
config: Vec<DomainType>,
}
#[derive(Debug, knuffel::Decode)]
struct Config {
#[knuffel(child)]
http: HttpConfig,
#[knuffel(children(name = "domain"))]
domains: Vec<DomainConfig>,
}
#[tokio::main]
async fn main() -> miette::Result<()> {
let opt: Opt = Opt::from_args();
let config_data = fs::read_to_string(&opt.config_file).into_diagnostic()?;
let Config { http, domains } =
knuffel::parse(&opt.config_file.to_string_lossy(), &config_data)?;
let http_port = http.port;
let domains: HashMap<_, _> = domains
.into_iter()
.map(|DomainConfig { domains, config }| {
let [config]: [DomainType; 1] = config.try_into().unwrap();
(domains, Arc::new(config.handler()))
})
.flat_map(|(domains, handler)| {
domains
.into_iter()
.map(move |domain| (domain, Arc::clone(&handler)))
})
.collect();
let domains = Arc::new(domains);
// TODO learn hyper
let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), http_port);
let make_svc = make_service_fn(move |_conn| {
let domains = domains.clone();
async move {
let domains = domains.clone();
Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
let domains = domains.clone();
async move {
let domains = domains.clone();
let req_domain = req.headers().get(header::HOST).unwrap();
let req_domain = req_domain.to_str().unwrap();
match domains.get(req_domain) {
Some(handler) => {
eprintln!("request {:?} matched domain {}", req, req_domain);
Ok::<_, Infallible>(handler.handle(req).await)
}
None => Ok::<_, Infallible>(
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("Not Found"))
.unwrap(),
),
}
}
}))
}
});
let server = Server::bind(&addr).serve(make_svc);
server.await.into_diagnostic()
}
|