forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
398 lines (339 loc) · 13.2 KB
/
config.rs
File metadata and controls
398 lines (339 loc) · 13.2 KB
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
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use std::path::Path;
use std::str::FromStr;
use std::{env, fs};
use config::{Config, ConfigError, File, FileFormat};
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, NoneAsEmptyString};
use {std, toml};
use crate::databases::driver::Driver;
use crate::tracker::mode;
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct UdpTracker {
pub enabled: bool,
pub bind_address: String,
}
#[serde_as]
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct HttpTracker {
pub enabled: bool,
pub bind_address: String,
pub ssl_enabled: bool,
#[serde_as(as = "NoneAsEmptyString")]
pub ssl_cert_path: Option<String>,
#[serde_as(as = "NoneAsEmptyString")]
pub ssl_key_path: Option<String>,
}
#[serde_as]
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct HttpApi {
pub enabled: bool,
pub bind_address: String,
pub ssl_enabled: bool,
#[serde_as(as = "NoneAsEmptyString")]
pub ssl_cert_path: Option<String>,
#[serde_as(as = "NoneAsEmptyString")]
pub ssl_key_path: Option<String>,
pub access_tokens: HashMap<String, String>,
}
impl HttpApi {
#[must_use]
pub fn contains_token(&self, token: &str) -> bool {
let tokens: HashMap<String, String> = self.access_tokens.clone();
let tokens: HashSet<String> = tokens.into_values().collect();
tokens.contains(token)
}
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct Configuration {
pub log_level: Option<String>,
pub mode: mode::Mode,
pub db_driver: Driver,
pub db_path: String,
pub announce_interval: u32,
pub min_announce_interval: u32,
pub max_peer_timeout: u32,
pub on_reverse_proxy: bool,
pub external_ip: Option<String>,
pub tracker_usage_statistics: bool,
pub persistent_torrent_completed_stat: bool,
pub inactive_peer_cleanup_interval: u64,
pub remove_peerless_torrents: bool,
pub udp_trackers: Vec<UdpTracker>,
pub http_trackers: Vec<HttpTracker>,
pub http_api: HttpApi,
}
#[derive(Debug)]
pub enum Error {
Message(String),
ConfigError(ConfigError),
IOError(std::io::Error),
ParseError(toml::de::Error),
TrackerModeIncompatible,
}
/// This configuration is used for testing. It generates random config values so they do not collide
/// if you run more than one tracker at the same time.
///
/// # Panics
///
/// Will panic if it can't convert the temp file path to string
#[must_use]
pub fn ephemeral_configuration() -> Configuration {
// todo: disable services that are not needed.
// For example: a test for the UDP tracker should disable the API and HTTP tracker.
let mut config = Configuration {
log_level: Some("off".to_owned()), // Change to `debug` for tests debugging
..Default::default()
};
// Ephemeral socket address for API
let api_port = random_port();
config.http_api.enabled = true;
config.http_api.bind_address = format!("127.0.0.1:{}", &api_port);
// Ephemeral socket address for UDP tracker
let upd_port = random_port();
config.udp_trackers[0].enabled = true;
config.udp_trackers[0].bind_address = format!("127.0.0.1:{}", &upd_port);
// Ephemeral socket address for HTTP tracker
let http_port = random_port();
config.http_trackers[0].enabled = true;
config.http_trackers[0].bind_address = format!("127.0.0.1:{}", &http_port);
// Ephemeral sqlite database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}_{}_{}.db", &api_port, &upd_port, &http_port));
config.db_path = temp_file.to_str().unwrap().to_owned();
config
}
fn random_port() -> u16 {
// todo: this may produce random test failures because two tests can try to bind the same port.
// We could create a pool of available ports (with read/write lock)
let mut rng = thread_rng();
rng.gen_range(49152..65535)
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::Message(e) => e.fmt(f),
Error::ConfigError(e) => e.fmt(f),
Error::IOError(e) => e.fmt(f),
Error::ParseError(e) => e.fmt(f),
Error::TrackerModeIncompatible => write!(f, "{self:?}"),
}
}
}
impl std::error::Error for Error {}
impl Default for Configuration {
fn default() -> Self {
let mut configuration = Configuration {
log_level: Option::from(String::from("info")),
mode: mode::Mode::Public,
db_driver: Driver::Sqlite3,
db_path: String::from("./storage/database/data.db"),
announce_interval: 120,
min_announce_interval: 120,
max_peer_timeout: 900,
on_reverse_proxy: false,
external_ip: Some(String::from("0.0.0.0")),
tracker_usage_statistics: true,
persistent_torrent_completed_stat: false,
inactive_peer_cleanup_interval: 600,
remove_peerless_torrents: true,
udp_trackers: Vec::new(),
http_trackers: Vec::new(),
http_api: HttpApi {
enabled: true,
bind_address: String::from("127.0.0.1:1212"),
ssl_enabled: false,
ssl_cert_path: None,
ssl_key_path: None,
access_tokens: [(String::from("admin"), String::from("MyAccessToken"))]
.iter()
.cloned()
.collect(),
},
};
configuration.udp_trackers.push(UdpTracker {
enabled: false,
bind_address: String::from("0.0.0.0:6969"),
});
configuration.http_trackers.push(HttpTracker {
enabled: false,
bind_address: String::from("0.0.0.0:7070"),
ssl_enabled: false,
ssl_cert_path: None,
ssl_key_path: None,
});
configuration
}
}
impl Configuration {
#[must_use]
pub fn get_ext_ip(&self) -> Option<IpAddr> {
match &self.external_ip {
None => None,
Some(external_ip) => match IpAddr::from_str(external_ip) {
Ok(external_ip) => Some(external_ip),
Err(_) => None,
},
}
}
/// # Errors
///
/// Will return `Err` if `path` does not exist or has a bad configuration.
pub fn load_from_file(path: &str) -> Result<Configuration, Error> {
let config_builder = Config::builder();
#[allow(unused_assignments)]
let mut config = Config::default();
if Path::new(path).exists() {
config = config_builder
.add_source(File::with_name(path))
.build()
.map_err(Error::ConfigError)?;
} else {
eprintln!("No config file found.");
eprintln!("Creating config file..");
let config = Configuration::default();
config.save_to_file(path)?;
return Err(Error::Message(
"Please edit the config.TOML and restart the tracker.".to_string(),
));
}
let torrust_config: Configuration = config.try_deserialize().map_err(Error::ConfigError)?;
Ok(torrust_config)
}
/// # Errors
///
/// Will return `Err` if the environment variable does not exist or has a bad configuration.
pub fn load_from_env_var(config_env_var_name: &str) -> Result<Configuration, Error> {
match env::var(config_env_var_name) {
Ok(config_toml) => {
let config_builder = Config::builder()
.add_source(File::from_str(&config_toml, FileFormat::Toml))
.build()
.map_err(Error::ConfigError)?;
let config = config_builder.try_deserialize().map_err(Error::ConfigError)?;
Ok(config)
}
Err(_) => Err(Error::Message(format!(
"No environment variable for configuration found: {}",
&config_env_var_name
))),
}
}
/// # Errors
///
/// Will return `Err` if `filename` does not exist or the user does not have
/// permission to read it.
pub fn save_to_file(&self, path: &str) -> Result<(), Error> {
let toml_string = toml::to_string(self).expect("Could not encode TOML value");
fs::write(path, toml_string).expect("Could not write to file!");
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::config::{Configuration, Error};
#[cfg(test)]
fn default_config_toml() -> String {
let config = r#"log_level = "info"
mode = "public"
db_driver = "Sqlite3"
db_path = "./storage/database/data.db"
announce_interval = 120
min_announce_interval = 120
max_peer_timeout = 900
on_reverse_proxy = false
external_ip = "0.0.0.0"
tracker_usage_statistics = true
persistent_torrent_completed_stat = false
inactive_peer_cleanup_interval = 600
remove_peerless_torrents = true
[[udp_trackers]]
enabled = false
bind_address = "0.0.0.0:6969"
[[http_trackers]]
enabled = false
bind_address = "0.0.0.0:7070"
ssl_enabled = false
ssl_cert_path = ""
ssl_key_path = ""
[http_api]
enabled = true
bind_address = "127.0.0.1:1212"
ssl_enabled = false
ssl_cert_path = ""
ssl_key_path = ""
[http_api.access_tokens]
admin = "MyAccessToken"
"#
.lines()
.map(str::trim_start)
.collect::<Vec<&str>>()
.join("\n");
config
}
#[test]
fn configuration_should_have_default_values() {
let configuration = Configuration::default();
let toml = toml::to_string(&configuration).expect("Could not encode TOML value");
assert_eq!(toml, default_config_toml());
}
#[test]
fn configuration_should_contain_the_external_ip() {
let configuration = Configuration::default();
assert_eq!(configuration.external_ip, Option::Some(String::from("0.0.0.0")));
}
#[test]
fn configuration_should_be_saved_in_a_toml_config_file() {
use std::{env, fs};
use uuid::Uuid;
// Build temp config file path
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4()));
// Convert to argument type for Configuration::save_to_file
let config_file_path = temp_file;
let path = config_file_path.to_string_lossy().to_string();
let default_configuration = Configuration::default();
default_configuration
.save_to_file(&path)
.expect("Could not save configuration to file");
let contents = fs::read_to_string(&path).expect("Something went wrong reading the file");
assert_eq!(contents, default_config_toml());
}
#[cfg(test)]
fn create_temp_config_file_with_default_config() -> String {
use std::env;
use std::fs::File;
use std::io::Write;
use uuid::Uuid;
// Build temp config file path
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4()));
// Convert to argument type for Configuration::load_from_file
let config_file_path = temp_file.clone();
let path = config_file_path.to_string_lossy().to_string();
// Write file contents
let mut file = File::create(temp_file).unwrap();
writeln!(&mut file, "{}", default_config_toml()).unwrap();
path
}
#[test]
fn configuration_should_be_loaded_from_a_toml_config_file() {
let config_file_path = create_temp_config_file_with_default_config();
let configuration = Configuration::load_from_file(&config_file_path).expect("Could not load configuration from file");
assert_eq!(configuration, Configuration::default());
}
#[test]
fn configuration_error_could_be_displayed() {
let error = Error::TrackerModeIncompatible;
assert_eq!(format!("{error}"), "TrackerModeIncompatible");
}
#[test]
fn http_api_configuration_should_check_if_it_contains_a_token() {
let configuration = Configuration::default();
assert!(configuration.http_api.contains_token("MyAccessToken"));
assert!(!configuration.http_api.contains_token("NonExistingToken"));
}
}