veloren_server/settings/
mod.rs

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    // explosion_burn_marks by players
110    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    /// Length of a day in minutes.
190    pub day_length: f64,
191    /// When set to None, loads the default map file (if available); otherwise,
192    /// uses the value of the file options to decide how to proceed.
193    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    /// Experimental feature. No guaranteed forwards-compatibility, may be
201    /// removed at *any time* with no migration.
202    #[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    /// path: Directory that contains the server config directory
247    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        // Create dir if it doesn't exist
284        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
293    /// path: Directory that contains the server config directory
294    pub fn singleplayer(path: &Path) -> Self {
295        let load = Self::load(path);
296        Self {
297            // BUG: theoretically another process can grab the port between here and server
298            // creation, however the time window is quite small.
299            gameserver_protocols: vec![Protocol::Tcp {
300                address: SocketAddr::from((
301                    Ipv4Addr::LOCALHOST,
302                    pick_unused_port().expect("Failed to find unused port!"),
303                )),
304            }],
305            auth_server_address: None,
306            // If loading the default map file, make sure the seed is also default.
307            world_seed: if load.map_file.is_some() {
308                load.world_seed
309            } else {
310                DEFAULT_WORLD_SEED
311            },
312            server_name: SINGLEPLAYER_SERVER_NAME.to_owned(),
313            max_players: 100,
314            max_view_distance: None,
315            client_timeout: Duration::from_secs(180),
316            ..load // Fill in remaining fields from server_settings.ron.
317        }
318    }
319
320    fn get_settings_path(path: &Path) -> PathBuf {
321        let mut path = with_config_dir(path);
322        path.push(SETTINGS_FILENAME);
323        path
324    }
325
326    fn validate(&mut self) {
327        const INVALID_SETTING_MSG: &str =
328            "Invalid value for setting in userdata/server/server_config/settings.ron.";
329
330        let default_values = Settings::default();
331
332        if self.day_length <= 0.0 {
333            warn!(
334                "{} Setting: day_length, Value: {}. Set day_length to it's default value of {}. \
335                 Help: day_length must be a positive floating point value above 0.",
336                INVALID_SETTING_MSG, self.day_length, default_values.day_length
337            );
338            self.day_length = default_values.day_length;
339        }
340    }
341
342    /// Derive a coefficient that is the relatively speed of the in-game
343    /// day/night cycle compared to reality.
344    pub fn day_cycle_coefficient(&self) -> f64 { 1440.0 / self.day_length }
345}
346
347pub enum InvalidSettingsError {
348    InvalidDayDuration,
349}
350impl Display for InvalidSettingsError {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        match self {
353            InvalidSettingsError::InvalidDayDuration => {
354                f.write_str("Invalid settings error: Day length was invalid (zero or negative).")
355            },
356        }
357    }
358}
359
360pub fn with_config_dir(path: &Path) -> PathBuf {
361    let mut path = PathBuf::from(path);
362    path.push(CONFIG_DIR);
363    path
364}
365
366/// Our upgrade guarantee is that if validation succeeds
367/// for an old version, then migration to the next version must always succeed
368/// and produce a valid settings file for that version (if we need to change
369/// this in the future, it should require careful discussion).  Therefore, we
370/// would normally panic if the upgrade produced an invalid settings file, which
371/// we would perform by doing the following post-validation (example
372/// is given for a hypothetical upgrade from Whitelist_V1 to Whitelist_V2):
373///
374/// Ok(Whitelist_V2::try_into().expect())
375const MIGRATION_UPGRADE_GUARANTEE: &str = "Any valid file of an old verison should be able to \
376                                           successfully migrate to the latest version.";
377
378/// Combines all the editable settings into one struct that is stored in the ecs
379#[derive(Clone)]
380pub struct EditableSettings {
381    pub whitelist: Whitelist,
382    pub banlist: Banlist,
383    pub server_description: ServerDescriptions,
384    pub admins: Admins,
385    pub server_physics_force_list: ServerPhysicsForceList,
386}
387
388impl EditableSettings {
389    pub fn load(data_dir: &Path) -> Self {
390        Self {
391            whitelist: Whitelist::load(data_dir),
392            banlist: Banlist::load(data_dir),
393            server_description: ServerDescriptions::load(data_dir),
394            admins: Admins::load(data_dir),
395            server_physics_force_list: ServerPhysicsForceList::load(data_dir),
396        }
397    }
398
399    pub fn singleplayer(data_dir: &Path) -> Self {
400        let load = Self::load(data_dir);
401
402        let motd = [
403            "A whole world to yourself! Time to stretch...",
404            "How's the serenity?",
405        ]
406        .iter()
407        .choose(&mut rand::rng())
408        .expect("Message of the day don't wanna play.");
409
410        let mut server_description = ServerDescriptions::default();
411        server_description
412            .descriptions
413            .insert("en".to_string(), ServerDescription {
414                motd: motd.to_string(),
415                rules: None,
416            });
417
418        let mut admins = Admins::default();
419        // TODO: Let the player choose if they want to use admin commands or not
420        admins.insert(
421            crate::login_provider::derive_singleplayer_uuid(),
422            AdminRecord {
423                username_when_admined: Some("singleplayer".into()),
424                date: Utc::now(),
425                role: admin::Role::Admin,
426            },
427        );
428
429        Self {
430            server_description,
431            admins,
432            ..load
433        }
434    }
435}