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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::collections::HashMap;
use std::env::args;
use std::fs::File;
use std::io::Read;
use crate::config::extended_hashmap::ExtendedMap;
use crate::logger::LogLevel;
use humphrey::krauss::wildcard_match;
#[derive(Debug, PartialEq, Eq)]
pub struct Config {
pub address: String,
pub port: u16,
pub threads: usize,
pub mode: ServerMode,
pub blacklist: Vec<String>,
pub blacklist_mode: BlacklistMode,
pub log_level: LogLevel,
pub log_console: bool,
pub log_file: Option<String>,
pub cache_limit: usize,
pub cache_time_limit: u64,
pub directory: Option<String>,
pub websocket_proxy: Option<String>,
#[cfg(feature = "plugins")]
pub plugin_libraries: Vec<String>,
pub proxy_target: Option<String>,
pub load_balancer_targets: Option<Vec<String>>,
pub load_balancer_mode: Option<LoadBalancerMode>,
pub raw: HashMap<String, String>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ServerMode {
Static,
Proxy,
LoadBalancer,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoadBalancerMode {
RoundRobin,
Random,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BlacklistMode {
Block,
Forbidden,
}
impl Default for LoadBalancerMode {
fn default() -> Self {
Self::RoundRobin
}
}
impl Default for BlacklistMode {
fn default() -> Self {
Self::Block
}
}
impl Default for Config {
fn default() -> Self {
Self {
address: "0.0.0.0".into(),
port: 80,
threads: 32,
mode: ServerMode::Static,
blacklist: Vec::new(),
blacklist_mode: BlacklistMode::Block,
log_level: LogLevel::Warn,
log_console: true,
log_file: None,
cache_limit: 0,
cache_time_limit: 0,
directory: Some(String::new()),
websocket_proxy: None,
#[cfg(feature = "plugins")]
plugin_libraries: Vec::new(),
proxy_target: None,
load_balancer_targets: None,
load_balancer_mode: None,
raw: HashMap::new(),
}
}
}
pub fn load_config(config_string: Option<String>) -> Result<Config, &'static str> {
let config = if config_string.is_some() {
config_string.unwrap()
} else if let Ok(config) = read_config() {
config
} else {
return Err("The configuration file could not be found");
};
let hashmap = parse_ini(&config).map_err(|_| "The configuration file could not be parsed")?;
let mode = hashmap.get_compulsory("server.mode", "The mode was not specified")?;
let address = hashmap.get_optional("server.address", "0.0.0.0".into());
let port: u16 = hashmap.get_optional_parsed("server.port", 80, "Invalid port")?;
let threads: usize =
hashmap.get_optional_parsed("server.threads", 32, "Invalid number of threads")?;
let blacklist = load_list_file(hashmap.get("blacklist.file".into()).clone())?;
let blacklist_mode = hashmap.get_optional("blacklist.mode", "block".into());
let blacklist_mode = match blacklist_mode.as_str() {
"block" => BlacklistMode::Block,
"forbidden" => BlacklistMode::Forbidden,
_ => return Err("The blacklist mode was invalid"),
};
if mode != "static" && blacklist_mode == BlacklistMode::Forbidden {
return Err("Blacklist mode 'forbidden' is only supported when serving static content");
}
let log_level =
hashmap.get_optional_parsed("log.level", LogLevel::Warn, "Invalid log level")?;
let log_file = hashmap.get_owned("log.file");
let log_console = hashmap.get("log.console".into()) != Some(&String::from("false"));
match mode.as_str() {
"static" => {
let cache_size_limit = hashmap.get_optional("static.cache", "0".into());
let cache_size_limit = parse_size(cache_size_limit)?;
let cache_time_limit: u64 =
hashmap.get_optional_parsed("static.cache_time", 60, "Invalid cache time limit")?;
let directory = hashmap.get_optional("static.directory", ".".into());
let websocket_proxy = hashmap.get("static.websocket").map(|s| s.to_string());
#[cfg(feature = "plugins")]
let plugin_libraries = load_list_file(hashmap.get("static.plugins".into()).clone())?;
Ok(Config {
address,
port,
threads,
mode: ServerMode::Static,
blacklist,
blacklist_mode,
log_level,
log_console,
log_file,
cache_limit: cache_size_limit,
cache_time_limit,
directory: Some(directory),
websocket_proxy,
#[cfg(feature = "plugins")]
plugin_libraries,
proxy_target: None,
load_balancer_targets: None,
load_balancer_mode: None,
raw: hashmap,
})
}
"proxy" => {
let proxy_target =
hashmap.get_compulsory("proxy.target", "The proxy target was not specified")?;
Ok(Config {
address,
port,
threads,
mode: ServerMode::Proxy,
blacklist,
blacklist_mode,
log_level,
log_console,
log_file,
cache_limit: 0,
cache_time_limit: 0,
directory: None,
websocket_proxy: None,
#[cfg(feature = "plugins")]
plugin_libraries: Vec::new(),
proxy_target: Some(proxy_target.clone()),
load_balancer_targets: None,
load_balancer_mode: None,
raw: hashmap,
})
}
"load_balancer" => {
let targets_file = hashmap.get_compulsory(
"load_balancer.targets",
"The load balancer targets file was not specified",
)?;
let mut targets_file = File::open(targets_file)
.map_err(|_| "The load balancer targets file could not be opened")?;
let mut buf = String::new();
targets_file
.read_to_string(&mut buf)
.map_err(|_| "The load balancer targets file could not be read")?;
let load_balancer_mode =
hashmap.get_optional("load_balancer.mode", "round-robin".into());
let load_balancer_mode = match load_balancer_mode.as_str() {
"round-robin" => LoadBalancerMode::RoundRobin,
"random" => LoadBalancerMode::Random,
_ => return Err("The load balancer mode was invalid"),
};
let targets: Vec<String> = buf.lines().map(|s| s.to_string()).collect();
Ok(Config {
address,
port,
threads,
mode: ServerMode::LoadBalancer,
blacklist,
blacklist_mode,
log_level,
log_console,
log_file,
cache_limit: 0,
cache_time_limit: 0,
directory: None,
websocket_proxy: None,
#[cfg(feature = "plugins")]
plugin_libraries: Vec::new(),
proxy_target: None,
load_balancer_targets: Some(targets),
load_balancer_mode: Some(load_balancer_mode),
raw: hashmap,
})
}
_ => Err("The server mode was invalid"),
}
}
fn read_config() -> Result<String, ()> {
let path = args().nth(1).unwrap_or("humphrey.ini".into());
if let Ok(mut file) = File::open(path) {
let mut string = String::new();
if let Ok(_) = file.read_to_string(&mut string) {
Ok(string)
} else {
Err(())
}
} else {
Err(())
}
}
pub fn parse_ini(ini: &str) -> Result<HashMap<String, String>, ()> {
let mut config: HashMap<String, String> = HashMap::new();
let mut section: Option<String> = None;
for line in ini.lines() {
if line.chars().nth(0) == Some(';') || line.len() == 0 {
continue;
}
if wildcard_match("[*]", line) {
section = Some(line[1..line.len() - 1].to_string());
continue;
}
let line = line.splitn(2, ';').nth(0).unwrap();
let mut key_value = line.splitn(2, '=');
let key = key_value.next();
let value = key_value.next();
if key.is_some() && value.is_some() {
let value = value.unwrap().trim();
let value = if wildcard_match("\"*\"", value) {
&value[1..value.len() - 1]
} else {
value
};
let full_key = if let Some(s) = §ion {
format!("{}.{}", s, key.unwrap().trim())
} else {
key.unwrap().trim().into()
};
config.insert(full_key, value.into());
} else {
return Err(());
}
}
Ok(config)
}
fn parse_size(size: String) -> Result<usize, &'static str> {
if size.len() == 0 {
Err("The specified size was invalid")
} else if size.len() == 1 {
size.parse::<usize>()
.map_err(|_| "The specified size was invalid")
} else {
let last_char = size.chars().last().unwrap().to_ascii_uppercase();
let number: usize = size[0..size.len() - 1]
.parse()
.map_err(|_| "The specified size was invalid")?;
match last_char {
'K' => Ok(number * 1024),
'M' => Ok(number * 1024 * 1024),
'G' => Ok(number * 1024 * 1024 * 1024),
'0'..='9' => size
.parse::<usize>()
.map_err(|_| "The specified size was invalid"),
_ => Err("The specified size was invalid"),
}
}
}
fn load_list_file(path: Option<&String>) -> Result<Vec<String>, &'static str> {
if let Some(path) = path {
let mut file = File::open(path).map_err(|_| "List file could not be opened")?;
let mut buf = String::new();
file.read_to_string(&mut buf)
.map_err(|_| "List file could not be read")?;
let list: Vec<String> = buf.lines().map(|s| s.to_string()).collect();
Ok(list)
} else {
Ok(Vec::new())
}
}