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
254
255
256
257
258
259
260
261
use std::{fmt, net::{IpAddr, SocketAddr}, path::PathBuf, str::FromStr};
use hyper::{Uri, http::uri};
use crate::{Controller, Server};
pub const DEFAULT_CONTROL_PATH: &str = "/~~penguin";
#[derive(Debug, Clone)]
pub struct Config {
pub(crate) bind_addr: SocketAddr,
pub(crate) proxy: Option<ProxyTarget>,
pub(crate) mounts: Vec<Mount>,
pub(crate) control_path: String,
}
impl Config {
pub fn proxy(&self) -> Option<&ProxyTarget> {
self.proxy.as_ref()
}
pub fn mounts(&self) -> &[Mount] {
&self.mounts
}
pub fn control_path(&self) -> &str {
&self.control_path
}
}
#[derive(Debug, Clone)]
pub struct Builder(Config);
impl Builder {
pub(crate) fn new(bind_addr: SocketAddr) -> Self {
Self(Config {
bind_addr,
proxy: None,
control_path: DEFAULT_CONTROL_PATH.into(),
mounts: Vec::new(),
})
}
pub fn proxy(mut self, target: ProxyTarget) -> Self {
if let Some(prev) = self.0.proxy {
panic!(
"`Builder::proxy` called a second time: is called with '{}' now \
but was previously called with '{}'",
target,
prev,
);
}
self.0.proxy = Some(target);
self
}
pub fn add_mount(
mut self,
uri_path: impl Into<String>,
fs_path: impl Into<PathBuf>,
) -> Result<Self, ConfigError> {
let mut uri_path = uri_path.into();
normalize_path(&mut uri_path);
if self.0.mounts.iter().any(|other| other.uri_path == uri_path) {
return Err(ConfigError::DuplicateUriPath(uri_path));
}
self.0.mounts.push(Mount {
uri_path,
fs_path: fs_path.into(),
});
Ok(self)
}
pub fn set_control_path(mut self, path: impl Into<String>) -> Self {
self.0.control_path = path.into();
normalize_path(&mut self.0.control_path);
self
}
pub fn build(self) -> Result<(Server, Controller), ConfigError> {
self.validate().map(Server::build)
}
pub fn validate(self) -> Result<Config, ConfigError> {
if self.0.proxy.is_none() && self.0.mounts.is_empty() {
return Err(ConfigError::NoProxyOrMount)
}
if self.0.proxy.is_some() && self.0.mounts.iter().any(|other| other.uri_path == "/") {
return Err(ConfigError::ProxyAndRootMount);
}
Ok(self.0)
}
}
fn normalize_path(path: &mut String) {
if path.len() > 1 && path.ends_with('/') {
path.pop();
}
if !path.starts_with('/') {
path.insert(0, '/');
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
#[error("URI path '{0}' was added as mount twice")]
DuplicateUriPath(String),
#[error("a proxy was configured but a mount on '/' was added as well (in \
that case, the proxy is would be ignored)")]
ProxyAndRootMount,
#[error("neither a proxy nor a mount was specified: server would always \
respond 404 in this case")]
NoProxyOrMount,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProxyTarget {
pub(crate) scheme: uri::Scheme,
pub(crate) authority: uri::Authority,
}
impl From<(uri::Scheme, uri::Authority)> for ProxyTarget {
fn from((scheme, authority): (uri::Scheme, uri::Authority)) -> Self {
Self { scheme, authority }
}
}
impl fmt::Display for ProxyTarget {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}://{}", self.scheme, self.authority)
}
}
impl FromStr for ProxyTarget {
type Err = ProxyTargetParseError;
fn from_str(src: &str) -> Result<Self, Self::Err> {
let parts = src.parse::<Uri>()?.into_parts();
let has_real_path = parts.path_and_query.as_ref()
.map_or(false, |pq| !pq.as_str().is_empty() && pq.as_str() != "/");
if has_real_path {
return Err(ProxyTargetParseError::HasPath);
}
let authority = parts.authority.ok_or(ProxyTargetParseError::MissingAuthority)?;
let scheme = parts.scheme
.or_else(|| {
let ip = authority.host().parse::<IpAddr>();
if authority.host() == "localhost" || ip.map_or(false, |ip| ip.is_loopback()) {
Some(uri::Scheme::HTTP)
} else {
None
}
})
.ok_or(ProxyTargetParseError::MissingScheme)?;
Ok(Self { scheme, authority })
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProxyTargetParseError {
#[error("invalid URI: {0}")]
InvalidUri(#[from] uri::InvalidUri),
#[error("proxy target has path which is not allowed")]
HasPath,
#[error("proxy target has no scheme ('http' or 'https') specified, but a \
scheme must be specified for non-local targets")]
MissingScheme,
#[error("proxy target has no authority (\"host\") specified")]
MissingAuthority,
}
#[derive(Debug, Clone)]
pub struct Mount {
pub uri_path: String,
pub fs_path: PathBuf,
}