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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
pub mod admin;
pub mod banlist;
mod editable;
pub mod server_description;
pub mod server_physics;
pub mod whitelist;

pub use editable::{EditableSetting, Error as SettingError};

pub use admin::{AdminRecord, Admins};
pub use banlist::{
    Ban, BanEntry, BanError, BanErrorKind, BanInfo, BanKind, BanOperation, BanOperationError,
    BanRecord, Banlist,
};
pub use server_description::ServerDescriptions;
pub use whitelist::{Whitelist, WhitelistInfo, WhitelistRecord};

use chrono::Utc;
use common::{
    calendar::{Calendar, CalendarEvent},
    consts::DAY_LENGTH_DEFAULT,
    resources::BattleMode,
    rtsim::WorldSettings,
};
use core::time::Duration;
use portpicker::pick_unused_port;
use serde::{Deserialize, Serialize};
use std::{
    fmt::Display,
    fs,
    net::{Ipv4Addr, Ipv6Addr, SocketAddr},
    path::{Path, PathBuf},
};
use tracing::{error, warn};
use world::sim::{FileOpts, DEFAULT_WORLD_SEED};

use self::server_description::ServerDescription;

use self::server_physics::ServerPhysicsForceList;

const CONFIG_DIR: &str = "server_config";
const SETTINGS_FILENAME: &str = "settings.ron";
const WHITELIST_FILENAME: &str = "whitelist.ron";
const BANLIST_FILENAME: &str = "banlist.ron";
const SERVER_DESCRIPTION_FILENAME: &str = "description.ron";
const ADMINS_FILENAME: &str = "admins.ron";
const SERVER_PHYSICS_FORCE_FILENAME: &str = "server_physics_force.ron";

pub const SINGLEPLAYER_SERVER_NAME: &str = "Singleplayer";

#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub enum ServerBattleMode {
    Global(BattleMode),
    PerPlayer { default: BattleMode },
}

impl Default for ServerBattleMode {
    fn default() -> Self { Self::Global(BattleMode::PvP) }
}

impl ServerBattleMode {
    pub fn allow_choosing(&self) -> bool {
        match self {
            ServerBattleMode::Global { .. } => false,
            ServerBattleMode::PerPlayer { .. } => true,
        }
    }

    pub fn default_mode(&self) -> BattleMode {
        match self {
            ServerBattleMode::Global(mode) => *mode,
            ServerBattleMode::PerPlayer { default: mode } => *mode,
        }
    }
}

