/* TShock, a server mod for Terraria Copyright (C) 2011-2019 Pryaxis & TShock Contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; using Rests; namespace TShockAPI { /// The config file class, which contains the configuration for a server that is serialized into JSON and deserialized on load. public class ConfigFile { /// Determines the size of invasion events. The equation for calculating invasion size = 100 + (multiplier * (number of active players > 200 hp)). [Description("Determines the size of invasion events.\nThe equation for calculating invasion size is 100 + (multiplier * (number of active players with greater than 200 health)).")] public int InvasionMultiplier = 1; /// The default maximum number of mobs that will spawn per wave. Higher means more mobs in that wave. [Description("The default maximum number of mobs that will spawn per wave. Higher means more mobs in that wave.")] public int DefaultMaximumSpawns = 5; /// The delay between waves. Lower values lead to more mobs. [Description("The delay between waves. Lower values lead to more mobs.")] public int DefaultSpawnRate = 600; /// The port the server runs on. [Description("The port the server runs on.")] public int ServerPort = 7777; /// Enable or disable the whitelist based on IP addresses in the whitelist.txt file. [Description("Enable or disable the whitelist based on IP addresses in the whitelist.txt file.")] public bool EnableWhitelist; /// Enables never-ending invasion events. You still need to start the event. [Description("Enables never ending invasion events. You still need to start the event, such as with the /invade command.")] public bool InfiniteInvasion; /// Sets the PvP mode. Valid types are: "normal", "always", "disabled". [Description("Sets the PvP mode. Valid types are: \"normal\", \"always\" and \"disabled\".")] public string PvPMode = "normal"; /// Prevents tiles from being placed within SpawnProtectionRadius of the default spawn. [Description("Prevents tiles from being placed within SpawnProtectionRadius of the default spawn.")] public bool SpawnProtection = true; /// The tile radius around the spawn tile that is protected by the SpawnProtection setting. [Description("The tile radius around the spawn tile that is protected by the SpawnProtection setting.")] public int SpawnProtectionRadius = 10; /// Maximum number of clients connected at once. If lower than Terraria's setting, the server will kick excess connections. [Description("Maximum number of clients connected at once.\nIf you want people to be kicked with \"Server is full\" set this to how many players you want max and then set Terraria max players to 2 higher.")] public int MaxSlots = 8; /// Enable or disable anti-cheat range checks based on distance between the player and their block placements. [Description("Enable or disable anti-cheat range checks based on distance between the player and their block placements.")] public bool RangeChecks = true; /// Disables any placing, or removal of blocks. [Description("Disables any placing, or removal of blocks.")] public bool DisableBuild; /// The chat color for the superadmin group. [Description("The chat color for the superadmin group.\n#.#.# = Red/Blue/Green\nMax value: 255")] public int[] SuperAdminChatRGB = { 255, 255, 255 }; /// The superadmin chat prefix. [Description("The superadmin chat prefix.")] public string SuperAdminChatPrefix = "(Super Admin) "; /// The superadmin chat suffix. [Description("The superadmin chat suffix.")] public string SuperAdminChatSuffix = ""; /// The interval between backups, in minutes. Backups are stored in the tshock/backups folder. [Description("The interval between backups, in minutes. Backups are stored in the tshock/backups folder.")] public int BackupInterval; /// For how long backups are kept in minutes. [Description("For how long backups are kept in minutes.\neg. 2880 = 2 days.")] public int BackupKeepFor = 60; /// Remembers where a player left off, based on their IP. Does not persist through server restarts. [Description("Remembers where a player left off, based on their IP. Does not persist through server restarts.\neg. When you try to disconnect, and reconnect to be automatically placed at spawn, you'll be at your last location.")] public bool RememberLeavePos; /// Prevents non-hardcore players from connecting. [Description("Prevents non-hardcore players from connecting.")] public bool HardcoreOnly; /// Prevents softcore players from connecting. [Description("Prevents softcore players from connecting.")] public bool MediumcoreOnly; /// Whether or not to kick mediumcore players on death. [Description("Whether or not to kick mediumcore players on death.")] public bool KickOnMediumcoreDeath; /// Whether or not to ban mediumcore players on death. [Description("Whether or not to ban mediumcore players on death.")] public bool BanOnMediumcoreDeath; /// Enable or disable Terraria's built-in world auto save. [Description("Enable or disable Terraria's built-in world auto save.")] public bool AutoSave = true; /// Enable or disable world save announcements. [Description("Enable or disable world save announcements.")] public bool AnnounceSave = true; /// Number of failed login attempts before kicking the player. [Description("Number of failed login attempts before kicking the player.")] public int MaximumLoginAttempts = 3; /// Replaces the world name during a session if UseServerName is true. [Description("Replaces the world name during a session if UseServerName is true.")] public string ServerName = ""; /// Whether or not to use ServerName in place of the world name. [Description("Whether or not to use ServerName in place of the world name.")] public bool UseServerName = false; /// The type of database to use when storing data (either "sqlite" or "mysql"). [Description("The type of database to use when storing data (either \"sqlite\" or \"mysql\").")] public string StorageType = "sqlite"; /// The path of sqlite db. [Description("The path of sqlite db.")] public string SqliteDBPath = "tshock.sqlite"; /// The MySQL hostname and port to direct connections to. [Description("The MySQL hostname and port to direct connections to.")] public string MySqlHost = "localhost:3306"; /// The database name to connect to when using MySQL as the database type. [Description("The database name to connect to when using MySQL as the database type.")] public string MySqlDbName = ""; /// The username used when connecting to a MySQL database. [Description("The username used when connecting to a MySQL database.")] public string MySqlUsername = ""; /// The password used when connecting to a MySQL database. [Description("The password used when connecting to a MySQL database.")] public string MySqlPassword = ""; /// The reason given if banning a mediumcore player on death. [Description("The reason given if banning a mediumcore player on death.")] public string MediumcoreBanReason = "Death results in a ban"; /// The reason given if kicking a mediumcore players on death. [Description("The reason given if kicking a mediumcore players on death.")] public string MediumcoreKickReason = "Death results in a kick"; /// Enables kicking banned users by matching their IP Address. [Description("Enables kicking banned users by matching their IP Address.")] public bool EnableIPBans = true; /// Enables kicking banned users by matching their client UUID. [Description("Enables kicking banned users by matching their client UUID.")] public bool EnableUUIDBans = true; /// Enables kicking banned users by matching their Character Name. [Description("Enables kicking banned users by matching their Character Name.")] public bool EnableBanOnUsernames; /// The default group name to place newly registered users under. [Description("The default group name to place newly registered users under.")] public string DefaultRegistrationGroupName = "default"; /// The default group name to place unregistered players under. [Description("The default group name to place unregistered players under.")] public string DefaultGuestGroupName = "guest"; /// Disables sending logs as messages to players with the log permission. [Description("Disables sending logs as messages to players with the log permission.")] public bool DisableSpewLogs = true; /// Prevents OnSecondUpdate checks from writing to the log file. [Description("Prevents OnSecondUpdate checks from writing to the log file.")] public bool DisableSecondUpdateLogs = false; /// The hash algorithm used to encrypt user passwords. /// Valid types: "sha512", "sha256" and "md5". Append with "-xp" for the xp supported algorithms. [Description("The hash algorithm used to encrypt user passwords. Valid types: \"sha512\", \"sha256\" and \"md5\". Append with \"-xp\" for the xp supported algorithms.")] public string HashAlgorithm = "sha512"; /// The reason given when kicking players that attempt to join while the server is full. [Description("The reason given when kicking players that attempt to join while the server is full.")] public string ServerFullReason = "Server is full"; /// The reason given when kicking players for not being on the whitelist. [Description("The reason given when kicking players for not being on the whitelist.")] public string WhitelistKickReason = "You are not on the whitelist."; /// The reason given when kicking players that attempt to join while the server is full with no reserved slots available. [Description("The reason given when kicking players that attempt to join while the server is full with no reserved slots available.")] public string ServerFullNoReservedReason = "Server is full. No reserved slots open."; /// Whether or not to save the world if the server crashes from an unhandled exception. [Description("Whether or not to save the world if the server crashes from an unhandled exception.")] public bool SaveWorldOnCrash = true; /// Whether or not to announce a player's geographic location on join, based on their IP. [Description("Whether or not to announce a player's geographic location on join, based on their IP.")] public bool EnableGeoIP; /// Whether or not to require token authentication to use the public REST API endpoints. [Description("Whether or not to require token authentication to use the public REST API endpoints.")] public bool EnableTokenEndpointAuthentication; /// Enable or disable the REST API. [Description("Enable or disable the REST API.")] public bool RestApiEnabled; /// The port used by the REST API. [Description("The port used by the REST API.")] public int RestApiPort = 7878; /// Disables tombstone dropping during death for all players. [Description("Disables tombstone dropping during death for all players.")] public bool DisableTombstones = true; /// Displays a player's IP on join to users with the log permission. [Description("Displays a player's IP on join to users with the log permission.")] public bool DisplayIPToAdmins; /// If GeoIP is enabled, this will kick users identified as being under a proxy. [Description("If GeoIP is enabled, this will kick users identified as being under a proxy.")] public bool KickProxyUsers = true; /// If enabled, hardmode will not be activated by the Wall of Flesh or the /starthardmode command. [Description("If enabled, hardmode will not be activated by the Wall of Flesh or the /starthardmode command.")] public bool DisableHardmode; /// Prevents the dungeon guardian from being spawned while sending players to their spawn point instead. [Description("Prevents the dungeon guardian from being spawned while sending players to their spawn point instead.")] public bool DisableDungeonGuardian; /// Disables clown bomb projectiles from spawning. [Description("Disables clown bomb projectiles from spawning.")] public bool DisableClownBombs; /// Disables snow ball projectiles from spawning. [Description("Disables snow ball projectiles from spawning.")] public bool DisableSnowBalls; /// Changes in-game chat format: {0} = Group Name, {1} = Group Prefix, {2} = Player Name, {3} = Group Suffix, {4} = Chat Message. [Description("Changes in-game chat format: {0} = Group Name, {1} = Group Prefix, {2} = Player Name, {3} = Group Suffix, {4} = Chat Message.")] public string ChatFormat = "{1}{2}{3}: {4}"; /// Changes the player name when using chat above heads. Starts with a player name wrapped in brackets, as per Terraria's formatting.\nSame formatting as ChatFormat without the message. [Description("Changes the player name when using chat above heads. Starts with a player name wrapped in brackets, as per Terraria's formatting.\nSame formatting as ChatFormat without the message.")] public string ChatAboveHeadsFormat = "{2}"; /// Forces the world time to be normal, day, or night. [Description("Forces the world time to be normal, day, or night.")] public string ForceTime = "normal"; /// Disables a player and reverts their actions if this number of tile kills is exceeded within 1 second. [Description("Disables a player and reverts their actions if this number of tile kills is exceeded within 1 second.")] public int TileKillThreshold = 60; /// Disables a player and reverts their actions if this number of tile places is exceeded within 1 second. [Description("Disables a player and reverts their actions if this number of tile places is exceeded within 1 second.")] public int TilePlaceThreshold = 20; /// Disables a player if this number of liquid sets is exceeded within 1 second. [Description("Disables a player if this number of liquid sets is exceeded within 1 second.")] public int TileLiquidThreshold = 15; /// Disable a player if this number of projectiles is created within 1 second. [Description("Disable a player if this number of projectiles is created within 1 second.")] public int ProjectileThreshold = 50; /// Disables a player if this number of HealOtherPlayer packets is sent within 1 second. [Description("Disables a player if this number of HealOtherPlayer packets is sent within 1 second.")] public int HealOtherThreshold = 50; /// Whether or not to ignore shrapnel from crystal bullets for the projectile threshold count. [Description("Whether or not to ignore shrapnel from crystal bullets for the projectile threshold count.")] public bool ProjIgnoreShrapnel = true; /// Require all players to register or login before being allowed to play. [Description("Require all players to register or login before being allowed to play.")] public bool RequireLogin; /// Disables the effect of invisibility potions while PvP is enabled by turning the player visible to the other clients. [Description("Disables the effect of invisibility potions while PvP is enabled by turning the player visible to the other clients.")] public bool DisableInvisPvP; /// The maximum distance, in tiles, that disabled players can move from. [Description("The maximum distance, in tiles, that disabled players can move from.")] public int MaxRangeForDisabled = 10; /// The server password required to join the server. [Description("The server password required to join the server.")] public string ServerPassword = ""; /// Whether or not region protection should apply to chests. [Description("Whether or not region protection should apply to chests.")] public bool RegionProtectChests; /// Whether or not region protection should apply to gem locks. [Description("Whether or not region protection should apply to gem locks.")] public bool RegionProtectGemLocks = true; /// Prevents users from being able to login before they finish connecting. [Description("Prevents users from being able to login before they finish connecting.")] public bool DisableLoginBeforeJoin; /// Prevents users from being able to login with their client UUID. [Description("Prevents users from being able to login with their client UUID.")] public bool DisableUUIDLogin; /// Kick clients that don't send their UUID to the server. [Description("Kick clients that don't send their UUID to the server.")] public bool KickEmptyUUID; /// Allows users to register a username that doesn't necessarily match their character name. [Description("Allows users to register a username that doesn't necessarily match their character name.")] public bool AllowRegisterAnyUsername; /// Allows users to login to any account even if the username doesn't match their character name. [Description("Allows users to login to any account even if the username doesn't match their character name.")] public bool AllowLoginAnyUsername = true; /// The maximum damage a player/NPC can inflict. [Description("The maximum damage a player/NPC can inflict.")] public int MaxDamage = 1175; /// The maximum damage a projectile can inflict. [Description("The maximum damage a projectile can inflict.")] public int MaxProjDamage = 1175; /// Whether or not to kick users when they surpass the MaxDamage threshold. [Description("Whether or not to kick users when they surpass the MaxDamage threshold.")] public bool KickOnDamageThresholdBroken = false; /// Ignores checks to see if a player 'can' update a projectile. [Description("Ignores checks to see if a player 'can' update a projectile.")] public bool IgnoreProjUpdate = false; /// Ignores checks to see if a player 'can' kill a projectile. [Description("Ignores checks to see if a player 'can' kill a projectile.")] public bool IgnoreProjKill = false; /// Allows ice placement even where a user cannot usually build. [Description("Allows ice placement even where a user cannot usually build.")] public bool AllowIce = false; /// Allows the crimson to spread when a world is in hardmode. [Description("Allows the crimson to spread when a world is in hardmode.")] public bool AllowCrimsonCreep = true; /// Allows the corruption to spread when a world is in hardmode. [Description("Allows the corruption to spread when a world is in hardmode.")] public bool AllowCorruptionCreep = true; /// Allows the hallow to spread when a world is in hardmode. [Description("Allows the hallow to spread when a world is in hardmode.")] public bool AllowHallowCreep = true; /// How many NPCs a statue can spawn within 200 pixels(?) before it stops spawning. [Description("How many NPCs a statue can spawn within 200 pixels(?) before it stops spawning.\nDefault = 3.")] public int StatueSpawn200 = 3; /// How many NPCs a statue can spawn within 600 pixels(?) before it stops spawning. [Description("How many NPCs a statue can spawn within 600 pixels(?) before it stops spawning.\nDefault = 6.")] public int StatueSpawn600 = 6; /// How many NPCs a statue can spawn before it stops spawning. [Description("How many NPCs a statue can spawn before it stops spawning.\nDefault = 10.")] public int StatueSpawnWorld = 10; /// Prevent banned items from being spawned or given with commands. [Description("Prevent banned items from being spawned or given with commands.")] public bool PreventBannedItemSpawn = false; /// Prevent players from interacting with the world while they are dead. [Description("Prevent players from interacting with the world while they are dead.")] public bool PreventDeadModification = true; /// Whether or not to display chat messages above players' heads. [Description("Whether or not to display chat messages above players' heads.")] public bool EnableChatAboveHeads = false; /// Forces Christmas-only events to occur all year. [Description("Forces Christmas-only events to occur all year.")] public bool ForceXmas = false; /// Allows groups on the banned item allowed list to spawn banned items even if PreventBannedItemSpawn is set to true. [Description("Allows groups on the banned item allowed list to spawn banned items even if PreventBannedItemSpawn is set to true.")] public bool AllowAllowedGroupsToSpawnBannedItems = false; /// Allows stacks in chests to go beyond the stack limit during world loading. [Description("Allows stacks in chests to go beyond the stack limit during world loading.")] public bool IgnoreChestStacksOnLoad = false; /// The path to the directory where logs should be written to. [Description("The path to the directory where logs should be written to.")] public string LogPath = "tshock"; /// Whether or not to save logs to the SQL database instead of a text file. [Description("Whether or not to save logs to the SQL database instead of a text file.\nDefault = false.")] public bool UseSqlLogs = false; /// Number of times the SQL log must fail to insert logs before falling back to the text log. [Description("Number of times the SQL log must fail to insert logs before falling back to the text log.")] public int RevertToTextLogsOnSqlFailures = 10; /// Prevents players from placing tiles with an invalid style. [Description("Prevents players from placing tiles with an invalid style.")] public bool PreventInvalidPlaceStyle = true; /// The RGB values used for the color of broadcast messages. [Description("The RGB values used for the color of broadcast messages.\n#.#.# = Red/Blue/Green\nMax value: 255")] public int[] BroadcastRGB = { 127, 255, 212 }; /// A dictionary of REST tokens that external applications may use to make queries to your server. [Description("A dictionary of REST tokens that external applications may use to make queries to your server.")] public Dictionary ApplicationRestTokens = new Dictionary(); /// The number of reserved slots past your max server slots that can be joined by reserved players. [Description("The number of reserved slots past your max server slots that can be joined by reserved players.")] public int ReservedSlots = 20; /// Whether or not to log REST API connections. [Description("Whether or not to log REST API connections.")] public bool LogRest = false; /// The number of seconds a player must wait before being respawned. Cannot be longer than normal value now. Use at your own risk. [Description("The number of seconds a player must wait before being respawned. Cannot be longer than normal value now. Use at your own risk.")] public int RespawnSeconds = 5; /// The number of seconds a player must wait before being respawned if there is a boss nearby. Cannot be longer than normal value now. Use at your own risk. [Description("The number of seconds a player must wait before being respawned if there is a boss nearby. Cannot be longer than normal value now. Use at your own risk.")] public int RespawnBossSeconds = 10; /// Disables a player if this number of tiles is painted within 1 second. [Description("Disables a player if this number of tiles is painted within 1 second.")] public int TilePaintThreshold = 15; /// Forces Halloween-only events to occur all year. [Description("Forces Halloween-only events to occur all year.")] public bool ForceHalloween = false; /// Allows players to break temporary tiles (grass, pots, etc) where they cannot usually build. [Description("Allows players to break temporary tiles (grass, pots, etc) where they cannot usually build.")] public bool AllowCutTilesAndBreakables = false; /// Specifies which string starts a command. /// Note: Will not function properly if the string length is bigger than 1. [Description("Specifies which string starts a command.\nNote: Will not function properly if the string length is bigger than 1.")] public string CommandSpecifier = "/"; /// Specifies which string starts a command silently. /// Note: Will not function properly if the string length is bigger than 1. [Description("Specifies which string starts a command silently.\nNote: Will not function properly if the string length is bigger than 1.")] public string CommandSilentSpecifier = "."; /// Whether or not to kick hardcore players on death. [Description("Whether or not to kick hardcore players on death.")] public bool KickOnHardcoreDeath; /// Whether or not to ban hardcore players on death. [Description("Whether or not to ban hardcore players on death.")] public bool BanOnHardcoreDeath; /// The reason given when banning hardcore players on death. [Description("The reason given when banning hardcore players on death.")] public string HardcoreBanReason = "Death results in a ban"; /// The reason given when kicking hardcore players on death. [Description("The reason given when kicking hardcore players on death.")] public string HardcoreKickReason = "Death results in a kick"; /// Whether or not to announce boss spawning or invasion starts. [Description("Whether or not to announce boss spawning or invasion starts.")] public bool AnonymousBossInvasions = true; /// The maximum HP a player can have, before equipment buffs. [Description("The maximum HP a player can have, before equipment buffs.")] public int MaxHP = 500; /// The maximum MP a player can have, before equipment buffs. [Description("The maximum MP a player can have, before equipment buffs.")] public int MaxMP = 200; /// Whether or not to save the world when the last player disconnects. [Description("Whether or not to save the world when the last player disconnects.")] public bool SaveWorldOnLastPlayerExit = true; /// Determines the BCrypt work factor to use. If increased, all passwords will be upgraded to new work-factor on verify. /// The number of computational rounds is 2^n. Increase with caution. Range: 5-31. [Description("Determines the BCrypt work factor to use. If increased, all passwords will be upgraded to new work-factor on verify. The number of computational rounds is 2^n. Increase with caution. Range: 5-31.")] public int BCryptWorkFactor = 7; /// The minimum password length for new user accounts. Can never be lower than 4. [Description("The minimum password length for new user accounts. Can never be lower than 4.")] public int MinimumPasswordLength = 4; /// The maximum REST requests in the bucket before denying requests. Minimum value is 5. [Description("The maximum REST requests in the bucket before denying requests. Minimum value is 5.")] public int RESTMaximumRequestsPerInterval = 5; /// How often in minutes the REST requests bucket is decreased by one. Minimum value is 1 minute. [Description("How often in minutes the REST requests bucket is decreased by one. Minimum value is 1 minute.")] public int RESTRequestBucketDecreaseIntervalMinutes = 1; /// Whether or not to show backup auto save messages. [Description("Whether or not to show backup auto save messages.")] public bool ShowBackupAutosaveMessages = true; [Description("Whether or not the server should output debug level messages related to system operation.")] public bool DebugLogs = false; [Description("Determines the range in tiles that a bomb can affect tiles.")] public int BombExplosionRadius = 5; /// /// Reads a configuration file from a given path /// /// string path /// ConfigFile object public static ConfigFile Read(string path) { if (!File.Exists(path)) return new ConfigFile(); using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { return Read(fs); } } /// /// Reads the configuration file from a stream /// /// stream /// ConfigFile object public static ConfigFile Read(Stream stream) { using (var sr = new StreamReader(stream)) { var cf = JsonConvert.DeserializeObject(sr.ReadToEnd()); if (ConfigRead != null) ConfigRead(cf); return cf; } } /// /// Writes the configuration to a given path /// /// string path - Location to put the config file public void Write(string path) { using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write)) { Write(fs); } } /// /// Writes the configuration to a stream /// /// stream public void Write(Stream stream) { var str = JsonConvert.SerializeObject(this, Formatting.Indented); using (var sw = new StreamWriter(stream)) { sw.Write(str); } } /// /// On config read hook /// public static Action ConfigRead; /// /// Dumps all configuration options to a text file in Markdown format /// public static void DumpDescriptions() { var sb = new StringBuilder(); var defaults = new ConfigFile(); foreach (var field in defaults.GetType().GetFields().OrderBy(f => f.Name)) { if (field.IsStatic) continue; var name = field.Name; var type = field.FieldType.Name; var descattr = field.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute; var desc = descattr != null && !string.IsNullOrWhiteSpace(descattr.Description) ? descattr.Description : "None"; var def = field.GetValue(defaults); sb.AppendLine("{0} ".SFormat(name)); sb.AppendLine("Type: {0} ".SFormat(type)); sb.AppendLine("Description: {0} ".SFormat(desc)); sb.AppendLine("Default: \"{0}\" ".SFormat(def)); sb.AppendLine(); } File.WriteAllText("ConfigDescriptions.txt", sb.ToString()); } } }