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
195 lines (175 loc) · 5.65 KB
/
config.rs
File metadata and controls
195 lines (175 loc) · 5.65 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
pub use crate::tracker::TrackerMode;
use config::{Config, ConfigError, File};
use serde::{Deserialize, Serialize, Serializer};
use std;
use std::collections::HashMap;
use std::fs;
use std::net::IpAddr;
use std::path::Path;
use std::str::FromStr;
use toml;
#[derive(Serialize, Deserialize)]
pub struct UdpTrackerConfig {
pub bind_address: String,
pub announce_interval: u32,
}
#[derive(Serialize, Deserialize)]
pub struct HttpTrackerConfig {
pub enabled: bool,
pub bind_address: String,
pub announce_interval: u32,
pub ssl_enabled: bool,
#[serde(serialize_with = "none_as_empty_string")]
pub ssl_cert_path: Option<String>,
#[serde(serialize_with = "none_as_empty_string")]
pub ssl_key_path: Option<String>,
}
impl HttpTrackerConfig {
pub fn is_ssl_enabled(&self) -> bool {
self.ssl_enabled && self.ssl_cert_path.is_some() && self.ssl_key_path.is_some()
}
}
#[derive(Serialize, Deserialize)]
pub struct HttpApiConfig {
pub enabled: bool,
pub bind_address: String,
pub access_tokens: HashMap<String, String>,
}
#[derive(Deserialize, Serialize, Copy, Clone, Debug)]
pub enum LogLevel {
#[serde(rename = "off")]
Off,
#[serde(rename = "trace")]
Trace,
#[serde(rename = "debug")]
Debug,
#[serde(rename = "info")]
Info,
#[serde(rename = "warn")]
Warn,
#[serde(rename = "error")]
Error,
}
impl Into<log::LevelFilter> for LogLevel {
fn into(self) -> log::LevelFilter {
match self {
LogLevel::Off => log::LevelFilter::Off,
LogLevel::Trace => log::LevelFilter::Trace,
LogLevel::Debug => log::LevelFilter::Debug,
LogLevel::Info => log::LevelFilter::Info,
LogLevel::Warn => log::LevelFilter::Warn,
LogLevel::Error => log::LevelFilter::Error,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct Configuration {
pub log_level: Option<LogLevel>,
pub mode: TrackerMode,
pub db_path: String,
pub cleanup_interval: Option<u64>,
pub external_ip: Option<IpAddr>,
pub udp_tracker: UdpTrackerConfig,
pub http_tracker: Option<HttpTrackerConfig>,
pub http_api: Option<HttpApiConfig>,
}
#[derive(Debug)]
pub enum ConfigurationError {
IOError(std::io::Error),
ParseError(toml::de::Error),
}
impl std::fmt::Display for ConfigurationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ConfigurationError::IOError(e) => e.fmt(formatter),
ConfigurationError::ParseError(e) => e.fmt(formatter),
}
}
}
impl std::error::Error for ConfigurationError {}
pub fn none_as_empty_string<T, S>(option: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
if let Some(value) = option {
value.serialize(serializer)
} else {
"".serialize(serializer)
}
}
impl Configuration {
pub fn load(data: &[u8]) -> Result<Configuration, toml::de::Error> {
toml::from_slice(data)
}
pub fn load_file(path: &str) -> Result<Configuration, ConfigurationError> {
match std::fs::read(path) {
Err(e) => Err(ConfigurationError::IOError(e)),
Ok(data) => match Self::load(data.as_slice()) {
Ok(cfg) => Ok(cfg),
Err(e) => Err(ConfigurationError::ParseError(e)),
},
}
}
pub fn get_ext_ip(&self) -> Option<IpAddr> {
self.external_ip.clone()
}
}
impl Configuration {
pub fn default() -> Configuration {
Configuration {
log_level: Some(LogLevel::Info),
mode: TrackerMode::PublicMode,
db_path: String::from("data.db"),
cleanup_interval: Some(600),
external_ip: IpAddr::from_str("0.0.0.0").ok(),
udp_tracker: UdpTrackerConfig {
bind_address: String::from("0.0.0.0:6969"),
announce_interval: 120,
},
http_tracker: Option::from(HttpTrackerConfig {
enabled: false,
bind_address: String::from("0.0.0.0:7878"),
announce_interval: 120,
ssl_enabled: false,
ssl_cert_path: None,
ssl_key_path: None,
}),
http_api: Option::from(HttpApiConfig {
enabled: true,
bind_address: String::from("127.0.0.1:1212"),
access_tokens: [(String::from("admin"), String::from("MyAccessToken"))]
.iter()
.cloned()
.collect(),
}),
}
}
pub fn load_from_file() -> Result<Configuration, ConfigError> {
let mut config = Config::new();
const CONFIG_PATH: &str = "config.toml";
if Path::new(CONFIG_PATH).exists() {
config.merge(File::with_name(CONFIG_PATH))?;
} else {
eprintln!("No config file found.");
eprintln!("Creating config file..");
let config = Configuration::default();
let _ = config.save_to_file();
return Err(ConfigError::Message(format!(
"Please edit the config.TOML in the root folder and restart the tracker."
)));
}
match config.try_into() {
Ok(data) => Ok(data),
Err(e) => Err(ConfigError::Message(format!(
"Errors while processing config: {}.",
e
))),
}
}
pub fn save_to_file(&self) -> Result<(), ()> {
let toml_string = toml::to_string(self).expect("Could not encode TOML value");
fs::write("config.toml", toml_string).expect("Could not write to file!");
Ok(())
}
}