impl From<ServerBattleMode> for veloren_query_server::proto::ServerBattleMode {
    fn from(value: ServerBattleMode) -> Self {
        use veloren_query_server::proto::ServerBattleMode as QueryBattleMode;

        match value {
            ServerBattleMode::Global(mode) => match mode {
                BattleMode::PvP => QueryBattleMode::GlobalPvP,
                BattleMode::PvE => QueryBattleMode::GlobalPvE,
            },
            ServerBattleMode::PerPlayer { .. } => QueryBattleMode::PerPlayer,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Protocol {
    Quic {
        address: SocketAddr,
        cert_file_path: PathBuf,
        key_file_path: PathBuf,
    },
    Tcp {
        address: SocketAddr,
    },
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GameplaySettings {
    #[serde(default)]
    pub battle_mode: ServerBattleMode,
    #[serde(default)]
    // explosion_burn_marks by players
    pub explosion_burn_marks: bool,
}

impl Default for GameplaySettings {
    fn default() -> Self {
        Self {
            battle_mode: ServerBattleMode::default(),
            explosion_burn_marks: true,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ModerationSettings {
    #[serde(default)]
    pub banned_words_files: Vec<PathBuf>,
    #[serde(default)]
    pub automod: bool,
    #[serde(default)]
    pub admins_exempt: bool,
}

impl ModerationSettings {
    pub fn load_banned_words(&self, data_dir: &Path) -> Vec<String> {
        let mut banned_words = Vec::new();
        for fname in self.banned_words_files.iter() {
            let mut path = with_config_dir(data_dir);
            path.push(fname);
            match std::fs::File::open(&path) {
                Ok(file) => match ron::de::from_reader(&file) {
                    Ok(mut words) => banned_words.append(&mut words),
                    Err(error) => error!(?error, ?file, "Couldn't read banned words file"),
                },
                Err(error) => error!(?error, ?path, "Couldn't open banned words file"),
            }
        }
        banned_words
    }
}

impl Default for ModerationSettings {
    fn default() -> Self {
        Self {
            banned_words_files: Vec::new(),
            automod: false,
            admins_exempt: true,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CalendarMode {
    None,
    Auto,
    Timezone(chrono_tz::Tz),
    Events(Vec<CalendarEvent>),
}

impl Default for CalendarMode {
    fn default() -> Self { Self::Auto }
}

impl CalendarMode {
    pub fn calendar_now(&self) -> Calendar {
        match self {
            CalendarMode::None => Calendar::default(),
            CalendarMode::Auto => Calendar::from_tz(None),
            CalendarMode::Timezone(tz) => Calendar::from_tz(Some(*tz)),
            CalendarMode::Events(events) => Calendar::from_events(events.clone()),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
    pub gameserver_protocols: Vec<Protocol>,
    pub auth_server_address: Option<String>,
    pub query_address: Option<SocketAddr>,
    pub max_players: u16,
    pub world_seed: u32,
    pub server_name: String,
    pub start_time: f64,
    /// Length of a day in minutes.
    pub day_length: f64,
    /// When set to None, loads the default map file (if available); otherwise,
    /// uses the value of the file options to decide how to proceed.
    pub map_file: Option<FileOpts>,
    pub max_view_distance: Option<u32>,
    pub max_player_group_size: u32,
    pub client_timeout: Duration,
    pub max_player_for_kill_broadcast: Option<usize>,
    pub calendar_mode: CalendarMode,

    /// Experimental feature. No guaranteed forwards-compatibility, may be
    /// removed at *any time* with no migration.
    #[serde(default, skip_serializing)]
    pub experimental_terrain_persistence: bool,

    #[serde(default)]
    pub gameplay: GameplaySettings,
    #[serde(default)]
    pub moderation: ModerationSettings,

    #[serde(default)]
    pub world: WorldSettings,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            gameserver_protocols: vec![
                Protocol::Tcp {
                    address: SocketAddr::from((Ipv6Addr::UNSPECIFIED, 14004)),
                },
                Protocol::Tcp {
                    address: SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14004)),
                },
            ],
            auth_server_address: Some("https://auth.veloren.net".into()),
            query_address: Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 14006))),
            world_seed: DEFAULT_WORLD_SEED,
            server_name: "Veloren Server".into(),
            max_players: 100,
            day_length: DAY_LENGTH_DEFAULT,
            start_time: 9.0 * 3600.0,
            map_file: None,
            max_view_distance: Some(65),
            max_player_group_size: 6,
            calendar_mode: CalendarMode::Auto,
            client_timeout: Duration::from_secs(40),
            max_player_for_kill_broadcast: None,
            experimental_terrain_persistence: false,
            gameplay: GameplaySettings::default(),
            moderation: ModerationSettings::default(),
            world: WorldSettings::default(),
        }
    }
}

impl Settings {
    /// path: Directory that contains the server config directory
    pub fn load(path: &Path) -> Self {
        let path = Self::get_settings_path(path);

        let mut settings = if let Ok(file) = fs::File::open(&path) {
            match ron::de::from_reader(file) {
                Ok(x) => x,
                Err(e) => {
                    let default_settings = Self::default();
                    let template_path = path.with_extension("template.ron");
                    warn!(
                        ?e,
                        "Failed to parse setting file! Falling back to default settings and \
                         creating a template file for you to migrate your current settings file: \
                         {}",
                        template_path.display()
                    );
                    if let Err(e) = default_settings.save_to_file(&template_path) {
                        error!(?e, "Failed to create template settings file")
                    }
                    default_settings
                },
            }
        } else {
            let default_settings = Self::default();

            if let Err(e) = default_settings.save_to_file(&path) {
                error!(?e, "Failed to create default settings file!");
            }
            default_settings
        };

        settings.validate();
        settings
    }

    fn save_to_file(&self, path: &Path) -> std::io::Result<()> {
        // Create dir if it doesn't exist
        if let Some(dir) = path.parent() {
            fs::create_dir_all(dir)?;
        }
        let ron = ron::ser::to_string_pretty(self, ron::ser::PrettyConfig::default())
            .expect("Failed serialize settings.");

        fs::write(path, ron.as_bytes())?;

        Ok(())
    }

    /// path: Directory that contains the server config directory
    pub fn singleplayer(path: &Path) -> Self {
        let load = Self::load(path);
        Self {
            // BUG: theoretically another process can grab the port between here and server
            // creation, however the time window is quite small.
            gameserver_protocols: vec![Protocol::Tcp {
                address: SocketAddr::from((
                    Ipv4Addr::LOCALHOST,
                    pick_unused_port().expect("Failed to find unused port!"),
                )),
            }],
            auth_server_address: None,
            // If loading the default map file, make sure the seed is also default.
            world_seed: if load.map_file.is_some() {
                load.world_seed
            } else {
                DEFAULT_WORLD_SEED
            },
            server_name: SINGLEPLAYER_SERVER_NAME.to_owned(),
            max_players: 100,
            max_view_distance: None,
            client_timeout: Duration::from_secs(180),
            ..load // Fill in remaining fields from server_settings.ron.
        }
    }

    fn get_settings_path(path: &Path) -> PathBuf {
        let mut path = with_config_dir(path);
        path.push(SETTINGS_FILENAME);
        path
    }

    fn validate(&mut self) {
        const INVALID_SETTING_MSG: &str =
            "Invalid value for setting in userdata/server/server_config/settings.ron.";

        let default_values = Settings::default();

        if self.day_length <= 0.0 {
            warn!(
                "{} Setting: day_length, Value: {}. Set day_length to it's default value of {}. \
                 Help: day_length must be a positive floating point value above 0.",
                INVALID_SETTING_MSG, self.day_length, default_values.day_length
            );
            self.day_length = default_values.day_length;
        }
    }

    /// Derive a coefficient that is the relatively speed of the in-game
    /// day/night cycle compared to reality.
    pub fn day_cycle_coefficient(&self) -> f64 { 1440.0 / self.day_length }
}

pub enum InvalidSettingsError {
    InvalidDayDuration,
}
impl Display for InvalidSettingsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InvalidSettingsError::InvalidDayDuration => {
                f.write_str("Invalid settings error: Day length was invalid (zero or negative).")
            },
        }
    }
}

pub fn with_config_dir(path: &Path) -> PathBuf {
    let mut path = PathBuf::from(path);
    path.push(CONFIG_DIR);
    path
}

/// Our upgrade guarantee is that if validation succeeds
/// for an old version, then migration to the next version must always succeed
/// and produce a valid settings file for that version (if we need to change
/// this in the future, it should require careful discussion).  Therefore, we
/// would normally panic if the upgrade produced an invalid settings file, which
/// we would perform by doing the following post-validation (example
/// is given for a hypothetical upgrade from Whitelist_V1 to Whitelist_V2):
///
/// Ok(Whitelist_V2::try_into().expect())
const MIGRATION_UPGRADE_GUARANTEE: &str = "Any valid file of an old verison should be able to \
                                           successfully migrate to the latest version.";

/// Combines all the editable settings into one struct that is stored in the ecs
#[derive(Clone)]
pub struct EditableSettings {
    pub whitelist: Whitelist,
    pub banlist: Banlist,
    pub server_description: ServerDescriptions,
    pub admins: Admins,
    pub server_physics_force_list: ServerPhysicsForceList,
}

impl EditableSettings {
    pub fn load(data_dir: &Path) -> Self {
        Self {
            whitelist: Whitelist::load(data_dir),
            banlist: Banlist::load(data_dir),
            server_description: ServerDescriptions::load(data_dir),
            admins: Admins::load(data_dir),
            server_physics_force_list: ServerPhysicsForceList::load(data_dir),
        }
    }

    pub fn singleplayer(data_dir: &Path) -> Self {
        let load = Self::load(data_dir);

        let mut server_description = ServerDescriptions::default();
        server_description
            .descriptions
            .insert("en".to_string(), ServerDescription {
                motd: "Who needs friends anyway?".to_string(),
                rules: None,
            });

        let mut admins = Admins::default();
        // TODO: Let the player choose if they want to use admin commands or not
        admins.insert(
            crate::login_provider::derive_singleplayer_uuid(),
            AdminRecord {
                username_when_admined: Some("singleplayer".into()),
                date: Utc::now(),
                role: admin::Role::Admin,
            },
        );

        Self {
            server_description,
            admins,
            ..load
        }
    }
}