1pub mod admin;
2pub mod banlist;
3mod editable;
4pub mod server_description;
5pub mod server_physics;
6pub mod whitelist;
7
8pub use editable::{EditableSetting, Error as SettingError};
9
10pub use admin::{AdminRecord, Admins};
11pub use banlist::{
12 Ban, BanEntry, BanError, BanErrorKind, BanInfo, BanKind, BanOperation, BanOperationError,
13 BanRecord, Banlist,
14};
15pub use server_description::ServerDescriptions;
16pub use whitelist::{Whitelist, WhitelistInfo, WhitelistRecord};
17
18use chrono::Utc;
19use common::{
20 calendar::{Calendar, CalendarEvent},
21 consts::DAY_LENGTH_DEFAULT,
22 resources::BattleMode,
23 rtsim::WorldSettings,
24};
25use core::time::Duration;
26use portpicker::pick_unused_port;
27use rand::prelude::SliceRandom;
28use serde::{Deserialize, Serialize};
29use std::{
30 fmt::Display,
31 fs,
32 net::{Ipv4Addr, Ipv6Addr, SocketAddr},
33 path::{Path, PathBuf},
34};
35use tracing::{error, warn};
36use world::sim::{DEFAULT_WORLD_SEED, FileOpts};
37
38use self::server_description::ServerDescription;
39
40use self::server_physics::ServerPhysicsForceList;
41
42const CONFIG_DIR: &str = "server_config";
43const SETTINGS_FILENAME: &str = "settings.ron";
44const WHITELIST_FILENAME: &str = "whitelist.ron";
45const BANLIST_FILENAME: &str = "banlist.ron";
46const SERVER_DESCRIPTION_FILENAME: &str = "description.ron";
47const ADMINS_FILENAME: &str = "admins.ron";
48const SERVER_PHYSICS_FORCE_FILENAME: &str = "server_physics_force.ron";
49
50pub const SINGLEPLAYER_SERVER_NAME: &str = "Singleplayer";
51
52#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
53pub enum ServerBattleMode {
54 Global(BattleMode),
55 PerPlayer { default: BattleMode },
56}
57
58impl Default for ServerBattleMode {
59 fn default() -> Self { Self::Global(BattleMode::PvP) }
60}
61
62impl ServerBattleMode {
63 pub fn allow_choosing(&self) -> bool {
64 match self {
65 ServerBattleMode::Global { .. } => false,
66 ServerBattleMode::PerPlayer { .. } => true,
67 }
68 }
69
70 pub fn default_mode(&self) -> BattleMode {
71 match self {
72 ServerBattleMode::Global(mode) => *mode,
73 ServerBattleMode::PerPlayer { default: mode } => *mode,
74 }
75 }
76}
77
78impl From<ServerBattleMode> for veloren_query_server::proto::ServerBattleMode {
79 fn from(value: ServerBattleMode) -> Self {
80 use veloren_query_server::proto::ServerBattleMode as QueryBattleMode;
81
82 match value {
83 ServerBattleMode::Global(mode) => match mode {
84 BattleMode::PvP => QueryBattleMode::GlobalPvP,
85 BattleMode::PvE => QueryBattleMode::GlobalPvE,
86 },
87 ServerBattleMode::PerPlayer { .. } => QueryBattleMode::PerPlayer,
88 }
89 }
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub enum Protocol {
94 Quic {
95 address: SocketAddr,
96 cert_file_path: PathBuf,
97 key_file_path: PathBuf,
98 },
99 Tcp {
100 address: SocketAddr,
101 },
102}
103
104#[derive(Clone, Debug, Serialize, Deserialize)]
105pub struct GameplaySettings {
106 #[serde(default)]
107 pub battle_mode: ServerBattleMode,
108 #[serde(default)]
109 pub explosion_burn_marks: bool,
111}
112
113impl Default for GameplaySettings {
114 fn default() -> Self {
115 Self {
116 battle_mode: ServerBattleMode::default(),
117 explosion_burn_marks: true,
118 }
119 }
120}
121
122#[derive(Clone, Debug, Serialize, Deserialize)]
123pub struct ModerationSettings {
124 #[serde(default)]
125 pub banned_words_files: Vec<PathBuf>,
126 #[serde(default)]
127 pub automod: bool,
128 #[serde(default)]
129 pub admins_exempt: bool,
130}
131
132impl ModerationSettings {
133 pub fn load_banned_words(&self, data_dir: &Path) -> Vec<String> {
134 let mut banned_words = Vec::new();
135 for fname in self.banned_words_files.iter() {
136 let mut path = with_config_dir(data_dir);
137 path.push(fname);
138 match std::fs::File::open(&path) {
139 Ok(file) => match ron::de::from_reader(&file) {
140 Ok(mut words) => banned_words.append(&mut words),
141 Err(error) => error!(?error, ?file, "Couldn't read banned words file"),
142 },
143 Err(error) => error!(?error, ?path, "Couldn't open banned words file"),
144 }
145 }
146 banned_words
147 }
148}
149
150impl Default for ModerationSettings {
151 fn default() -> Self {
152 Self {
153 banned_words_files: Vec::new(),
154 automod: false,
155 admins_exempt: true,
156 }
157 }
158}
159
160#[derive(Clone, Debug, Serialize, Deserialize)]
161pub enum CalendarMode {
162 None,
163 Auto,
164 Timezone(chrono_tz::Tz),
165 Events(Vec<CalendarEvent>),
166}
167
168impl Default for CalendarMode {
169 fn default() -> Self { Self::Auto }
170}
171
172impl CalendarMode {
173 pub fn calendar_now(&self) -> Calendar {
174 match self {
175 CalendarMode::None => Calendar::default(),
176 CalendarMode::Auto => Calendar::from_tz(None),
177 CalendarMode::Timezone(tz) => Calendar::from_tz(Some(*tz)),
178 CalendarMode::Events(events) => Calendar::from_events(events.clone()),
179 }
180 }
181}
182
183#[derive(Clone, Debug, Serialize, Deserialize)]
184#[serde(default)]
185pub struct Settings {
186 pub gameserver_protocols: Vec<Protocol>,
187 pub auth_server_address: Option<String>,
188 pub query_address: Option<SocketAddr>,
189 pub max_players: u16,
190 pub world_seed: u32,
191 pub server_name: String,
192 pub day_length: f64,
194 pub map_file: Option<FileOpts>,
197 pub max_view_distance: Option<u32>,
198 pub max_player_group_size: u32,
199 pub client_timeout: Duration,
200 pub max_player_for_kill_broadcast: Option<usize>,
201 pub calendar_mode: CalendarMode,
202
203 #[serde(default, skip_serializing)]
206 pub experimental_terrain_persistence: bool,
207
208 #[serde(default)]
209 pub gameplay: GameplaySettings,
210 #[serde(default)]
211 pub moderation: ModerationSettings,
212
213 #[serde(default)]
214 pub world: WorldSettings,
215}
216
217impl Default for Settings {
218 fn default() -> Self {
219 Self {
220 gameserver_protocols: vec![
221 Protocol::Tcp {
222 address: SocketAddr::from((Ipv6Addr::UNSPECIFIED, 14004)),
223 },
224 Protocol::Tcp {
225 address: SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14004)),
226 },
227 ],
228 auth_server_address: Some("https://auth.veloren.net".into()),
229 query_address: Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14006))),
230 world_seed: DEFAULT_WORLD_SEED,
231 server_name: "Veloren Server".into(),
232 max_players: 100,
233 day_length: DAY_LENGTH_DEFAULT,
234 map_file: None,
235 max_view_distance: Some(65),
236 max_player_group_size: 6,
237 calendar_mode: CalendarMode::Auto,
238 client_timeout: Duration::from_secs(40),
239 max_player_for_kill_broadcast: None,
240 experimental_terrain_persistence: false,
241 gameplay: GameplaySettings::default(),
242 moderation: ModerationSettings::default(),
243 world: WorldSettings::default(),
244 }
245 }
246}
247
248impl Settings {
249 pub fn load(path: &Path) -> Self {
251 let path = Self::get_settings_path(path);
252
253 let mut settings = if let Ok(file) = fs::File::open(&path) {
254 match ron::de::from_reader(file) {
255 Ok(x) => x,
256 Err(e) => {
257 let default_settings = Self::default();
258 let template_path = path.with_extension("template.ron");
259 warn!(
260 ?e,
261 "Failed to parse setting file! Falling back to default settings and \
262 creating a template file for you to migrate your current settings file: \
263 {}",
264 template_path.display()
265 );
266 if let Err(e) = default_settings.save_to_file(&template_path) {
267 error!(?e, "Failed to create template settings file")
268 }
269 default_settings
270 },
271 }
272 } else {
273 let default_settings = Self::default();
274
275 if let Err(e) = default_settings.save_to_file(&path) {
276 error!(?e, "Failed to create default settings file!");
277 }
278 default_settings
279 };
280
281 settings.validate();
282 settings
283 }
284
285 fn save_to_file(&self, path: &Path) -> std::io::Result<()> {
286 if let Some(dir) = path.parent() {
288 fs::create_dir_all(dir)?;
289 }
290 let ron = ron::ser::to_string_pretty(self, ron::ser::PrettyConfig::default())
291 .expect("Failed serialize settings.");
292
293 fs::write(path, ron.as_bytes())?;
294
295 Ok(())
296 }
297
298 pub fn singleplayer(path: &Path) -> Self {
300 let load = Self::load(path);
301 Self {
302 gameserver_protocols: vec![Protocol::Tcp {
305 address: SocketAddr::from((
306 Ipv4Addr::LOCALHOST,
307 pick_unused_port().expect("Failed to find unused port!"),
308 )),
309 }],
310 auth_server_address: None,
311 world_seed: if load.map_file.is_some() {
313 load.world_seed
314 } else {
315 DEFAULT_WORLD_SEED
316 },
317 server_name: SINGLEPLAYER_SERVER_NAME.to_owned(),
318 max_players: 100,
319 max_view_distance: None,
320 client_timeout: Duration::from_secs(180),
321 ..load }
323 }
324
325 fn get_settings_path(path: &Path) -> PathBuf {
326 let mut path = with_config_dir(path);
327 path.push(SETTINGS_FILENAME);
328 path
329 }
330
331 fn validate(&mut self) {
332 const INVALID_SETTING_MSG: &str =
333 "Invalid value for setting in userdata/server/server_config/settings.ron.";
334
335 let default_values = Settings::default();
336
337 if self.day_length <= 0.0 {
338 warn!(
339 "{} Setting: day_length, Value: {}. Set day_length to it's default value of {}. \
340 Help: day_length must be a positive floating point value above 0.",
341 INVALID_SETTING_MSG, self.day_length, default_values.day_length
342 );
343 self.day_length = default_values.day_length;
344 }
345 }
346
347 pub fn day_cycle_coefficient(&self) -> f64 { 1440.0 / self.day_length }
350}
351
352pub enum InvalidSettingsError {
353 InvalidDayDuration,
354}
355impl Display for InvalidSettingsError {
356 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357 match self {
358 InvalidSettingsError::InvalidDayDuration => {
359 f.write_str("Invalid settings error: Day length was invalid (zero or negative).")
360 },
361 }
362 }
363}
364
365pub fn with_config_dir(path: &Path) -> PathBuf {
366 let mut path = PathBuf::from(path);
367 path.push(CONFIG_DIR);
368 path
369}
370
371const MIGRATION_UPGRADE_GUARANTEE: &str = "Any valid file of an old verison should be able to \
381 successfully migrate to the latest version.";
382
383#[derive(Clone)]
385pub struct EditableSettings {
386 pub whitelist: Whitelist,
387 pub banlist: Banlist,
388 pub server_description: ServerDescriptions,
389 pub admins: Admins,
390 pub server_physics_force_list: ServerPhysicsForceList,
391}
392
393impl EditableSettings {
394 pub fn load(data_dir: &Path) -> Self {
395 Self {
396 whitelist: Whitelist::load(data_dir),
397 banlist: Banlist::load(data_dir),
398 server_description: ServerDescriptions::load(data_dir),
399 admins: Admins::load(data_dir),
400 server_physics_force_list: ServerPhysicsForceList::load(data_dir),
401 }
402 }
403
404 pub fn singleplayer(data_dir: &Path) -> Self {
405 let load = Self::load(data_dir);
406
407 let motd = [
408 "A whole world to yourself! Time to stretch...",
409 "How's the serenity?",
410 ]
411 .choose(&mut rand::thread_rng())
412 .expect("Message of the day don't wanna play.");
413
414 let mut server_description = ServerDescriptions::default();
415 server_description
416 .descriptions
417 .insert("en".to_string(), ServerDescription {
418 motd: motd.to_string(),
419 rules: None,
420 });
421
422 let mut admins = Admins::default();
423 admins.insert(
425 crate::login_provider::derive_singleplayer_uuid(),
426 AdminRecord {
427 username_when_admined: Some("singleplayer".into()),
428 date: Utc::now(),
429 role: admin::Role::Admin,
430 },
431 );
432
433 Self {
434 server_description,
435 admins,
436 ..load
437 }
438 }
439}