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::seq::IteratorRandom;
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, Default)]
161pub enum CalendarMode {
162 None,
163 #[default]
164 Auto,
165 Timezone(chrono_tz::Tz),
166 Events(Vec<CalendarEvent>),
167}
168
169impl CalendarMode {
170 pub fn calendar_now(&self) -> Calendar {
171 match self {
172 CalendarMode::None => Calendar::default(),
173 CalendarMode::Auto => Calendar::from_tz(None),
174 CalendarMode::Timezone(tz) => Calendar::from_tz(Some(*tz)),
175 CalendarMode::Events(events) => Calendar::from_events(events.clone()),
176 }
177 }
178}
179
180#[derive(Clone, Debug, Serialize, Deserialize)]
181#[serde(default)]
182pub struct Settings {
183 pub gameserver_protocols: Vec<Protocol>,
184 pub auth_server_address: Option<String>,
185 pub query_address: Option<SocketAddr>,
186 pub max_players: u16,
187 pub world_seed: u32,
188 pub server_name: String,
189 pub day_length: f64,
191 pub map_file: Option<FileOpts>,
194 pub max_view_distance: Option<u32>,
195 pub max_player_group_size: u32,
196 pub client_timeout: Duration,
197 pub max_player_for_kill_broadcast: Option<usize>,
198 pub calendar_mode: CalendarMode,
199
200 #[serde(default, skip_serializing)]
203 pub experimental_terrain_persistence: bool,
204
205 #[serde(default)]
206 pub gameplay: GameplaySettings,
207 #[serde(default)]
208 pub moderation: ModerationSettings,
209
210 #[serde(default)]
211 pub world: WorldSettings,
212}
213
214impl Default for Settings {
215 fn default() -> Self {
216 Self {
217 gameserver_protocols: vec![
218 Protocol::Tcp {
219 address: SocketAddr::from((Ipv6Addr::UNSPECIFIED, 14004)),
220 },
221 Protocol::Tcp {
222 address: SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14004)),
223 },
224 ],
225 auth_server_address: Some("https://auth.veloren.net".into()),
226 query_address: Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14006))),
227 world_seed: DEFAULT_WORLD_SEED,
228 server_name: "Veloren Server".into(),
229 max_players: 100,
230 day_length: DAY_LENGTH_DEFAULT,
231 map_file: None,
232 max_view_distance: Some(65),
233 max_player_group_size: 6,
234 calendar_mode: CalendarMode::Auto,
235 client_timeout: Duration::from_secs(40),
236 max_player_for_kill_broadcast: None,
237 experimental_terrain_persistence: false,
238 gameplay: GameplaySettings::default(),
239 moderation: ModerationSettings::default(),
240 world: WorldSettings::default(),
241 }
242 }
243}
244
245impl Settings {
246 pub fn load(path: &Path) -> Self {
248 let path = Self::get_settings_path(path);
249
250 let mut settings = if let Ok(file) = fs::File::open(&path) {
251 match ron::de::from_reader(file) {
252 Ok(x) => x,
253 Err(e) => {
254 let default_settings = Self::default();
255 let template_path = path.with_extension("template.ron");
256 warn!(
257 ?e,
258 "Failed to parse setting file! Falling back to default settings and \
259 creating a template file for you to migrate your current settings file: \
260 {}",
261 template_path.display()
262 );
263 if let Err(e) = default_settings.save_to_file(&template_path) {
264 error!(?e, "Failed to create template settings file")
265 }
266 default_settings
267 },
268 }
269 } else {
270 let default_settings = Self::default();
271
272 if let Err(e) = default_settings.save_to_file(&path) {
273 error!(?e, "Failed to create default settings file!");
274 }
275 default_settings
276 };
277
278 settings.validate();
279 settings
280 }
281
282 fn save_to_file(&self, path: &Path) -> std::io::Result<()> {
283 if let Some(dir) = path.parent() {
285 fs::create_dir_all(dir)?;
286 }
287 let ron = ron::ser::to_string_pretty(self, ron::ser::PrettyConfig::default())
288 .expect("Failed serialize settings.");
289
290 fs::write(path, ron.as_bytes())?;
291
292 Ok(())
293 }
294
295 pub fn singleplayer(path: &Path) -> Self {
297 let load = Self::load(path);
298 Self {
299 gameserver_protocols: vec![Protocol::Tcp {
302 address: SocketAddr::from((
303 Ipv4Addr::LOCALHOST,
304 pick_unused_port().expect("Failed to find unused port!"),
305 )),
306 }],
307 auth_server_address: None,
308 world_seed: if load.map_file.is_some() {
310 load.world_seed
311 } else {
312 DEFAULT_WORLD_SEED
313 },
314 server_name: SINGLEPLAYER_SERVER_NAME.to_owned(),
315 max_players: 100,
316 max_view_distance: None,
317 client_timeout: Duration::from_secs(180),
318 ..load }
320 }
321
322 fn get_settings_path(path: &Path) -> PathBuf {
323 let mut path = with_config_dir(path);
324 path.push(SETTINGS_FILENAME);
325 path
326 }
327
328 fn validate(&mut self) {
329 const INVALID_SETTING_MSG: &str =
330 "Invalid value for setting in userdata/server/server_config/settings.ron.";
331
332 let default_values = Settings::default();
333
334 if self.day_length <= 0.0 {
335 warn!(
336 "{} Setting: day_length, Value: {}. Set day_length to it's default value of {}. \
337 Help: day_length must be a positive floating point value above 0.",
338 INVALID_SETTING_MSG, self.day_length, default_values.day_length
339 );
340 self.day_length = default_values.day_length;
341 }
342 }
343
344 pub fn day_cycle_coefficient(&self) -> f64 { 1440.0 / self.day_length }
347}
348
349pub enum InvalidSettingsError {
350 InvalidDayDuration,
351}
352impl Display for InvalidSettingsError {
353 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354 match self {
355 InvalidSettingsError::InvalidDayDuration => {
356 f.write_str("Invalid settings error: Day length was invalid (zero or negative).")
357 },
358 }
359 }
360}
361
362pub fn with_config_dir(path: &Path) -> PathBuf {
363 let mut path = PathBuf::from(path);
364 path.push(CONFIG_DIR);
365 path
366}
367
368const MIGRATION_UPGRADE_GUARANTEE: &str = "Any valid file of an old verison should be able to \
378 successfully migrate to the latest version.";
379
380#[derive(Clone)]
382pub struct EditableSettings {
383 pub whitelist: Whitelist,
384 pub banlist: Banlist,
385 pub server_description: ServerDescriptions,
386 pub admins: Admins,
387 pub server_physics_force_list: ServerPhysicsForceList,
388}
389
390impl EditableSettings {
391 pub fn load(data_dir: &Path) -> Self {
392 Self {
393 whitelist: Whitelist::load(data_dir),
394 banlist: Banlist::load(data_dir),
395 server_description: ServerDescriptions::load(data_dir),
396 admins: Admins::load(data_dir),
397 server_physics_force_list: ServerPhysicsForceList::load(data_dir),
398 }
399 }
400
401 pub fn singleplayer(data_dir: &Path) -> Self {
402 let load = Self::load(data_dir);
403
404 let motd = [
405 "A whole world to yourself! Time to stretch...",
406 "How's the serenity?",
407 ]
408 .iter()
409 .choose(&mut rand::rng())
410 .expect("Message of the day don't wanna play.");
411
412 let mut server_description = ServerDescriptions::default();
413 server_description
414 .descriptions
415 .insert("en".to_string(), ServerDescription {
416 motd: motd.to_string(),
417 rules: None,
418 });
419
420 let mut admins = Admins::default();
421 admins.insert(
423 crate::login_provider::derive_singleplayer_uuid(),
424 AdminRecord {
425 username_when_admined: Some("singleplayer".into()),
426 date: Utc::now(),
427 role: admin::Role::Admin,
428 },
429 );
430
431 Self {
432 server_description,
433 admins,
434 ..load
435 }
436 }
437}