From 8c1cf3c15ed337c56911f2ac5a09059c747d9651 Mon Sep 17 00:00:00 2001
From: Pia Mancini
Date: Thu, 20 Apr 2017 11:45:15 -0400
Subject: [PATCH 001/430] Add backers and sponsors from Open Collective
Now your open collective backers and sponsors can to appear directly on your README.
see how it'll look [here](https://github.com/apex/apex#backers)
[More info](https://github.com/opencollective/opencollective/wiki/Github-banner)
Also add badges on top
---
README.md | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 73 insertions(+)
diff --git a/README.md b/README.md
index b379295e..da702579 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,9 @@
+[](#backers)
+[](#sponsors)
+
TShock is a server modification for Terraria, written in C#, and based upon the [Terraria Server API](https://github.com/NyxStudios/TerrariaAPI-Server). It uses JSON for configuration management, and offers several features not present in the Terraria Server normally.
## :star: Quick Start
@@ -38,3 +41,73 @@ Please see the contributing file before sending pull requests.
* [Development Builds](https://travis.tshock.co/)
* [Plugins](https://tshock.co/xf/index.php?resources/)
* [Very, very old versions of TShock](https://github.com/TShock/TShock/downloads)
+
+## Backers
+
+Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/tshock#backer)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Sponsors
+
+Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/tshock#sponsor)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
From 0e051d1e80b8f6faf4652b7b1a5b0cae781c2abd Mon Sep 17 00:00:00 2001
From: Hussein Farran
Date: Mon, 15 May 2017 14:43:20 -0400
Subject: [PATCH 002/430] Changed Slack references to Discord
So Deathmax can sleep easy
---
CONTRIBUTING.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6382cc88..01735e16 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -18,7 +18,7 @@ Note: This includes the API by default. If you need only the API, you need to cd
- Run ```msbuild TShock.sln``` in the root of the cloned folder on Windows in a 'Developer Command Prompt' OR
- Run ```xbuild TShock.sln``` in the root of the cloned folder on Unix.
-Need help? Drop by Slack and we'll be happy to explain it with more words, step by step.
+Need help? Drop by Discord and we'll be happy to explain it with more words, step by step.
### TShock Additions
@@ -26,7 +26,7 @@ If something is better suited to be a plugin for TShock, rather than a TShock co
_If you are confused, make a suggestion. We will determine scope and relevance for you._
-_If a person makes a suggestion in Slack, capture the suggestion as a Github issue. If a suggestion crops up on the forums, make a Github issue to capture it. If you want, direct the user to make a suggestion on Github, but set an alarm/timer/reminder so that if they don't know how to use Github or they don't have an account, an issue is still made and discussed. Make it clear that the issue is a surrogate issue for a suggestion from Slack/the forums too._
+_If a person makes a suggestion in Discord, capture the suggestion as a Github issue. If a suggestion crops up on the forums, make a Github issue to capture it. If you want, direct the user to make a suggestion on Github, but set an alarm/timer/reminder so that if they don't know how to use Github or they don't have an account, an issue is still made and discussed. Make it clear that the issue is a surrogate issue for a suggestion from Discord/the forums too._
### Pull Request Dev Guidelines
From 81e21f31dc9f68d4db77f15dbb207d2b3373cb63 Mon Sep 17 00:00:00 2001
From: death
Date: Tue, 16 May 2017 22:41:27 +1000
Subject: [PATCH 003/430] Submodule update and new grass creep checks
Pulls through the latest OTAPI to make use of the new WorldGrassSpread hook which should allow corruption/crimsion/hallow creep config options work.
---
TShockAPI/TShock.cs | 44 ++++++++++++++++++++++++++++++++++++--------
TerrariaServerAPI | 2 +-
2 files changed, 37 insertions(+), 9 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 0d1c2bc7..42cd9ef1 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -349,6 +349,7 @@ namespace TShockAPI
ServerApi.Hooks.WorldHalloweenCheck.Register(this, OnHalloweenCheck);
ServerApi.Hooks.NetNameCollision.Register(this, NetHooks_NameCollision);
ServerApi.Hooks.ItemForceIntoChest.Register(this, OnItemForceIntoChest);
+ ServerApi.Hooks.WorldGrassSpread.Register(this, OnWorldGrassSpread);
Hooks.PlayerHooks.PlayerPreLogin += OnPlayerPreLogin;
Hooks.PlayerHooks.PlayerPostLogin += OnPlayerLogin;
Hooks.AccountHooks.AccountDelete += OnAccountDelete;
@@ -419,6 +420,7 @@ namespace TShockAPI
ServerApi.Hooks.WorldHalloweenCheck.Deregister(this, OnHalloweenCheck);
ServerApi.Hooks.NetNameCollision.Deregister(this, NetHooks_NameCollision);
ServerApi.Hooks.ItemForceIntoChest.Deregister(this, OnItemForceIntoChest);
+ ServerApi.Hooks.WorldGrassSpread.Deregister(this, OnWorldGrassSpread);
TShockAPI.Hooks.PlayerHooks.PlayerPostLogin -= OnPlayerLogin;
if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
@@ -1208,24 +1210,50 @@ namespace TShockAPI
if (args.Handled)
return;
- if (!Config.AllowCrimsonCreep && (args.Type == TileID.Dirt || args.Type == TileID.FleshWeeds
- || TileID.Sets.Crimson[args.Type]))
+ if (!OnCreep(args.Type))
{
args.Handled = true;
+ }
+ }
+
+ /// OnWorldGrassSpread - Fired when grass is attempting to spread.
+ /// args - The GrassSpreadEventArgs object.
+ private void OnWorldGrassSpread(GrassSpreadEventArgs args)
+ {
+ if (args.Handled)
return;
+
+ if(!OnCreep(args.Grass))
+ {
+ args.Handled = true;
+ }
+ }
+
+ ///
+ /// Checks if the tile type is allowed to creep
+ ///
+ /// Tile id
+ /// True if allowed, otherwise false
+ private bool OnCreep(int tileType)
+ {
+ if (!Config.AllowCrimsonCreep && (tileType == TileID.Dirt || tileType == TileID.FleshWeeds
+ || TileID.Sets.Crimson[tileType]))
+ {
+ return false;
}
- if (!Config.AllowCorruptionCreep && (args.Type == TileID.Dirt || args.Type == TileID.CorruptThorns
- || TileID.Sets.Corrupt[args.Type]))
+ if (!Config.AllowCorruptionCreep && (tileType == TileID.Dirt || tileType == TileID.CorruptThorns
+ || TileID.Sets.Corrupt[tileType]))
{
- args.Handled = true;
- return;
+ return false;
}
- if (!Config.AllowHallowCreep && (TileID.Sets.Hallow[args.Type]))
+ if (!Config.AllowHallowCreep && (TileID.Sets.Hallow[tileType]))
{
- args.Handled = true;
+ return false;
}
+
+ return true;
}
/// OnStatueSpawn - Fired when a statue spawns.
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index a9d1b0e4..d3b7d9f4 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit a9d1b0e4e096ecbd0b2033ce4ff636759c9448c3
+Subproject commit d3b7d9f4575602f468cf1e009ebc4bc5b79547c4
From c841a86cdf7987a079f5665aa7608ca02f12ef99 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Wed, 7 Jun 2017 10:46:46 +0300
Subject: [PATCH 004/430] hooks added
---
TShockAPI/Hooks/PlayerHooks.cs | 158 +++++++++++++++++++++++++++++++++
1 file changed, 158 insertions(+)
diff --git a/TShockAPI/Hooks/PlayerHooks.cs b/TShockAPI/Hooks/PlayerHooks.cs
index 43684387..062a78b8 100644
--- a/TShockAPI/Hooks/PlayerHooks.cs
+++ b/TShockAPI/Hooks/PlayerHooks.cs
@@ -18,6 +18,7 @@ along with this program. If not, see .
using System.Collections.Generic;
using System.ComponentModel;
+using TShockAPI.DB;
namespace TShockAPI.Hooks
{
@@ -166,6 +167,87 @@ namespace TShockAPI.Hooks
}
}
+ ///
+ /// EventArgs used for the event.
+ ///
+ public class PlayerItembanPermissionEventArgs : HandledEventArgs
+ {
+ ///
+ /// The player who fired the event.
+ ///
+ public TSPlayer Player { get; set; }
+
+ ///
+ /// The banned item being checked.
+ ///
+ public ItemBan BannedItem { get; set; }
+
+ ///
+ /// Initializes a new instance of the PlayerItembanPermissionEventArgs class.
+ ///
+ /// The player who fired the event.
+ /// The permission being checked.
+ public PlayerItembanPermissionEventArgs(TSPlayer player, ItemBan bannedItem)
+ {
+ Player = player;
+ BannedItem = bannedItem;
+ }
+ }
+
+ ///
+ /// EventArgs used for the event.
+ ///
+ public class PlayerProjbanPermissionEventArgs : HandledEventArgs
+ {
+ ///
+ /// The player who fired the event.
+ ///
+ public TSPlayer Player { get; set; }
+
+ ///
+ /// The banned projectile being checked.
+ ///
+ public ProjectileBan BannedProjectile { get; set; }
+
+ ///
+ /// Initializes a new instance of the PlayerProjbanPermissionEventArgs class.
+ ///
+ /// The player who fired the event.
+ /// The banned projectile being checked.
+ public PlayerProjbanPermissionEventArgs(TSPlayer player, ProjectileBan checkedProjectile)
+ {
+ Player = player;
+ BannedProjectile = checkedProjectile;
+ }
+ }
+
+ ///
+ /// EventArgs used for the event.
+ ///
+ public class PlayerTilebanPermissionEventArgs : HandledEventArgs
+ {
+ ///
+ /// The player who fired the event.
+ ///
+ public TSPlayer Player { get; set; }
+
+ ///
+ /// The banned tile being checked.
+ ///
+ public TileBan BannedTile { get; set; }
+
+ ///
+ /// Initializes a new instance of the PlayerTilebanPermissionEventArgs class.
+ ///
+ /// The player who fired the event.
+ /// The banned tile being checked.
+ public PlayerTilebanPermissionEventArgs(TSPlayer player, TileBan checkedTile)
+ {
+ Player = player;
+ BannedTile = checkedTile;
+ }
+ }
+
///
/// A collection of events fired by players that can be hooked to.
///
@@ -232,6 +314,37 @@ namespace TShockAPI.Hooks
///
public static event PlayerPermissionD PlayerPermission;
+ ///
+ /// The delegate of the event.
+ ///
+ /// The EventArgs for this event.
+ public delegate void PlayerItembanPermissionD(PlayerItembanPermissionEventArgs e);
+ ///
+ /// Fired by players every time a permission check on banned items involving them occurs.
+ ///
+ public static event PlayerItembanPermissionD PlayerItembanPermission;
+
+ ///
+ /// The delegate of the event.
+ ///
+ /// The EventArgs for this event.
+ public delegate void PlayerProjbanPermissionD(PlayerProjbanPermissionEventArgs e);
+ ///
+ /// Fired by players every time a permission check on banned projectiles involving them occurs.
+ ///
+ public static event PlayerProjbanPermissionD PlayerProjbanPermission;
+
+ ///
+ /// The delegate of the event.
+ ///
+ /// The EventArgs for this event.
+ public delegate void PlayerTilebanPermissionD(PlayerTilebanPermissionEventArgs e);
+ ///
+ /// Fired by players every time a permission check on banned tiles involving them occurs.
+ ///
+ public static event PlayerTilebanPermissionD PlayerTilebanPermission;
+
+
///
/// Fires the event.
///
@@ -336,5 +449,50 @@ namespace TShockAPI.Hooks
PlayerPermission(args);
return args.Handled;
}
+
+ ///
+ /// Fires the event.
+ ///
+ /// The player firing the event.
+ /// True if the event has been handled.
+ public static bool OnPlayerItembanPermission(TSPlayer player, ItemBan bannedItem)
+ {
+ if (PlayerItembanPermission == null)
+ return false;
+
+ var args = new PlayerItembanPermissionEventArgs(player, bannedItem);
+ PlayerItembanPermission(args);
+ return args.Handled;
+ }
+
+ ///
+ /// Fires the event.
+ ///
+ /// The player firing the event.
+ /// True if the event has been handled.
+ public static bool OnPlayerProjbanPermission(TSPlayer player, ProjectileBan bannedProj)
+ {
+ if (PlayerProjbanPermission == null)
+ return false;
+
+ var args = new PlayerProjbanPermissionEventArgs(player, bannedProj);
+ PlayerProjbanPermission(args);
+ return args.Handled;
+ }
+
+ ///
+ /// Fires the event.
+ ///
+ /// The player firing the event.
+ /// True if the event has been handled.
+ public static bool OnPlayerTilebanPermission(TSPlayer player, TileBan bannedTile)
+ {
+ if (PlayerTilebanPermission == null)
+ return false;
+
+ var args = new PlayerTilebanPermissionEventArgs(player, bannedTile);
+ PlayerTilebanPermission(args);
+ return args.Handled;
+ }
}
}
From 81cb1381b44fdc16882da43ddb2df1f294277ba7 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Wed, 7 Jun 2017 15:32:40 +0300
Subject: [PATCH 005/430] Add hooks for item/projectile/tile bans
---
TShockAPI/DB/ItemManager.cs | 4 ++++
TShockAPI/DB/ProjectileManager.cs | 4 ++++
TShockAPI/DB/TileManager.cs | 4 ++++
TShockAPI/TSPlayer.cs | 18 ++++++++++++++++++
4 files changed, 30 insertions(+)
diff --git a/TShockAPI/DB/ItemManager.cs b/TShockAPI/DB/ItemManager.cs
index 4ce43066..0ff89b40 100644
--- a/TShockAPI/DB/ItemManager.cs
+++ b/TShockAPI/DB/ItemManager.cs
@@ -21,6 +21,7 @@ using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
+using TShockAPI.Hooks;
namespace TShockAPI.DB
{
@@ -200,6 +201,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.usebanneditem))
return true;
+ if (PlayerHooks.OnPlayerItembanPermission(ply, this))
+ return true;
+
var cur = ply.Group;
var traversed = new List();
while (cur != null)
diff --git a/TShockAPI/DB/ProjectileManager.cs b/TShockAPI/DB/ProjectileManager.cs
index 3f736c9b..79bf9a37 100644
--- a/TShockAPI/DB/ProjectileManager.cs
+++ b/TShockAPI/DB/ProjectileManager.cs
@@ -21,6 +21,7 @@ using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
+using TShockAPI.Hooks;
namespace TShockAPI.DB
{
@@ -205,6 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedprojectiles))
return true;
+ if (PlayerHooks.OnPlayerProjbanPermission(ply, this))
+ return true;
+
var cur = ply.Group;
var traversed = new List();
while (cur != null)
diff --git a/TShockAPI/DB/TileManager.cs b/TShockAPI/DB/TileManager.cs
index 911bf27b..90a235f8 100644
--- a/TShockAPI/DB/TileManager.cs
+++ b/TShockAPI/DB/TileManager.cs
@@ -21,6 +21,7 @@ using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
+using TShockAPI.Hooks;
namespace TShockAPI.DB
{
@@ -205,6 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedtiles))
return true;
+ if (PlayerHooks.OnPlayerTilebanPermission(ply, this))
+ return true;
+
var cur = ply.Group;
var traversed = new List();
while (cur != null)
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 43f7fe18..9b42d7b4 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -1253,6 +1253,24 @@ namespace TShockAPI
else
return Group.HasPermission(permission);
}
+
+ ///
+ public bool HasPermission(ItemBan bannedItem)
+ {
+ return TShock.Itembans.ItemIsBanned(bannedItem.Name, this);
+ }
+
+ ///
+ public bool HasPermission(ProjectileBan bannedProj)
+ {
+ return TShock.ProjectileBans.ProjectileIsBanned(bannedProj.ID, this);
+ }
+
+ ///
+ public bool HasPermission(TileBan bannedTile)
+ {
+ return TShock.TileBans.TileIsBanned(bannedTile.ID, this);
+ }
}
public class TSRestPlayer : TSPlayer
From 8ae0a3b5a6518a573f1287356f23d7a03398678a Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Thu, 8 Jun 2017 17:18:38 +0300
Subject: [PATCH 006/430] Write proper docs
---
TShockAPI/TSPlayer.cs | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 9b42d7b4..42d1b157 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -1254,19 +1254,33 @@ namespace TShockAPI
return Group.HasPermission(permission);
}
- ///
+ ///
+ /// Checks to see if a player has permission to use the specific banned item.
+ /// Fires the hook which may be handled to override item ban permission checks.
+ ///
+ /// The to check.
+ /// True if the player has permission to use the banned item.
public bool HasPermission(ItemBan bannedItem)
{
return TShock.Itembans.ItemIsBanned(bannedItem.Name, this);
}
- ///
+ ///
+ /// Checks to see if a player has permission to use the specific banned projectile.
+ /// Fires the hook which may be handled to override projectile ban permission checks.
+ ///
+ /// The to check.
+ /// True if the player has permission to use the banned projectile.
public bool HasPermission(ProjectileBan bannedProj)
{
return TShock.ProjectileBans.ProjectileIsBanned(bannedProj.ID, this);
}
-
- ///
+ ///
+ /// Checks to see if a player has permission to use the specific banned tile.
+ /// Fires the hook which may be handled to override tile ban permission checks.
+ ///
+ /// The to check.
+ /// True if the player has permission to use the banned tile.
public bool HasPermission(TileBan bannedTile)
{
return TShock.TileBans.TileIsBanned(bannedTile.ID, this);
From 331eeb8cec794a963c05980178327cc6ef866b10 Mon Sep 17 00:00:00 2001
From: MarioE
Date: Mon, 19 Jun 2017 01:15:45 -0400
Subject: [PATCH 007/430] Fix SaveManager saving when 1 player is on the server
and another joins
The real fix would be to fix ServerLeave to not fire incorrectly when a player joins, but this will do for now.
---
TShockAPI/TShock.cs | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 42cd9ef1..776846fa 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1405,9 +1405,14 @@ namespace TShockAPI
}
var tsplr = Players[args.Who];
+ if (tsplr == null)
+ {
+ return;
+ }
+
Players[args.Who] = null;
- if (tsplr != null && tsplr.ReceivedInfo)
+ if (tsplr.ReceivedInfo)
{
if (!tsplr.SilentKickInProgress && tsplr.State >= 3)
Utils.Broadcast(tsplr.Name + " has left.", Color.Yellow);
@@ -1431,7 +1436,7 @@ namespace TShockAPI
}
// Fire the OnPlayerLogout hook too, if the player was logged in and they have a TSPlayer object.
- if (tsplr != null && tsplr.IsLoggedIn)
+ if (tsplr.IsLoggedIn)
{
Hooks.PlayerHooks.OnPlayerLogout(tsplr);
}
From 9ad63c37a616e2b920fcdbc6d7fdc28cbcfae250 Mon Sep 17 00:00:00 2001
From: MarioE
Date: Wed, 21 Jun 2017 01:21:32 -0400
Subject: [PATCH 008/430] Fix /spawnmob not spawning negative IDs again.
---
TShockAPI/Commands.cs | 2 +-
TShockAPI/TSServerPlayer.cs | 7 +------
2 files changed, 2 insertions(+), 7 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index ee9106fc..3b07ca75 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -2300,7 +2300,7 @@ namespace TShockAPI
var npc = npcs[0];
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113)
{
- TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY, 50, 20);
+ TSPlayer.Server.SpawnNPC(npc.netID, npc.FullName, amount, args.Player.TileX, args.Player.TileY, 50, 20);
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned {0} {1} time(s).", npc.FullName, amount);
diff --git a/TShockAPI/TSServerPlayer.cs b/TShockAPI/TSServerPlayer.cs
index a1084d61..b811e9a8 100644
--- a/TShockAPI/TSServerPlayer.cs
+++ b/TShockAPI/TSServerPlayer.cs
@@ -152,12 +152,7 @@ namespace TShockAPI
int spawnTileY;
TShock.Utils.GetRandomClearTileWithInRange(startTileX, startTileY, tileXRange, tileYRange, out spawnTileX,
out spawnTileY);
- int npcid = NPC.NewNPC(spawnTileX * 16, spawnTileY * 16, type, 0);
-
- // TODO: If special slimes break look at the git blame for this spot
- // It's probably because I removed something that didn't work
- Main.npc[npcid].SetDefaults(type);
-
+ NPC.NewNPC(spawnTileX * 16, spawnTileY * 16, type);
}
}
From 40e3a9d5b872ea005e72e6f25bdee351226030b3 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Thu, 22 Jun 2017 21:05:14 +0200
Subject: [PATCH 009/430] fix comment typo
---
TShockAPI/DB/WarpsManager.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/DB/WarpsManager.cs b/TShockAPI/DB/WarpsManager.cs
index d48ba40e..6ed72f4e 100644
--- a/TShockAPI/DB/WarpsManager.cs
+++ b/TShockAPI/DB/WarpsManager.cs
@@ -61,7 +61,7 @@ namespace TShockAPI.DB
/// The X position.
/// The Y position.
/// The name.
- /// Whether the opration succeeded.
+ /// Whether the operation succeeded.
public bool Add(int x, int y, string name)
{
try
From 241d4c566faedd740796822ed1f5cdb10c377dfd Mon Sep 17 00:00:00 2001
From: MarioE
Date: Fri, 23 Jun 2017 14:44:17 -0400
Subject: [PATCH 010/430] Fix incorrect slot calculation, and update submodule.
---
TShockAPI/TShock.cs | 6 +++---
TerrariaServerAPI | 2 +-
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 776846fa..022e70e5 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -2237,9 +2237,9 @@ namespace TShockAPI
Netplay.ListenPort = file.ServerPort;
}
- if (file.MaxSlots > 235)
- file.MaxSlots = 235;
- Main.maxNetPlayers = file.MaxSlots + 20;
+ if (file.MaxSlots > Main.maxPlayers - file.ReservedSlots)
+ file.MaxSlots = Main.maxPlayers - file.ReservedSlots;
+ Main.maxNetPlayers = file.MaxSlots + file.ReservedSlots;
Netplay.ServerPassword = "";
if (!string.IsNullOrEmpty(_cliPassword))
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index d3b7d9f4..bc9f7c69 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit d3b7d9f4575602f468cf1e009ebc4bc5b79547c4
+Subproject commit bc9f7c69becb60816fc1e4587bbca15991231317
From 50a4b07bc39ad58dcec4f5c16cf5ea31135bd6f7 Mon Sep 17 00:00:00 2001
From: MarioE
Date: Fri, 23 Jun 2017 14:47:38 -0400
Subject: [PATCH 011/430] Add "new" EditActions.
---
TShockAPI/GetDataHandlers.cs | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 0bb216e1..2a7ddd00 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1909,7 +1909,10 @@ namespace TShockAPI
KillWire2,
PlaceWire3,
KillWire3,
- SlopeTile
+ SlopeTile,
+ FrameTrack,
+ PlaceWire4,
+ KillWire4
}
public enum EditType
{
From 6b3f18b1da7142ad23fe7fe27c93a13d6677e349 Mon Sep 17 00:00:00 2001
From: ProfessorXZ
Date: Wed, 5 Jul 2017 15:09:31 +0200
Subject: [PATCH 012/430] Validate tile placement on PlaceObject, update
CHANGELOG.md. Fixes #1418
---
CHANGELOG.md | 6 ++++++
TShockAPI/GetDataHandlers.cs | 9 +++++++++
2 files changed, 15 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa42a2aa..267c8ece 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,7 +3,13 @@
This is the rolling changelog for TShock for Terraria. Use past tense when adding new entries; sign your name off when you add or change something. This should primarily be things like user changes, not necessarily codebase changes unless it's really relevant or large.
## Upcoming Changes
+* API: Added hooks for item, projectile and tile bans (@deadsurgeon42)
+* API: New WorldGrassSpread hook which shold allow corruption/crimson/hallow creep config options to work (@DeathCradle)
+* Fixed saving when one player is one the server and another one joins (@MarioE)
+* Fixed /spawnmob not spawning negative IDs (@MarioE)
+* Validated tile placement on PlaceObject; clients can no longer place frames, paintings etc with dirt blocks (@bartico6, @ProfessorXZ)
+## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
* Updated Terraria Server API to 1.3.5.3 (@WhiteXZ, @hakusaro)
* Updated TShock core components to 1.3.5.3 (@hakusaro)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 2a7ddd00..77e37c03 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2350,6 +2350,15 @@ namespace TShockAPI
return true;
}
+ // This is neccessary to check in order to prevent special tiles such as
+ // queen bee larva, paintings etc that use this packet from being placed
+ // without selecting the right item.
+ if (type != args.TPlayer.inventory[args.TPlayer.selectedItem].createTile)
+ {
+ args.Player.SendTileSquare(x, y, 4);
+ return true;
+ }
+
TileObjectData tileData = TileObjectData.GetTileData(type, style, 0);
if (tileData == null)
return true;
From db480a16f0308d2d36d8eb672ce4ced772bf3782 Mon Sep 17 00:00:00 2001
From: Pia Mancini
Date: Thu, 20 Apr 2017 11:45:15 -0400
Subject: [PATCH 013/430] Add backers and sponsors from Open Collective
Now your open collective backers and sponsors can to appear directly on your README.
see how it'll look [here](https://github.com/apex/apex#backers)
[More info](https://github.com/opencollective/opencollective/wiki/Github-banner)
Also add badges on top
---
README.md | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 73 insertions(+)
diff --git a/README.md b/README.md
index 9fa0710d..2d024912 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,9 @@
+[](#backers)
+[](#sponsors)
+
TShock is a server modification for Terraria, written in C#, and based upon the [Terraria Server API](https://github.com/NyxStudios/TerrariaAPI-Server). It uses JSON for configuration management, and offers several features not present in the Terraria Server normally.
## :star: Quick Start
@@ -44,3 +47,73 @@ Please see the contributing file before sending pull requests.
* [Development Builds](https://travis.tshock.co/)
* [Plugins](https://tshock.co/xf/index.php?resources/)
* [Very, very old versions of TShock](https://github.com/TShock/TShock/downloads)
+
+## Backers
+
+Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/tshock#backer)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Sponsors
+
+Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/tshock#sponsor)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
From 587d1b739079a1a38ecf03bfe347a55087c8800f Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Thu, 22 Jun 2017 21:05:14 +0200
Subject: [PATCH 014/430] fix comment typo
---
TShockAPI/DB/WarpsManager.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/DB/WarpsManager.cs b/TShockAPI/DB/WarpsManager.cs
index d48ba40e..6ed72f4e 100644
--- a/TShockAPI/DB/WarpsManager.cs
+++ b/TShockAPI/DB/WarpsManager.cs
@@ -61,7 +61,7 @@ namespace TShockAPI.DB
/// The X position.
/// The Y position.
/// The name.
- /// Whether the opration succeeded.
+ /// Whether the operation succeeded.
public bool Add(int x, int y, string name)
{
try
From 983a678ff3f2a8fce397c3e6d0e444faac4e2528 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 15 Jul 2017 13:32:27 -0600
Subject: [PATCH 015/430] Fix issue 1467 - Password is now hashed when adding a
user via REST API
---
TShockAPI/Rest/RestManager.cs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs
index eace08ee..bd10de2d 100644
--- a/TShockAPI/Rest/RestManager.cs
+++ b/TShockAPI/Rest/RestManager.cs
@@ -520,9 +520,10 @@ namespace TShockAPI
return RestMissingParam("password");
// NOTE: ip can be blank
- User user = new User(username, password, "", group, "", "", "");
+ User user = new User(username, "", "", group, "", "", "");
try
{
+ user.CreateBCryptHash(password);
TShock.Users.AddUser(user);
}
catch (Exception e)
From ac8fe2a2153f183068096a489317da44d2cd3c28 Mon Sep 17 00:00:00 2001
From: MarioE
Date: Tue, 11 Jul 2017 00:33:34 -0400
Subject: [PATCH 016/430] Remove netID handling of GiveItem, and provide a
smaller overload
---
TShockAPI/Commands.cs | 4 +-
TShockAPI/TSPlayer.cs | 130 ++++++++++++++++++++++++------------------
2 files changed, 77 insertions(+), 57 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 3b07ca75..5e7b84bf 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -5297,7 +5297,7 @@ namespace TShockAPI
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
- if (args.Player.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), item.width, item.height, itemAmount, prefixId))
+ if (args.Player.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefixId))
{
item.prefix = (byte)prefixId;
args.Player.SendSuccessMessage("Gave {0} {1}(s).", itemAmount, item.AffixName());
@@ -5436,7 +5436,7 @@ namespace TShockAPI
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
- if (plr.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), item.width, item.height, itemAmount, prefix))
+ if (plr.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefix))
{
args.Player.SendSuccessMessage(string.Format("Gave {0} {1} {2}(s).", plr.Name, itemAmount, item.Name));
plr.SendSuccessMessage(string.Format("{0} gave you {1} {2}(s).", args.Player.Name, itemAmount, item.Name));
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 42d1b157..8d0819bf 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -375,7 +375,7 @@ namespace TShockAPI
get
{
return RealPlayer
- && (Netplay.Clients[Index] != null && Netplay.Clients[Index].IsActive && !Netplay.Clients[Index].PendingTermination);
+ && (Netplay.Clients[Index] != null && Netplay.Clients[Index].IsActive && !Netplay.Clients[Index].PendingTermination);
}
}
@@ -413,10 +413,10 @@ namespace TShockAPI
{
if (string.IsNullOrEmpty(CacheIP))
return
- CacheIP = RealPlayer ? (Netplay.Clients[Index].Socket.IsConnected()
- ? TShock.Utils.GetRealIP(Netplay.Clients[Index].Socket.GetRemoteAddress().ToString())
- : "")
- : "";
+ CacheIP = RealPlayer ? (Netplay.Clients[Index].Socket.IsConnected()
+ ? TShock.Utils.GetRealIP(Netplay.Clients[Index].Socket.GetRemoteAddress().ToString())
+ : "")
+ : "";
else
return CacheIP;
}
@@ -522,7 +522,7 @@ namespace TShockAPI
///
public float X
{
- get { return RealPlayer ? TPlayer.position.X : Main.spawnTileX*16; }
+ get { return RealPlayer ? TPlayer.position.X : Main.spawnTileX * 16; }
}
///
@@ -530,7 +530,7 @@ namespace TShockAPI
///
public float Y
{
- get { return RealPlayer ? TPlayer.position.Y : Main.spawnTileY*16; }
+ get { return RealPlayer ? TPlayer.position.Y : Main.spawnTileY * 16; }
}
///
@@ -538,7 +538,7 @@ namespace TShockAPI
///
public int TileX
{
- get { return (int) (X/16); }
+ get { return (int)(X / 16); }
}
///
@@ -546,7 +546,7 @@ namespace TShockAPI
///
public int TileY
{
- get { return (int) (Y/16); }
+ get { return (int)(Y / 16); }
}
///
@@ -688,7 +688,7 @@ namespace TShockAPI
TilesDestroyed = new Dictionary();
TilesCreated = new Dictionary();
Index = -1;
- FakePlayer = new Player {name = playerName, whoAmI = -1};
+ FakePlayer = new Player { name = playerName, whoAmI = -1 };
Group = Group.DefaultGroup;
AwaitingResponse = new Dictionary>();
}
@@ -744,7 +744,7 @@ namespace TShockAPI
y = 992;
}
- SendTileSquare((int) (x/16), (int) (y/16), 15);
+ SendTileSquare((int)(x / 16), (int)(y / 16), 15);
TPlayer.Teleport(new Vector2(x, y), style);
NetMessage.SendData((int)PacketTypes.Teleport, -1, -1, NetworkText.Empty, 0, TPlayer.whoAmI, x, y, style);
return true;
@@ -784,11 +784,11 @@ namespace TShockAPI
using (var ms = new MemoryStream())
{
var msg = new SpawnMsg
- {
- PlayerIndex = (byte) Index,
- TileX = (short)tilex,
- TileY = (short)tiley
- };
+ {
+ PlayerIndex = (byte)Index,
+ TileX = (short)tilex,
+ TileY = (short)tiley
+ };
msg.PackFull(ms);
SendRawData(ms.ToArray());
}
@@ -804,10 +804,10 @@ namespace TShockAPI
using (var ms = new MemoryStream())
{
var msg = new ProjectileRemoveMsg
- {
- Index = (short) index,
- Owner = (byte) owner
- };
+ {
+ Index = (short)index,
+ Owner = (byte)owner
+ };
msg.PackFull(ms);
SendRawData(ms.ToArray());
}
@@ -817,7 +817,7 @@ namespace TShockAPI
{
try
{
- int num = (size - 1)/2;
+ int num = (size - 1) / 2;
int m_x = 0;
int m_y = 0;
@@ -866,18 +866,37 @@ namespace TShockAPI
///
/// Gives an item to the player. Includes banned item spawn prevention to check if the player can spawn the item.
///
- ///
- ///
- ///
- ///
- ///
- ///
+ /// The item ID.
+ /// The item name.
+ /// The item stack.
+ /// The item prefix.
/// True or false, depending if the item passed the check or not.
+ public bool GiveItemCheck(int type, string name, int stack, int prefix = 0)
+ {
+ if ((TShock.Itembans.ItemIsBanned(name) && TShock.Config.PreventBannedItemSpawn) &&
+ (TShock.Itembans.ItemIsBanned(name, this) || !TShock.Config.AllowAllowedGroupsToSpawnBannedItems))
+ return false;
+
+ GiveItem(type, stack, prefix);
+ return true;
+ }
+
+ ///
+ /// Gives an item to the player. Includes banned item spawn prevention to check if the player can spawn the item.
+ ///
+ /// The item ID.
+ /// The item name.
+ /// The width of the receiver.
+ /// The height of the receiver.
+ /// The item stack.
+ /// The item prefix.
+ /// True or false, depending if the item passed the check or not.
+ [Obsolete("Use the GiveItemCheck overload with fewer parameters.")]
public bool GiveItemCheck(int type, string name, int width, int height, int stack, int prefix = 0)
{
if ((TShock.Itembans.ItemIsBanned(name) && TShock.Config.PreventBannedItemSpawn) &&
- (TShock.Itembans.ItemIsBanned(name, this) || !TShock.Config.AllowAllowedGroupsToSpawnBannedItems))
- return false;
+ (TShock.Itembans.ItemIsBanned(name, this) || !TShock.Config.AllowAllowedGroupsToSpawnBannedItems))
+ return false;
GiveItem(type, name, width, height, stack, prefix);
return true;
@@ -886,28 +905,29 @@ namespace TShockAPI
///
/// Gives an item to the player.
///
- /// The item's netID.
- /// The tiem's name.
- /// The item's width.
- /// The item's height.
- /// The item's stack.
- /// The item's prefix.
+ /// The item ID.
+ /// The item stack.
+ /// The item prefix.
+ public virtual void GiveItem(int type, int stack, int prefix = 0)
+ {
+ int itemIndex = Item.NewItem((int)X, (int)Y, TPlayer.width, TPlayer.height, type, stack, true, prefix, true);
+ SendData(PacketTypes.ItemDrop, "", itemIndex);
+ }
+
+ ///
+ /// Gives an item to the player.
+ ///
+ /// The item ID.
+ /// The item name. This parameter is unused.
+ /// The width of the receiver.
+ /// The height of the receiver.
+ /// The item stack.
+ /// The item prefix.
+ [Obsolete("Use the GiveItem overload with fewer parameters.")]
public virtual void GiveItem(int type, string name, int width, int height, int stack, int prefix = 0)
{
- int itemid = Item.NewItem((int) X, (int) Y, width, height, type, stack, true, prefix, true);
-
- // This is for special pickaxe/hammers/swords etc
- Main.item[itemid].netDefaults(type);
- // The set default overrides the wet and stack set by NewItem
- Main.item[itemid].wet = Collision.WetCollision(Main.item[itemid].position, Main.item[itemid].width,
- Main.item[itemid].height);
- Main.item[itemid].stack = stack;
- Main.item[itemid].owner = Index;
- Main.item[itemid].prefix = (byte) prefix;
- Main.item[itemid].noGrabDelay = 1;
- Main.item[itemid].velocity = Main.player[this.Index].velocity;
- NetMessage.SendData((int)PacketTypes.ItemDrop, -1, -1, NetworkText.Empty, itemid, 0f, 0f, 0f);
- NetMessage.SendData((int)PacketTypes.ItemOwner, -1, -1, NetworkText.Empty, itemid, 0f, 0f, 0f);
+ int itemIndex = Item.NewItem((int)X, (int)Y, width, height, type, stack, true, prefix, true);
+ SendData(PacketTypes.ItemDrop, "", itemIndex);
}
///
@@ -1144,7 +1164,7 @@ namespace TShockAPI
/// The
public virtual void Whoopie(object time)
{
- var time2 = (int) time;
+ var time2 = (int)time;
var launch = DateTime.UtcNow;
var startname = Name;
SendInfoMessage("You are now being annoyed.");
@@ -1186,7 +1206,7 @@ namespace TShockAPI
if (RealPlayer && !ConnectionAlive)
return;
- NetMessage.SendData((int) msgType, Index, -1, NetworkText.FromLiteral(text), number, number2, number3, number4, number5);
+ NetMessage.SendData((int)msgType, Index, -1, NetworkText.FromLiteral(text), number, number2, number3, number4, number5);
}
///
@@ -1205,7 +1225,7 @@ namespace TShockAPI
if (RealPlayer && !ConnectionAlive)
return;
- NetMessage.SendData((int) msgType, Index, -1, NetworkText.FromFormattable(text), ply, number2, number3, number4, number5);
+ NetMessage.SendData((int)msgType, Index, -1, NetworkText.FromFormattable(text), ply, number2, number3, number4, number5);
}
///
@@ -1225,9 +1245,9 @@ namespace TShockAPI
///
/// The string representing the command i.e "yes" == /yes
/// The method that will be executed on confirmation ie user accepts
- public void AddResponse( string name, Action callback)
+ public void AddResponse(string name, Action callback)
{
- if( AwaitingResponse.ContainsKey(name))
+ if (AwaitingResponse.ContainsKey(name))
{
AwaitingResponse.Remove(name);
}
@@ -1291,7 +1311,7 @@ namespace TShockAPI
{
internal List CommandOutput = new List();
- public TSRestPlayer(string playerName, Group playerGroup): base(playerName)
+ public TSRestPlayer(string playerName, Group playerGroup) : base(playerName)
{
Group = playerGroup;
AwaitingResponse = new Dictionary>();
From 1cdd33a78a9aa9c4a0e5ad71590878652937d289 Mon Sep 17 00:00:00 2001
From: Jordan Coulam
Date: Mon, 17 Jul 2017 03:56:56 +0100
Subject: [PATCH 017/430] Added ignoreVersion and loaded plugin list to
StatTracking for issue #1444 (#1445)
---
TShockAPI/StatTracker.cs | 117 ++++++++++++++++++++++++++-------------
1 file changed, 79 insertions(+), 38 deletions(-)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index 78aa10f5..d1c01c1c 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -22,11 +22,13 @@ using System.Threading;
using System.Web;
using TerrariaApi.Server;
using System.Diagnostics;
+using System.Linq;
using System.Runtime.InteropServices;
using System.Net.Http;
using System.Threading.Tasks;
using TShockAPI.Extensions;
+
namespace TShockAPI
{
///
@@ -52,10 +54,11 @@ namespace TShockAPI
///
public bool OptOut = false;
+ private PluginItem[] plugins;
+
private long totalMem = 0;
private string serverId = "";
private HttpClient _client;
-
private const string TrackerUrl = "http://stats.tshock.co/submit/{0}";
///
@@ -103,11 +106,9 @@ namespace TShockAPI
private async Task SendUpdateAsync()
{
JsonData data = PrepareJsonData();
-
var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var encoded = HttpUtility.UrlEncode(serialized);
- var uri = String.Format(TrackerUrl, encoded);
-
+ var uri = string.Format(TrackerUrl, encoded);
try
{
HttpResponseMessage msg = await _client.GetAsync(uri);
@@ -139,49 +140,81 @@ namespace TShockAPI
private JsonData PrepareJsonData()
{
- if (ServerApi.RunningMono)
- {
- if (totalMem == 0)
- {
- //Only do this if we haven't already cached the total physicaly memory
- var pc = new PerformanceCounter("Mono Memory", "Total Physical Memory");
- totalMem = (pc.RawValue / 1024 / 1024 / 1024);
- }
-
- return new JsonData
- {
- port = Terraria.Netplay.ListenPort,
- currentPlayers = TShock.Utils.ActivePlayers(),
- maxPlayers = TShock.Config.MaxSlots,
- systemRam = totalMem,
- version = TShock.VersionNum.ToString(),
- terrariaVersion = Terraria.Main.versionNumber2,
- providerId = ProviderToken,
- serverId = serverId,
- mono = true
- };
- }
-
- if (totalMem == 0)
- {
- //Again, only call this if it hasn't previously been cached
- GetPhysicallyInstalledSystemMemory(out totalMem);
- totalMem = (totalMem / 1024 / 1024); // Super hardcore maths to convert to Gb from Kb
- }
-
- return new JsonData
+ return new JsonData()
{
port = Terraria.Netplay.ListenPort,
currentPlayers = TShock.Utils.ActivePlayers(),
maxPlayers = TShock.Config.MaxSlots,
- systemRam = totalMem,
+ systemRam = GetTotalSystemRam(ServerApi.RunningMono),
version = TShock.VersionNum.ToString(),
terrariaVersion = Terraria.Main.versionNumber2,
providerId = ProviderToken,
serverId = serverId,
- mono = false
+ mono = ServerApi.RunningMono,
+ ignorePluginVersion = ServerApi.IgnoreVersion,
+ loadedPlugins = GetLoadedPlugins()
};
}
+
+ private PluginItem[] GetLoadedPlugins()
+ {
+ if (plugins != null)
+ {
+ return plugins;//Return early
+ }
+
+ plugins = new PluginItem[ServerApi.Plugins.Count];//Initialize with enough room to store the ammount of plugins loaded.
+ for (var i = 0; i < ServerApi.Plugins.Count; i++)
+ {
+ var pluginItem = new PluginItem();
+ var apiAttribute = (ApiVersionAttribute)ServerApi.Plugins[i].Plugin.GetType().GetCustomAttributes(typeof(ApiVersionAttribute), false).FirstOrDefault();
+ //The current implementation of loading plugins doesn't allow for a plugin to be loaded without an ApiVersion, the UNKNOWN is there incase a change is made to allow it
+ pluginItem.apiVersion = apiAttribute?.ApiVersion.ToString() ?? "UNKNOWN";
+ pluginItem.name = ServerApi.Plugins[i].Plugin.Name;
+ pluginItem.version = ServerApi.Plugins[i].Plugin.Version.ToString();
+ plugins[i] = pluginItem;
+ }
+ return plugins;
+ }
+
+ private long GetTotalSystemRam(bool isMono)
+ {
+ if (totalMem != 0)
+ {
+ return totalMem;//Return early
+ }
+
+ if (isMono)//Set totalMem so it can be returned later
+ {
+ var pc = new PerformanceCounter("Mono Memory", "Total Physical Memory");
+ totalMem = (pc.RawValue / 1024 / 1024 / 1024);
+ }
+ else
+ {
+ GetPhysicallyInstalledSystemMemory(out totalMem);
+ totalMem = (totalMem / 1024 / 1024); // Super hardcore maths to convert to Gb from Kb
+ }
+
+ return totalMem;
+ }
+ }
+ ///
+ /// Holding information regarding loaded plugins
+ ///
+ public struct PluginItem
+ {
+ ///
+ /// Plugin name
+ ///
+ public string name;
+ ///
+ /// Assembly version
+ ///
+ public string version;
+ ///
+ /// Api version or UNKNOWN if attribute is missing, which is currently impossible
+ ///
+ public string apiVersion;
}
///
@@ -210,6 +243,14 @@ namespace TShockAPI
///
public string version;
///
+ /// Whether or not server was started with --ignoreversion
+ ///
+ public bool ignorePluginVersion;
+ ///
+ /// List of loaded plugins and version name:
+ ///
+ public PluginItem[] loadedPlugins;
+ ///
/// The Terraria version supported by the server
///
public string terrariaVersion;
@@ -226,4 +267,4 @@ namespace TShockAPI
///
public bool mono;
}
-}
+}
\ No newline at end of file
From b387d42e5342eb2c3eda941a40f0a2ec922b0677 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 16 Jul 2017 21:21:42 -0600
Subject: [PATCH 018/430] Add PR template file
---
PULL_REQUEST_TEMPLATE.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 PULL_REQUEST_TEMPLATE.md
diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..9e7b1cc8
--- /dev/null
+++ b/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1 @@
+
From 4216501c458698b2235a185f3912cf6bfd5dcfcc Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Thu, 13 Jul 2017 16:00:40 +0300
Subject: [PATCH 019/430] Make User implement IEquatable for more consistent
comparisons
---
TShockAPI/DB/UserManager.cs | 64 ++++++++++++++++++++++++++++++++++---
1 file changed, 60 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs
index e79fb933..88103899 100644
--- a/TShockAPI/DB/UserManager.cs
+++ b/TShockAPI/DB/UserManager.cs
@@ -363,7 +363,7 @@ namespace TShockAPI.DB
}
/// A database user.
- public class User
+ public class User : IEquatable
{
/// The database ID of the user.
public int ID { get; set; }
@@ -581,10 +581,66 @@ namespace TShockAPI.DB
return HashPassword(Encoding.UTF8.GetBytes(password));
}
- }
+ #region IEquatable
- /// UserManagerException - An exception generated by the user manager.
- [Serializable]
+ /// Indicates whether the current is equal to another .
+ /// true if the is equal to the parameter; otherwise, false.
+ /// An to compare with this .
+ public bool Equals(User other)
+ {
+ if (ReferenceEquals(null, other)) return false;
+ if (ReferenceEquals(this, other)) return true;
+ return ID == other.ID && string.Equals(Name, other.Name);
+ }
+
+ /// Indicates whether the current is equal to another object.
+ /// true if the is equal to the parameter; otherwise, false.
+ /// An to compare with this .
+ public override bool Equals(object obj)
+ {
+ if (ReferenceEquals(null, obj)) return false;
+ if (ReferenceEquals(this, obj)) return true;
+ if (obj.GetType() != this.GetType()) return false;
+ return Equals((User)obj);
+ }
+
+ /// Serves as the hash function.
+ /// A hash code for the current .
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ return (ID * 397) ^ (Name != null ? Name.GetHashCode() : 0);
+ }
+ }
+
+ ///
+ /// Compares equality of two objects.
+ ///
+ /// Left hand of the comparison.
+ /// Right hand of the comparison.
+ /// true if the objects are equal; otherwise, false.
+ public static bool operator ==(User left, User right)
+ {
+ return Equals(left, right);
+ }
+
+ ///
+ /// Compares equality of two objects.
+ ///
+ /// Left hand of the comparison.
+ /// Right hand of the comparison.
+ /// true if the objects aren't equal; otherwise, false.
+ public static bool operator !=(User left, User right)
+ {
+ return !Equals(left, right);
+ }
+
+ #endregion
+ }
+
+ /// UserManagerException - An exception generated by the user manager.
+ [Serializable]
public class UserManagerException : Exception
{
/// Creates a new UserManagerException object.
From c8e31231ba135465160eb43e20858d3c38c41a68 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Thu, 13 Jul 2017 16:01:47 +0300
Subject: [PATCH 020/430] override ToString of user
---
TShockAPI/DB/UserManager.cs | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs
index 88103899..f93f9935 100644
--- a/TShockAPI/DB/UserManager.cs
+++ b/TShockAPI/DB/UserManager.cs
@@ -637,7 +637,12 @@ namespace TShockAPI.DB
}
#endregion
- }
+
+ public override string ToString()
+ {
+ return Name;
+ }
+ }
/// UserManagerException - An exception generated by the user manager.
[Serializable]
From 5e1be5b19b08350d833a96c46917248641b32782 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Thu, 13 Jul 2017 16:04:17 +0300
Subject: [PATCH 021/430] Fix formatting below IEquatable block
---
TShockAPI/DB/UserManager.cs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs
index f93f9935..368c2dae 100644
--- a/TShockAPI/DB/UserManager.cs
+++ b/TShockAPI/DB/UserManager.cs
@@ -644,8 +644,8 @@ namespace TShockAPI.DB
}
}
- /// UserManagerException - An exception generated by the user manager.
- [Serializable]
+ /// UserManagerException - An exception generated by the user manager.
+ [Serializable]
public class UserManagerException : Exception
{
/// Creates a new UserManagerException object.
@@ -704,4 +704,4 @@ namespace TShockAPI.DB
{
}
}
-}
\ No newline at end of file
+}
From 02be378a2ec5b71ab1e878d22ac14a37b19f3da1 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Fri, 14 Jul 2017 08:03:16 +0300
Subject: [PATCH 022/430] change doc of Equals
---
TShockAPI/DB/UserManager.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs
index 368c2dae..07662b2b 100644
--- a/TShockAPI/DB/UserManager.cs
+++ b/TShockAPI/DB/UserManager.cs
@@ -595,7 +595,7 @@ namespace TShockAPI.DB
/// Indicates whether the current is equal to another object.
/// true if the is equal to the parameter; otherwise, false.
- /// An to compare with this .
+ /// An to compare with this .
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
From 79f66f554febef5efa2167a13eec544a79f43413 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Tue, 11 Jul 2017 10:37:17 +0300
Subject: [PATCH 023/430] Turn the player hooks into a tristate
---
TShockAPI/DB/ItemManager.cs | 5 +-
TShockAPI/DB/ProjectileManager.cs | 5 +-
TShockAPI/DB/TileManager.cs | 5 +-
TShockAPI/Hooks/PlayerHooks.cs | 89 +++++++++++++++++++++++++------
TShockAPI/TSPlayer.cs | 6 ++-
5 files changed, 85 insertions(+), 25 deletions(-)
diff --git a/TShockAPI/DB/ItemManager.cs b/TShockAPI/DB/ItemManager.cs
index 0ff89b40..54ae8ee5 100644
--- a/TShockAPI/DB/ItemManager.cs
+++ b/TShockAPI/DB/ItemManager.cs
@@ -201,8 +201,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.usebanneditem))
return true;
- if (PlayerHooks.OnPlayerItembanPermission(ply, this))
- return true;
+ PermissionResult hookResult = PlayerHooks.OnPlayerItembanPermission(ply, this);
+ if (hookResult != PermissionResult.Inconclusive)
+ return hookResult == PermissionResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/DB/ProjectileManager.cs b/TShockAPI/DB/ProjectileManager.cs
index 79bf9a37..234d3cca 100644
--- a/TShockAPI/DB/ProjectileManager.cs
+++ b/TShockAPI/DB/ProjectileManager.cs
@@ -206,8 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedprojectiles))
return true;
- if (PlayerHooks.OnPlayerProjbanPermission(ply, this))
- return true;
+ PermissionResult hookResult = PlayerHooks.OnPlayerProjbanPermission(ply, this);
+ if (hookResult != PermissionResult.Inconclusive)
+ return hookResult == PermissionResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/DB/TileManager.cs b/TShockAPI/DB/TileManager.cs
index 90a235f8..83b079ab 100644
--- a/TShockAPI/DB/TileManager.cs
+++ b/TShockAPI/DB/TileManager.cs
@@ -206,8 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedtiles))
return true;
- if (PlayerHooks.OnPlayerTilebanPermission(ply, this))
- return true;
+ PermissionResult hookResult = PlayerHooks.OnPlayerTilebanPermission(ply, this);
+ if (hookResult != PermissionResult.Inconclusive)
+ return hookResult == PermissionResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/Hooks/PlayerHooks.cs b/TShockAPI/Hooks/PlayerHooks.cs
index 062a78b8..7f2e8601 100644
--- a/TShockAPI/Hooks/PlayerHooks.cs
+++ b/TShockAPI/Hooks/PlayerHooks.cs
@@ -155,6 +155,11 @@ namespace TShockAPI.Hooks
///
public string Permission { get; set; }
+ ///
+ /// of the hook.
+ ///
+ public PermissionResult Result { get; set; }
+
///
/// Initializes a new instance of the PlayerPermissionEventArgs class.
///
@@ -164,6 +169,7 @@ namespace TShockAPI.Hooks
{
Player = player;
Permission = permission;
+ Result = PermissionResult.Inconclusive;
}
}
@@ -182,15 +188,21 @@ namespace TShockAPI.Hooks
///
public ItemBan BannedItem { get; set; }
+ ///
+ /// of the hook.
+ ///
+ public PermissionResult Result { get; set; }
+
///
/// Initializes a new instance of the PlayerItembanPermissionEventArgs class.
///
/// The player who fired the event.
- /// The permission being checked.
+ /// The banned item being checked.
public PlayerItembanPermissionEventArgs(TSPlayer player, ItemBan bannedItem)
{
Player = player;
BannedItem = bannedItem;
+ Result = PermissionResult.Inconclusive;
}
}
@@ -209,6 +221,11 @@ namespace TShockAPI.Hooks
///
public ProjectileBan BannedProjectile { get; set; }
+ ///
+ /// of the hook.
+ ///
+ public PermissionResult Result { get; set; }
+
///
/// Initializes a new instance of the PlayerProjbanPermissionEventArgs class.
///
@@ -218,6 +235,7 @@ namespace TShockAPI.Hooks
{
Player = player;
BannedProjectile = checkedProjectile;
+ Result = PermissionResult.Inconclusive;
}
}
@@ -236,6 +254,11 @@ namespace TShockAPI.Hooks
///
public TileBan BannedTile { get; set; }
+ ///
+ /// of the hook.
+ ///
+ public PermissionResult Result { get; set; }
+
///
/// Initializes a new instance of the PlayerTilebanPermissionEventArgs class.
///
@@ -245,6 +268,7 @@ namespace TShockAPI.Hooks
{
Player = player;
BannedTile = checkedTile;
+ Result = PermissionResult.Inconclusive;
}
}
@@ -439,60 +463,91 @@ namespace TShockAPI.Hooks
/// Fires the event.
///
/// The player firing the event.
- /// True if the event has been handled.
- public static bool OnPlayerPermission(TSPlayer player, string permission)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionResult OnPlayerPermission(TSPlayer player, string permission)
{
if (PlayerPermission == null)
- return false;
+ return PermissionResult.Inconclusive;
var args = new PlayerPermissionEventArgs(player, permission);
PlayerPermission(args);
- return args.Handled;
+
+ if (args.Handled)
+ return args.Result;
+ else
+ return PermissionResult.Inconclusive;
}
///
/// Fires the event.
///
/// The player firing the event.
- /// True if the event has been handled.
- public static bool OnPlayerItembanPermission(TSPlayer player, ItemBan bannedItem)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionResult OnPlayerItembanPermission(TSPlayer player, ItemBan bannedItem)
{
if (PlayerItembanPermission == null)
- return false;
+ return PermissionResult.Inconclusive;
var args = new PlayerItembanPermissionEventArgs(player, bannedItem);
PlayerItembanPermission(args);
- return args.Handled;
+
+ if (args.Handled)
+ return args.Result;
+ else
+ return PermissionResult.Inconclusive;
}
///
/// Fires the event.
///
/// The player firing the event.
- /// True if the event has been handled.
- public static bool OnPlayerProjbanPermission(TSPlayer player, ProjectileBan bannedProj)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionResult OnPlayerProjbanPermission(TSPlayer player, ProjectileBan bannedProj)
{
if (PlayerProjbanPermission == null)
- return false;
+ return PermissionResult.Inconclusive;
var args = new PlayerProjbanPermissionEventArgs(player, bannedProj);
PlayerProjbanPermission(args);
- return args.Handled;
+
+ if (args.Handled)
+ return args.Result;
+ else
+ return PermissionResult.Inconclusive;
}
///
/// Fires the event.
///
/// The player firing the event.
- /// True if the event has been handled.
- public static bool OnPlayerTilebanPermission(TSPlayer player, TileBan bannedTile)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionResult OnPlayerTilebanPermission(TSPlayer player, TileBan bannedTile)
{
if (PlayerTilebanPermission == null)
- return false;
+ return PermissionResult.Inconclusive;
var args = new PlayerTilebanPermissionEventArgs(player, bannedTile);
PlayerTilebanPermission(args);
- return args.Handled;
+
+ if (args.Handled)
+ return args.Result;
+ else
+ return PermissionResult.Inconclusive;
}
+
}
+
+ ///
+ /// Defines the possible outcomes of handlers.
+ ///
+ public enum PermissionResult
+ {
+ /// Hook doesn't return a result on the permission check.
+ Inconclusive,
+ /// Permission is explicitly denied by a hook.
+ Denied,
+ /// Permission is explicitly granted by a hook.
+ Granted
+ }
+
}
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 8d0819bf..930c587b 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -1265,8 +1265,10 @@ namespace TShockAPI
/// True if the player has that permission.
public bool HasPermission(string permission)
{
- if (PlayerHooks.OnPlayerPermission(this, permission))
- return true;
+ PermissionResult hookResult = PlayerHooks.OnPlayerPermission(this, permission);
+
+ if (hookResult != PermissionResult.Inconclusive)
+ return hookResult == PermissionResult.Granted;
if (tempGroup != null)
return tempGroup.HasPermission(permission);
From 3764527d3d390091c4e12f14481cad54b2b0a63d Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Tue, 11 Jul 2017 16:29:48 +0300
Subject: [PATCH 024/430] don't inherit handled event args for them
---
TShockAPI/Hooks/PlayerHooks.cs | 28 ++++++++--------------------
1 file changed, 8 insertions(+), 20 deletions(-)
diff --git a/TShockAPI/Hooks/PlayerHooks.cs b/TShockAPI/Hooks/PlayerHooks.cs
index 7f2e8601..6e3db3d5 100644
--- a/TShockAPI/Hooks/PlayerHooks.cs
+++ b/TShockAPI/Hooks/PlayerHooks.cs
@@ -143,7 +143,7 @@ namespace TShockAPI.Hooks
///
/// EventArgs used for the event.
///
- public class PlayerPermissionEventArgs : HandledEventArgs
+ public class PlayerPermissionEventArgs
{
///
/// The player who fired the event.
@@ -176,7 +176,7 @@ namespace TShockAPI.Hooks
///
/// EventArgs used for the event.
///
- public class PlayerItembanPermissionEventArgs : HandledEventArgs
+ public class PlayerItembanPermissionEventArgs
{
///
/// The player who fired the event.
@@ -209,7 +209,7 @@ namespace TShockAPI.Hooks
///
/// EventArgs used for the event.
///
- public class PlayerProjbanPermissionEventArgs : HandledEventArgs
+ public class PlayerProjbanPermissionEventArgs
{
///
/// The player who fired the event.
@@ -242,7 +242,7 @@ namespace TShockAPI.Hooks
///
/// EventArgs used for the event.
///
- public class PlayerTilebanPermissionEventArgs : HandledEventArgs
+ public class PlayerTilebanPermissionEventArgs
{
///
/// The player who fired the event.
@@ -472,10 +472,7 @@ namespace TShockAPI.Hooks
var args = new PlayerPermissionEventArgs(player, permission);
PlayerPermission(args);
- if (args.Handled)
- return args.Result;
- else
- return PermissionResult.Inconclusive;
+ return args.Result;
}
///
@@ -491,10 +488,7 @@ namespace TShockAPI.Hooks
var args = new PlayerItembanPermissionEventArgs(player, bannedItem);
PlayerItembanPermission(args);
- if (args.Handled)
- return args.Result;
- else
- return PermissionResult.Inconclusive;
+ return args.Result;
}
///
@@ -510,10 +504,7 @@ namespace TShockAPI.Hooks
var args = new PlayerProjbanPermissionEventArgs(player, bannedProj);
PlayerProjbanPermission(args);
- if (args.Handled)
- return args.Result;
- else
- return PermissionResult.Inconclusive;
+ return args.Result;
}
///
@@ -529,10 +520,7 @@ namespace TShockAPI.Hooks
var args = new PlayerTilebanPermissionEventArgs(player, bannedTile);
PlayerTilebanPermission(args);
- if (args.Handled)
- return args.Result;
- else
- return PermissionResult.Inconclusive;
+ return args.Result;
}
}
From 685d9964f0be1e36ace592e655f69cf416abaf66 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Wed, 12 Jul 2017 08:47:27 +0300
Subject: [PATCH 025/430] Change enum names for clarity
---
TShockAPI/DB/ItemManager.cs | 6 ++--
TShockAPI/DB/ProjectileManager.cs | 6 ++--
TShockAPI/DB/TileManager.cs | 6 ++--
TShockAPI/Hooks/PlayerHooks.cs | 52 +++++++++++++++----------------
TShockAPI/TSPlayer.cs | 6 ++--
5 files changed, 38 insertions(+), 38 deletions(-)
diff --git a/TShockAPI/DB/ItemManager.cs b/TShockAPI/DB/ItemManager.cs
index 54ae8ee5..c3d92840 100644
--- a/TShockAPI/DB/ItemManager.cs
+++ b/TShockAPI/DB/ItemManager.cs
@@ -201,9 +201,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.usebanneditem))
return true;
- PermissionResult hookResult = PlayerHooks.OnPlayerItembanPermission(ply, this);
- if (hookResult != PermissionResult.Inconclusive)
- return hookResult == PermissionResult.Granted;
+ PermissionHookResult hookResult = PlayerHooks.OnPlayerItembanPermission(ply, this);
+ if (hookResult != PermissionHookResult.Unhandled)
+ return hookResult == PermissionHookResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/DB/ProjectileManager.cs b/TShockAPI/DB/ProjectileManager.cs
index 234d3cca..4214fce6 100644
--- a/TShockAPI/DB/ProjectileManager.cs
+++ b/TShockAPI/DB/ProjectileManager.cs
@@ -206,9 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedprojectiles))
return true;
- PermissionResult hookResult = PlayerHooks.OnPlayerProjbanPermission(ply, this);
- if (hookResult != PermissionResult.Inconclusive)
- return hookResult == PermissionResult.Granted;
+ PermissionHookResult hookResult = PlayerHooks.OnPlayerProjbanPermission(ply, this);
+ if (hookResult != PermissionHookResult.Unhandled)
+ return hookResult == PermissionHookResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/DB/TileManager.cs b/TShockAPI/DB/TileManager.cs
index 83b079ab..c291b21a 100644
--- a/TShockAPI/DB/TileManager.cs
+++ b/TShockAPI/DB/TileManager.cs
@@ -206,9 +206,9 @@ namespace TShockAPI.DB
if (ply.HasPermission(Permissions.canusebannedtiles))
return true;
- PermissionResult hookResult = PlayerHooks.OnPlayerTilebanPermission(ply, this);
- if (hookResult != PermissionResult.Inconclusive)
- return hookResult == PermissionResult.Granted;
+ PermissionHookResult hookResult = PlayerHooks.OnPlayerTilebanPermission(ply, this);
+ if (hookResult != PermissionHookResult.Unhandled)
+ return hookResult == PermissionHookResult.Granted;
var cur = ply.Group;
var traversed = new List();
diff --git a/TShockAPI/Hooks/PlayerHooks.cs b/TShockAPI/Hooks/PlayerHooks.cs
index 6e3db3d5..91f9612c 100644
--- a/TShockAPI/Hooks/PlayerHooks.cs
+++ b/TShockAPI/Hooks/PlayerHooks.cs
@@ -156,9 +156,9 @@ namespace TShockAPI.Hooks
public string Permission { get; set; }
///
- /// of the hook.
+ /// of the hook.
///
- public PermissionResult Result { get; set; }
+ public PermissionHookResult Result { get; set; }
///
/// Initializes a new instance of the PlayerPermissionEventArgs class.
@@ -169,7 +169,7 @@ namespace TShockAPI.Hooks
{
Player = player;
Permission = permission;
- Result = PermissionResult.Inconclusive;
+ Result = PermissionHookResult.Unhandled;
}
}
@@ -189,9 +189,9 @@ namespace TShockAPI.Hooks
public ItemBan BannedItem { get; set; }
///
- /// of the hook.
+ /// of the hook.
///
- public PermissionResult Result { get; set; }
+ public PermissionHookResult Result { get; set; }
///
/// Initializes a new instance of the PlayerItembanPermissionEventArgs class.
@@ -202,7 +202,7 @@ namespace TShockAPI.Hooks
{
Player = player;
BannedItem = bannedItem;
- Result = PermissionResult.Inconclusive;
+ Result = PermissionHookResult.Unhandled;
}
}
@@ -222,9 +222,9 @@ namespace TShockAPI.Hooks
public ProjectileBan BannedProjectile { get; set; }
///
- /// of the hook.
+ /// of the hook.
///
- public PermissionResult Result { get; set; }
+ public PermissionHookResult Result { get; set; }
///
/// Initializes a new instance of the PlayerProjbanPermissionEventArgs class.
@@ -235,7 +235,7 @@ namespace TShockAPI.Hooks
{
Player = player;
BannedProjectile = checkedProjectile;
- Result = PermissionResult.Inconclusive;
+ Result = PermissionHookResult.Unhandled;
}
}
@@ -255,9 +255,9 @@ namespace TShockAPI.Hooks
public TileBan BannedTile { get; set; }
///
- /// of the hook.
+ /// of the hook.
///
- public PermissionResult Result { get; set; }
+ public PermissionHookResult Result { get; set; }
///
/// Initializes a new instance of the PlayerTilebanPermissionEventArgs class.
@@ -268,7 +268,7 @@ namespace TShockAPI.Hooks
{
Player = player;
BannedTile = checkedTile;
- Result = PermissionResult.Inconclusive;
+ Result = PermissionHookResult.Unhandled;
}
}
@@ -463,11 +463,11 @@ namespace TShockAPI.Hooks
/// Fires the event.
///
/// The player firing the event.
- /// Event result if the event has been handled, otherwise .
- public static PermissionResult OnPlayerPermission(TSPlayer player, string permission)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionHookResult OnPlayerPermission(TSPlayer player, string permission)
{
if (PlayerPermission == null)
- return PermissionResult.Inconclusive;
+ return PermissionHookResult.Unhandled;
var args = new PlayerPermissionEventArgs(player, permission);
PlayerPermission(args);
@@ -479,11 +479,11 @@ namespace TShockAPI.Hooks
/// Fires the event.
///
/// The player firing the event.
- /// Event result if the event has been handled, otherwise .
- public static PermissionResult OnPlayerItembanPermission(TSPlayer player, ItemBan bannedItem)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionHookResult OnPlayerItembanPermission(TSPlayer player, ItemBan bannedItem)
{
if (PlayerItembanPermission == null)
- return PermissionResult.Inconclusive;
+ return PermissionHookResult.Unhandled;
var args = new PlayerItembanPermissionEventArgs(player, bannedItem);
PlayerItembanPermission(args);
@@ -495,11 +495,11 @@ namespace TShockAPI.Hooks
/// Fires the event.
///
/// The player firing the event.
- /// Event result if the event has been handled, otherwise .
- public static PermissionResult OnPlayerProjbanPermission(TSPlayer player, ProjectileBan bannedProj)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionHookResult OnPlayerProjbanPermission(TSPlayer player, ProjectileBan bannedProj)
{
if (PlayerProjbanPermission == null)
- return PermissionResult.Inconclusive;
+ return PermissionHookResult.Unhandled;
var args = new PlayerProjbanPermissionEventArgs(player, bannedProj);
PlayerProjbanPermission(args);
@@ -511,11 +511,11 @@ namespace TShockAPI.Hooks
/// Fires the event.
///
/// The player firing the event.
- /// Event result if the event has been handled, otherwise .
- public static PermissionResult OnPlayerTilebanPermission(TSPlayer player, TileBan bannedTile)
+ /// Event result if the event has been handled, otherwise .
+ public static PermissionHookResult OnPlayerTilebanPermission(TSPlayer player, TileBan bannedTile)
{
if (PlayerTilebanPermission == null)
- return PermissionResult.Inconclusive;
+ return PermissionHookResult.Unhandled;
var args = new PlayerTilebanPermissionEventArgs(player, bannedTile);
PlayerTilebanPermission(args);
@@ -528,10 +528,10 @@ namespace TShockAPI.Hooks
///
/// Defines the possible outcomes of handlers.
///
- public enum PermissionResult
+ public enum PermissionHookResult
{
/// Hook doesn't return a result on the permission check.
- Inconclusive,
+ Unhandled,
/// Permission is explicitly denied by a hook.
Denied,
/// Permission is explicitly granted by a hook.
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 930c587b..8f7b831e 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -1265,10 +1265,10 @@ namespace TShockAPI
/// True if the player has that permission.
public bool HasPermission(string permission)
{
- PermissionResult hookResult = PlayerHooks.OnPlayerPermission(this, permission);
+ PermissionHookResult hookResult = PlayerHooks.OnPlayerPermission(this, permission);
- if (hookResult != PermissionResult.Inconclusive)
- return hookResult == PermissionResult.Granted;
+ if (hookResult != PermissionHookResult.Unhandled)
+ return hookResult == PermissionHookResult.Granted;
if (tempGroup != null)
return tempGroup.HasPermission(permission);
From 7f68053d3a8bee0a555d89353510f07bab7ce230 Mon Sep 17 00:00:00 2001
From: Ruby Rose
Date: Tue, 11 Jul 2017 16:33:59 +0300
Subject: [PATCH 026/430] Update CHANGELOG.md
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa42a2aa..f0d0f29c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
## Upcoming Changes
+* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
* Updated Terraria Server API to 1.3.5.3 (@WhiteXZ, @hakusaro)
* Updated TShock core components to 1.3.5.3 (@hakusaro)
From 156ce5284518b8b4dceda0eb0a973930a1625b29 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 20 Jul 2017 18:10:16 -0600
Subject: [PATCH 027/430] Closes #1478
This addresses code feedback in the previously deleted pull request
---
CHANGELOG.md | 1 +
TShockAPI/StatTracker.cs | 8 ++++----
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91b371a2..d7ab5308 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed saving when one player is one the server and another one joins (@MarioE)
* Fixed /spawnmob not spawning negative IDs (@MarioE)
* Validated tile placement on PlaceObject; clients can no longer place frames, paintings etc with dirt blocks (@bartico6, @ProfessorXZ)
+* Updated to new stat tracking system with more data so we can actually make informed software decisions (Jordan Coulam)
## TShock 4.3.24
* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index d1c01c1c..47e5d2cc 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -160,10 +160,10 @@ namespace TShockAPI
{
if (plugins != null)
{
- return plugins;//Return early
+ return plugins; //Return early
}
- plugins = new PluginItem[ServerApi.Plugins.Count];//Initialize with enough room to store the ammount of plugins loaded.
+ plugins = new PluginItem[ServerApi.Plugins.Count]; //Initialize with enough room to store the ammount of plugins loaded.
for (var i = 0; i < ServerApi.Plugins.Count; i++)
{
var pluginItem = new PluginItem();
@@ -181,10 +181,10 @@ namespace TShockAPI
{
if (totalMem != 0)
{
- return totalMem;//Return early
+ return totalMem; //Return early
}
- if (isMono)//Set totalMem so it can be returned later
+ if (isMono) //Set totalMem so it can be returned later
{
var pc = new PerformanceCounter("Mono Memory", "Total Physical Memory");
totalMem = (pc.RawValue / 1024 / 1024 / 1024);
From 0753e6d2136231d0c0b456891ad874d352be07f3 Mon Sep 17 00:00:00 2001
From: Leo Li
Date: Sun, 23 Jul 2017 20:42:42 -0700
Subject: [PATCH 028/430] Add more HintPaths for OTAPI
This will help msbuild to find missing libraries when create release
with `/p:Configuration=Release`.
With this patch, the searching order will be:
- If OTAPI with same configuration found, use that.
- Else if OTAPI with Release configuration found, use that.
- Else use OTAPI with Debug configuration.
---
TShockAPI/TShockAPI.csproj | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/TShockAPI.csproj b/TShockAPI/TShockAPI.csproj
index 9bf2ebd9..08e9323d 100644
--- a/TShockAPI/TShockAPI.csproj
+++ b/TShockAPI/TShockAPI.csproj
@@ -74,7 +74,9 @@
False
- ..\TerrariaServerAPI\TerrariaServerAPI\bin\Debug\OTAPI.dll
+ ..\TerrariaServerAPI\TerrariaServerAPI\bin\Debug\OTAPI.dll
+ ..\TerrariaServerAPI\TerrariaServerAPI\bin\Release\OTAPI.dll
+ ..\TerrariaServerAPI\TerrariaServerAPI\bin\$(Configuration)\OTAPI.dll
@@ -214,4 +216,4 @@
-->
-
\ No newline at end of file
+
From 7768511e6e7a778acbbde7e8c7d02aba2e1e45d6 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 23 Jul 2017 22:05:55 -0600
Subject: [PATCH 029/430] Update travis ci badge
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 2d024912..2ad38b13 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
-
+
From 031ef517e3875e7be8edae0ae53b95052daff4a2 Mon Sep 17 00:00:00 2001
From: quake1337
Date: Fri, 4 Aug 2017 12:52:07 +0200
Subject: [PATCH 030/430] Change field visibility
---
TShockAPI/Sockets/LinuxTcpSocket.cs | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/TShockAPI/Sockets/LinuxTcpSocket.cs b/TShockAPI/Sockets/LinuxTcpSocket.cs
index 98df1674..86381237 100644
--- a/TShockAPI/Sockets/LinuxTcpSocket.cs
+++ b/TShockAPI/Sockets/LinuxTcpSocket.cs
@@ -12,23 +12,23 @@ namespace TShockAPI.Sockets
{
public class LinuxTcpSocket : ISocket
{
- private byte[] _packetBuffer = new byte[1024];
+ public byte[] _packetBuffer = new byte[1024];
- private int _packetBufferLength;
+ public int _packetBufferLength;
- private List _callbackBuffer = new List();
+ public List _callbackBuffer = new List();
- private int _messagesInQueue;
+ public int _messagesInQueue;
- private TcpClient _connection;
+ public TcpClient _connection;
- private TcpListener _listener;
+ public TcpListener _listener;
- private SocketConnectionAccepted _listenerCallback;
+ public SocketConnectionAccepted _listenerCallback;
- private RemoteAddress _remoteAddress;
+ public RemoteAddress _remoteAddress;
- private bool _isListening;
+ public bool _isListening;
public int MessagesInQueue
{
From 68437f0a224580de572737d853addadc06cc5970 Mon Sep 17 00:00:00 2001
From: quake1337
Date: Mon, 14 Aug 2017 14:39:22 +0200
Subject: [PATCH 031/430] Add "less than 2gb ram" warning
---
TShockAPI/StatTracker.cs | 2 +-
TShockAPI/TShock.cs | 4 ++++
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index 47e5d2cc..61f42d14 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -177,7 +177,7 @@ namespace TShockAPI
return plugins;
}
- private long GetTotalSystemRam(bool isMono)
+ public long GetTotalSystemRam(bool isMono)
{
if (totalMem != 0)
{
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 022e70e5..8a109a08 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -329,6 +329,10 @@ namespace TShockAPI
Log.ConsoleInfo("TShock {0} ({1}) now running.", Version, VersionCodename);
+ if (StatTracker.GetTotalSystemRam(ServerApi.RunningMono) < 2)
+ {
+ Log.ConsoleInfo("This machine has less than 2 gigabytes of RAM installed. Be advised that it might not be enough to run TShock.");
+ }
ServerApi.Hooks.GamePostInitialize.Register(this, OnPostInit);
ServerApi.Hooks.GameUpdate.Register(this, OnUpdate);
ServerApi.Hooks.GameHardmodeTileUpdate.Register(this, OnHardUpdate);
From 5a04b6651427dca02018effe87ab4ae208cf48fe Mon Sep 17 00:00:00 2001
From: ProfessorXZ
Date: Fri, 8 Sep 2017 21:59:13 +0200
Subject: [PATCH 032/430] Make Utils.GetBuffDescription actually return the
buff's description & properly read 'buffTime' from the stream. Fixes #1469
---
TShockAPI/GetDataHandlers.cs | 8 ++++----
TShockAPI/Utils.cs | 2 +-
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 77e37c03..b593af2c 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -895,14 +895,14 @@ namespace TShockAPI
///
/// Time the buff lasts
///
- public short Time { get; set; }
+ public int Time { get; set; }
}
///
/// PlayerBuff - Called when a player is buffed
///
public static HandlerList PlayerBuff;
- private static bool OnPlayerBuff(byte id, byte type, short time)
+ private static bool OnPlayerBuff(byte id, byte type, int time)
{
if (PlayerBuff == null)
return false;
@@ -911,7 +911,7 @@ namespace TShockAPI
{
ID = id,
Type = type,
- Time = time,
+ Time = time
};
PlayerBuff.Invoke(null, args);
return args.Handled;
@@ -3425,7 +3425,7 @@ namespace TShockAPI
{
var id = args.Data.ReadInt8();
var type = args.Data.ReadInt8();
- var time = args.Data.ReadInt16();
+ var time = args.Data.ReadInt32();
if (OnPlayerBuff(id, type, time))
return true;
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 520bed9c..5081f8e4 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -465,7 +465,7 @@ namespace TShockAPI
/// description
public string GetBuffDescription(int id)
{
- return (id > 0 && id < Main.maxBuffTypes) ? Lang.GetBuffName(id) : "null";
+ return (id > 0 && id < Main.maxBuffTypes) ? Lang.GetBuffDescription(id) : "null";
}
///
From c8549db08726122a5ea1cc62946fc1fe3249d625 Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Tue, 19 Sep 2017 21:00:15 +0200
Subject: [PATCH 033/430] Update Commands.cs
(time % 1.0) * 60.0 can be equal to 59.8, then it gets rounded to undesirable 60 displayed in the time format
---
TShockAPI/Commands.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 5e7b84bf..fbc6c061 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -3872,7 +3872,7 @@ namespace TShockAPI
if (!Main.dayTime)
time += 15.0;
time = time % 24.0;
- args.Player.SendInfoMessage("The current time is {0}:{1:D2}.", (int)Math.Floor(time), (int)Math.Round((time % 1.0) * 60.0));
+ args.Player.SendInfoMessage("The current time is {0}:{1:D2}.", (int)Math.Floor(time), (int)Math.Floor((time % 1.0) * 60.0));
return;
}
From 65582ceaecb4be28acecf88059a4bc4798e38bbd Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Tue, 19 Sep 2017 21:22:56 +0200
Subject: [PATCH 034/430] Update CHANGELOG.md
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7ab5308..efa71d54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed /spawnmob not spawning negative IDs (@MarioE)
* Validated tile placement on PlaceObject; clients can no longer place frames, paintings etc with dirt blocks (@bartico6, @ProfessorXZ)
* Updated to new stat tracking system with more data so we can actually make informed software decisions (Jordan Coulam)
+* Fixed /time display at the end of Terraria hours (@koneko-nyan)
## TShock 4.3.24
* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
From e6ec63a90ee17ac374fba66a8ec3441e4ec8f421 Mon Sep 17 00:00:00 2001
From: quake1337
Date: Wed, 20 Sep 2017 09:27:28 +0200
Subject: [PATCH 035/430] Add @ijwu's changes + add /proc/meminfo trick for
linux
---
TShockAPI/StatTracker.cs | 38 +++++++++++++++++++++++++++++++++++---
TShockAPI/TShock.cs | 6 ++++--
2 files changed, 39 insertions(+), 5 deletions(-)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index 61f42d14..1e4124b6 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -27,7 +27,8 @@ using System.Runtime.InteropServices;
using System.Net.Http;
using System.Threading.Tasks;
using TShockAPI.Extensions;
-
+using System.IO;
+using System.Text.RegularExpressions;
namespace TShockAPI
{
@@ -176,7 +177,38 @@ namespace TShockAPI
}
return plugins;
}
-
+ public long GetFreeSystemRam(bool mono)
+ {
+ if (mono)
+ {
+ //Temporary in case mono won't work
+ if (File.Exists("/proc/meminfo"))
+ {
+ var l = File.ReadAllLines("/proc/meminfo");
+ foreach (string s in l)
+ {
+ if (s.StartsWith("MemFree:"))
+ {
+ var m = Regex.Match(s, "MemFree:(\\s*)(\\d*) kB");
+ if (m.Success)
+ {
+ long val;
+ if (long.TryParse(m.Groups[2].Value, out val))
+ {
+ return val / 1024;
+ }
+ }
+ }
+ }
+ }
+ return -1;
+ }
+ else
+ {
+ var pc = new PerformanceCounter("Memory", "Available MBytes");
+ return pc.RawValue;
+ }
+ }
public long GetTotalSystemRam(bool isMono)
{
if (totalMem != 0)
@@ -267,4 +299,4 @@ namespace TShockAPI
///
public bool mono;
}
-}
\ No newline at end of file
+}
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 8a109a08..db15277b 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -329,10 +329,12 @@ namespace TShockAPI
Log.ConsoleInfo("TShock {0} ({1}) now running.", Version, VersionCodename);
- if (StatTracker.GetTotalSystemRam(ServerApi.RunningMono) < 2)
+ var systemRam = StatTracker.GetFreeSystemRam(ServerApi.RunningMono);
+ if (systemRam > -1 && systemRam < 2048)
{
- Log.ConsoleInfo("This machine has less than 2 gigabytes of RAM installed. Be advised that it might not be enough to run TShock.");
+ Log.ConsoleError("This machine has less than 2 gigabytes of RAM free. Be advised that it might not be enough to run TShock.");
}
+
ServerApi.Hooks.GamePostInitialize.Register(this, OnPostInit);
ServerApi.Hooks.GameUpdate.Register(this, OnUpdate);
ServerApi.Hooks.GameHardmodeTileUpdate.Register(this, OnHardUpdate);
From 4aa81a3d308998c83b6ce6269ccacbcc93284227 Mon Sep 17 00:00:00 2001
From: quake1337
Date: Wed, 20 Sep 2017 17:39:38 +0200
Subject: [PATCH 036/430] Add changes requested by @hakusaro
---
TShockAPI/StatTracker.cs | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index 1e4124b6..b59d5cbc 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -177,6 +177,12 @@ namespace TShockAPI
}
return plugins;
}
+
+ ///
+ /// Returns the amount of free RAM, in megabytes.
+ ///
+ /// Whether or not this program is being executed in a Mono runtime
+ /// Free RAM memory amount, in megabytes
public long GetFreeSystemRam(bool mono)
{
if (mono)
@@ -209,6 +215,11 @@ namespace TShockAPI
return pc.RawValue;
}
}
+ ///
+ /// Returns the total amount of installed RAM, in gigabytes.
+ ///
+ /// Whether or not this program is being executed in a Mono runtime
+ /// Total RAM memory amount, in gigabytes
public long GetTotalSystemRam(bool isMono)
{
if (totalMem != 0)
From 7d5a74330a6e4b5a611e81abde5dda11336b8686 Mon Sep 17 00:00:00 2001
From: quake1337
Date: Wed, 20 Sep 2017 17:42:32 +0200
Subject: [PATCH 037/430] Ate one newline.
---
TShockAPI/StatTracker.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/TShockAPI/StatTracker.cs b/TShockAPI/StatTracker.cs
index b59d5cbc..1151d170 100644
--- a/TShockAPI/StatTracker.cs
+++ b/TShockAPI/StatTracker.cs
@@ -215,6 +215,7 @@ namespace TShockAPI
return pc.RawValue;
}
}
+
///
/// Returns the total amount of installed RAM, in gigabytes.
///
From d396dc5cbbd7d4de2b48b24d750ec2e6aeae5c9c Mon Sep 17 00:00:00 2001
From: quake1337
Date: Wed, 20 Sep 2017 18:42:36 +0200
Subject: [PATCH 038/430] Add CHANGELOG.md entry
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index efa71d54..2e455dab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Validated tile placement on PlaceObject; clients can no longer place frames, paintings etc with dirt blocks (@bartico6, @ProfessorXZ)
* Updated to new stat tracking system with more data so we can actually make informed software decisions (Jordan Coulam)
* Fixed /time display at the end of Terraria hours (@koneko-nyan)
+* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
## TShock 4.3.24
* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
From 02806a24297e22763fb47f509e17576dc08ad980 Mon Sep 17 00:00:00 2001
From: ProfessorXZ
Date: Thu, 21 Sep 2017 10:51:37 +0200
Subject: [PATCH 039/430] Added support for renaming groups. Fixes #1420
---
CHANGELOG.md | 3 +-
TShockAPI/Commands.cs | 24 ++++++
TShockAPI/DB/GroupManager.cs | 160 +++++++++++++++++++++++++++++++----
3 files changed, 168 insertions(+), 19 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e455dab..8e59d2ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
## Upcoming Changes
* API: Added hooks for item, projectile and tile bans (@deadsurgeon42)
+* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
* API: New WorldGrassSpread hook which shold allow corruption/crimson/hallow creep config options to work (@DeathCradle)
* Fixed saving when one player is one the server and another one joins (@MarioE)
* Fixed /spawnmob not spawning negative IDs (@MarioE)
@@ -11,9 +12,9 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Updated to new stat tracking system with more data so we can actually make informed software decisions (Jordan Coulam)
* Fixed /time display at the end of Terraria hours (@koneko-nyan)
* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
+* Added /group rename to allow changing group names (@ColinBohn, @ProfessorXZ)
## TShock 4.3.24
-* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
* Updated Terraria Server API to 1.3.5.3 (@WhiteXZ, @hakusaro)
* Updated TShock core components to 1.3.5.3 (@hakusaro)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index fbc6c061..6fd3ca93 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -2865,6 +2865,7 @@ namespace TShockAPI
"add - Adds a new group.",
"addperm - Adds permissions to a group.",
"color - Changes a group's chat color.",
+ "rename - Changes a group's name.",
"del - Deletes a group.",
"delperm - Removes permissions from a group.",
"list [page] - Lists groups.",
@@ -3074,6 +3075,29 @@ namespace TShockAPI
}
#endregion
return;
+ case "rename":
+ #region Rename group
+ {
+ if (args.Parameters.Count != 3)
+ {
+ args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename ", Specifier);
+ return;
+ }
+
+ string group = args.Parameters[1];
+ string newName = args.Parameters[2];
+ try
+ {
+ string response = TShock.Groups.RenameGroup(group, newName);
+ args.Player.SendSuccessMessage(response);
+ }
+ catch (GroupManagerException ex)
+ {
+ args.Player.SendErrorMessage(ex.Message);
+ }
+ }
+ #endregion
+ return;
case "del":
#region Delete group
{
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 62bad891..0332379f 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -26,6 +26,9 @@ using MySql.Data.MySqlClient;
namespace TShockAPI.DB
{
+ ///
+ /// Represents the GroupManager, which is in charge of group management.
+ ///
public class GroupManager : IEnumerable
{
private IDbConnection database;
@@ -36,17 +39,17 @@ namespace TShockAPI.DB
database = db;
var table = new SqlTable("GroupList",
- new SqlColumn("GroupName", MySqlDbType.VarChar, 32) {Primary = true},
- new SqlColumn("Parent", MySqlDbType.VarChar, 32),
- new SqlColumn("Commands", MySqlDbType.Text),
- new SqlColumn("ChatColor", MySqlDbType.Text),
- new SqlColumn("Prefix", MySqlDbType.Text),
- new SqlColumn("Suffix", MySqlDbType.Text)
- );
+ new SqlColumn("GroupName", MySqlDbType.VarChar, 32) { Primary = true },
+ new SqlColumn("Parent", MySqlDbType.VarChar, 32),
+ new SqlColumn("Commands", MySqlDbType.Text),
+ new SqlColumn("ChatColor", MySqlDbType.Text),
+ new SqlColumn("Prefix", MySqlDbType.Text),
+ new SqlColumn("Suffix", MySqlDbType.Text)
+ );
var creator = new SqlTableCreator(db,
- db.GetSqlType() == SqlType.Sqlite
- ? (IQueryBuilder) new SqliteQueryCreator()
- : new MysqlQueryCreator());
+ db.GetSqlType() == SqlType.Sqlite
+ ? (IQueryBuilder)new SqliteQueryCreator()
+ : new MysqlQueryCreator());
if (creator.EnsureTableStructure(table))
{
// Add default groups if they don't exist
@@ -85,7 +88,11 @@ namespace TShockAPI.DB
AddGroup(name, parent, permissions, Group.defaultChatColor);
}
-
+ ///
+ /// Determines whether the given group exists.
+ ///
+ /// The group.
+ /// true if it does; otherwise, false .
public bool GroupExists(string group)
{
if (group == "superadmin")
@@ -99,11 +106,20 @@ namespace TShockAPI.DB
return GetEnumerator();
}
+ ///
+ /// Gets the enumerator.
+ ///
+ /// The enumerator.
public IEnumerator GetEnumerator()
{
return groups.GetEnumerator();
}
+ ///
+ /// Gets the group matching the specified name.
+ ///
+ /// The name.
+ /// The group.
public Group GetGroupByName(string name)
{
var ret = groups.Where(g => g.Name == name);
@@ -139,8 +155,8 @@ namespace TShockAPI.DB
}
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
- ? "INSERT OR IGNORE INTO GroupList (GroupName, Parent, Commands, ChatColor) VALUES (@0, @1, @2, @3);"
- : "INSERT IGNORE INTO GroupList SET GroupName=@0, Parent=@1, Commands=@2, ChatColor=@3";
+ ? "INSERT OR IGNORE INTO GroupList (GroupName, Parent, Commands, ChatColor) VALUES (@0, @1, @2, @3);"
+ : "INSERT IGNORE INTO GroupList SET GroupName=@0, Parent=@1, Commands=@2, ChatColor=@3";
if (database.Query(query, name, parentname, permissions, chatcolor) == 1)
{
groups.Add(group);
@@ -200,6 +216,70 @@ namespace TShockAPI.DB
group.Suffix = suffix;
}
+ ///
+ /// Renames the specified group.
+ ///
+ /// The group's name.
+ /// The new name.
+ /// The response.
+ public String RenameGroup(string name, string newName)
+ {
+ if (!GroupExists(name))
+ {
+ throw new GroupNotExistException(name);
+ }
+
+ if (GroupExists(newName))
+ {
+ throw new GroupExistsException(newName);
+ }
+
+ if (database.Query("UPDATE GroupList SET GroupName = @0 WHERE GroupName = @1", newName, name) == 1)
+ {
+ var oldGroup = GetGroupByName(name);
+ var newGroup = new Group(newName, oldGroup.Parent, oldGroup.ChatColor, oldGroup.Permissions)
+ {
+ Prefix = oldGroup.Prefix,
+ Suffix = oldGroup.Suffix
+ };
+
+ groups.Remove(oldGroup);
+ groups.Add(newGroup);
+ // We need to check if the old group has been referenced as a parent and update those references accordingly
+ database.Query("UPDATE GroupList SET Parent = @0 WHERE Parent = @1", newName, name);
+ foreach (var group in groups.Where(g => g.Parent != null && g.Parent == oldGroup))
+ {
+ group.Parent = newGroup;
+ }
+
+ if (TShock.Config.DefaultGuestGroupName == oldGroup.Name)
+ {
+ TShock.Config.DefaultGuestGroupName = newGroup.Name;
+ Group.DefaultGroup = newGroup;
+ }
+ if (TShock.Config.DefaultRegistrationGroupName == oldGroup.Name)
+ {
+ TShock.Config.DefaultRegistrationGroupName = newGroup.Name;
+ }
+
+ TShock.Config.Write(FileTools.ConfigPath);
+ database.Query("UPDATE Users SET Usergroup = @0 WHERE Usergroup = @1", newName, name);
+ foreach (var player in TShock.Players.Where(p => p?.Group == oldGroup))
+ {
+ player.Group = newGroup;
+ }
+ return $"Group \"{name}\" has been renamed to \"{newName}\".";
+ }
+
+ throw new GroupManagerException($"Failed to rename group \"{name}\".");
+ }
+
+ ///
+ /// Deletes the specified group.
+ ///
+ /// The group's name.
+ /// Whether exceptions will be thrown in case something goes wrong.
+ ///
public String DeleteGroup(String name, bool exceptions = false)
{
if (!GroupExists(name))
@@ -214,12 +294,18 @@ namespace TShockAPI.DB
groups.Remove(TShock.Utils.GetGroup(name));
return "Group " + name + " has been deleted successfully.";
}
- else if (exceptions)
- throw new GroupManagerException("Failed to delete group '" + name + ".'");
- return "";
+ if (exceptions)
+ throw new GroupManagerException("Failed to delete group '" + name + ".'");
+ return "Failed to delete group '" + name + ".'";
}
+ ///
+ /// Enumerates the given permission list and adds permissions for the specified group accordingly.
+ ///
+ /// The group name.
+ /// The permission list.
+ ///
public String AddPermissions(String name, List permissions)
{
if (!GroupExists(name))
@@ -237,6 +323,12 @@ namespace TShockAPI.DB
return "";
}
+ ///
+ /// Enumerates the given permission list and removes valid permissions for the specified group accordingly.
+ ///
+ /// The group name.
+ /// The permission list.
+ ///
public String DeletePermissions(String name, List permissions)
{
if (!GroupExists(name))
@@ -254,12 +346,15 @@ namespace TShockAPI.DB
return "";
}
+ ///
+ /// Enumerates the group list and loads permissions for each group appropriately.
+ ///
public void LoadPermisions()
{
try
{
List newGroups = new List(groups.Count);
- Dictionary newGroupParents = new Dictionary(groups.Count);
+ Dictionary newGroupParents = new Dictionary(groups.Count);
using (var reader = database.QueryReader("SELECT * FROM GroupList"))
{
while (reader.Read())
@@ -271,7 +366,8 @@ namespace TShockAPI.DB
continue;
}
- newGroups.Add(new Group(groupName, null, reader.Get("ChatColor"), reader.Get("Commands")) {
+ newGroups.Add(new Group(groupName, null, reader.Get("ChatColor"), reader.Get("Commands"))
+ {
Prefix = reader.Get("Prefix"),
Suffix = reader.Get("Suffix"),
});
@@ -360,32 +456,60 @@ namespace TShockAPI.DB
}
}
+ ///
+ /// Represents the base GroupManager exception.
+ ///
[Serializable]
public class GroupManagerException : Exception
{
+ ///
+ /// Initializes a new instance of the with the specified message.
+ ///
+ /// The message.
public GroupManagerException(string message)
: base(message)
{
}
+ ///
+ /// Initializes a new instance of the with the specified message and inner exception.
+ ///
+ /// The message.
+ /// The inner exception.
public GroupManagerException(string message, Exception inner)
: base(message, inner)
{
}
}
+ ///
+ /// Represents the GroupExists exception.
+ /// This exception is thrown whenever an attempt to add an existing group into the database is made.
+ ///
[Serializable]
public class GroupExistsException : GroupManagerException
{
+ ///
+ /// Initializes a new instance of the with the specified group name.
+ ///
+ /// The group name.
public GroupExistsException(string name)
: base("Group '" + name + "' already exists")
{
}
}
+ ///
+ /// Represents the GroupNotExist exception.
+ /// This exception is thrown whenever we try to access a group that does not exist.
+ ///
[Serializable]
public class GroupNotExistException : GroupManagerException
{
+ ///
+ /// Initializes a new instance of the with the specified group name.
+ ///
+ /// The group name.
public GroupNotExistException(string name)
: base("Group '" + name + "' does not exist")
{
From 08e182f59e1f4fc679c8535152239ad4291fceeb Mon Sep 17 00:00:00 2001
From: ProfessorXZ
Date: Sat, 23 Sep 2017 22:41:41 +0200
Subject: [PATCH 040/430] All GroupManager.RenameGroup() database calls are now
done in a transaction
As pointed out by @hakusaro, in order to prevent any damage during the process all database calls need to be done in a transaction. Transactions allow us to rollback from a pending state in case something goes wrong.
---
TShockAPI/Commands.cs | 32 +++++-----
TShockAPI/DB/GroupManager.cs | 110 +++++++++++++++++++++++++----------
2 files changed, 94 insertions(+), 48 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 6fd3ca93..c171c1e0 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -3077,25 +3077,25 @@ namespace TShockAPI
return;
case "rename":
#region Rename group
- {
- if (args.Parameters.Count != 3)
{
- args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename ", Specifier);
- return;
- }
+ if (args.Parameters.Count != 3)
+ {
+ args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename ", Specifier);
+ return;
+ }
- string group = args.Parameters[1];
- string newName = args.Parameters[2];
- try
- {
- string response = TShock.Groups.RenameGroup(group, newName);
- args.Player.SendSuccessMessage(response);
+ string group = args.Parameters[1];
+ string newName = args.Parameters[2];
+ try
+ {
+ string response = TShock.Groups.RenameGroup(group, newName);
+ args.Player.SendSuccessMessage(response);
+ }
+ catch (GroupManagerException ex)
+ {
+ args.Player.SendErrorMessage(ex.Message);
+ }
}
- catch (GroupManagerException ex)
- {
- args.Player.SendErrorMessage(ex.Message);
- }
- }
#endregion
return;
case "del":
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 0332379f..78596083 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -34,6 +34,10 @@ namespace TShockAPI.DB
private IDbConnection database;
public readonly List groups = new List();
+ ///
+ /// Initializes a new instance of the class with the specified database connection.
+ ///
+ /// The connection.
public GroupManager(IDbConnection db)
{
database = db;
@@ -234,41 +238,83 @@ namespace TShockAPI.DB
throw new GroupExistsException(newName);
}
- if (database.Query("UPDATE GroupList SET GroupName = @0 WHERE GroupName = @1", newName, name) == 1)
+ using (var db = database.CloneEx())
{
- var oldGroup = GetGroupByName(name);
- var newGroup = new Group(newName, oldGroup.Parent, oldGroup.ChatColor, oldGroup.Permissions)
+ db.Open();
+ using (var transaction = db.BeginTransaction())
{
- Prefix = oldGroup.Prefix,
- Suffix = oldGroup.Suffix
- };
+ try
+ {
+ using (var command = db.CreateCommand())
+ {
+ command.CommandText = "UPDATE GroupList SET GroupName = @0 WHERE GroupName = @1";
+ command.AddParameter("@0", newName);
+ command.AddParameter("@1", name);
+ command.ExecuteNonQuery();
+ }
- groups.Remove(oldGroup);
- groups.Add(newGroup);
- // We need to check if the old group has been referenced as a parent and update those references accordingly
- database.Query("UPDATE GroupList SET Parent = @0 WHERE Parent = @1", newName, name);
- foreach (var group in groups.Where(g => g.Parent != null && g.Parent == oldGroup))
- {
- group.Parent = newGroup;
- }
+ var oldGroup = GetGroupByName(name);
+ var newGroup = new Group(newName, oldGroup.Parent, oldGroup.ChatColor, oldGroup.Permissions)
+ {
+ Prefix = oldGroup.Prefix,
+ Suffix = oldGroup.Suffix
+ };
+ groups.Remove(oldGroup);
+ groups.Add(newGroup);
- if (TShock.Config.DefaultGuestGroupName == oldGroup.Name)
- {
- TShock.Config.DefaultGuestGroupName = newGroup.Name;
- Group.DefaultGroup = newGroup;
- }
- if (TShock.Config.DefaultRegistrationGroupName == oldGroup.Name)
- {
- TShock.Config.DefaultRegistrationGroupName = newGroup.Name;
- }
+ // We need to check if the old group has been referenced as a parent and update those references accordingly
+ using (var command = db.CreateCommand())
+ {
+ command.CommandText = "UPDATE GroupList SET Parent = @0 WHERE Parent = @1";
+ command.AddParameter("@0", newName);
+ command.AddParameter("@1", name);
+ command.ExecuteNonQuery();
+ }
+ foreach (var group in groups.Where(g => g.Parent != null && g.Parent == oldGroup))
+ {
+ group.Parent = newGroup;
+ }
- TShock.Config.Write(FileTools.ConfigPath);
- database.Query("UPDATE Users SET Usergroup = @0 WHERE Usergroup = @1", newName, name);
- foreach (var player in TShock.Players.Where(p => p?.Group == oldGroup))
- {
- player.Group = newGroup;
+ if (TShock.Config.DefaultGuestGroupName == oldGroup.Name)
+ {
+ TShock.Config.DefaultGuestGroupName = newGroup.Name;
+ Group.DefaultGroup = newGroup;
+ }
+ if (TShock.Config.DefaultRegistrationGroupName == oldGroup.Name)
+ {
+ TShock.Config.DefaultRegistrationGroupName = newGroup.Name;
+ }
+ TShock.Config.Write(FileTools.ConfigPath);
+
+ // We also need to check if any users belong to the old group and automatically apply changes
+ using (var command = db.CreateCommand())
+ {
+ command.CommandText = "UPDATE Users SET Usergroup = @0 WHERE Usergroup = @1";
+ command.AddParameter("@0", newName);
+ command.AddParameter("@1", name);
+ command.ExecuteNonQuery();
+ }
+ foreach (var player in TShock.Players.Where(p => p?.Group == oldGroup))
+ {
+ player.Group = newGroup;
+ }
+
+ transaction.Commit();
+ return $"Group \"{name}\" has been renamed to \"{newName}\".";
+ }
+ catch (Exception ex)
+ {
+ TShock.Log.Error($"An exception has occured during database transaction: {ex.Message}");
+ try
+ {
+ transaction.Rollback();
+ }
+ catch (Exception rollbackEx)
+ {
+ TShock.Log.Error($"An exception has occured during database rollback: {rollbackEx.Message}");
+ }
+ }
}
- return $"Group \"{name}\" has been renamed to \"{newName}\".";
}
throw new GroupManagerException($"Failed to rename group \"{name}\".");
@@ -279,7 +325,7 @@ namespace TShockAPI.DB
///
/// The group's name.
/// Whether exceptions will be thrown in case something goes wrong.
- ///
+ /// The response.
public String DeleteGroup(String name, bool exceptions = false)
{
if (!GroupExists(name))
@@ -305,7 +351,7 @@ namespace TShockAPI.DB
///
/// The group name.
/// The permission list.
- ///
+ /// The response.
public String AddPermissions(String name, List permissions)
{
if (!GroupExists(name))
@@ -328,7 +374,7 @@ namespace TShockAPI.DB
///
/// The group name.
/// The permission list.
- ///
+ /// The response.
public String DeletePermissions(String name, List permissions)
{
if (!GroupExists(name))
From ec435e266e99e63068db97227fe9666140438b3d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 25 Sep 2017 12:18:41 -0600
Subject: [PATCH 041/430] Make our string based error handling more explicit
(Please, someone, please, get rid of this).
---
TShockAPI/DB/GroupManager.cs | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 78596083..6a7d8c4d 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -225,7 +225,7 @@ namespace TShockAPI.DB
///
/// The group's name.
/// The new name.
- /// The response.
+ /// The result from the operation to be sent back to the user.
public String RenameGroup(string name, string newName)
{
if (!GroupExists(name))
@@ -325,7 +325,7 @@ namespace TShockAPI.DB
///
/// The group's name.
/// Whether exceptions will be thrown in case something goes wrong.
- /// The response.
+ /// The result from the operation to be sent back to the user.
public String DeleteGroup(String name, bool exceptions = false)
{
if (!GroupExists(name))
@@ -351,7 +351,7 @@ namespace TShockAPI.DB
///
/// The group name.
/// The permission list.
- /// The response.
+ /// The result from the operation to be sent back to the user.
public String AddPermissions(String name, List permissions)
{
if (!GroupExists(name))
@@ -374,7 +374,7 @@ namespace TShockAPI.DB
///
/// The group name.
/// The permission list.
- /// The response.
+ /// The result from the operation to be sent back to the user.
public String DeletePermissions(String name, List permissions)
{
if (!GroupExists(name))
From 6f8d795a65d0d553bcfc831d3b3aa9a6b41b3383 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 25 Sep 2017 12:28:25 -0600
Subject: [PATCH 042/430] Switch to msbuild commands
Fixes #1494
---
scripts/create_release.py | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/scripts/create_release.py b/scripts/create_release.py
index 3a25f76d..735c664c 100755
--- a/scripts/create_release.py
+++ b/scripts/create_release.py
@@ -145,7 +145,7 @@ def update_terraria_source():
def run_bootstrapper():
for build_config in ['Debug','Release'] :
- mintaka = subprocess.Popen(['xbuild', './TerrariaServerAPI/TShock.4.OTAPI.sln', '/p:Configuration=' + build_config])
+ mintaka = subprocess.Popen(['msbuild', './TerrariaServerAPI/TShock.4.OTAPI.sln', '/p:Configuration=' + build_config])
mintaka.wait()
@@ -161,7 +161,7 @@ def run_bootstrapper():
if (bootstrapper_proc.returncode != 0):
raise CalledProcessError(bootstrapper_proc.returncode)
- tsapi_proc = subprocess.Popen(['xbuild', './TerrariaServerAPI/TerrariaServerAPI/TerrariaServerAPI.csproj', '/p:Configuration=' + build_config])
+ tsapi_proc = subprocess.Popen(['msbuild', './TerrariaServerAPI/TerrariaServerAPI/TerrariaServerAPI.csproj', '/p:Configuration=' + build_config])
tsapi_proc.wait()
@@ -169,8 +169,8 @@ def run_bootstrapper():
raise CalledProcessError(tsapi_proc.returncode)
def build_software():
- release_proc = subprocess.Popen(['xbuild', './TShockAPI/TShockAPI.csproj', '/p:Configuration=Release'])
- debug_proc = subprocess.Popen(['xbuild', './TShockAPI/TShockAPI.csproj', '/p:Configuration=Debug'])
+ release_proc = subprocess.Popen(['msbuild', './TShockAPI/TShockAPI.csproj', '/p:Configuration=Release'])
+ debug_proc = subprocess.Popen(['msbuild', './TShockAPI/TShockAPI.csproj', '/p:Configuration=Debug'])
release_proc.wait()
debug_proc.wait()
if (release_proc.returncode != 0):
From 639ffb3c7cc21d9db20e08e1eae6bcfadc3b1f8b Mon Sep 17 00:00:00 2001
From: ProfessorXZ
Date: Thu, 28 Sep 2017 16:40:03 +0200
Subject: [PATCH 043/430] Fix GroupManager.RenameGroup() overwriting unsaved
config changes
---
TShockAPI/DB/GroupManager.cs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 6a7d8c4d..7d4f5a1b 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -275,6 +275,8 @@ namespace TShockAPI.DB
group.Parent = newGroup;
}
+ // Read the config file to prevent the possible loss of any unsaved changes
+ TShock.Config = ConfigFile.Read(FileTools.ConfigPath);
if (TShock.Config.DefaultGuestGroupName == oldGroup.Name)
{
TShock.Config.DefaultGuestGroupName = newGroup.Name;
From d652fd6c83558e2b058f3788714fe53f6c960e7f Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Mon, 2 Oct 2017 17:36:50 +0200
Subject: [PATCH 044/430] Add OnRegionRenamed hook
---
TShockAPI/Hooks/RegionHooks.cs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/TShockAPI/Hooks/RegionHooks.cs b/TShockAPI/Hooks/RegionHooks.cs
index 9f1b1e78..dcf8d6ce 100644
--- a/TShockAPI/Hooks/RegionHooks.cs
+++ b/TShockAPI/Hooks/RegionHooks.cs
@@ -110,5 +110,29 @@ namespace TShockAPI.Hooks
RegionDeleted(new RegionDeletedEventArgs(region));
}
+
+ public class RegionRenamedEventArgs
+ {
+ public Region Region { get; private set; }
+ public string OldName { get; private set; }
+ public string NewName { get; private set; }
+
+ public RegionRenamedEventArgs(Region region, string oldName, string newName)
+ {
+ Region = region;
+ OldName = oldName;
+ NewName = newName;
+ }
+ }
+
+ public delegate void RegionRenamedD(RegionRenamedEventArgs args);
+ public static event RegionRenamedD RegionRenamed;
+ public static void OnRegionRenamed(Region region, string oldName, string newName)
+ {
+ if (RegionRenamed == null)
+ return;
+
+ RegionRenamed(new RegionRenamedEventArgs(region, oldName, newName));
+ }
}
}
From f5f516d409cc17b74d6f1e358dae7e00e813c068 Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Mon, 2 Oct 2017 17:39:07 +0200
Subject: [PATCH 045/430] Add a CHANGELOG.md entry
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e455dab..94698e0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Updated to new stat tracking system with more data so we can actually make informed software decisions (Jordan Coulam)
* Fixed /time display at the end of Terraria hours (@koneko-nyan)
* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
+* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
## TShock 4.3.24
* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
From 30475be268d1be3ddeb938ae56386d12f7f011a8 Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Mon, 2 Oct 2017 17:42:22 +0200
Subject: [PATCH 046/430] Add RegionRename
---
TShockAPI/DB/RegionManager.cs | 34 ++++++++++++++++++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/TShockAPI/DB/RegionManager.cs b/TShockAPI/DB/RegionManager.cs
index 661ec1c5..8649dedf 100644
--- a/TShockAPI/DB/RegionManager.cs
+++ b/TShockAPI/DB/RegionManager.cs
@@ -401,7 +401,41 @@ namespace TShockAPI.DB
}
return false;
}
+
+ ///
+ /// Renames a region
+ ///
+ /// Name of the region to rename
+ /// New name of the region
+ /// true if renamed successfully, false otherwise
+ public bool RenameRegion(string oldName, string newName)
+ {
+ Region region = null;
+ string worldID = Main.worldID.ToString();
+ bool result = false;
+
+ try
+ {
+ int q = database.Query("UPDATE Regions SET RegionName = @0 WHERE RegionName=@1 AND WorldID=@2",
+ newName, oldName, worldID);
+
+ if (q > 0)
+ {
+ region = Regions.First(r => r.Name == oldName && r.WorldID == worldID);
+ region.Name = newName;
+ Hooks.RegionHooks.OnRegionRenamed(region, oldName, newName);
+ result = true;
+ }
+ }
+ catch (Exception ex)
+ {
+ TShock.Log.Error(ex.ToString());
+ }
+
+ return result;
+ }
+
///
/// Removes an allowed user from a region
///
From aaa84d1ba9c010dae726b207a1dab6bfc0de518e Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Mon, 2 Oct 2017 17:45:57 +0200
Subject: [PATCH 047/430] Add 'rename' sub-command to /region
---
TShockAPI/Commands.cs | 46 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 46 insertions(+)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index fbc6c061..615ba59f 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -4530,6 +4530,51 @@ namespace TShockAPI
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize ", Specifier);
break;
}
+ case "rename":
+ {
+ if (args.Parameters.Count != 3)
+ {
+ args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region rename ", Specifier);
+ break;
+ }
+ else
+ {
+ string oldName = args.Parameters[1];
+ string newName = args.Parameters[2];
+
+ if (oldName == newName)
+ {
+ args.Player.SendErrorMessage("Error: both names are the same.");
+ break;
+ }
+
+ Region oldRegion = TShock.Regions.GetRegionByName(oldName);
+
+ if (oldRegion == null)
+ {
+ args.Player.SendErrorMessage("Invalid region \"{0}\".", oldName);
+ break;
+ }
+
+ Region newRegion = TShock.Regions.GetRegionByName(newName);
+
+ if (newRegion != null)
+ {
+ args.Player.SendErrorMessage("Region \"{0}\" already exists.", newName);
+ break;
+ }
+
+ if(TShock.Regions.RenameRegion(oldName, newName))
+ {
+ args.Player.SendInfoMessage("Region renamed successfully!");
+ }
+ else
+ {
+ args.Player.SendErrorMessage("Failed to rename the region.");
+ }
+ }
+ break;
+ }
case "tp":
{
if (!args.Player.HasPermission(Permissions.tp))
@@ -4570,6 +4615,7 @@ namespace TShockAPI
"define - Defines the region with the given name.",
"delete - Deletes the given region.",
"name [-u][-z][-p] - Shows the name of the region at the given point.",
+ "rename - Renames the given region.",
"list - Lists all regions.",
"resize - Resizes a region.",
"allow - Allows a user to a region.",
From 7f9d76f71fe3d9f6d154b102263d995a09e5586a Mon Sep 17 00:00:00 2001
From: Innectic
Date: Fri, 6 Oct 2017 12:52:33 -0700
Subject: [PATCH 048/430] Put Github files where they belong
Closes #1495
---
CONTRIBUTING.md => .github/CONTRIBUTING.md | 0
PULL_REQUEST_TEMPLATE.md => .github/PULL_REQUEST_TEMPLATE.md | 0
2 files changed, 0 insertions(+), 0 deletions(-)
rename CONTRIBUTING.md => .github/CONTRIBUTING.md (100%)
rename PULL_REQUEST_TEMPLATE.md => .github/PULL_REQUEST_TEMPLATE.md (100%)
diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md
similarity index 100%
rename from CONTRIBUTING.md
rename to .github/CONTRIBUTING.md
diff --git a/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
similarity index 100%
rename from PULL_REQUEST_TEMPLATE.md
rename to .github/PULL_REQUEST_TEMPLATE.md
From 70019002c9013fe99cc5505d8c1060b6087edacb Mon Sep 17 00:00:00 2001
From: Innectic
Date: Fri, 6 Oct 2017 12:58:17 -0700
Subject: [PATCH 049/430] Add issue template
---
.github/ISSUE_TEMPLATE.md | 11 +++++++++++
1 file changed, 11 insertions(+)
create mode 100644 .github/ISSUE_TEMPLATE.md
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000..2b249480
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,11 @@
+
+## TShock version
+
+
+## Any stack traces that may have happened when the issue occurred
+
+
+## Steps to reproduce
+
+
+## Screenshots of the problem, if applicable
From 9d12461f8d8f1ca3a57c8c5b5c0b150324767e28 Mon Sep 17 00:00:00 2001
From: koneko-nyan <31385587+koneko-nyan@users.noreply.github.com>
Date: Fri, 13 Oct 2017 09:12:56 +0200
Subject: [PATCH 050/430] Fix some spaces
---
TShockAPI/DB/RegionManager.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/DB/RegionManager.cs b/TShockAPI/DB/RegionManager.cs
index 8649dedf..f94b2a48 100644
--- a/TShockAPI/DB/RegionManager.cs
+++ b/TShockAPI/DB/RegionManager.cs
@@ -417,7 +417,7 @@ namespace TShockAPI.DB
try
{
- int q = database.Query("UPDATE Regions SET RegionName = @0 WHERE RegionName=@1 AND WorldID=@2",
+ int q = database.Query("UPDATE Regions SET RegionName = @0 WHERE RegionName = @1 AND WorldID = @2",
newName, oldName, worldID);
if (q > 0)
From 744c8123234f2c2276b6bdc368d4be132903270e Mon Sep 17 00:00:00 2001
From: Ziteng Wang
Date: Mon, 20 Nov 2017 14:51:42 -0800
Subject: [PATCH 051/430] Fix item frame not working properly
---
TShockAPI/GetDataHandlers.cs | 10 +++-------
1 file changed, 3 insertions(+), 7 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index b593af2c..2fa9cbd0 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2109,7 +2109,9 @@ namespace TShockAPI
return true;
}
// If the tile is a pickaxe tile and they aren't selecting a pickaxe, they're hacking.
- else if ((!Main.tileAxe[tile.type] && !Main.tileHammer[tile.type]) && tile.wall == 0 && ((args.TPlayer.mount.Type != 8 && selectedItem.pick == 0) && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0))
+ // Item frames can be modified without pickaxe tile.
+ else if (tile.type != TileID.ItemFrame
+ && !Main.tileAxe[tile.type] && !Main.tileHammer[tile.type] && tile.wall == 0 && args.TPlayer.mount.Type != 8 && selectedItem.pick == 0 && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0)
{
args.Player.SendTileSquare(tileX, tileY, 4);
return true;
@@ -4376,12 +4378,6 @@ namespace TShockAPI
return true;
}
- if (itemFrame.item?.netID == args.TPlayer.inventory[args.TPlayer.selectedItem]?.netID)
- {
- NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, itemFrame.ID, 0, 1);
- return true;
- }
-
return false;
}
From 9dee0aee7d6b1a401c8855d60035cc8fc01615d9 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 1 Dec 2017 23:12:06 -0700
Subject: [PATCH 052/430] Rewrote the /ban add sub command
/ban add now replaces add, addtemp, and addip.
New syntax: /ban add [time] [reason]
Examples:
- /ban add Shank 10d Rewrote the ban system.
- /ban add Ash
- /ban add 127.0.0.1 5d Go work on homework.
Note that if you want to specify a reason and a permaban, you need
to use 0 (zero) as the duration.
Examples:
- /ban add Ash 0 Love ya.
- /ban add Shank 0 Hacking.
Closes #1510
---
TShockAPI/Commands.cs | 341 +++++++++++++++++++++---------------------
1 file changed, 171 insertions(+), 170 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 493aa956..87559392 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -35,6 +35,7 @@ using Terraria.GameContent.Events;
using Microsoft.Xna.Framework;
using OTAPI.Tile;
using TShockAPI.Localization;
+using System.Text.RegularExpressions;
namespace TShockAPI
{
@@ -1273,200 +1274,202 @@ namespace TShockAPI
switch (subcmd)
{
case "add":
- #region Add ban
+ #region Add Ban
{
if (args.Parameters.Count < 2)
{
- args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban add [reason]", Specifier);
+ args.Player.SendErrorMessage("Invalid command. Format: {0}ban add [time] [reason]", Specifier);
+ args.Player.SendErrorMessage("Example: {0}ban add Shank 10d Hacking and cheating", Specifier);
+ args.Player.SendErrorMessage("Example: {0}ban add Ash", Specifier);
+ args.Player.SendErrorMessage("Use the time 0 (zero) for a permanent ban.");
return;
}
+ // Used only to notify if a ban was successful and who the ban was about
+ bool success = false;
+ string targetGeneralizedName = "";
+
+ // What if caller is console? Name?
+
+ // Effective ban target assignment
List players = TShock.Utils.FindPlayer(args.Parameters[1]);
- string reason = args.Parameters.Count > 2 ? String.Join(" ", args.Parameters.Skip(2)) : "Misbehavior.";
- if (players.Count == 0)
+ User offlineUser = TShock.Users.GetUserByName(args.Parameters[1]);
+
+ // Determines if the caller is effective root for overriding permissions
+ bool callerIsEffectiveRoot = false;
+
+ // A ban source is effective root if they are not not real and not rest
+ // Super admins ingame who attempt to run this will have to remove
+ // the immune to ban permission if they want to ban an immune player
+ if (!(args.Player is TSRestPlayer) && !args.Player.RealPlayer)
{
- var user = TShock.Users.GetUserByName(args.Parameters[1]);
- if (user != null)
- {
- bool force = !args.Player.RealPlayer;
-
- if (user.Name == args.Player.Name && !force)
- {
- args.Player.SendErrorMessage("You can't ban yourself!");
- return;
- }
-
- if (TShock.Groups.GetGroupByName(user.Group).HasPermission(Permissions.immunetoban) && !force)
- args.Player.SendErrorMessage("You can't ban {0}!", user.Name);
- else
- {
- if (user.KnownIps == null)
- {
- args.Player.SendErrorMessage("Cannot ban {0} because they have no IPs to ban.", user.Name);
- return;
- }
- var knownIps = JsonConvert.DeserializeObject>(user.KnownIps);
- TShock.Bans.AddBan(knownIps.Last(), user.Name, user.UUID, reason, false, args.Player.User.Name);
- if (String.IsNullOrWhiteSpace(args.Player.User.Name))
- {
- if (args.Silent)
- {
- args.Player.SendInfoMessage("{0} was {1}banned for '{2}'.", user.Name, force ? "Force " : "", reason);
- }
- else
- {
- TSPlayer.All.SendInfoMessage("{0} was {1}banned for '{2}'.", user.Name, force ? "Force " : "", reason);
- }
- }
- else
- {
- if (args.Silent)
- {
- args.Player.SendInfoMessage("{0}banned {1} for '{2}'.", force ? "Force " : "", user.Name, reason);
- }
- else
- {
- TSPlayer.All.SendInfoMessage("{0} {1}banned {2} for '{3}'.", args.Player.Name, force ? "Force " : "", user.Name, reason);
- }
- }
- }
- }
- else
- args.Player.SendErrorMessage("Invalid player or account!");
+ callerIsEffectiveRoot = true;
}
- else if (players.Count > 1)
+
+ // The ban reason the ban is going to have
+ string banReason = "Unknown.";
+
+ // The default ban length
+ // 0 is permanent ban, otherwise temp ban
+ int banLengthInSeconds = 0;
+
+ // Figure out if param 2 is a time or 0 or garbage
+ if (args.Parameters.Count >= 3)
+ {
+ bool parsedOkay = false;
+ if (!(args.Parameters[2] == "0"))
+ {
+ parsedOkay = TShock.Utils.TryParseTime(args.Parameters[2], out banLengthInSeconds);
+ } else {
+ parsedOkay = true;
+ }
+
+ if (!parsedOkay)
+ {
+ args.Player.SendErrorMessage("Invalid time format. Example: 10d+5h+3m-2s.");
+ args.Player.SendErrorMessage("Use 0 (zero) for a permanent ban.");
+ return;
+ }
+ }
+
+ // If a reason exists, use the given reason.
+ if (args.Parameters.Count > 3)
+ {
+ banReason = String.Join(" ", args.Parameters.Skip(3));
+ }
+
+ // Bad case: Players contains more than 1 person so we can't ban them
+ if (players.Count > 1)
+ {
TShock.Utils.SendMultipleMatchError(args.Player, players.Select(p => p.Name));
- else
- {
- if (!TShock.Utils.Ban(players[0], reason, !args.Player.RealPlayer, args.Player.User.Name))
- args.Player.SendErrorMessage("You can't ban {0}!", players[0].Name);
- }
- }
- #endregion
- return;
- case "addip":
- #region Add IP ban
- {
- if (args.Parameters.Count < 2)
- {
- args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban addip [reason]", Specifier);
return;
}
- string ip = args.Parameters[1];
- string reason = args.Parameters.Count > 2
- ? String.Join(" ", args.Parameters.GetRange(2, args.Parameters.Count - 2))
- : "Manually added IP address ban.";
- TShock.Bans.AddBan(ip, "", "", reason, false, args.Player.User.Name);
- args.Player.SendSuccessMessage("Banned IP {0}.", ip);
- }
- #endregion
- return;
- case "addtemp":
- #region Add temp ban
- {
- if (args.Parameters.Count < 3)
+ // Good case: Online ban for matching character.
+ if (players.Count == 1)
{
- args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban addtemp [reason]", Specifier);
- return;
- }
+ TSPlayer target = players[0];
- int time;
- if (!TShock.Utils.TryParseTime(args.Parameters[2], out time))
- {
- args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
- args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
- return;
- }
-
- string reason = args.Parameters.Count > 3
- ? String.Join(" ", args.Parameters.Skip(3))
- : "Misbehavior.";
-
- List players = TShock.Utils.FindPlayer(args.Parameters[1]);
- if (players.Count == 0)
- {
- var user = TShock.Users.GetUserByName(args.Parameters[1]);
- if (user != null)
+ if (target.HasPermission(Permissions.immunetoban) && !callerIsEffectiveRoot)
{
- bool force = !args.Player.RealPlayer;
- if (TShock.Groups.GetGroupByName(user.Group).HasPermission(Permissions.immunetoban) && !force)
- args.Player.SendErrorMessage("You can't ban {0}!", user.Name);
- else
- {
- var knownIps = JsonConvert.DeserializeObject>(user.KnownIps);
- TShock.Bans.AddBan(knownIps.Last(), user.Name, user.UUID, reason, false, args.Player.User.Name, DateTime.UtcNow.AddSeconds(time).ToString("s"));
- if (String.IsNullOrWhiteSpace(args.Player.User.Name))
- {
- if (args.Silent)
- {
- args.Player.SendInfoMessage("{0} was {1}banned for '{2}'.", user.Name, force ? "force " : "", reason);
- }
- else
- {
- TSPlayer.All.SendInfoMessage("{0} was {1}banned for '{2}'.", user.Name, force ? "force " : "", reason);
- }
- }
- else
- {
- if (args.Silent)
- {
- args.Player.SendInfoMessage("{0} was {1}banned for '{2}'.", user.Name, force ? "force " : "", reason);
- }
- else
- {
- TSPlayer.All.SendInfoMessage("{0} {1}banned {2} for '{3}'.", args.Player.Name, force ? "force " : "", user.Name, reason);
- }
- }
- }
- }
- else
- {
- args.Player.SendErrorMessage("Invalid player or account!");
- }
- }
- else if (players.Count > 1)
- TShock.Utils.SendMultipleMatchError(args.Player, players.Select(p => p.Name));
- else
- {
- if (args.Player.RealPlayer && players[0].HasPermission(Permissions.immunetoban))
- {
- args.Player.SendErrorMessage("You can't ban {0}!", players[0].Name);
+ args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", target.Name);
return;
}
- if (TShock.Bans.AddBan(players[0].IP, players[0].Name, players[0].UUID, reason,
- false, args.Player.Name, DateTime.UtcNow.AddSeconds(time).ToString("s")))
+ targetGeneralizedName = target.Name;
+ success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, banReason, false, args.Player.User.Name,
+ banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+
+ // Since this is an online ban, we need to dc the player and tell them now.
+ if (success)
{
- players[0].Disconnect(String.Format("Banned: {0}", reason));
- string verb = args.Player.RealPlayer ? "Force " : "";
- if (args.Player.RealPlayer)
- if (args.Silent)
- {
- args.Player.SendSuccessMessage("{0}banned {1} for '{2}'", verb, players[0].Name, reason);
- }
- else
- {
- TSPlayer.All.SendSuccessMessage("{0} {1}banned {2} for '{3}'", args.Player.Name, verb, players[0].Name, reason);
- }
+ if (banLengthInSeconds == 0)
+ {
+ target.Disconnect(String.Format("Permanently banned for {0}", banReason));
+ }
else
{
- if (args.Silent)
- {
- args.Player.SendSuccessMessage("{0}banned {1} for '{2}'", verb, players[0].Name, reason);
- }
- else
- {
- TSPlayer.All.SendSuccessMessage("{0} was {1}banned for '{2}'", players[0].Name, verb, reason);
- }
+ target.Disconnect(String.Format("Banned for {0} seconds for {1}", banLengthInSeconds, banReason));
}
}
- else
- args.Player.SendErrorMessage("Failed to ban {0}, check logs.", players[0].Name);
}
+
+ // Case: Players & user are invalid, could be IP?
+ // Note: Order matters. If this method is above the online player check,
+ // This enables you to ban an IP even if the player exists in the database as a player.
+ // You'll get two bans for the price of one, in theory, because both IP and user named IP will be banned.
+ // ??? edge cases are weird, but this is going to happen
+ // The only way around this is to either segregate off the IP code or do something else.
+ if (players.Count == 0)
+ {
+ // If the target is a valid IP...
+ string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
+ Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
+ if (r.IsMatch(args.Parameters[1])) {
+ targetGeneralizedName = String.Join(" ", "IP:", args.Parameters[1]);
+ success = TShock.Bans.AddBan(args.Parameters[1], "", "", banReason,
+ false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+ if (success && offlineUser != null)
+ {
+ args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
+ args.Player.SendErrorMessage("Note: An account named with this IP address also exists.");
+ args.Player.SendErrorMessage("Note: It will also be banned.");
+ }
+ } else {
+ // Apparently there is no way to not IP ban someone
+ // This means that where we would normally just ban a "character name" here
+ // We can't because it requires some IP as a primary key.
+ if (offlineUser == null)
+ {
+ args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]);
+ args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user.");
+ return;
+ }
+ }
+
+ }
+
+ // Case: Offline ban
+ if (players.Count == 0 && offlineUser != null)
+ {
+ // Catch: we don't know an offline player's last login character name
+ // This means that we're banning their *user name* on the assumption that
+ // user name == character name
+ // (which may not be true)
+ // This needs to be fixed in a future implementation.
+ targetGeneralizedName = offlineUser.Name;
+
+ if (TShock.Groups.GetGroupByName(offlineUser.Group).HasPermission(Permissions.immunetoban) &&
+ !callerIsEffectiveRoot)
+ {
+ args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
+ return;
+ }
+
+ if (offlineUser.KnownIps == null)
+ {
+ args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
+ return;
+ }
+
+ string lastIP = JsonConvert.DeserializeObject>(offlineUser.KnownIps).Last();
+
+ success =
+ TShock.Bans.AddBan(lastIP,
+ offlineUser.Name, offlineUser.UUID, banReason, false, args.Player.User.Name,
+ banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+ }
+
+
+ if (success)
+ {
+ args.Player.SendSuccessMessage("{0} was successfully banned.", targetGeneralizedName);
+ args.Player.SendInfoMessage("Length: {0}", banLengthInSeconds == 0 ? "Permanent." : banLengthInSeconds + " seconds.");
+ args.Player.SendInfoMessage("Reason: {0}", banReason);
+ if (!args.Silent)
+ {
+ if (banLengthInSeconds == 0)
+ {
+ TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
+ targetGeneralizedName, args.Player.User.Name, banReason);
+ }
+ else
+ {
+ TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}",
+ targetGeneralizedName, banLengthInSeconds, args.Player.User.Name, banReason);
+ }
+ }
+ }
+ else
+ {
+ args.Player.SendErrorMessage("{0} was NOT banned due to a database error or other system problem.", targetGeneralizedName);
+ args.Player.SendErrorMessage("If this player is online, they have NOT been kicked.");
+ args.Player.SendErrorMessage("Check the system logs for details.");
+ }
+
+ return;
}
#endregion
- return;
case "del":
#region Delete ban
{
@@ -1522,9 +1525,7 @@ namespace TShockAPI
var lines = new List
{
- "add [reason] - Bans a player or user account if the player is not online.",
- "addip [reason] - Bans an IP.",
- "addtemp [reason] - Temporarily bans a player.",
+ "add [reason] - Bans a player or user account if the player is not online.",
"del - Unbans a player.",
"delip - Unbans an IP.",
"list [page] - Lists all player bans.",
From d10c8d65f61763ee3d0f511cebc60deaa2110238 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 1 Dec 2017 23:20:34 -0700
Subject: [PATCH 053/430] Removed minor comment
Turns out that ServerConsole gets a name if caller is unknown.
---
TShockAPI/Commands.cs | 2 --
1 file changed, 2 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 87559392..67b0643c 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1289,8 +1289,6 @@ namespace TShockAPI
bool success = false;
string targetGeneralizedName = "";
- // What if caller is console? Name?
-
// Effective ban target assignment
List players = TShock.Utils.FindPlayer(args.Parameters[1]);
User offlineUser = TShock.Users.GetUserByName(args.Parameters[1]);
From ec2a5425649463152c8743c9c6900bd0b5ba53f3 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 1 Dec 2017 23:27:51 -0700
Subject: [PATCH 054/430] Remove silly string join since snoons is right
> String.Join(" ", str1, str2) is far less clear than str1 + " " + str2
---
TShockAPI/Commands.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 67b0643c..26ed7fc5 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1384,7 +1384,7 @@ namespace TShockAPI
string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(args.Parameters[1])) {
- targetGeneralizedName = String.Join(" ", "IP:", args.Parameters[1]);
+ targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan(args.Parameters[1], "", "", banReason,
false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
if (success && offlineUser != null)
From 1e68ac22c7d7c191f05e6f86b7847c2b4f885340 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 14:25:33 -0700
Subject: [PATCH 055/430] Remove superadmin customization config options
---
TShockAPI/ConfigFile.cs | 12 ------------
TShockAPI/Group.cs | 10 +++++-----
2 files changed, 5 insertions(+), 17 deletions(-)
diff --git a/TShockAPI/ConfigFile.cs b/TShockAPI/ConfigFile.cs
index e5fa3320..5cfed41b 100644
--- a/TShockAPI/ConfigFile.cs
+++ b/TShockAPI/ConfigFile.cs
@@ -78,18 +78,6 @@ namespace TShockAPI
[Description("Disables any building / placing of blocks.")]
public bool DisableBuild;
- /// SuperAdminChatRGB - The chat color for the superadmin group.
- [Description("#.#.# = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255.")]
- public int[] SuperAdminChatRGB = { 255, 0, 0 };
-
- /// SuperAdminChatPrefix - The superadmin chat prefix.
- [Description("Super admin group chat prefix.")]
- public string SuperAdminChatPrefix = "(Admin) ";
-
- /// SuperAdminChatSuffix - The superadmin chat suffix.
- [Description("Super admin group chat suffix.")]
- public string SuperAdminChatSuffix = "";
-
/// BackupInterval - The backup frequency in minutes.
[Description("Backup frequency in minutes. So, a value of 60 = 60 minutes. Backups are stored in the \\tshock\\backups folder.")]
public int BackupInterval;
diff --git a/TShockAPI/Group.cs b/TShockAPI/Group.cs
index 1eb5d48f..448f8442 100644
--- a/TShockAPI/Group.cs
+++ b/TShockAPI/Group.cs
@@ -340,11 +340,11 @@ namespace TShockAPI
public SuperAdminGroup()
: base("superadmin")
{
- R = (byte)TShock.Config.SuperAdminChatRGB[0];
- G = (byte)TShock.Config.SuperAdminChatRGB[1];
- B = (byte)TShock.Config.SuperAdminChatRGB[2];
- Prefix = TShock.Config.SuperAdminChatPrefix;
- Suffix = TShock.Config.SuperAdminChatSuffix;
+ R = (byte)255;
+ G = (byte)255;
+ B = (byte)255;
+ Prefix = "(Super Admin) ";
+ Suffix = "";
}
///
From 3a8aa7fa29388e0e8dddb2ec5d731adddfeb3c1f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 14:28:12 -0700
Subject: [PATCH 056/430] Brilliant idea: Remove unused code instead of leaving
it there.
---
TShockAPI/TSPlayer.cs | 5 -----
1 file changed, 5 deletions(-)
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 8f7b831e..e2eedd1a 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -549,11 +549,6 @@ namespace TShockAPI
get { return (int)(Y / 16); }
}
- ///
- /// Unused.
- ///
- public bool TpLock;
-
///
/// Checks if the player has any inventory slots available.
///
From 0bbd128f13368c23e9c72f490fbb53b7e8500559 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 15:06:32 -0700
Subject: [PATCH 057/430] Implement /su command & default group owner
/su elevates you to superadmin for 10 minutes.
Account creation instructions tell you to use the "owner" group.
If you fail to run a command but have the su permission, you're told
that you can override it.
Fixes #1505
---
TShockAPI/Commands.cs | 35 ++++++++++++++++++++++++++++++++---
TShockAPI/DB/GroupManager.cs | 2 ++
TShockAPI/Permissions.cs | 3 +++
3 files changed, 37 insertions(+), 3 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 493aa956..8ebee559 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -311,6 +311,10 @@ namespace TShockAPI
{
HelpText = "Temporarily sets another player's group."
});
+ add(new Command(Permissions.su, SubstituteUser, "su")
+ {
+ HelpText = "Temporarily elevates you to Super Admin."
+ });
add(new Command(Permissions.userinfo, GrabUserUserInfo, "userinfo", "ui")
{
HelpText = "Shows information about a player."
@@ -685,6 +689,10 @@ namespace TShockAPI
{
TShock.Utils.SendLogs(string.Format("{0} tried to execute {1}{2}.", player.Name, Specifier, cmdText), Color.PaleVioletRed, player);
player.SendErrorMessage("You do not have access to this command.");
+ if (player.HasPermission(Permissions.su))
+ {
+ player.SendInfoMessage("You can use {0}su to temporarily become Super Admin, which can run this command.", Specifier);
+ }
}
else if (!cmd.AllowServer && !player.RealPlayer)
{
@@ -1814,6 +1822,27 @@ namespace TShockAPI
}
}
+ private static void SubstituteUser(CommandArgs args)
+ {
+
+ if (args.Player.tempGroup != null)
+ {
+ args.Player.tempGroup = null;
+ args.Player.tempGroupTimer.Stop();
+ args.Player.SendSuccessMessage("Your previous permission set has been restored.");
+ return;
+ }
+ else
+ {
+ args.Player.tempGroup = new SuperAdminGroup();
+ args.Player.tempGroupTimer = new System.Timers.Timer(600 * 1000);
+ args.Player.tempGroupTimer.Elapsed += args.Player.TempGroupTimerElapsed;
+ args.Player.tempGroupTimer.Start();
+ args.Player.SendSuccessMessage("Your account has been elevated to Super Admin for 10 minutes.");
+ return;
+ }
+ }
+
#endregion Player Management Commands
#region Server Maintenence Commands
@@ -4842,10 +4871,10 @@ namespace TShockAPI
if (args.Player.Group.Name != "superadmin")
args.Player.tempGroup = new SuperAdminGroup();
- args.Player.SendInfoMessage("Superadmin has been temporarily given to you. It will be removed on logout.");
+ args.Player.SendInfoMessage("Temporary system access has been given to you, so you can run one command.");
args.Player.SendInfoMessage("Please use the following to create a permanent account for you.");
- args.Player.SendInfoMessage("{0}user add superadmin", Specifier);
- args.Player.SendInfoMessage("Creates: with the password as part of the superadmin group.");
+ args.Player.SendInfoMessage("{0}user add owner", Specifier);
+ args.Player.SendInfoMessage("Creates: with the password as part of the owner group.");
args.Player.SendInfoMessage("Please use {0}login after this process.", Specifier);
args.Player.SendInfoMessage("If you understand, please {0}login now, and then type {0}auth.", Specifier);
return;
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 7d4f5a1b..9da13b9e 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -77,6 +77,8 @@ namespace TShockAPI.DB
string.Join(",", Permissions.maintenance, "tshock.cfg.*", "tshock.world.*", Permissions.butcher, Permissions.item, Permissions.give,
Permissions.heal, Permissions.immunetoban, Permissions.usebanneditem));
+ AddDefaultGroup("owner", "trustedadmin", string.Join(",", Permissions.su));
+
AddDefaultGroup("vip", "default", string.Join(",", Permissions.reservedslot));
}
diff --git a/TShockAPI/Permissions.cs b/TShockAPI/Permissions.cs
index 95eb6153..37340e48 100644
--- a/TShockAPI/Permissions.cs
+++ b/TShockAPI/Permissions.cs
@@ -221,6 +221,9 @@ namespace TShockAPI
[Description("Meant for super admins only.")]
public static readonly string user = "tshock.superadmin.user";
+ [Description("Allows a user to elevate to superadmin for 10 minutes.")]
+ public static readonly string su = "tshock.su";
+
// tshock.tp nodes
[Description("User can teleport *everyone* to them.")]
From fdca4421383939e6beca1fe2d17338717c1365e0 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 15:15:31 -0700
Subject: [PATCH 058/430] Update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ecbd7138..76764b0e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
* Added /group rename to allow changing group names (@ColinBohn, @ProfessorXZ)
* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
+* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. If a user has the tshock.su permission, they're informed that they have access to /su if they can't run a command as a result from their degraded permission set. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
## TShock 4.3.24
From d972f60fa058536896d3cce744eb9d16378655c8 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 17:17:20 -0700
Subject: [PATCH 059/430] Add /sudo command.
Usage: /sudo /command.
Works on the same basis as /su (requires tshock.su).
Replaces message that /su should be used for a one off command.
---
TShockAPI/Commands.cs | 23 ++++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 8ebee559..7e180f3c 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -315,6 +315,10 @@ namespace TShockAPI
{
HelpText = "Temporarily elevates you to Super Admin."
});
+ add(new Command(Permissions.su, SubstituteUserDo, "sudo")
+ {
+ HelpText = "Executes a command as the super admin."
+ });
add(new Command(Permissions.userinfo, GrabUserUserInfo, "userinfo", "ui")
{
HelpText = "Shows information about a player."
@@ -691,7 +695,7 @@ namespace TShockAPI
player.SendErrorMessage("You do not have access to this command.");
if (player.HasPermission(Permissions.su))
{
- player.SendInfoMessage("You can use {0}su to temporarily become Super Admin, which can run this command.", Specifier);
+ player.SendInfoMessage("You can use '{0}sudo {0}{1}' to override this check.", Specifier, cmdText);
}
}
else if (!cmd.AllowServer && !player.RealPlayer)
@@ -1847,6 +1851,23 @@ namespace TShockAPI
#region Server Maintenence Commands
+ // Executes a command as a superuser if you have sudo rights.
+ private static void SubstituteUserDo(CommandArgs args)
+ {
+ if (args.Parameters.Count == 0)
+ {
+ args.Player.SendErrorMessage("Usage: /sudo [command].");
+ args.Player.SendErrorMessage("Example: /sudo /ban add Shank 2d Hacking.");
+ return;
+ }
+
+ string replacementCommand = String.Join(" ", args.Parameters);
+ args.Player.tempGroup = new SuperAdminGroup();
+ HandleCommand(args.Player, replacementCommand);
+ args.Player.tempGroup = null;
+ return;
+ }
+
private static void Broadcast(CommandArgs args)
{
string message = string.Join(" ", args.Parameters);
From 6ee5ddf12ed94c6d29c9f3062b2b5780cfa48afc Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 17:19:23 -0700
Subject: [PATCH 060/430] Update changelog to point to /sudo
---
CHANGELOG.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 76764b0e..11c6aad5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,7 +14,8 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
* Added /group rename to allow changing group names (@ColinBohn, @ProfessorXZ)
* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
-* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. If a user has the tshock.su permission, they're informed that they have access to /su if they can't run a command as a result from their degraded permission set. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
+* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
+* Added /sudo, which runs a command as the superadmin group. If a user fails to execute a command but can sudo, they'll be told that they can override the permission check with sudo. Much better than just telling them to run /su and then re-run the command. (@hakusaro)
## TShock 4.3.24
From 6b2c9c47c3b5cff8674cfbfdb8893fa8b6f8cc3f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 17:38:43 -0700
Subject: [PATCH 061/430] Update chagnelog with ban stuff
---
CHANGELOG.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ecbd7138..534e143b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,7 +14,8 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added a warning notifying users of the minimum memory required to run TShock (@bartico6)
* Added /group rename to allow changing group names (@ColinBohn, @ProfessorXZ)
* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
-
+* Rebuilt /ban add. New syntax is /ban add [time] [reason] where target is the target online player, offline player, or IP; where time is the time format or 0 for permanent; and where [reason] is the reason. (@hakusaro)
+* Removed /ban addip and /ban addtemp. Now covered under /ban add. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 204f4c3f4f245e5be73d4b39d79dee887596e4d6 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 18:09:24 -0700
Subject: [PATCH 062/430] Add succinct GPL disclaimer. Fixes #1430.
---
TShockAPI/TShock.cs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index db15277b..7c2d1ab8 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -375,7 +375,9 @@ namespace TShockAPI
if (Initialized != null)
Initialized();
- Log.ConsoleInfo("Welcome to TShock for Terraria. Initialization complete.");
+ Log.ConsoleInfo("Welcome to TShock for Terraria!");
+ Log.ConsoleInfo("TShock comes with no warranty & is free software.");
+ Log.ConsoleInfo("You can modify & distribute it under the terms of the GNU GPLv3.");
}
catch (Exception ex)
{
From 0edfc6834f8f5c329d50e2bf7a7624dd3ee01e88 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 19:19:17 -0700
Subject: [PATCH 063/430] Add technical infrastructure for adding account bans
---
TShockAPI/DB/BanManager.cs | 63 ++++++++++++++++++++++++++++++++------
1 file changed, 54 insertions(+), 9 deletions(-)
diff --git a/TShockAPI/DB/BanManager.cs b/TShockAPI/DB/BanManager.cs
index 8bfe9d86..8fa40375 100644
--- a/TShockAPI/DB/BanManager.cs
+++ b/TShockAPI/DB/BanManager.cs
@@ -43,6 +43,7 @@ namespace TShockAPI.DB
new SqlColumn("IP", MySqlDbType.String, 16) { Primary = true },
new SqlColumn("Name", MySqlDbType.Text),
new SqlColumn("UUID", MySqlDbType.Text),
+ new SqlColumn("AccountName", MySqlDbType.Text),
new SqlColumn("Reason", MySqlDbType.Text),
new SqlColumn("BanningUser", MySqlDbType.Text),
new SqlColumn("Date", MySqlDbType.Text),
@@ -75,7 +76,7 @@ namespace TShockAPI.DB
using (var reader = database.QueryReader("SELECT * FROM Bans WHERE IP=@0", ip))
{
if (reader.Read())
- return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
+ return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("AccountName"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
}
}
catch (Exception ex)
@@ -104,7 +105,7 @@ namespace TShockAPI.DB
{
while (reader.Read())
{
- banlist.Add(new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration")));
+ banlist.Add(new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("AccountName"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration")));
}
banlist.Sort(new BanComparer(sortMethod));
@@ -135,7 +136,7 @@ namespace TShockAPI.DB
using (var reader = database.QueryReader("SELECT * FROM Bans WHERE " + namecol + "=@0", name))
{
if (reader.Read())
- return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
+ return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("AccountName"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
}
}
catch (Exception ex)
@@ -157,7 +158,7 @@ namespace TShockAPI.DB
using (var reader = database.QueryReader("SELECT * FROM Bans WHERE UUID=@0", uuid))
{
if (reader.Read())
- return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
+ return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("AccountName"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
}
}
catch (Exception ex)
@@ -179,6 +180,22 @@ namespace TShockAPI.DB
/// Banner.
/// Expiration date.
public bool AddBan(string ip, string name = "", string uuid = "", string reason = "", bool exceptions = false, string banner = "", string expiration = "")
+ {
+ return AddBan2(ip, name, uuid, "", reason, exceptions, banner, expiration);
+ }
+
+ ///
+ /// Adds a ban.
+ ///
+ /// true , if ban was added, false otherwise.
+ /// Ip.
+ /// Name.
+ /// UUID.
+ /// Reason.
+ /// If set to true enable throwing exceptions.
+ /// Banner.
+ /// Expiration date.
+ public bool AddBan2(string ip, string name = "", string uuid = "", string accountName = "", string reason = "", bool exceptions = false, string banner = "", string expiration = "")
{
try
{
@@ -192,7 +209,7 @@ namespace TShockAPI.DB
}
else
{
- return database.Query("INSERT INTO Bans (IP, Name, UUID, Reason, BanningUser, Date, Expiration) VALUES (@0, @1, @2, @3, @4, @5, @6);", ip, name, uuid, reason, banner, DateTime.UtcNow.ToString("s"), expiration) != 0;
+ return database.Query("INSERT INTO Bans (IP, Name, UUID, AccountName, Reason, BanningUser, Date, Expiration) VALUES (@0, @1, @2, @3, @4, @5, @6, @7);", ip, name, uuid, accountName, reason, banner, DateTime.UtcNow.ToString("s"), expiration) != 0;
}
}
catch (Exception ex)
@@ -231,6 +248,26 @@ namespace TShockAPI.DB
return false;
}
+ ///
+ /// Removes a ban by account name (not character/player name).
+ ///
+ /// true , if ban was removed, false otherwise.
+ /// Match.
+ /// If set to true casesensitive.
+ public bool RemoveBanByAccountName(string match, bool casesensitive = true)
+ {
+ try
+ {
+ var namecol = casesensitive ? "AccountName" : "UPPER(AccountName)";
+ return database.Query("DELETE FROM Bans WHERE " + namecol + "=@0", casesensitive ? match : match.ToUpper()) != 0;
+ }
+ catch (Exception ex)
+ {
+ TShock.Log.Error(ex.ToString());
+ }
+ return false;
+ }
+
///
/// Clears bans.
///
@@ -380,6 +417,12 @@ namespace TShockAPI.DB
/// The UUID
public string UUID { get; set; }
+ ///
+ /// Gets or sets the account name of the ban
+ ///
+ /// The account name
+ public String AccountName { get; set; }
+
///
/// Gets or sets the ban reason.
///
@@ -424,11 +467,12 @@ namespace TShockAPI.DB
/// Banner.
/// UTC ban date.
/// Expiration time
- public Ban(string ip, string name, string uuid, string reason, string banner, string date, string exp)
+ public Ban(string ip, string name, string uuid, string accountName, string reason, string banner, string date, string exp)
{
IP = ip;
Name = name;
UUID = uuid;
+ AccountName = accountName;
Reason = reason;
BanningUser = banner;
Date = date;
@@ -454,10 +498,11 @@ namespace TShockAPI.DB
IP = string.Empty;
Name = string.Empty;
UUID = string.Empty;
+ AccountName = string.Empty;
Reason = string.Empty;
- BanningUser = "";
- Date = "";
- Expiration = "";
+ BanningUser = string.Empty;
+ Date = string.Empty;
+ Expiration = string.Empty;
}
}
}
From 718525904a43bc50137e25ee445404301d74fe26 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 20:41:14 -0700
Subject: [PATCH 064/430] Add remaining backbone for banning accounts (sort of)
Frontend still doesn't work properly. In particular:
1. Need a way to list bans by account name.
2. Need a way to unban by account name.
3. Really need a way to change the IP on a ban lol.
Ban system still needs to be be rebuilt fully, but at least this
doesn't necessarily character ban someone if you were going for an IP
ban.
Fixes #1412
---
TShockAPI/Commands.cs | 8 ++++----
TShockAPI/DB/BanManager.cs | 33 ++++++++++++++++++++++++++++++---
TShockAPI/Rest/RestManager.cs | 4 ++--
TShockAPI/TShock.cs | 24 +++++++++++++++++++++++-
TShockAPI/Utils.cs | 2 +-
5 files changed, 60 insertions(+), 11 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 630927e3..f11e3326 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1367,7 +1367,7 @@ namespace TShockAPI
}
targetGeneralizedName = target.Name;
- success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, banReason, false, args.Player.User.Name,
+ success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.User.Name, banReason, false, args.Player.User.Name,
banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
// Since this is an online ban, we need to dc the player and tell them now.
@@ -1397,7 +1397,7 @@ namespace TShockAPI
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(args.Parameters[1])) {
targetGeneralizedName = "IP: " + args.Parameters[1];
- success = TShock.Bans.AddBan(args.Parameters[1], "", "", banReason,
+ success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason,
false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
if (success && offlineUser != null)
{
@@ -1445,8 +1445,8 @@ namespace TShockAPI
string lastIP = JsonConvert.DeserializeObject>(offlineUser.KnownIps).Last();
success =
- TShock.Bans.AddBan(lastIP,
- offlineUser.Name, offlineUser.UUID, banReason, false, args.Player.User.Name,
+ TShock.Bans.AddBan2(lastIP,
+ "", offlineUser.UUID, offlineUser.Name, banReason, false, args.Player.User.Name,
banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
}
diff --git a/TShockAPI/DB/BanManager.cs b/TShockAPI/DB/BanManager.cs
index 8fa40375..7ee0fa29 100644
--- a/TShockAPI/DB/BanManager.cs
+++ b/TShockAPI/DB/BanManager.cs
@@ -43,11 +43,11 @@ namespace TShockAPI.DB
new SqlColumn("IP", MySqlDbType.String, 16) { Primary = true },
new SqlColumn("Name", MySqlDbType.Text),
new SqlColumn("UUID", MySqlDbType.Text),
- new SqlColumn("AccountName", MySqlDbType.Text),
new SqlColumn("Reason", MySqlDbType.Text),
new SqlColumn("BanningUser", MySqlDbType.Text),
new SqlColumn("Date", MySqlDbType.Text),
- new SqlColumn("Expiration", MySqlDbType.Text)
+ new SqlColumn("Expiration", MySqlDbType.Text),
+ new SqlColumn("AccountName", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
@@ -146,6 +146,32 @@ namespace TShockAPI.DB
return null;
}
+ ///
+ /// Gets a ban by account name (not player/character name).
+ ///
+ /// The name.
+ /// Whether to check with case sensitivity.
+ /// The ban.
+ public Ban GetBanByAccountName(string name, bool casesensitive = false)
+ {
+ try
+ {
+ var namecol = casesensitive ? "AccountName" : "UPPER(AccountName)";
+ if (!casesensitive)
+ name = name.ToUpper();
+ using (var reader = database.QueryReader("SELECT * FROM Bans WHERE " + namecol + "=@0", name))
+ {
+ if (reader.Read())
+ return new Ban(reader.Get("IP"), reader.Get("Name"), reader.Get("UUID"), reader.Get("AccountName"), reader.Get("Reason"), reader.Get("BanningUser"), reader.Get("Date"), reader.Get("Expiration"));
+ }
+ }
+ catch (Exception ex)
+ {
+ TShock.Log.Error(ex.ToString());
+ }
+ return null;
+ }
+
///
/// Gets a ban by UUID.
///
@@ -179,6 +205,7 @@ namespace TShockAPI.DB
/// If set to true enable throwing exceptions.
/// Banner.
/// Expiration date.
+ [Obsolete("Use AddBan2 instead of AddBan.", true)]
public bool AddBan(string ip, string name = "", string uuid = "", string reason = "", bool exceptions = false, string banner = "", string expiration = "")
{
return AddBan2(ip, name, uuid, "", reason, exceptions, banner, expiration);
@@ -209,7 +236,7 @@ namespace TShockAPI.DB
}
else
{
- return database.Query("INSERT INTO Bans (IP, Name, UUID, AccountName, Reason, BanningUser, Date, Expiration) VALUES (@0, @1, @2, @3, @4, @5, @6, @7);", ip, name, uuid, accountName, reason, banner, DateTime.UtcNow.ToString("s"), expiration) != 0;
+ return database.Query("INSERT INTO Bans (IP, Name, UUID, Reason, BanningUser, Date, Expiration, AccountName) VALUES (@0, @1, @2, @3, @4, @5, @6, @7);", ip, name, uuid, reason, banner, DateTime.UtcNow.ToString("s"), expiration, accountName) != 0;
}
}
catch (Exception ex)
diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs
index bd10de2d..9c2c818a 100644
--- a/TShockAPI/Rest/RestManager.cs
+++ b/TShockAPI/Rest/RestManager.cs
@@ -645,7 +645,7 @@ namespace TShockAPI
try
{
- TShock.Bans.AddBan(ip, name, "", args.Parameters["reason"], true, args.TokenData.Username);
+ TShock.Bans.AddBan2(ip, name, "", "", args.Parameters["reason"], true, args.TokenData.Username);
}
catch (Exception e)
{
@@ -1022,7 +1022,7 @@ namespace TShockAPI
TSPlayer player = (TSPlayer)ret;
var reason = null == args.Parameters["reason"] ? "Banned via web" : args.Parameters["reason"];
- TShock.Bans.AddBan(player.IP, player.Name, "", reason);
+ TShock.Bans.AddBan2(player.IP, player.Name, "", "", reason);
TShock.Utils.ForceKick(player, reason, false, true);
return RestResponse("Player " + player.Name + " was banned");
}
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 7c2d1ab8..d07a466c 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -472,6 +472,28 @@ namespace TShockAPI
args.Player.User.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented);
Users.UpdateLogin(args.Player.User);
+
+ Ban potentialBan = Bans.GetBanByAccountName(args.Player.User.Name);
+
+ if (potentialBan != null)
+ {
+ // A user just signed in successfully despite being banned by account name.
+ // We should fix the ban database so that all of their ban info is up to date.
+ Bans.AddBan2(args.Player.IP, args.Player.Name, args.Player.UUID, args.Player.User.Name,
+ potentialBan.Reason, false, potentialBan.BanningUser, potentialBan.Expiration);
+
+ // And then get rid of them.
+ if (potentialBan.Expiration == "")
+ {
+ Utils.ForceKick(args.Player, String.Format("Permanently banned by {0} for {1}", potentialBan.BanningUser
+ ,potentialBan.Reason), false, false);
+ }
+ else
+ {
+ Utils.ForceKick(args.Player, String.Format("Still banned by {0} for {1}", potentialBan.BanningUser,
+ potentialBan.Reason), false, false);
+ }
+ }
}
/// OnAccountDelete - Internal hook fired on account delete.
@@ -488,7 +510,7 @@ namespace TShockAPI
CharacterDB.SeedInitialData(Users.GetUser(args.User));
}
- /// OnPlayerPreLogin - Internal hook fired when on player pre login.
+ /// OnPlayerPreLoginOnPlayerPreLogin - Internal hook fired when on player pre login.
/// args - The PlayerPreLoginEventArgs object.
private void OnPlayerPreLogin(Hooks.PlayerPreLoginEventArgs args)
{
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 5081f8e4..9efa8b99 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -675,7 +675,7 @@ namespace TShockAPI
string ip = player.IP;
string uuid = player.UUID;
string playerName = player.Name;
- TShock.Bans.AddBan(ip, playerName, uuid, reason, false, adminUserName);
+ TShock.Bans.AddBan2(ip, playerName, uuid, "", reason, false, adminUserName);
player.Disconnect(string.Format("Banned: {0}", reason));
string verb = force ? "force " : "";
if (string.IsNullOrWhiteSpace(adminUserName))
From 7160e758b2fc485174c0c7037baf4440813ba9a4 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 20:44:17 -0700
Subject: [PATCH 065/430] Unbreak comment OnPlayerPreLoginOnPlayerPreLogin
---
TShockAPI/TShock.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index d07a466c..f808ce44 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -510,7 +510,7 @@ namespace TShockAPI
CharacterDB.SeedInitialData(Users.GetUser(args.User));
}
- /// OnPlayerPreLoginOnPlayerPreLogin - Internal hook fired when on player pre login.
+ /// OnPlayerPreLogin - Internal hook fired when on player pre login.
/// args - The PlayerPreLoginEventArgs object.
private void OnPlayerPreLogin(Hooks.PlayerPreLoginEventArgs args)
{
From 35c61e53f1e9d85623eca283f1c844e9beaee5a7 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 20:45:55 -0700
Subject: [PATCH 066/430] Remove some space left around
---
TShockAPI/Commands.cs | 1 -
1 file changed, 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index f11e3326..461af221 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1450,7 +1450,6 @@ namespace TShockAPI
banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
}
-
if (success)
{
args.Player.SendSuccessMessage("{0} was successfully banned.", targetGeneralizedName);
From 39733a116d8b21e1c3e79643dd99c25445daf569 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 2 Dec 2017 20:59:30 -0700
Subject: [PATCH 067/430] Fix issue where temp bans were stored incorrectly
Bans were being stored as seconds, should be a DateTime in s format
with seconds added on to existing time.
---
TShockAPI/Commands.cs | 6 +++---
TShockAPI/TShock.cs | 2 +-
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 461af221..8abcbedd 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1368,7 +1368,7 @@ namespace TShockAPI
targetGeneralizedName = target.Name;
success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.User.Name, banReason, false, args.Player.User.Name,
- banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+ banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now.
if (success)
@@ -1398,7 +1398,7 @@ namespace TShockAPI
if (r.IsMatch(args.Parameters[1])) {
targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason,
- false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+ false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
if (success && offlineUser != null)
{
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
@@ -1447,7 +1447,7 @@ namespace TShockAPI
success =
TShock.Bans.AddBan2(lastIP,
"", offlineUser.UUID, offlineUser.Name, banReason, false, args.Player.User.Name,
- banLengthInSeconds == 0 ? "" : banLengthInSeconds.ToString());
+ banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
}
if (success)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index f808ce44..e4fdf0ff 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1387,7 +1387,7 @@ namespace TShockAPI
DateTime exp;
if (!DateTime.TryParse(ban.Expiration, out exp))
{
- player.Disconnect("You are banned forever: " + ban.Reason);
+ player.Disconnect("Permanently banned for: " + ban.Reason);
}
else
{
From 3204ef2a83bfd14a336b6593cc2f7a8363245007 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 09:49:45 -0700
Subject: [PATCH 068/430] callerIsEffectiveRoot -> callerIsServerConsole in ban
system
This code clarity improvement helps make the code base clearer.
Thanks @deadsurgeon42
---
TShockAPI/Commands.cs | 18 ++++++++----------
1 file changed, 8 insertions(+), 10 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 8abcbedd..2b2a9b73 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1305,15 +1305,13 @@ namespace TShockAPI
List players = TShock.Utils.FindPlayer(args.Parameters[1]);
User offlineUser = TShock.Users.GetUserByName(args.Parameters[1]);
- // Determines if the caller is effective root for overriding permissions
- bool callerIsEffectiveRoot = false;
-
- // A ban source is effective root if they are not not real and not rest
- // Super admins ingame who attempt to run this will have to remove
- // the immune to ban permission if they want to ban an immune player
- if (!(args.Player is TSRestPlayer) && !args.Player.RealPlayer)
+ // Storage variable to determine if the command executor is the server console
+ // If it is, we assume they have full control and let them override permission checks
+ bool callerIsServerConsole = false;
+
+ if (args.Player is TSServerPlayer)
{
- callerIsEffectiveRoot = true;
+ callerIsServerConsole = true;
}
// The ban reason the ban is going to have
@@ -1360,7 +1358,7 @@ namespace TShockAPI
{
TSPlayer target = players[0];
- if (target.HasPermission(Permissions.immunetoban) && !callerIsEffectiveRoot)
+ if (target.HasPermission(Permissions.immunetoban) && !callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", target.Name);
return;
@@ -1430,7 +1428,7 @@ namespace TShockAPI
targetGeneralizedName = offlineUser.Name;
if (TShock.Groups.GetGroupByName(offlineUser.Group).HasPermission(Permissions.immunetoban) &&
- !callerIsEffectiveRoot)
+ !callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return;
From c869464d812ad09709fa39fe508239f11ad0d390 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 12:56:34 -0700
Subject: [PATCH 069/430] Add DumpPermissionMatrix() which dumps a markdown
permission matrix
Note that -dump apparently isn't working lately. You probably want
to call Utils.Dump() manually and invoke it in a custom build.
---
TShockAPI/Utils.cs | 48 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 5081f8e4..2e0b8f82 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1204,6 +1204,7 @@ namespace TShockAPI
Permissions.DumpDescriptions();
ServerSideCharacters.ServerSideConfig.DumpDescriptions();
RestManager.DumpDescriptions();
+ DumpPermissionMatrix("PermissionMatrix.txt");
DumpBuffs("BuffList.txt");
DumpItems("Items-1_0.txt", -48, 235);
DumpItems("Items-1_1.txt", 235, 604);
@@ -1212,6 +1213,7 @@ namespace TShockAPI
DumpNPCs("NPCs.txt");
DumpProjectiles("Projectiles.txt");
DumpPrefixes("Prefixes.txt");
+
if (exit)
{
Environment.Exit(1);
@@ -1223,6 +1225,52 @@ namespace TShockAPI
for(int i = 0; i < Main.recipe.Length; i++)
Main.recipe[i] = new Recipe();
}
+
+ // Dumps a matrix of all permissions and all groups in markdown format
+ // Hard coded to default groups because apparently we have poor querying tools
+ public void DumpPermissionMatrix(string path)
+ {
+ StringBuilder output = new StringBuilder();
+ output.Append("|Permission|");
+
+ // Traverse to build group name list
+ foreach (Group g in TShock.Groups.groups)
+ {
+ output.Append(g.Name);
+ output.Append("|");
+ }
+
+ output.AppendLine();
+ output.Append("|-------|");
+
+ foreach (Group g in TShock.Groups.groups)
+ {
+ output.Append("-------|");
+ }
+ output.AppendLine();
+
+ foreach (var field in typeof(Permissions).GetFields().OrderBy(f => f.Name))
+ {
+ output.Append("|");
+ output.Append((string) field.GetValue(null));
+ output.Append("|");
+
+ foreach (Group g in TShock.Groups.groups)
+ {
+ if (g.HasPermission((string) field.GetValue(null)))
+ {
+ output.Append("✔|");
+ }
+ else
+ {
+ output.Append("|");
+ }
+ }
+ output.AppendLine();
+ }
+
+ File.WriteAllText(path, output.ToString());
+ }
public void DumpBuffs(string path)
{
From 9aaf425330c040ee6161e798fd209f5bc3c9e475 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 15:04:50 -0700
Subject: [PATCH 070/430] Modify default permission sets to be more modern
---
TShockAPI/DB/GroupManager.cs | 121 +++++++++++++++++++++++++++++++----
1 file changed, 107 insertions(+), 14 deletions(-)
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index 9da13b9e..f952fee2 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -58,28 +58,121 @@ namespace TShockAPI.DB
{
// Add default groups if they don't exist
AddDefaultGroup("guest", "",
- string.Join(",", Permissions.canbuild, Permissions.canregister, Permissions.canlogin, Permissions.canpartychat,
- Permissions.cantalkinthird, Permissions.canchat));
+ string.Join(",",
+ Permissions.canbuild,
+ Permissions.canregister,
+ Permissions.canlogin,
+ Permissions.canpartychat,
+ Permissions.cantalkinthird,
+ Permissions.canchat));
AddDefaultGroup("default", "guest",
- string.Join(",", Permissions.warp, Permissions.canchangepassword, Permissions.canlogout));
+ string.Join(",",
+ Permissions.warp,
+ Permissions.canchangepassword,
+ Permissions.canlogout,
+ Permissions.summonboss,
+ Permissions.whisper,
+ Permissions.wormhole,
+ Permissions.canpaint));
- AddDefaultGroup("newadmin", "default",
- string.Join(",", Permissions.kick, Permissions.editspawn, Permissions.reservedslot));
+ AddDefaultGroup("vip", "default",
+ string.Join(",",
+ Permissions.reservedslot,
+ Permissions.renamenpc,
+ Permissions.startinvasion,
+ Permissions.summonboss,
+ Permissions.whisper,
+ Permissions.wormhole));
+
+ AddDefaultGroup("newadmin", "vip",
+ string.Join(",",
+ Permissions.kick,
+ Permissions.editspawn,
+ Permissions.reservedslot,
+ Permissions.annoy,
+ Permissions.checkaccountinfo,
+ Permissions.getpos,
+ Permissions.mute,
+ Permissions.rod,
+ Permissions.savessc,
+ Permissions.seeids,
+ "tshock.world.time.*"));
AddDefaultGroup("admin", "newadmin",
- string.Join(",", Permissions.ban, Permissions.whitelist, "tshock.world.time.*", Permissions.spawnboss,
- Permissions.spawnmob, Permissions.managewarp, Permissions.time, Permissions.tp, Permissions.slap,
- Permissions.kill, Permissions.logs,
- Permissions.immunetokick, Permissions.tpothers));
+ string.Join(",",
+ Permissions.ban,
+ Permissions.whitelist,
+ Permissions.spawnboss,
+ Permissions.spawnmob,
+ Permissions.managewarp,
+ Permissions.time,
+ Permissions.tp,
+ Permissions.slap,
+ Permissions.kill,
+ Permissions.logs,
+ Permissions.immunetokick,
+ Permissions.tpothers,
+ Permissions.advaccountinfo,
+ Permissions.broadcast,
+ Permissions.home,
+ Permissions.tpallothers,
+ Permissions.tpallow,
+ Permissions.tpnpc,
+ Permissions.tppos,
+ Permissions.tpsilent,
+ Permissions.userinfo));
AddDefaultGroup("trustedadmin", "admin",
- string.Join(",", Permissions.maintenance, "tshock.cfg.*", "tshock.world.*", Permissions.butcher, Permissions.item, Permissions.give,
- Permissions.heal, Permissions.immunetoban, Permissions.usebanneditem));
+ string.Join(",",
+ Permissions.maintenance,
+ "tshock.cfg.*",
+ "tshock.world.*",
+ Permissions.butcher,
+ Permissions.item,
+ Permissions.give,
+ Permissions.heal,
+ Permissions.immunetoban,
+ Permissions.usebanneditem,
+ Permissions.allowclientsideworldedit,
+ Permissions.buff,
+ Permissions.buffplayer,
+ Permissions.clear,
+ Permissions.clearangler,
+ Permissions.godmode,
+ Permissions.godmodeother,
+ Permissions.ignoredamagecap,
+ Permissions.ignorehp,
+ Permissions.ignorekilltiledetection,
+ Permissions.ignoreliquidsetdetection,
+ Permissions.ignoremp,
+ Permissions.ignorenoclipdetection,
+ Permissions.ignorepaintdetection,
+ Permissions.ignoreplacetiledetection,
+ Permissions.ignoreprojectiledetection,
+ Permissions.ignorestackhackdetection,
+ Permissions.invade,
+ Permissions.startdd2,
+ Permissions.uploaddata,
+ Permissions.uploadothersdata));
- AddDefaultGroup("owner", "trustedadmin", string.Join(",", Permissions.su));
-
- AddDefaultGroup("vip", "default", string.Join(",", Permissions.reservedslot));
+ AddDefaultGroup("owner", "trustedadmin",
+ string.Join(",",
+ Permissions.su,
+ Permissions.allowdroppingbanneditems,
+ Permissions.antibuild,
+ Permissions.canusebannedprojectiles,
+ Permissions.canusebannedtiles,
+ Permissions.managegroup,
+ Permissions.manageitem,
+ Permissions.manageprojectile,
+ Permissions.manageregion,
+ Permissions.managetile,
+ Permissions.maxspawns,
+ Permissions.serverinfo,
+ Permissions.settempgroup,
+ Permissions.spawnrate,
+ Permissions.tpoverride));
}
// Load Permissions from the DB
From d1500d78410f04339905ca1ac7cea76a3cb7bba2 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 15:13:30 -0700
Subject: [PATCH 071/430] Update changelog w/ permissions
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11c6aad5..ac93c9c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
* Added /sudo, which runs a command as the superadmin group. If a user fails to execute a command but can sudo, they'll be told that they can override the permission check with sudo. Much better than just telling them to run /su and then re-run the command. (@hakusaro)
+* Default permission sets for new databases are more modern. (@hakusaro)
## TShock 4.3.24
From ec59549f2f78598e7d5d39ca8e2690c7cc48a24a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 15:55:40 -0700
Subject: [PATCH 072/430] Update changelog to add note about account bans
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05ff1fe8..14a0931d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed /ban addip and /ban addtemp. Now covered under /ban add. (@hakusaro)
* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
* Added /sudo, which runs a command as the superadmin group. If a user fails to execute a command but can sudo, they'll be told that they can override the permission check with sudo. Much better than just telling them to run /su and then re-run the command. (@hakusaro)
+* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From cdbc37b0244c7420b9deb7ac8876556f70080fd6 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 16:22:46 -0700
Subject: [PATCH 073/430] Allow /savessc to work on players that bypass ssc
Fixes #1506
---
TShockAPI/Commands.cs | 2 +-
TShockAPI/DB/CharacterManager.cs | 6 +++---
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 7e180f3c..11d41505 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -1636,7 +1636,7 @@ namespace TShockAPI
{
if (player != null && player.IsLoggedIn && !player.IgnoreActionsForClearingTrashCan)
{
- TShock.CharacterDB.InsertPlayerData(player);
+ TShock.CharacterDB.InsertPlayerData(player, true);
}
}
}
diff --git a/TShockAPI/DB/CharacterManager.cs b/TShockAPI/DB/CharacterManager.cs
index ab663ef1..2c264138 100644
--- a/TShockAPI/DB/CharacterManager.cs
+++ b/TShockAPI/DB/CharacterManager.cs
@@ -156,17 +156,17 @@ namespace TShockAPI.DB
///
/// player to take data from
/// true if inserted successfully
- public bool InsertPlayerData(TSPlayer player)
+ public bool InsertPlayerData(TSPlayer player, bool fromCommand = false)
{
PlayerData playerData = player.PlayerData;
if (!player.IsLoggedIn)
return false;
- if (player.HasPermission(Permissions.bypassssc))
+ if (player.HasPermission(Permissions.bypassssc) && !fromCommand)
{
TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.User.Name); // Debug code
- return true;
+ return false;
}
if (!GetPlayerData(player, player.User.ID).exists)
From f319ec94b42fd55007e244e9e829d9eb47fb5c36 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 3 Dec 2017 16:26:41 -0700
Subject: [PATCH 074/430] Updated changelog to reflect ssc changes
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11c6aad5..fb2bc485 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added /region rename and OnRegionRenamed hook (@koneko-nyan, @deadsurgeon42)
* Added /su, which temporarily elevates players with the tshock.su permission to super admin. In addition added, a new group, owner, that is suggested for new users to setup TShock with as opposed to superadmin. Finally, /su is implemented such that a 10 minute timeout will occur preventing people from just camping with it on. (@hakusaro)
* Added /sudo, which runs a command as the superadmin group. If a user fails to execute a command but can sudo, they'll be told that they can override the permission check with sudo. Much better than just telling them to run /su and then re-run the command. (@hakusaro)
+* Fixed /savessc not bothering to save ssc data for people who bypass ssc. (@hakusaro)
## TShock 4.3.24
From 7c47fbb3f2bb6dbddf54cf7e2a19c767031e2b53 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 4 Dec 2017 21:45:25 -0700
Subject: [PATCH 075/430] Move FixChestStacks() to utils
---
TShockAPI/TShock.cs | 21 +--------------------
TShockAPI/Utils.cs | 19 +++++++++++++++++++
2 files changed, 20 insertions(+), 20 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 7c2d1ab8..4d0a8dbd 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -876,7 +876,7 @@ namespace TShockAPI
Warps.ReloadWarps();
ComputeMaxStyles();
- FixChestStacks();
+ Utils.FixChestStacks();
Utils.UpgradeMotD();
@@ -909,25 +909,6 @@ namespace TShockAPI
}
}
- /// FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.
- private void FixChestStacks()
- {
- if (Config.IgnoreChestStacksOnLoad)
- return;
-
- foreach (Chest chest in Main.chest)
- {
- if (chest != null)
- {
- foreach (Item item in chest.item)
- {
- if (item != null && item.stack > item.maxStack)
- item.stack = item.maxStack;
- }
- }
- }
- }
-
/// LastCheck - Used to keep track of the last check for basically all time based checks.
private DateTime LastCheck = DateTime.UtcNow;
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 5081f8e4..3304acb4 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1427,5 +1427,24 @@ namespace TShockAPI
}
}
}
+
+ /// FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.
+ public void FixChestStacks()
+ {
+ if (TShock.Config.IgnoreChestStacksOnLoad)
+ return;
+
+ foreach (Chest chest in Main.chest)
+ {
+ if (chest != null)
+ {
+ foreach (Item item in chest.item)
+ {
+ if (item != null && item.stack > item.maxStack)
+ item.stack = item.maxStack;
+ }
+ }
+ }
+ }
}
}
From 17982bd766791da2bbb1f02d739b6924954fb3b0 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 4 Dec 2017 21:49:56 -0700
Subject: [PATCH 076/430] Move SetConsoleTitle to utils
---
TShockAPI/TShock.cs | 16 +++-------------
TShockAPI/Utils.cs | 12 +++++++++++-
2 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 4d0a8dbd..b3e91a02 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -822,7 +822,7 @@ namespace TShockAPI
/// args - The EventArgs object.
private void OnPostInit(EventArgs args)
{
- SetConsoleTitle(false);
+ Utils.SetConsoleTitle(false);
//This is to prevent a bug where a CLI-defined password causes packets to be
//sent in an unexpected order, resulting in clients being unable to connect
@@ -1179,17 +1179,7 @@ namespace TShockAPI
}
}
}
- SetConsoleTitle(false);
- }
-
- /// SetConsoleTitle - Updates the console title with some pertinent information.
- /// empty - True/false if the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.
- private void SetConsoleTitle(bool empty)
- {
- Console.Title = string.Format("{0}{1}/{2} on {3} @ {4}:{5} (TShock for Terraria v{6})",
- !string.IsNullOrWhiteSpace(Config.ServerName) ? Config.ServerName + " - " : "",
- empty ? 0 : Utils.ActivePlayers(),
- Config.MaxSlots, Main.worldName, Netplay.ServerIP.ToString(), Netplay.ListenPort, Version);
+ Utils.SetConsoleTitle(false);
}
/// OnHardUpdate - Fired when a hardmode tile update event happens.
@@ -1435,7 +1425,7 @@ namespace TShockAPI
{
if (Config.SaveWorldOnLastPlayerExit)
SaveManager.Instance.SaveWorld();
- SetConsoleTitle(true);
+ Utils.SetConsoleTitle(true);
}
}
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 3304acb4..eaa62dd3 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1429,7 +1429,7 @@ namespace TShockAPI
}
/// FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.
- public void FixChestStacks()
+ internal void FixChestStacks()
{
if (TShock.Config.IgnoreChestStacksOnLoad)
return;
@@ -1446,5 +1446,15 @@ namespace TShockAPI
}
}
}
+
+ /// SetConsoleTitle - Updates the console title with some pertinent information.
+ /// empty - True/false if the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.
+ internal void SetConsoleTitle(bool empty)
+ {
+ Console.Title = string.Format("{0}{1}/{2} on {3} @ {4}:{5} (TShock for Terraria v{6})",
+ !string.IsNullOrWhiteSpace(TShock.Config.ServerName) ? TShock.Config.ServerName + " - " : "",
+ empty ? 0 : ActivePlayers(),
+ TShock.Config.MaxSlots, Main.worldName, Netplay.ServerIP.ToString(), Netplay.ListenPort, TShock.VersionNum);
+ }
}
}
From e85d79e23d2487cd89481e5dec9110016da2329d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 4 Dec 2017 21:53:46 -0700
Subject: [PATCH 077/430] Move Distance to Utils.Distance
---
TShockAPI/TShock.cs | 8 +++-----
TShockAPI/Utils.cs | 12 ++++++++++++
2 files changed, 15 insertions(+), 5 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index b3e91a02..4edf40d5 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1978,19 +1978,17 @@ namespace TShockAPI
{
Vector2 tile = new Vector2(x, y);
Vector2 spawn = new Vector2(Main.spawnTileX, Main.spawnTileY);
- return Distance(spawn, tile) <= Config.SpawnProtectionRadius;
+ return Utils.Distance(spawn, tile) <= Config.SpawnProtectionRadius;
}
/// Distance - Determines the distance between two vectors.
/// value1 - The first vector location.
/// value2 - The second vector location.
/// float - The distance between the two vectors.
+ [Obsolete("Use TShock.Utils.Distance(Vector2, Vector2) instead.", true)]
public static float Distance(Vector2 value1, Vector2 value2)
{
- float num2 = value1.X - value2.X;
- float num = value1.Y - value2.Y;
- float num3 = (num2 * num2) + (num * num);
- return (float)Math.Sqrt(num3);
+ return Utils.Distance(value1, value2);
}
/// HackedInventory - Checks to see if a user has a hacked inventory. In addition, messages players the result.
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index eaa62dd3..5175934d 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1456,5 +1456,17 @@ namespace TShockAPI
empty ? 0 : ActivePlayers(),
TShock.Config.MaxSlots, Main.worldName, Netplay.ServerIP.ToString(), Netplay.ListenPort, TShock.VersionNum);
}
+
+ /// Distance - Determines the distance between two vectors.
+ /// value1 - The first vector location.
+ /// value2 - The second vector location.
+ /// float - The distance between the two vectors.
+ public static float Distance(Vector2 value1, Vector2 value2)
+ {
+ float num2 = value1.X - value2.X;
+ float num = value1.Y - value2.Y;
+ float num3 = (num2 * num2) + (num * num);
+ return (float)Math.Sqrt(num3);
+ }
}
}
From fc233bd3f1abae9b544a0fcbdf3d899fa3c27467 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 4 Dec 2017 21:57:59 -0700
Subject: [PATCH 078/430] Move ComputeMaxStyles to Utils
---
TShockAPI/TShock.cs | 22 +---------------------
TShockAPI/Utils.cs | 20 ++++++++++++++++++++
2 files changed, 21 insertions(+), 21 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 4edf40d5..27ae3fc2 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -875,7 +875,7 @@ namespace TShockAPI
Regions.Reload();
Warps.ReloadWarps();
- ComputeMaxStyles();
+ Utils.ComputeMaxStyles();
Utils.FixChestStacks();
Utils.UpgradeMotD();
@@ -889,26 +889,6 @@ namespace TShockAPI
StatTracker.Start();
}
- /// ComputeMaxStyles - Computes the max styles...
- private void ComputeMaxStyles()
- {
- var item = new Item();
- for (int i = 0; i < Main.maxItemTypes; i++)
- {
- item.netDefaults(i);
- if (item.placeStyle > 0)
- {
- if (GetDataHandlers.MaxPlaceStyles.ContainsKey(item.createTile))
- {
- if (item.placeStyle > GetDataHandlers.MaxPlaceStyles[item.createTile])
- GetDataHandlers.MaxPlaceStyles[item.createTile] = item.placeStyle;
- }
- else
- GetDataHandlers.MaxPlaceStyles.Add(item.createTile, item.placeStyle);
- }
- }
- }
-
/// LastCheck - Used to keep track of the last check for basically all time based checks.
private DateTime LastCheck = DateTime.UtcNow;
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 5175934d..3626775e 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1468,5 +1468,25 @@ namespace TShockAPI
float num3 = (num2 * num2) + (num * num);
return (float)Math.Sqrt(num3);
}
+
+ /// ComputeMaxStyles - Computes the max styles...
+ internal void ComputeMaxStyles()
+ {
+ var item = new Item();
+ for (int i = 0; i < Main.maxItemTypes; i++)
+ {
+ item.netDefaults(i);
+ if (item.placeStyle > 0)
+ {
+ if (GetDataHandlers.MaxPlaceStyles.ContainsKey(item.createTile))
+ {
+ if (item.placeStyle > GetDataHandlers.MaxPlaceStyles[item.createTile])
+ GetDataHandlers.MaxPlaceStyles[item.createTile] = item.placeStyle;
+ }
+ else
+ GetDataHandlers.MaxPlaceStyles.Add(item.createTile, item.placeStyle);
+ }
+ }
+ }
}
}
From e782a07564cff2b54082bf653238bd80cc419872 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 5 Dec 2017 02:32:33 -0700
Subject: [PATCH 079/430] Move SendTileSquare handling for Bouncer into Bouncer
---
TShockAPI/Bouncer.cs | 258 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 175 ++----------------------
TShockAPI/TShock.cs | 2 +
TShockAPI/TShockAPI.csproj | 1 +
4 files changed, 276 insertions(+), 160 deletions(-)
create mode 100644 TShockAPI/Bouncer.cs
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
new file mode 100644
index 00000000..804531eb
--- /dev/null
+++ b/TShockAPI/Bouncer.cs
@@ -0,0 +1,258 @@
+/*
+TShock, a server mod for Terraria
+Copyright (C) 2011-2017 Nyx Studios (fka. The TShock Team)
+
+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 Terraria;
+using TerrariaApi.Server;
+using TShockAPI.Hooks;
+using TShockAPI;
+using TerrariaApi.Server;
+using Terraria.ID;
+using Terraria.ObjectData;
+using Terraria.DataStructures;
+using Terraria.GameContent.Tile_Entities;
+using Terraria.Localization;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.IO;
+using System.IO.Streams;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Terraria.ID;
+using TShockAPI.Net;
+
+namespace TShockAPI
+{
+ /// Bouncer - The TShock anti-hack and build guardian system
+ public class Bouncer
+ {
+ /// Bouncer - Constructor call initializes Bouncer & related functionality.
+ /// A new Bouncer.
+ public Bouncer(TerrariaPlugin pluginInstance)
+ {
+ // Setup hooks
+
+ // SendTileSquareEventArgs args = new GetDataHandlers.SendTileSquareEventArgs();
+ GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
+ }
+
+ public void OnSendTileSquare(object sender, GetDataHandlers.SendTileSquareEventArgs args)
+ {
+ short size = args.Size;
+ int tileX = args.TileX;
+ int tileY = args.TileY;
+
+ if (args.Player.HasPermission(Permissions.allowclientsideworldedit))
+ {
+ args.Handled = false;
+ return;
+ }
+
+ if (size > 5)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendTileSquare(tileX, tileY, size);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendTileSquare(tileX, tileY, size);
+ args.Handled = true;
+ return;
+ }
+
+ try
+ {
+ var tiles = new NetTile[size, size];
+ for (int x = 0; x < size; x++)
+ {
+ for (int y = 0; y < size; y++)
+ {
+ tiles[x, y] = new NetTile(args.Data);
+ }
+ }
+
+ bool changed = false;
+ for (int x = 0; x < size; x++)
+ {
+ int realx = tileX + x;
+ if (realx < 0 || realx >= Main.maxTilesX)
+ continue;
+
+ for (int y = 0; y < size; y++)
+ {
+ int realy = tileY + y;
+ if (realy < 0 || realy >= Main.maxTilesY)
+ continue;
+
+ var tile = Main.tile[realx, realy];
+ var newtile = tiles[x, y];
+ if (TShock.CheckTilePermission(args.Player, realx, realy) ||
+ TShock.CheckRangePermission(args.Player, realx, realy))
+ {
+ continue;
+ }
+
+ // Fixes the Flower Boots not creating flowers issue
+ if (size == 1 && args.Player.Accessories.Any(i => i.active && i.netID == ItemID.FlowerBoots))
+ {
+ if (Main.tile[realx, realy + 1].type == TileID.Grass && (newtile.Type == TileID.Plants || newtile.Type == TileID.Plants2))
+ {
+ args.Handled = false;
+ return;
+ }
+
+ if (Main.tile[realx, realy + 1].type == TileID.HallowedGrass && (newtile.Type == TileID.HallowedPlants || newtile.Type == TileID.HallowedPlants2))
+ {
+ args.Handled = false;
+ return;
+ }
+
+ if (Main.tile[realx, realy + 1].type == TileID.JungleGrass && newtile.Type == TileID.JunglePlants2)
+ {
+ args.Handled = false;
+ return;
+ }
+ }
+
+ // Junction Box
+ if (tile.type == TileID.WirePipe)
+ {
+ args.Handled = false;
+ return;
+ }
+
+ // Orientable tiles
+ if (tile.type == newtile.Type && orientableTiles.Contains(tile.type))
+ {
+ Main.tile[realx, realy].frameX = newtile.FrameX;
+ Main.tile[realx, realy].frameY = newtile.FrameY;
+ changed = true;
+ }
+ // Landmine
+ if (tile.type == TileID.LandMine && !newtile.Active)
+ {
+ Main.tile[realx, realy].active(false);
+ changed = true;
+ }
+ // Sensors
+ if(newtile.Type == TileID.LogicSensor && !Main.tile[realx, realy].active())
+ {
+ Main.tile[realx, realy].type = newtile.Type;
+ Main.tile[realx, realy].frameX = newtile.FrameX;
+ Main.tile[realx, realy].frameY = newtile.FrameY;
+ Main.tile[realx, realy].active(true);
+ changed = true;
+ }
+
+ if (tile.active() && newtile.Active && tile.type != newtile.Type)
+ {
+ // Grass <-> Grass
+ if ((TileID.Sets.Conversion.Grass[tile.type] && TileID.Sets.Conversion.Grass[newtile.Type]) ||
+ // Dirt <-> Dirt
+ ((tile.type == 0 || tile.type == 59) &&
+ (newtile.Type == 0 || newtile.Type == 59)) ||
+ // Ice <-> Ice
+ (TileID.Sets.Conversion.Ice[tile.type] && TileID.Sets.Conversion.Ice[newtile.Type]) ||
+ // Stone <-> Stone
+ ((TileID.Sets.Conversion.Stone[tile.type] || Main.tileMoss[tile.type]) &&
+ (TileID.Sets.Conversion.Stone[newtile.Type] || Main.tileMoss[newtile.Type])) ||
+ // Sand <-> Sand
+ (TileID.Sets.Conversion.Sand[tile.type] && TileID.Sets.Conversion.Sand[newtile.Type]) ||
+ // Sandstone <-> Sandstone
+ (TileID.Sets.Conversion.Sandstone[tile.type] && TileID.Sets.Conversion.Sandstone[newtile.Type]) ||
+ // Hardened Sand <-> Hardened Sand
+ (TileID.Sets.Conversion.HardenedSand[tile.type] && TileID.Sets.Conversion.HardenedSand[newtile.Type]))
+ {
+ Main.tile[realx, realy].type = newtile.Type;
+ changed = true;
+ }
+ }
+ // Stone wall <-> Stone wall
+ if (((tile.wall == 1 || tile.wall == 3 || tile.wall == 28 || tile.wall == 83) &&
+ (newtile.Wall == 1 || newtile.Wall == 3 || newtile.Wall == 28 || newtile.Wall == 83)) ||
+ // Leaf wall <-> Leaf wall
+ (((tile.wall >= 63 && tile.wall <= 70) || tile.wall == 81) &&
+ ((newtile.Wall >= 63 && newtile.Wall <= 70) || newtile.Wall == 81)))
+ {
+ Main.tile[realx, realy].wall = newtile.Wall;
+ changed = true;
+ }
+
+ if ((tile.type == TileID.TrapdoorClosed && (newtile.Type == TileID.TrapdoorOpen || !newtile.Active)) ||
+ (tile.type == TileID.TrapdoorOpen && (newtile.Type == TileID.TrapdoorClosed || !newtile.Active)) ||
+ (!tile.active() && newtile.Active && (newtile.Type == TileID.TrapdoorOpen||newtile.Type == TileID.TrapdoorClosed)))
+ {
+ Main.tile[realx, realy].type = newtile.Type;
+ Main.tile[realx, realy].frameX = newtile.FrameX;
+ Main.tile[realx, realy].frameY = newtile.FrameY;
+ Main.tile[realx, realy].active(newtile.Active);
+ changed = true;
+ }
+ }
+ }
+
+ if (changed)
+ {
+ TSPlayer.All.SendTileSquare(tileX, tileY, size + 1);
+ WorldGen.RangeFrame(tileX, tileY, tileX + size, tileY + size);
+ }
+ else
+ {
+ args.Player.SendTileSquare(tileX, tileY, size);
+ }
+ }
+ catch
+ {
+ args.Player.SendTileSquare(tileX, tileY, size);
+ }
+ args.Handled = true;
+ return;
+ }
+
+ private static int[] orientableTiles = new int[]
+ {
+ TileID.Cannon,
+ TileID.Chairs,
+ TileID.Beds,
+ TileID.Bathtubs,
+ TileID.Statues,
+ TileID.Mannequin,
+ TileID.Traps,
+ TileID.MusicBoxes,
+ TileID.ChristmasTree,
+ TileID.WaterFountain,
+ TileID.Womannequin,
+ TileID.MinecartTrack,
+ TileID.WeaponsRack,
+ TileID.ItemFrame,
+ TileID.LunarMonolith,
+ TileID.TargetDummy,
+ TileID.Campfire
+ };
+
+ }
+}
\ No newline at end of file
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 2fa9cbd0..e9c7ae8a 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -537,14 +537,22 @@ namespace TShockAPI
///
public class SendTileSquareEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
+
+ /// The raw memory stream from the original event
+ public MemoryStream Data { get; set; }
+
///
/// Size of the area
///
public short Size { get; set; }
+
///
/// A corner of the section
///
public int TileX { get; set; }
+
///
/// A corner of the section
///
@@ -555,13 +563,15 @@ namespace TShockAPI
///
public static HandlerList SendTileSquare;
- private static bool OnSendTileSquare(short size, int tilex, int tiley)
+ private static bool OnSendTileSquare(TSPlayer player, MemoryStream data, short size, int tilex, int tiley)
{
if (SendTileSquare == null)
return false;
var args = new SendTileSquareEventArgs
{
+ Player = player,
+ Data = data,
Size = size,
TileX = tilex,
TileY = tiley,
@@ -1726,171 +1736,16 @@ namespace TShockAPI
private static bool HandleSendTileSquare(GetDataHandlerArgs args)
{
+ var player = args.Player;
var size = args.Data.ReadInt16();
var tileX = args.Data.ReadInt16();
var tileY = args.Data.ReadInt16();
+ var data = args.Data;
- if (args.Player.HasPermission(Permissions.allowclientsideworldedit))
- return false;
-
- if (OnSendTileSquare(size, tileX, tileY))
+ if (OnSendTileSquare(player, data, size, tileX, tileY))
return true;
- if (size > 5)
- return true;
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendTileSquare(tileX, tileY, size);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendTileSquare(tileX, tileY, size);
- return true;
- }
-
- try
- {
- var tiles = new NetTile[size, size];
- for (int x = 0; x < size; x++)
- {
- for (int y = 0; y < size; y++)
- {
- tiles[x, y] = new NetTile(args.Data);
- }
- }
-
- bool changed = false;
- for (int x = 0; x < size; x++)
- {
- int realx = tileX + x;
- if (realx < 0 || realx >= Main.maxTilesX)
- continue;
-
- for (int y = 0; y < size; y++)
- {
- int realy = tileY + y;
- if (realy < 0 || realy >= Main.maxTilesY)
- continue;
-
- var tile = Main.tile[realx, realy];
- var newtile = tiles[x, y];
- if (TShock.CheckTilePermission(args.Player, realx, realy) ||
- TShock.CheckRangePermission(args.Player, realx, realy))
- {
- continue;
- }
-
- // Fixes the Flower Boots not creating flowers issue
- if (size == 1 && args.Player.Accessories.Any(i => i.active && i.netID == ItemID.FlowerBoots))
- {
- if (Main.tile[realx, realy + 1].type == TileID.Grass && (newtile.Type == TileID.Plants || newtile.Type == TileID.Plants2))
- {
- return false;
- }
-
- if (Main.tile[realx, realy + 1].type == TileID.HallowedGrass && (newtile.Type == TileID.HallowedPlants || newtile.Type == TileID.HallowedPlants2))
- {
- return false;
- }
-
- if (Main.tile[realx, realy + 1].type == TileID.JungleGrass && newtile.Type == TileID.JunglePlants2)
- {
- return false;
- }
- }
-
- // Junction Box
- if (tile.type == TileID.WirePipe)
- return false;
-
- // Orientable tiles
- if (tile.type == newtile.Type && orientableTiles.Contains(tile.type))
- {
- Main.tile[realx, realy].frameX = newtile.FrameX;
- Main.tile[realx, realy].frameY = newtile.FrameY;
- changed = true;
- }
- // Landmine
- if (tile.type == TileID.LandMine && !newtile.Active)
- {
- Main.tile[realx, realy].active(false);
- changed = true;
- }
- // Sensors
- if(newtile.Type == TileID.LogicSensor && !Main.tile[realx, realy].active())
- {
- Main.tile[realx, realy].type = newtile.Type;
- Main.tile[realx, realy].frameX = newtile.FrameX;
- Main.tile[realx, realy].frameY = newtile.FrameY;
- Main.tile[realx, realy].active(true);
- changed = true;
- }
-
- if (tile.active() && newtile.Active && tile.type != newtile.Type)
- {
- // Grass <-> Grass
- if ((TileID.Sets.Conversion.Grass[tile.type] && TileID.Sets.Conversion.Grass[newtile.Type]) ||
- // Dirt <-> Dirt
- ((tile.type == 0 || tile.type == 59) &&
- (newtile.Type == 0 || newtile.Type == 59)) ||
- // Ice <-> Ice
- (TileID.Sets.Conversion.Ice[tile.type] && TileID.Sets.Conversion.Ice[newtile.Type]) ||
- // Stone <-> Stone
- ((TileID.Sets.Conversion.Stone[tile.type] || Main.tileMoss[tile.type]) &&
- (TileID.Sets.Conversion.Stone[newtile.Type] || Main.tileMoss[newtile.Type])) ||
- // Sand <-> Sand
- (TileID.Sets.Conversion.Sand[tile.type] && TileID.Sets.Conversion.Sand[newtile.Type]) ||
- // Sandstone <-> Sandstone
- (TileID.Sets.Conversion.Sandstone[tile.type] && TileID.Sets.Conversion.Sandstone[newtile.Type]) ||
- // Hardened Sand <-> Hardened Sand
- (TileID.Sets.Conversion.HardenedSand[tile.type] && TileID.Sets.Conversion.HardenedSand[newtile.Type]))
- {
- Main.tile[realx, realy].type = newtile.Type;
- changed = true;
- }
- }
- // Stone wall <-> Stone wall
- if (((tile.wall == 1 || tile.wall == 3 || tile.wall == 28 || tile.wall == 83) &&
- (newtile.Wall == 1 || newtile.Wall == 3 || newtile.Wall == 28 || newtile.Wall == 83)) ||
- // Leaf wall <-> Leaf wall
- (((tile.wall >= 63 && tile.wall <= 70) || tile.wall == 81) &&
- ((newtile.Wall >= 63 && newtile.Wall <= 70) || newtile.Wall == 81)))
- {
- Main.tile[realx, realy].wall = newtile.Wall;
- changed = true;
- }
-
- if ((tile.type == TileID.TrapdoorClosed && (newtile.Type == TileID.TrapdoorOpen || !newtile.Active)) ||
- (tile.type == TileID.TrapdoorOpen && (newtile.Type == TileID.TrapdoorClosed || !newtile.Active)) ||
- (!tile.active() && newtile.Active && (newtile.Type == TileID.TrapdoorOpen||newtile.Type == TileID.TrapdoorClosed)))
- {
- Main.tile[realx, realy].type = newtile.Type;
- Main.tile[realx, realy].frameX = newtile.FrameX;
- Main.tile[realx, realy].frameY = newtile.FrameY;
- Main.tile[realx, realy].active(newtile.Active);
- changed = true;
- }
- }
- }
-
- if (changed)
- {
- TSPlayer.All.SendTileSquare(tileX, tileY, size + 1);
- WorldGen.RangeFrame(tileX, tileY, tileX + size, tileY + size);
- }
- else
- {
- args.Player.SendTileSquare(tileX, tileY, size);
- }
- }
- catch
- {
- args.Player.SendTileSquare(tileX, tileY, size);
- }
- return true;
+ return false;
}
public enum EditAction
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 27ae3fc2..01a7fd8a 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -378,6 +378,8 @@ namespace TShockAPI
Log.ConsoleInfo("Welcome to TShock for Terraria!");
Log.ConsoleInfo("TShock comes with no warranty & is free software.");
Log.ConsoleInfo("You can modify & distribute it under the terms of the GNU GPLv3.");
+
+ Bouncer b = new Bouncer(this);
}
catch (Exception ex)
{
diff --git a/TShockAPI/TShockAPI.csproj b/TShockAPI/TShockAPI.csproj
index 08e9323d..e61ed3cb 100644
--- a/TShockAPI/TShockAPI.csproj
+++ b/TShockAPI/TShockAPI.csproj
@@ -134,6 +134,7 @@
+
True
True
From 758e403b6656469261abb432929388280d89e9c2 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 5 Dec 2017 02:34:08 -0700
Subject: [PATCH 080/430] Mark Bouncer's OnSendTileSquare as internal
---
TShockAPI/Bouncer.cs | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 804531eb..41a5f65a 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -52,7 +52,10 @@ namespace TShockAPI
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
}
- public void OnSendTileSquare(object sender, GetDataHandlers.SendTileSquareEventArgs args)
+ /// OnSendTileSquare - The handler for SendTileSquare events in Bouncer
+ /// sender
+ /// args
+ internal void OnSendTileSquare(object sender, GetDataHandlers.SendTileSquareEventArgs args)
{
short size = args.Size;
int tileX = args.TileX;
From db7ae627ae9490292b9086295df1e4a5effdafd4 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 5 Dec 2017 02:35:04 -0700
Subject: [PATCH 081/430] Move orientable tiles into Bouncer
---
TShockAPI/Bouncer.cs | 19 +++++++++++++++++
TShockAPI/GetDataHandlers.cs | 40 ------------------------------------
2 files changed, 19 insertions(+), 40 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 41a5f65a..309712c9 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -236,6 +236,25 @@ namespace TShockAPI
return;
}
+ ///
+ /// Tile IDs that can be oriented:
+ /// Cannon,
+ /// Chairs,
+ /// Beds,
+ /// Bathtubs,
+ /// Statues,
+ /// Mannequin,
+ /// Traps,
+ /// MusicBoxes,
+ /// ChristmasTree,
+ /// WaterFountain,
+ /// Womannequin,
+ /// MinecartTrack,
+ /// WeaponsRack,
+ /// LunarMonolith,
+ /// TargetDummy,
+ /// Campfire
+ ///
private static int[] orientableTiles = new int[]
{
TileID.Cannon,
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index e9c7ae8a..40eec2c5 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1694,46 +1694,6 @@ namespace TShockAPI
return false;
}
- ///
- /// Tile IDs that can be oriented:
- /// Cannon,
- /// Chairs,
- /// Beds,
- /// Bathtubs,
- /// Statues,
- /// Mannequin,
- /// Traps,
- /// MusicBoxes,
- /// ChristmasTree,
- /// WaterFountain,
- /// Womannequin,
- /// MinecartTrack,
- /// WeaponsRack,
- /// LunarMonolith,
- /// TargetDummy,
- /// Campfire
- ///
- private static int[] orientableTiles = new int[]
- {
- TileID.Cannon,
- TileID.Chairs,
- TileID.Beds,
- TileID.Bathtubs,
- TileID.Statues,
- TileID.Mannequin,
- TileID.Traps,
- TileID.MusicBoxes,
- TileID.ChristmasTree,
- TileID.WaterFountain,
- TileID.Womannequin,
- TileID.MinecartTrack,
- TileID.WeaponsRack,
- TileID.ItemFrame,
- TileID.LunarMonolith,
- TileID.TargetDummy,
- TileID.Campfire
- };
-
private static bool HandleSendTileSquare(GetDataHandlerArgs args)
{
var player = args.Player;
From 0d2d50b3de208672b04134c18d51892720c73a0f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 5 Dec 2017 02:35:30 -0700
Subject: [PATCH 082/430] Don't leave comments in code
---
TShockAPI/Bouncer.cs | 1 -
1 file changed, 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 309712c9..27715e81 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -48,7 +48,6 @@ namespace TShockAPI
{
// Setup hooks
- // SendTileSquareEventArgs args = new GetDataHandlers.SendTileSquareEventArgs();
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
}
From f065e99a0ea4569b863f0d05a700b5a2531861c1 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 5 Dec 2017 11:59:27 -0700
Subject: [PATCH 083/430] Add HealOtherPlayer hook; integrate with Bouncer
---
TShockAPI/Bouncer.cs | 40 ++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 59 +++++++++++++++++++++++-------------
2 files changed, 78 insertions(+), 21 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 27715e81..d76d488f 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -49,6 +49,46 @@ namespace TShockAPI
// Setup hooks
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
+ GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
+ }
+
+ /// OnHealOtherPlayer - The handler for the HealOther events in Bouncer
+ /// sender
+ /// args
+ internal void OnHealOtherPlayer(object sender, GetDataHandlers.HealOtherPlayerEventArgs args)
+ {
+ short amount = args.Amount;
+ byte plr = args.TargetPlayerIndex;
+
+ if (amount <= 0 || Main.player[plr] == null || !Main.player[plr].active)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (amount > TShock.Config.MaxDamage * 0.2)
+ {
+ args.Player.Disable("HealOtherPlayer cheat attempt!", DisableFlags.WriteToLogAndConsole);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.HealOtherThreshold > TShock.Config.HealOtherThreshold)
+ {
+ args.Player.Disable("Reached HealOtherPlayer threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player) || (DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ args.Player.HealOtherThreshold++;
+ args.Handled = false;
+ return;
}
/// OnSendTileSquare - The handler for SendTileSquare events in Bouncer
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 40eec2c5..153bd7a1 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -532,6 +532,43 @@ namespace TShockAPI
return false;
}
+ /// HandledEventArgs - The event args object for the HealOtherPlayer event
+ public class HealOtherPlayerEventArgs : HandledEventArgs
+ {
+ /// Player - The TSPlayer object that caused the event
+ public TSPlayer Player { get; set; }
+
+ /// TargetPlayerIndex - The Terraria player index of the target player
+ public byte TargetPlayerIndex { get; set; }
+
+ /// Amount - The amount to heal by
+ public short Amount { get; set; }
+ }
+
+ /// HealOtherPlayer - When a player heals another player
+ public static HandlerList HealOtherPlayer;
+
+ /// OnHealOtherPlayer - Fires the HealOtherPlayer event
+ /// player - The TSPlayer that started the event
+ /// targetPlayerIndex - The Terraria player index that the event targets
+ /// amount - The amount to heal
+ /// bool
+ private static bool OnHealOtherPlayer(TSPlayer player, byte targetPlayerIndex, short amount)
+ {
+ if (HealOtherPlayer == null)
+ return false;
+
+ var args = new HealOtherPlayerEventArgs
+ {
+ Player = player,
+ TargetPlayerIndex = targetPlayerIndex,
+ Amount = amount,
+ };
+
+ HealOtherPlayer.Invoke(null, args);
+ return args.Handled;
+ }
+
///
/// For use in a SendTileSquare event
///
@@ -1312,29 +1349,9 @@ namespace TShockAPI
byte plr = args.Data.ReadInt8();
short amount = args.Data.ReadInt16();
- if (amount <= 0 || Main.player[plr] == null || !Main.player[plr].active)
- {
+ if (OnHealOtherPlayer(args.Player, plr, amount))
return true;
- }
- if (amount > TShock.Config.MaxDamage * 0.2)
- {
- args.Player.Disable("HealOtherPlayer cheat attempt!", DisableFlags.WriteToLogAndConsole);
- return true;
- }
-
- if (args.Player.HealOtherThreshold > TShock.Config.HealOtherThreshold)
- {
- args.Player.Disable("Reached HealOtherPlayer threshold.", DisableFlags.WriteToLogAndConsole);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player) || (DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- return true;
- }
-
- args.Player.HealOtherThreshold++;
return false;
}
From 9ba0907dc0bcbe38c1a9008095511481d77d62b3 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:02:23 -0700
Subject: [PATCH 084/430] Fix most of the stupid comments in Bouncer
---
TShockAPI/Bouncer.cs | 8 ++++----
TShockAPI/GetDataHandlers.cs | 20 ++++++++++----------
2 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index d76d488f..69455328 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -39,10 +39,10 @@ using TShockAPI.Net;
namespace TShockAPI
{
- /// Bouncer - The TShock anti-hack and build guardian system
+ /// Bouncer is the TShock anti-hack and build guardian system
public class Bouncer
{
- /// Bouncer - Constructor call initializes Bouncer & related functionality.
+ /// Constructor call initializes Bouncer & related functionality.
/// A new Bouncer.
public Bouncer(TerrariaPlugin pluginInstance)
{
@@ -52,7 +52,7 @@ namespace TShockAPI
GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
}
- /// OnHealOtherPlayer - The handler for the HealOther events in Bouncer
+ /// The handler for the HealOther events in Bouncer
/// sender
/// args
internal void OnHealOtherPlayer(object sender, GetDataHandlers.HealOtherPlayerEventArgs args)
@@ -91,7 +91,7 @@ namespace TShockAPI
return;
}
- /// OnSendTileSquare - The handler for SendTileSquare events in Bouncer
+ /// The handler for SendTileSquare events in Bouncer
/// sender
/// args
internal void OnSendTileSquare(object sender, GetDataHandlers.SendTileSquareEventArgs args)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 153bd7a1..9cae47e6 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -532,26 +532,26 @@ namespace TShockAPI
return false;
}
- /// HandledEventArgs - The event args object for the HealOtherPlayer event
+ /// The event args object for the HealOtherPlayer event
public class HealOtherPlayerEventArgs : HandledEventArgs
{
- /// Player - The TSPlayer object that caused the event
+ /// The TSPlayer object that caused the event
public TSPlayer Player { get; set; }
- /// TargetPlayerIndex - The Terraria player index of the target player
+ /// The Terraria player index of the target player
public byte TargetPlayerIndex { get; set; }
- /// Amount - The amount to heal by
+ /// The amount to heal by
public short Amount { get; set; }
}
- /// HealOtherPlayer - When a player heals another player
+ /// When a player heals another player
public static HandlerList HealOtherPlayer;
- /// OnHealOtherPlayer - Fires the HealOtherPlayer event
- /// player - The TSPlayer that started the event
- /// targetPlayerIndex - The Terraria player index that the event targets
- /// amount - The amount to heal
+ /// Fires the HealOtherPlayer event
+ /// The TSPlayer that started the event
+ /// The Terraria player index that the event targets
+ /// The amount to heal
/// bool
private static bool OnHealOtherPlayer(TSPlayer player, byte targetPlayerIndex, short amount)
{
@@ -596,7 +596,7 @@ namespace TShockAPI
public int TileY { get; set; }
}
///
- /// SendTileSquare - When the player sends a tile square
+ /// When the player sends a tile square
///
public static HandlerList SendTileSquare;
From 1d5a013adb392a8b7910e1ed4bcb341a942d7cae Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:05:29 -0700
Subject: [PATCH 085/430] Seal the Bouncer inside his house
---
TShockAPI/Bouncer.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 69455328..c04682fe 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -40,11 +40,11 @@ using TShockAPI.Net;
namespace TShockAPI
{
/// Bouncer is the TShock anti-hack and build guardian system
- public class Bouncer
+ internal sealed class Bouncer
{
/// Constructor call initializes Bouncer & related functionality.
/// A new Bouncer.
- public Bouncer(TerrariaPlugin pluginInstance)
+ internal Bouncer(TerrariaPlugin pluginInstance)
{
// Setup hooks
From 5abf0f9d8e279898a36673547fcbf9620eff356d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:07:05 -0700
Subject: [PATCH 086/430] Comment magic number 5
---
TShockAPI/Bouncer.cs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index c04682fe..96b5abb9 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -106,6 +106,8 @@ namespace TShockAPI
return;
}
+ // From White:
+ // IIRC it's because 5 means a 5x5 square which is normal for a tile square, and anything bigger is a non-vanilla tile modification attempt
if (size > 5)
{
args.Handled = true;
From 349770e6edf432d191853d8dd5f1483f10f3ab5e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:10:05 -0700
Subject: [PATCH 087/430] Remove more silly comment style problems
---
TShockAPI/Utils.cs | 16 ++++++++--------
1 file changed, 8 insertions(+), 8 deletions(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 3626775e..dcd142ea 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1428,7 +1428,7 @@ namespace TShockAPI
}
}
- /// FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.
+ /// Verifies that each stack in each chest is valid and not over the max stack count.
internal void FixChestStacks()
{
if (TShock.Config.IgnoreChestStacksOnLoad)
@@ -1447,8 +1447,8 @@ namespace TShockAPI
}
}
- /// SetConsoleTitle - Updates the console title with some pertinent information.
- /// empty - True/false if the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.
+ /// Updates the console title with some pertinent information.
+ /// If the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.
internal void SetConsoleTitle(bool empty)
{
Console.Title = string.Format("{0}{1}/{2} on {3} @ {4}:{5} (TShock for Terraria v{6})",
@@ -1457,10 +1457,10 @@ namespace TShockAPI
TShock.Config.MaxSlots, Main.worldName, Netplay.ServerIP.ToString(), Netplay.ListenPort, TShock.VersionNum);
}
- /// Distance - Determines the distance between two vectors.
- /// value1 - The first vector location.
- /// value2 - The second vector location.
- /// float - The distance between the two vectors.
+ /// Determines the distance between two vectors.
+ /// The first vector location.
+ /// The second vector location.
+ /// The distance between the two vectors.
public static float Distance(Vector2 value1, Vector2 value2)
{
float num2 = value1.X - value2.X;
@@ -1469,7 +1469,7 @@ namespace TShockAPI
return (float)Math.Sqrt(num3);
}
- /// ComputeMaxStyles - Computes the max styles...
+ /// Computes the max styles...
internal void ComputeMaxStyles()
{
var item = new Item();
From e91968ca9116c48d60c679eab820a530f0a2c665 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:35:51 -0700
Subject: [PATCH 088/430] Revert "Remove superadmin customization config
options"
This reverts commit 1e68ac22c7d7c191f05e6f86b7847c2b4f885340.
---
TShockAPI/ConfigFile.cs | 12 ++++++++++++
TShockAPI/Group.cs | 10 +++++-----
2 files changed, 17 insertions(+), 5 deletions(-)
diff --git a/TShockAPI/ConfigFile.cs b/TShockAPI/ConfigFile.cs
index 5cfed41b..e5fa3320 100644
--- a/TShockAPI/ConfigFile.cs
+++ b/TShockAPI/ConfigFile.cs
@@ -78,6 +78,18 @@ namespace TShockAPI
[Description("Disables any building / placing of blocks.")]
public bool DisableBuild;
+ /// SuperAdminChatRGB - The chat color for the superadmin group.
+ [Description("#.#.# = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255.")]
+ public int[] SuperAdminChatRGB = { 255, 0, 0 };
+
+ /// SuperAdminChatPrefix - The superadmin chat prefix.
+ [Description("Super admin group chat prefix.")]
+ public string SuperAdminChatPrefix = "(Admin) ";
+
+ /// SuperAdminChatSuffix - The superadmin chat suffix.
+ [Description("Super admin group chat suffix.")]
+ public string SuperAdminChatSuffix = "";
+
/// BackupInterval - The backup frequency in minutes.
[Description("Backup frequency in minutes. So, a value of 60 = 60 minutes. Backups are stored in the \\tshock\\backups folder.")]
public int BackupInterval;
diff --git a/TShockAPI/Group.cs b/TShockAPI/Group.cs
index 448f8442..1eb5d48f 100644
--- a/TShockAPI/Group.cs
+++ b/TShockAPI/Group.cs
@@ -340,11 +340,11 @@ namespace TShockAPI
public SuperAdminGroup()
: base("superadmin")
{
- R = (byte)255;
- G = (byte)255;
- B = (byte)255;
- Prefix = "(Super Admin) ";
- Suffix = "";
+ R = (byte)TShock.Config.SuperAdminChatRGB[0];
+ G = (byte)TShock.Config.SuperAdminChatRGB[1];
+ B = (byte)TShock.Config.SuperAdminChatRGB[2];
+ Prefix = TShock.Config.SuperAdminChatPrefix;
+ Suffix = TShock.Config.SuperAdminChatSuffix;
}
///
From 8708d55d86bdc6ed6f0912cd3dd7a636cdd0945a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 17:39:09 -0700
Subject: [PATCH 089/430] But still use discouragement colors
---
TShockAPI/ConfigFile.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/ConfigFile.cs b/TShockAPI/ConfigFile.cs
index e5fa3320..85e340cf 100644
--- a/TShockAPI/ConfigFile.cs
+++ b/TShockAPI/ConfigFile.cs
@@ -80,11 +80,11 @@ namespace TShockAPI
/// SuperAdminChatRGB - The chat color for the superadmin group.
[Description("#.#.# = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255.")]
- public int[] SuperAdminChatRGB = { 255, 0, 0 };
+ public int[] SuperAdminChatRGB = { 255, 255, 255 };
/// SuperAdminChatPrefix - The superadmin chat prefix.
[Description("Super admin group chat prefix.")]
- public string SuperAdminChatPrefix = "(Admin) ";
+ public string SuperAdminChatPrefix = "(Super Admin) ";
/// SuperAdminChatSuffix - The superadmin chat suffix.
[Description("Super admin group chat suffix.")]
From a4d9f0295a0858459c6ea6e5aab32ca3a7812d46 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 22:16:19 -0700
Subject: [PATCH 090/430] Move OnTileEdit stuff to Bouncer
There are probably a few components in here that don't make sense
for bouncer (looking at you, regions code). However, it's on my todo
list rather than being an imminent thing.
---
TShockAPI/Bouncer.cs | 378 ++++++++++++++++++++++++++++++++++-
TShockAPI/GetDataHandlers.cs | 340 ++-----------------------------
2 files changed, 382 insertions(+), 336 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 96b5abb9..4a9e766a 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -15,16 +15,6 @@ 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 Terraria;
-using TerrariaApi.Server;
-using TShockAPI.Hooks;
-using TShockAPI;
-using TerrariaApi.Server;
-using Terraria.ID;
-using Terraria.ObjectData;
-using Terraria.DataStructures;
-using Terraria.GameContent.Tile_Entities;
-using Terraria.Localization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -35,7 +25,19 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria.ID;
+using TShockAPI.DB;
using TShockAPI.Net;
+using Terraria;
+using Terraria.ObjectData;
+using Terraria.DataStructures;
+using Terraria.GameContent.Tile_Entities;
+using Terraria.Localization;
+using Microsoft.Xna.Framework;
+using OTAPI.Tile;
+using TShockAPI.Localization;
+using static TShockAPI.GetDataHandlers;
+using TerrariaApi.Server;
+
namespace TShockAPI
{
@@ -50,6 +52,360 @@ namespace TShockAPI
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
+ GetDataHandlers.TileEdit.Register(OnTileEdit);
+ }
+
+ internal void OnTileEdit(object sender, GetDataHandlers.TileEditEventArgs args)
+ {
+ EditAction action = args.Action;
+ int tileX = args.X;
+ int tileY = args.Y;
+ short editData = args.EditData;
+ EditType type = args.editDetail;
+ byte style = args.Style;
+
+ try
+ {
+ if (editData < 0)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (!TShock.Utils.TilePlacementValid(tileX, tileY))
+ args.Handled = true;
+ return;
+ if (action == EditAction.KillTile && Main.tile[tileX, tileY].type == TileID.MagicalIceBlock)
+ args.Handled = false;
+ return;
+ if (args.Player.Dead && TShock.Config.PreventDeadModification)
+ args.Handled = true;
+ return;
+
+ if (args.Player.AwaitingName)
+ {
+ bool includeUnprotected = false;
+ bool includeZIndexes = false;
+ bool persistentMode = false;
+ foreach (string parameter in args.Player.AwaitingNameParameters)
+ {
+ if (parameter.Equals("-u", StringComparison.InvariantCultureIgnoreCase))
+ includeUnprotected = true;
+ if (parameter.Equals("-z", StringComparison.InvariantCultureIgnoreCase))
+ includeZIndexes = true;
+ if (parameter.Equals("-p", StringComparison.InvariantCultureIgnoreCase))
+ persistentMode = true;
+ }
+
+ List outputRegions = new List();
+ foreach (Region region in TShock.Regions.Regions.OrderBy(r => r.Z).Reverse())
+ {
+ if (!includeUnprotected && !region.DisableBuild)
+ continue;
+ if (tileX < region.Area.Left || tileX > region.Area.Right)
+ continue;
+ if (tileY < region.Area.Top || tileY > region.Area.Bottom)
+ continue;
+
+ string format = "{1}";
+ if (includeZIndexes)
+ format = "{1} (z:{0})";
+
+ outputRegions.Add(string.Format(format, region.Z, region.Name));
+ }
+
+ if (outputRegions.Count == 0)
+ {
+ if (includeUnprotected)
+ args.Player.SendInfoMessage("There are no regions at this point.");
+ else
+ args.Player.SendInfoMessage("There are no regions at this point or they are not protected.");
+ }
+ else
+ {
+ if (includeUnprotected)
+ args.Player.SendSuccessMessage("Regions at this point:");
+ else
+ args.Player.SendSuccessMessage("Protected regions at this point:");
+
+ foreach (string line in PaginationTools.BuildLinesFromTerms(outputRegions))
+ args.Player.SendMessage(line, Color.White);
+ }
+
+ if (!persistentMode)
+ {
+ args.Player.AwaitingName = false;
+ args.Player.AwaitingNameParameters = null;
+ }
+
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.AwaitingTempPoint > 0)
+ {
+ args.Player.TempPoints[args.Player.AwaitingTempPoint - 1].X = tileX;
+ args.Player.TempPoints[args.Player.AwaitingTempPoint - 1].Y = tileY;
+ args.Player.SendInfoMessage("Set temp point {0}.", args.Player.AwaitingTempPoint);
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Player.AwaitingTempPoint = 0;
+ args.Handled = true;
+ return;
+ }
+
+ Item selectedItem = args.Player.SelectedItem;
+ int lastKilledProj = args.Player.LastKilledProjectile;
+ ITile tile = Main.tile[tileX, tileY];
+
+ if (action == EditAction.PlaceTile)
+ {
+ if (TShock.TileBans.TileIsBanned(editData, args.Player))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Player.SendErrorMessage("You do not have permission to place this tile.");
+ args.Handled = true;
+ return;
+ }
+ }
+
+ if (action == EditAction.KillTile && !Main.tileCut[tile.type] && !breakableTiles.Contains(tile.type))
+ {
+ //TPlayer.mount.Type 8 => Drill Containment Unit.
+
+ // If the tile is an axe tile and they aren't selecting an axe, they're hacking.
+ if (Main.tileAxe[tile.type] && ((args.Player.TPlayer.mount.Type != 8 && selectedItem.axe == 0) && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+ // If the tile is a hammer tile and they aren't selecting a hammer, they're hacking.
+ else if (Main.tileHammer[tile.type] && ((args.Player.TPlayer.mount.Type != 8 && selectedItem.hammer == 0) && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+ // If the tile is a pickaxe tile and they aren't selecting a pickaxe, they're hacking.
+ // Item frames can be modified without pickaxe tile.
+ else if (tile.type != TileID.ItemFrame
+ && !Main.tileAxe[tile.type] && !Main.tileHammer[tile.type] && tile.wall == 0 && args.Player.TPlayer.mount.Type != 8 && selectedItem.pick == 0 && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+ }
+ else if (action == EditAction.KillWall)
+ {
+ // If they aren't selecting a hammer, they could be hacking.
+ if (selectedItem.hammer == 0 && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0 && selectedItem.createWall == 0)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+ else if (action == EditAction.PlaceTile && (projectileCreatesTile.ContainsKey(lastKilledProj) && editData == projectileCreatesTile[lastKilledProj]))
+ {
+ args.Player.LastKilledProjectile = 0;
+ }
+ else if (action == EditAction.PlaceTile || action == EditAction.PlaceWall)
+ {
+ if ((action == EditAction.PlaceTile && TShock.Config.PreventInvalidPlaceStyle) &&
+ (MaxPlaceStyles.ContainsKey(editData) && style > MaxPlaceStyles[editData]) &&
+ (ExtraneousPlaceStyles.ContainsKey(editData) && style > ExtraneousPlaceStyles[editData]))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ // If they aren't selecting the item which creates the tile or wall, they're hacking.
+ if (!(selectedItem.netID == ItemID.IceRod && editData == TileID.MagicalIceBlock) &&
+ (editData != (action == EditAction.PlaceTile ? selectedItem.createTile : selectedItem.createWall) &&
+ !(ropeCoilPlacements.ContainsKey(selectedItem.netID) && editData == ropeCoilPlacements[selectedItem.netID])))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ // Using the actuation accessory can lead to actuator hacking
+ if (TShock.Itembans.ItemIsBanned("Actuator", args.Player) && args.Player.TPlayer.autoActuator)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Player.SendErrorMessage("You do not have permission to place actuators.");
+ args.Handled = true;
+ return;
+ }
+ if (TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(selectedItem.netID), args.Player) || editData >= (action == EditAction.PlaceTile ? Main.maxTileSets : Main.maxWallTypes))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+ if (action == EditAction.PlaceTile && (editData == 29 || editData == 97) && Main.ServerSideCharacter)
+ {
+ args.Player.SendErrorMessage("You cannot place this tile because server side characters are enabled.");
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+ if (action == EditAction.PlaceTile && (editData == TileID.Containers || editData == TileID.Containers2))
+ {
+ if (TShock.Utils.MaxChests())
+ {
+ args.Player.SendErrorMessage("The world's chest limit has been reached - unable to place more.");
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+ if ((TShock.Utils.TilePlacementValid(tileX, tileY + 1) && Main.tile[tileX, tileY + 1].type == TileID.Boulder) ||
+ (TShock.Utils.TilePlacementValid(tileX + 1, tileY + 1) && Main.tile[tileX + 1, tileY + 1].type == TileID.Boulder))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+ }
+ }
+ else if (action == EditAction.PlaceWire || action == EditAction.PlaceWire2 || action == EditAction.PlaceWire3)
+ {
+ // If they aren't selecting a wrench, they're hacking.
+ // WireKite = The Grand Design
+ if (selectedItem.type != ItemID.Wrench
+ && selectedItem.type != ItemID.BlueWrench
+ && selectedItem.type != ItemID.GreenWrench
+ && selectedItem.type != ItemID.YellowWrench
+ && selectedItem.type != ItemID.MulticolorWrench
+ && selectedItem.type != ItemID.WireKite)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+ else if (action == EditAction.KillActuator || action == EditAction.KillWire ||
+ action == EditAction.KillWire2 || action == EditAction.KillWire3)
+ {
+ // If they aren't selecting the wire cutter, they're hacking.
+ if (selectedItem.type != ItemID.WireCutter
+ && selectedItem.type != ItemID.WireKite
+ && selectedItem.type != ItemID.MulticolorWrench)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+ else if (action == EditAction.PlaceActuator)
+ {
+ // If they aren't selecting the actuator and don't have the Presserator equipped, they're hacking.
+ if (selectedItem.type != ItemID.Actuator && !args.Player.TPlayer.autoActuator)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+ if (TShock.Config.AllowCutTilesAndBreakables && Main.tileCut[tile.type])
+ {
+ if (action == EditAction.KillWall)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ args.Handled = false;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, tileX, tileY, editData, action))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, tileX, tileY))
+ {
+ if (action == EditAction.PlaceTile && (editData == TileID.Rope || editData == TileID.SilkRope || editData == TileID.VineRope || editData == TileID.WebRope))
+ {
+ args.Handled = false;
+ return;
+ }
+
+ if (action == EditAction.KillTile || action == EditAction.KillWall && ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0)
+ {
+ args.Handled = false;
+ return;
+ }
+
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.TileKillThreshold >= TShock.Config.TileKillThreshold)
+ {
+ args.Player.Disable("Reached TileKill threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.TilePlaceThreshold >= TShock.Config.TilePlaceThreshold)
+ {
+ args.Player.Disable("Reached TilePlace threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if ((action == EditAction.PlaceTile || action == EditAction.PlaceWall) && !args.Player.HasPermission(Permissions.ignoreplacetiledetection))
+ {
+ args.Player.TilePlaceThreshold++;
+ var coords = new Vector2(tileX, tileY);
+ lock (args.Player.TilesCreated)
+ if (!args.Player.TilesCreated.ContainsKey(coords))
+ args.Player.TilesCreated.Add(coords, Main.tile[tileX, tileY]);
+ }
+
+ if ((action == EditAction.KillTile || action == EditAction.KillTileNoItem || action == EditAction.KillWall) && Main.tileSolid[Main.tile[tileX, tileY].type] &&
+ !args.Player.HasPermission(Permissions.ignorekilltiledetection))
+ {
+ args.Player.TileKillThreshold++;
+ var coords = new Vector2(tileX, tileY);
+ lock (args.Player.TilesDestroyed)
+ if (!args.Player.TilesDestroyed.ContainsKey(coords))
+ args.Player.TilesDestroyed.Add(coords, Main.tile[tileX, tileY]);
+ }
+ args.Handled = false;
+ return;
+ }
+ catch
+ {
+ args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Handled = true;
+ return;
+ }
}
/// The handler for the HealOther events in Bouncer
@@ -273,7 +629,7 @@ namespace TShockAPI
{
args.Player.SendTileSquare(tileX, tileY, size);
}
- args.Handled = true;
+ args.Handled = false;
return;
}
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 9cae47e6..7fbfd560 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1756,7 +1756,7 @@ namespace TShockAPI
///
/// Tiles that can be broken without any pickaxes/etc.
///
- private static int[] breakableTiles = new int[]
+ internal static int[] breakableTiles = new int[]
{
TileID.Books,
TileID.Bottles,
@@ -1780,7 +1780,7 @@ namespace TShockAPI
///
/// These projectiles create tiles on death.
///
- private static Dictionary projectileCreatesTile = new Dictionary
+ internal static Dictionary projectileCreatesTile = new Dictionary
{
{ ProjectileID.DirtBall, TileID.Dirt },
{ ProjectileID.SandBallGun, TileID.Sand },
@@ -1789,7 +1789,7 @@ namespace TShockAPI
{ ProjectileID.CrimsandBallGun, TileID.Crimsand },
};
- private static Dictionary ropeCoilPlacements = new Dictionary
+ internal static Dictionary ropeCoilPlacements = new Dictionary
{
{ItemID.RopeCoil, TileID.Rope},
{ItemID.SilkRopeCoil, TileID.SilkRope},
@@ -1800,7 +1800,7 @@ namespace TShockAPI
///
/// Extra place style limits for strange hardcoded values in Terraria
///
- private static Dictionary ExtraneousPlaceStyles = new Dictionary
+ internal static Dictionary ExtraneousPlaceStyles = new Dictionary
{
{TileID.MinecartTrack, 3}
};
@@ -1810,330 +1810,20 @@ namespace TShockAPI
EditAction action = (EditAction)args.Data.ReadInt8();
var tileX = args.Data.ReadInt16();
var tileY = args.Data.ReadInt16();
+ var editData = args.Data.ReadInt16();
+ EditType type = (action == EditAction.KillTile || action == EditAction.KillWall ||
+ action == EditAction.KillTileNoItem)
+ ? EditType.Fail
+ : (action == EditAction.PlaceTile || action == EditAction.PlaceWall)
+ ? EditType.Type
+ : EditType.Slope;
- try
- {
- var editData = args.Data.ReadInt16();
- EditType type = (action == EditAction.KillTile || action == EditAction.KillWall ||
- action == EditAction.KillTileNoItem)
- ? EditType.Fail
- : (action == EditAction.PlaceTile || action == EditAction.PlaceWall)
- ? EditType.Type
- : EditType.Slope;
+ var style = args.Data.ReadInt8();
- var style = args.Data.ReadInt8();
-
- if (editData < 0)
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (OnTileEdit(args.Player, tileX, tileY, action, type, editData, style))
- return true;
- if (!TShock.Utils.TilePlacementValid(tileX, tileY))
- return true;
- if (action == EditAction.KillTile && Main.tile[tileX, tileY].type == TileID.MagicalIceBlock)
- return false;
- if (args.Player.Dead && TShock.Config.PreventDeadModification)
- return true;
-
- if (args.Player.AwaitingName)
- {
- Debug.Assert(args.Player.AwaitingNameParameters != null);
-
- bool includeUnprotected = false;
- bool includeZIndexes = false;
- bool persistentMode = false;
- foreach (string parameter in args.Player.AwaitingNameParameters)
- {
- if (parameter.Equals("-u", StringComparison.InvariantCultureIgnoreCase))
- includeUnprotected = true;
- if (parameter.Equals("-z", StringComparison.InvariantCultureIgnoreCase))
- includeZIndexes = true;
- if (parameter.Equals("-p", StringComparison.InvariantCultureIgnoreCase))
- persistentMode = true;
- }
-
- List outputRegions = new List();
- foreach (Region region in TShock.Regions.Regions.OrderBy(r => r.Z).Reverse())
- {
- if (!includeUnprotected && !region.DisableBuild)
- continue;
- if (tileX < region.Area.Left || tileX > region.Area.Right)
- continue;
- if (tileY < region.Area.Top || tileY > region.Area.Bottom)
- continue;
-
- string format = "{1}";
- if (includeZIndexes)
- format = "{1} (z:{0})";
-
- outputRegions.Add(string.Format(format, region.Z, region.Name));
- }
-
- if (outputRegions.Count == 0)
- {
- if (includeUnprotected)
- args.Player.SendInfoMessage("There are no regions at this point.");
- else
- args.Player.SendInfoMessage("There are no regions at this point or they are not protected.");
- }
- else
- {
- if (includeUnprotected)
- args.Player.SendSuccessMessage("Regions at this point:");
- else
- args.Player.SendSuccessMessage("Protected regions at this point:");
-
- foreach (string line in PaginationTools.BuildLinesFromTerms(outputRegions))
- args.Player.SendMessage(line, Color.White);
- }
-
- if (!persistentMode)
- {
- args.Player.AwaitingName = false;
- args.Player.AwaitingNameParameters = null;
- }
-
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (args.Player.AwaitingTempPoint > 0)
- {
- args.Player.TempPoints[args.Player.AwaitingTempPoint - 1].X = tileX;
- args.Player.TempPoints[args.Player.AwaitingTempPoint - 1].Y = tileY;
- args.Player.SendInfoMessage("Set temp point {0}.", args.Player.AwaitingTempPoint);
- args.Player.SendTileSquare(tileX, tileY, 4);
- args.Player.AwaitingTempPoint = 0;
- return true;
- }
-
- Item selectedItem = args.Player.SelectedItem;
- int lastKilledProj = args.Player.LastKilledProjectile;
- ITile tile = Main.tile[tileX, tileY];
-
- if (action == EditAction.PlaceTile)
- {
- if (TShock.TileBans.TileIsBanned(editData, args.Player))
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- args.Player.SendErrorMessage("You do not have permission to place this tile.");
- return true;
- }
- }
-
- if (action == EditAction.KillTile && !Main.tileCut[tile.type] && !breakableTiles.Contains(tile.type))
- {
- //TPlayer.mount.Type 8 => Drill Containment Unit.
-
- // If the tile is an axe tile and they aren't selecting an axe, they're hacking.
- if (Main.tileAxe[tile.type] && ((args.Player.TPlayer.mount.Type != 8 && selectedItem.axe == 0) && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
- // If the tile is a hammer tile and they aren't selecting a hammer, they're hacking.
- else if (Main.tileHammer[tile.type] && ((args.Player.TPlayer.mount.Type != 8 && selectedItem.hammer == 0) && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
- // If the tile is a pickaxe tile and they aren't selecting a pickaxe, they're hacking.
- // Item frames can be modified without pickaxe tile.
- else if (tile.type != TileID.ItemFrame
- && !Main.tileAxe[tile.type] && !Main.tileHammer[tile.type] && tile.wall == 0 && args.TPlayer.mount.Type != 8 && selectedItem.pick == 0 && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0)
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
- }
- else if (action == EditAction.KillWall)
- {
- // If they aren't selecting a hammer, they could be hacking.
- if (selectedItem.hammer == 0 && !ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0 && selectedItem.createWall == 0)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- }
- else if (action == EditAction.PlaceTile && (projectileCreatesTile.ContainsKey(lastKilledProj) && editData == projectileCreatesTile[lastKilledProj]))
- {
- args.Player.LastKilledProjectile = 0;
- }
- else if (action == EditAction.PlaceTile || action == EditAction.PlaceWall)
- {
- if ((action == EditAction.PlaceTile && TShock.Config.PreventInvalidPlaceStyle) &&
- (MaxPlaceStyles.ContainsKey(editData) && style > MaxPlaceStyles[editData]) &&
- (ExtraneousPlaceStyles.ContainsKey(editData) && style > ExtraneousPlaceStyles[editData]))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- // If they aren't selecting the item which creates the tile or wall, they're hacking.
- if (!(selectedItem.netID == ItemID.IceRod && editData == TileID.MagicalIceBlock) &&
- (editData != (action == EditAction.PlaceTile ? selectedItem.createTile : selectedItem.createWall) &&
- !(ropeCoilPlacements.ContainsKey(selectedItem.netID) && editData == ropeCoilPlacements[selectedItem.netID])))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- // Using the actuation accessory can lead to actuator hacking
- if (TShock.Itembans.ItemIsBanned("Actuator", args.Player) && args.Player.TPlayer.autoActuator)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- args.Player.SendErrorMessage("You do not have permission to place actuators.");
- return true;
- }
- if (TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(selectedItem.netID), args.Player) || editData >= (action == EditAction.PlaceTile ? Main.maxTileSets : Main.maxWallTypes))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
- if (action == EditAction.PlaceTile && (editData == 29 || editData == 97) && Main.ServerSideCharacter)
- {
- args.Player.SendErrorMessage("You cannot place this tile because server side characters are enabled.");
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
- if (action == EditAction.PlaceTile && (editData == TileID.Containers || editData == TileID.Containers2))
- {
- if (TShock.Utils.MaxChests())
- {
- args.Player.SendErrorMessage("The world's chest limit has been reached - unable to place more.");
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
- if ((TShock.Utils.TilePlacementValid(tileX, tileY + 1) && Main.tile[tileX, tileY + 1].type == TileID.Boulder) ||
- (TShock.Utils.TilePlacementValid(tileX + 1, tileY + 1) && Main.tile[tileX + 1, tileY + 1].type == TileID.Boulder))
- {
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
- }
- }
- else if (action == EditAction.PlaceWire || action == EditAction.PlaceWire2 || action == EditAction.PlaceWire3)
- {
- // If they aren't selecting a wrench, they're hacking.
- // WireKite = The Grand Design
- if (selectedItem.type != ItemID.Wrench
- && selectedItem.type != ItemID.BlueWrench
- && selectedItem.type != ItemID.GreenWrench
- && selectedItem.type != ItemID.YellowWrench
- && selectedItem.type != ItemID.MulticolorWrench
- && selectedItem.type != ItemID.WireKite)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- }
- else if (action == EditAction.KillActuator || action == EditAction.KillWire ||
- action == EditAction.KillWire2 || action == EditAction.KillWire3)
- {
- // If they aren't selecting the wire cutter, they're hacking.
- if (selectedItem.type != ItemID.WireCutter
- && selectedItem.type != ItemID.WireKite
- && selectedItem.type != ItemID.MulticolorWrench)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- }
- else if (action == EditAction.PlaceActuator)
- {
- // If they aren't selecting the actuator and don't have the Presserator equipped, they're hacking.
- if (selectedItem.type != ItemID.Actuator && !args.Player.TPlayer.autoActuator)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- }
- if (TShock.Config.AllowCutTilesAndBreakables && Main.tileCut[tile.type])
- {
- if (action == EditAction.KillWall)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- return false;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (TShock.CheckTilePermission(args.Player, tileX, tileY, editData, action))
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, tileX, tileY))
- {
- if (action == EditAction.PlaceTile && (editData == TileID.Rope || editData == TileID.SilkRope || editData == TileID.VineRope || editData == TileID.WebRope))
- {
- return false;
- }
-
- if (action == EditAction.KillTile || action == EditAction.KillWall && ItemID.Sets.Explosives[selectedItem.netID] && args.Player.RecentFuse == 0)
- {
- return false;
- }
-
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (args.Player.TileKillThreshold >= TShock.Config.TileKillThreshold)
- {
- args.Player.Disable("Reached TileKill threshold.", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if (args.Player.TilePlaceThreshold >= TShock.Config.TilePlaceThreshold)
- {
- args.Player.Disable("Reached TilePlace threshold.", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
- return true;
- }
-
- if ((action == EditAction.PlaceTile || action == EditAction.PlaceWall) && !args.Player.HasPermission(Permissions.ignoreplacetiledetection))
- {
- args.Player.TilePlaceThreshold++;
- var coords = new Vector2(tileX, tileY);
- lock (args.Player.TilesCreated)
- if (!args.Player.TilesCreated.ContainsKey(coords))
- args.Player.TilesCreated.Add(coords, Main.tile[tileX, tileY]);
- }
-
- if ((action == EditAction.KillTile || action == EditAction.KillTileNoItem || action == EditAction.KillWall) && Main.tileSolid[Main.tile[tileX, tileY].type] &&
- !args.Player.HasPermission(Permissions.ignorekilltiledetection))
- {
- args.Player.TileKillThreshold++;
- var coords = new Vector2(tileX, tileY);
- lock (args.Player.TilesDestroyed)
- if (!args.Player.TilesDestroyed.ContainsKey(coords))
- args.Player.TilesDestroyed.Add(coords, Main.tile[tileX, tileY]);
- }
- return false;
- }
- catch
- {
- args.Player.SendTileSquare(tileX, tileY, 4);
+ if (OnTileEdit(args.Player, tileX, tileY, action, type, editData, style))
return true;
- }
+
+ return false;
}
From c46dae328df57c2805e8f32e638e083ad5816f16 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 23:37:09 -0700
Subject: [PATCH 091/430] Optimize imports
I now have VSCode installed for one reason: to optimize imports.
This required:
1. Installing VSCode.
2. Installing OmniSharp in VSCode.
3. Installing .NET Core so that OmniSharp could start in VSCode.
VSCode is a Microsoft product. It doesn't ship .NET Core. Or Omni
Sharp. Instead, you have to do all of this yourself.
It's not batteries included or anything.
It's actually harder to use OmniSharp in VSCode than it is to use
it in Sublime Text. Except Sublime Text's OmniSharp maintainer
went off and abandoned the project without telling anyone at OmniS
harp. Which gave me the idea that OmniSharp still was maintained
on Sublime Text.
And I just upgraded my Sublime Text license today.
Thanks OmniSharp developer.
---
TShockAPI/Bouncer.cs | 14 ++------------
1 file changed, 2 insertions(+), 12 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 4a9e766a..e8e732be 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -17,21 +17,11 @@ along with this program. If not, see .
*/
using System;
using System.Collections.Generic;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.IO;
-using System.IO.Streams;
using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
using Terraria.ID;
using TShockAPI.DB;
using TShockAPI.Net;
using Terraria;
-using Terraria.ObjectData;
-using Terraria.DataStructures;
-using Terraria.GameContent.Tile_Entities;
-using Terraria.Localization;
using Microsoft.Xna.Framework;
using OTAPI.Tile;
using TShockAPI.Localization;
@@ -41,8 +31,8 @@ using TerrariaApi.Server;
namespace TShockAPI
{
- /// Bouncer is the TShock anti-hack and build guardian system
- internal sealed class Bouncer
+ /// Bouncer is the TShock anti-hack and build guardian system
+ internal sealed class Bouncer
{
/// Constructor call initializes Bouncer & related functionality.
/// A new Bouncer.
From 6630b70ae1e8cef50e51b887053f706269123476 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 6 Dec 2017 23:42:14 -0700
Subject: [PATCH 092/430] Un-botch tab/spacing in this file. Thanks VS Code!
Now I know that if I merely open and save a file using Visual Studi
o code, it will automatically munge my tab/spaces on two lines just
for kicks. Thanks Microsoft! You're great at this!
---
TShockAPI/Bouncer.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index e8e732be..5199dcb0 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -31,8 +31,8 @@ using TerrariaApi.Server;
namespace TShockAPI
{
- /// Bouncer is the TShock anti-hack and build guardian system
- internal sealed class Bouncer
+ /// Bouncer is the TShock anti-hack and build guardian system
+ internal sealed class Bouncer
{
/// Constructor call initializes Bouncer & related functionality.
/// A new Bouncer.
From 6589531868d23d8022f46b767f9a40792ef3cb7c Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Fri, 8 Dec 2017 01:38:15 +0100
Subject: [PATCH 093/430] Renamed TShockAPI.DB 'User' to 'UserAccount'
---
TShockAPI/Commands.cs | 206 +++++++++----------
TShockAPI/DB/CharacterManager.cs | 18 +-
TShockAPI/DB/RegionManager.cs | 6 +-
TShockAPI/DB/UserManager.cs | 329 ++++++++++++++++---------------
TShockAPI/GetDataHandlers.cs | 18 +-
TShockAPI/Hooks/AccountHooks.cs | 12 +-
TShockAPI/Rest/RestManager.cs | 34 ++--
TShockAPI/Rest/SecureRest.cs | 4 +-
TShockAPI/TSPlayer.cs | 8 +-
TShockAPI/TSServerPlayer.cs | 2 +-
TShockAPI/TShock.cs | 24 +--
TShockAPI/Utils.cs | 2 +-
12 files changed, 335 insertions(+), 328 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 72cddc6a..592177cf 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -193,11 +193,17 @@ namespace TShockAPI
public static List ChatCommands = new List();
public static ReadOnlyCollection TShockCommands = new ReadOnlyCollection(new List());
+ ///
+ /// The command specifier, defaults to "/"
+ ///
public static string Specifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; }
}
+ ///
+ /// The silent command specifier, defaults to "."
+ ///
public static string SilentSpecifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; }
@@ -787,7 +793,7 @@ namespace TShockAPI
return;
}
- User user = TShock.Users.GetUserByName(args.Player.Name);
+ UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
string password = "";
bool usingUUID = false;
if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin)
@@ -813,7 +819,7 @@ namespace TShockAPI
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1]))
return;
- user = TShock.Users.GetUserByName(args.Parameters[0]);
+ account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
password = args.Parameters[1];
}
else
@@ -826,21 +832,21 @@ namespace TShockAPI
}
try
{
- if (user == null)
+ if (account == null)
{
- args.Player.SendErrorMessage("A user by that name does not exist.");
+ args.Player.SendErrorMessage("A user account by that name does not exist.");
}
- else if (user.VerifyPassword(password) ||
- (usingUUID && user.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
+ else if (account.VerifyPassword(password) ||
+ (usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
!String.IsNullOrWhiteSpace(args.Player.UUID)))
{
- args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID);
+ args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
- var group = TShock.Utils.GetGroup(user.Group);
+ var group = TShock.Utils.GetGroup(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
- args.Player.User = user;
+ args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none";
@@ -861,9 +867,9 @@ namespace TShockAPI
if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IgnoreActionsForDisabledArmor = "none";
- args.Player.SendSuccessMessage("Authenticated as " + user.Name + " successfully.");
+ args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully.");
- TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + user.Name + ".");
+ TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + account.Name + ".");
if ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos))
{
if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero)
@@ -874,7 +880,7 @@ namespace TShockAPI
args.Player.LoginHarassed = false;
}
- TShock.Users.SetUserUUID(user, args.Player.UUID);
+ TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
}
@@ -888,7 +894,7 @@ namespace TShockAPI
{
args.Player.SendErrorMessage("Invalid password!");
}
- TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + user.Name + ".");
+ TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + account.Name + ".");
args.Player.LoginAttempts++;
}
}
@@ -922,14 +928,14 @@ namespace TShockAPI
if (args.Player.IsLoggedIn && args.Parameters.Count == 2)
{
string password = args.Parameters[0];
- if (args.Player.User.VerifyPassword(password))
+ if (args.Player.Account.VerifyPassword(password))
{
try
{
args.Player.SendSuccessMessage("You changed your password!");
- TShock.Users.SetUserPassword(args.Player.User, args.Parameters[1]); // SetUserPassword will hash it for you.
+ TShock.UserAccounts.SetUserAccountPassword(args.Player.Account, args.Parameters[1]); // SetUserPassword will hash it for you.
TShock.Log.ConsoleInfo(args.Player.IP + " named " + args.Player.Name + " changed the password of account " +
- args.Player.User.Name + ".");
+ args.Player.Account.Name + ".");
}
catch (ArgumentOutOfRangeException)
{
@@ -940,7 +946,7 @@ namespace TShockAPI
{
args.Player.SendErrorMessage("You failed to change your password!");
TShock.Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for account: " +
- args.Player.User.Name + ".");
+ args.Player.Account.Name + ".");
}
}
else
@@ -948,7 +954,7 @@ namespace TShockAPI
args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password ", Specifier);
}
}
- catch (UserManagerException ex)
+ catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("PasswordUser returned an error: " + ex);
@@ -959,15 +965,15 @@ namespace TShockAPI
{
try
{
- var user = new User();
+ var account = new UserAccount();
string echoPassword = "";
if (args.Parameters.Count == 1)
{
- user.Name = args.Player.Name;
+ account.Name = args.Player.Name;
echoPassword = args.Parameters[0];
try
{
- user.CreateBCryptHash(args.Parameters[0]);
+ account.CreateBCryptHash(args.Parameters[0]);
}
catch (ArgumentOutOfRangeException)
{
@@ -977,11 +983,11 @@ namespace TShockAPI
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
{
- user.Name = args.Parameters[0];
+ account.Name = args.Parameters[0];
echoPassword = args.Parameters[1];
try
{
- user.CreateBCryptHash(args.Parameters[1]);
+ account.CreateBCryptHash(args.Parameters[1]);
}
catch (ArgumentOutOfRangeException)
{
@@ -995,24 +1001,24 @@ namespace TShockAPI
return;
}
- user.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
- user.UUID = args.Player.UUID;
+ account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
+ account.UUID = args.Player.UUID;
- if (TShock.Users.GetUserByName(user.Name) == null && user.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
+ if (TShock.UserAccounts.GetUserAccountByName(account.Name) == null && account.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
{
- args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", user.Name);
+ args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", account.Name);
args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
- TShock.Users.AddUser(user);
- TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, user.Name);
+ TShock.UserAccounts.AddUserAccount(account);
+ TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name);
}
else
{
- args.Player.SendErrorMessage("Sorry, " + user.Name + " was already taken by another person.");
+ args.Player.SendErrorMessage("Sorry, " + account.Name + " was already taken by another person.");
args.Player.SendErrorMessage("Please try a different username.");
- TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + user.Name);
+ TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + account.Name);
}
}
- catch (UserManagerException ex)
+ catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
@@ -1033,57 +1039,57 @@ namespace TShockAPI
// Add requires a username, password, and a group specified.
if (subcmd == "add" && args.Parameters.Count == 4)
{
- var user = new User();
+ var account = new UserAccount();
- user.Name = args.Parameters[1];
+ account.Name = args.Parameters[1];
try
{
- user.CreateBCryptHash(args.Parameters[2]);
+ account.CreateBCryptHash(args.Parameters[2]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
- user.Group = args.Parameters[3];
+ account.Group = args.Parameters[3];
try
{
- TShock.Users.AddUser(user);
- args.Player.SendSuccessMessage("Account " + user.Name + " has been added to group " + user.Group + "!");
- TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group);
+ TShock.UserAccounts.AddUserAccount(account);
+ args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!");
+ TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group);
}
catch (GroupNotExistsException)
{
- args.Player.SendErrorMessage("Group " + user.Group + " does not exist!");
+ args.Player.SendErrorMessage("Group " + account.Group + " does not exist!");
}
- catch (UserExistsException)
+ catch (UserAccountExistsException)
{
- args.Player.SendErrorMessage("User " + user.Name + " already exists!");
+ args.Player.SendErrorMessage("User " + account.Name + " already exists!");
}
- catch (UserManagerException e)
+ catch (UserAccountManagerException e)
{
- args.Player.SendErrorMessage("User " + user.Name + " could not be added, check console for details.");
+ args.Player.SendErrorMessage("User " + account.Name + " could not be added, check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
// User deletion requires a username
else if (subcmd == "del" && args.Parameters.Count == 2)
{
- var user = new User();
- user.Name = args.Parameters[1];
+ var account = new UserAccount();
+ account.Name = args.Parameters[1];
try
{
- TShock.Users.RemoveUser(user);
+ TShock.UserAccounts.RemoveUserAccount(account);
args.Player.SendSuccessMessage("Account removed successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
}
- catch (UserNotExistException)
+ catch (UserAccountNotExistException)
{
- args.Player.SendErrorMessage("The user " + user.Name + " does not exist! Deleted nobody!");
+ args.Player.SendErrorMessage("The user " + account.Name + " does not exist! Deleted nobody!");
}
- catch (UserManagerException ex)
+ catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
TShock.Log.ConsoleError(ex.ToString());
@@ -1093,22 +1099,22 @@ namespace TShockAPI
// Password changing requires a username, and a new password to set
else if (subcmd == "password" && args.Parameters.Count == 3)
{
- var user = new User();
- user.Name = args.Parameters[1];
+ var account = new UserAccount();
+ account.Name = args.Parameters[1];
try
{
- TShock.Users.SetUserPassword(user, args.Parameters[2]);
- TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + user.Name);
- args.Player.SendSuccessMessage("Password change succeeded for " + user.Name + ".");
+ TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]);
+ TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name);
+ args.Player.SendSuccessMessage("Password change succeeded for " + account.Name + ".");
}
- catch (UserNotExistException)
+ catch (UserAccountNotExistException)
{
- args.Player.SendErrorMessage("User " + user.Name + " does not exist!");
+ args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
- catch (UserManagerException e)
+ catch (UserAccountManagerException e)
{
- args.Player.SendErrorMessage("Password change for " + user.Name + " failed! Check console!");
+ args.Player.SendErrorMessage("Password change for " + account.Name + " failed! Check console!");
TShock.Log.ConsoleError(e.ToString());
}
catch (ArgumentOutOfRangeException)
@@ -1119,26 +1125,26 @@ namespace TShockAPI
// Group changing requires a username or IP address, and a new group to set
else if (subcmd == "group" && args.Parameters.Count == 3)
{
- var user = new User();
- user.Name = args.Parameters[1];
+ var account = new UserAccount();
+ account.Name = args.Parameters[1];
try
{
- TShock.Users.SetUserGroup(user, args.Parameters[2]);
- TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + user.Name + " to group " + args.Parameters[2] + ".");
- args.Player.SendSuccessMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!");
+ TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]);
+ TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + ".");
+ args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!");
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("That group does not exist!");
}
- catch (UserNotExistException)
+ catch (UserAccountNotExistException)
{
- args.Player.SendErrorMessage("User " + user.Name + " does not exist!");
+ args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
- catch (UserManagerException e)
+ catch (UserAccountManagerException e)
{
- args.Player.SendErrorMessage("User " + user.Name + " could not be added. Check console for details.");
+ args.Player.SendErrorMessage("User " + account.Name + " could not be added. Check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
@@ -1198,8 +1204,8 @@ namespace TShockAPI
{
var message = new StringBuilder();
message.Append("IP Address: ").Append(players[0].IP);
- if (players[0].User != null && players[0].IsLoggedIn)
- message.Append(" | Logged in as: ").Append(players[0].User.Name).Append(" | Group: ").Append(players[0].Group.Name);
+ if (players[0].Account != null && players[0].IsLoggedIn)
+ message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name);
args.Player.SendSuccessMessage(message.ToString());
}
}
@@ -1215,28 +1221,28 @@ namespace TShockAPI
string username = String.Join(" ", args.Parameters);
if (!string.IsNullOrWhiteSpace(username))
{
- var user = TShock.Users.GetUserByName(username);
- if (user != null)
+ var account = TShock.UserAccounts.GetUserAccountByName(username);
+ if (account != null)
{
DateTime LastSeen;
string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#");
- if (DateTime.TryParse(user.LastAccessed, out LastSeen))
+ if (DateTime.TryParse(account.LastAccessed, out LastSeen))
{
- LastSeen = DateTime.Parse(user.LastAccessed).ToLocalTime();
- args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", user.Name, LastSeen.ToShortDateString(),
+ LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime();
+ args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(),
LastSeen.ToShortTimeString(), Timezone);
}
if (args.Player.Group.HasPermission(Permissions.advaccountinfo))
{
- List KnownIps = JsonConvert.DeserializeObject>(user.KnownIps?.ToString() ?? string.Empty);
+ List KnownIps = JsonConvert.DeserializeObject>(account.KnownIps?.ToString() ?? string.Empty);
string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A";
- DateTime Registered = DateTime.Parse(user.Registered).ToLocalTime();
+ DateTime Registered = DateTime.Parse(account.Registered).ToLocalTime();
- args.Player.SendSuccessMessage("{0}'s group is {1}.", user.Name, user.Group);
- args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", user.Name, ip);
- args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", user.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
+ args.Player.SendSuccessMessage("{0}'s group is {1}.", account.Name, account.Group);
+ args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", account.Name, ip);
+ args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
}
}
else
@@ -1303,7 +1309,7 @@ namespace TShockAPI
// Effective ban target assignment
List players = TShock.Utils.FindPlayer(args.Parameters[1]);
- User offlineUser = TShock.Users.GetUserByName(args.Parameters[1]);
+ UserAccount offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(args.Parameters[1]);
// Storage variable to determine if the command executor is the server console
// If it is, we assume they have full control and let them override permission checks
@@ -1365,7 +1371,7 @@ namespace TShockAPI
}
targetGeneralizedName = target.Name;
- success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.User.Name, banReason, false, args.Player.User.Name,
+ success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.Account.Name, banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now.
@@ -1396,8 +1402,8 @@ namespace TShockAPI
if (r.IsMatch(args.Parameters[1])) {
targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason,
- false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
- if (success && offlineUser != null)
+ false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
+ if (success && offlineUserAccount != null)
{
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
args.Player.SendErrorMessage("Note: An account named with this IP address also exists.");
@@ -1407,7 +1413,7 @@ namespace TShockAPI
// Apparently there is no way to not IP ban someone
// This means that where we would normally just ban a "character name" here
// We can't because it requires some IP as a primary key.
- if (offlineUser == null)
+ if (offlineUserAccount == null)
{
args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]);
args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user.");
@@ -1418,33 +1424,33 @@ namespace TShockAPI
}
// Case: Offline ban
- if (players.Count == 0 && offlineUser != null)
+ if (players.Count == 0 && offlineUserAccount != null)
{
// Catch: we don't know an offline player's last login character name
// This means that we're banning their *user name* on the assumption that
// user name == character name
// (which may not be true)
// This needs to be fixed in a future implementation.
- targetGeneralizedName = offlineUser.Name;
+ targetGeneralizedName = offlineUserAccount.Name;
- if (TShock.Groups.GetGroupByName(offlineUser.Group).HasPermission(Permissions.immunetoban) &&
+ if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(Permissions.immunetoban) &&
!callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return;
}
- if (offlineUser.KnownIps == null)
+ if (offlineUserAccount.KnownIps == null)
{
args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
return;
}
- string lastIP = JsonConvert.DeserializeObject>(offlineUser.KnownIps).Last();
+ string lastIP = JsonConvert.DeserializeObject>(offlineUserAccount.KnownIps).Last();
success =
TShock.Bans.AddBan2(lastIP,
- "", offlineUser.UUID, offlineUser.Name, banReason, false, args.Player.User.Name,
+ "", offlineUserAccount.UUID, offlineUserAccount.Name, banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
}
@@ -1458,12 +1464,12 @@ namespace TShockAPI
if (banLengthInSeconds == 0)
{
TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
- targetGeneralizedName, args.Player.User.Name, banReason);
+ targetGeneralizedName, args.Player.Account.Name, banReason);
}
else
{
TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}",
- targetGeneralizedName, banLengthInSeconds, args.Player.User.Name, banReason);
+ targetGeneralizedName, banLengthInSeconds, args.Player.Account.Name, banReason);
}
}
}
@@ -1780,7 +1786,7 @@ namespace TShockAPI
if (ply.Count > 1)
{
- TShock.Utils.SendMultipleMatchError(args.Player, ply.Select(p => p.User.Name));
+ TShock.Utils.SendMultipleMatchError(args.Player, ply.Select(p => p.Account.Name));
}
if (!TShock.Groups.GroupExists(args.Parameters[1]))
@@ -4187,7 +4193,7 @@ namespace TShockAPI
var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X);
var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y);
- if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.User.Name,
+ if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.Account.Name,
Main.worldID.ToString()))
{
args.Player.TempPoints[0] = Point.Zero;
@@ -4276,7 +4282,7 @@ namespace TShockAPI
regionName = regionName + " " + args.Parameters[i];
}
}
- if (TShock.Users.GetUserByName(playerName) != null)
+ if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.AddNewUser(regionName, playerName))
{
@@ -4311,7 +4317,7 @@ namespace TShockAPI
regionName = regionName + " " + args.Parameters[i];
}
}
- if (TShock.Users.GetUserByName(playerName) != null)
+ if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.RemoveUser(regionName, playerName))
{
@@ -4452,9 +4458,9 @@ namespace TShockAPI
{
IEnumerable sharedUsersSelector = region.AllowedIDs.Select(userId =>
{
- User user = TShock.Users.GetUserByID(userId);
- if (user != null)
- return user.Name;
+ UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId);
+ if (account != null)
+ return account.Name;
return string.Concat("{ID: ", userId, "}");
});
diff --git a/TShockAPI/DB/CharacterManager.cs b/TShockAPI/DB/CharacterManager.cs
index 2c264138..132ab6ef 100644
--- a/TShockAPI/DB/CharacterManager.cs
+++ b/TShockAPI/DB/CharacterManager.cs
@@ -120,7 +120,7 @@ namespace TShockAPI.DB
return playerData;
}
- public bool SeedInitialData(User user)
+ public bool SeedInitialData(UserAccount user)
{
var inventory = new StringBuilder();
@@ -165,17 +165,17 @@ namespace TShockAPI.DB
if (player.HasPermission(Permissions.bypassssc) && !fromCommand)
{
- TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.User.Name); // Debug code
+ TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.Account.Name); // Debug code
return false;
}
- if (!GetPlayerData(player, player.User.ID).exists)
+ if (!GetPlayerData(player, player.Account.ID).exists)
{
try
{
database.Query(
"INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20);",
- player.User.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished);
+ player.Account.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished);
return true;
}
catch (Exception ex)
@@ -189,7 +189,7 @@ namespace TShockAPI.DB
{
database.Query(
"UPDATE tsCharacter SET Health = @0, MaxHealth = @1, Mana = @2, MaxMana = @3, Inventory = @4, spawnX = @6, spawnY = @7, hair = @8, hairDye = @9, hairColor = @10, pantsColor = @11, shirtColor = @12, underShirtColor = @13, shoeColor = @14, hideVisuals = @15, skinColor = @16, eyeColor = @17, questsCompleted = @18, skinVariant = @19, extraSlot = @20 WHERE Account = @5;",
- playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), player.User.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0);
+ playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), player.Account.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0);
return true;
}
catch (Exception ex)
@@ -235,17 +235,17 @@ namespace TShockAPI.DB
if (player.HasPermission(Permissions.bypassssc))
{
- TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.User.Name); // Debug code
+ TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.Account.Name); // Debug code
return true;
}
- if (!GetPlayerData(player, player.User.ID).exists)
+ if (!GetPlayerData(player, player.Account.ID).exists)
{
try
{
database.Query(
"INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20);",
- player.User.ID,
+ player.Account.ID,
playerData.health,
playerData.maxHealth,
playerData.mana,
@@ -284,7 +284,7 @@ namespace TShockAPI.DB
playerData.mana,
playerData.maxMana,
String.Join("~", playerData.inventory),
- player.User.ID,
+ player.Account.ID,
playerData.spawnX,
playerData.spawnX,
playerData.skinVariant,
diff --git a/TShockAPI/DB/RegionManager.cs b/TShockAPI/DB/RegionManager.cs
index f94b2a48..608f691d 100644
--- a/TShockAPI/DB/RegionManager.cs
+++ b/TShockAPI/DB/RegionManager.cs
@@ -447,7 +447,7 @@ namespace TShockAPI.DB
Region r = GetRegionByName(regionName);
if (r != null)
{
- if (!r.RemoveID(TShock.Users.GetUserID(userName)))
+ if (!r.RemoveID(TShock.UserAccounts.GetUserAccountID(userName)))
{
return false;
}
@@ -479,7 +479,7 @@ namespace TShockAPI.DB
mergedIDs = reader.Get("UserIds");
}
- string userIdToAdd = Convert.ToString(TShock.Users.GetUserID(userName));
+ string userIdToAdd = Convert.ToString(TShock.UserAccounts.GetUserAccountID(userName));
string[] ids = mergedIDs.Split(',');
// Is the user already allowed to the region?
if (ids.Contains(userIdToAdd))
@@ -788,7 +788,7 @@ namespace TShockAPI.DB
return false;
}
- return ply.HasPermission(Permissions.editregion) || AllowedIDs.Contains(ply.User.ID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.User.Name;
+ return ply.HasPermission(Permissions.editregion) || AllowedIDs.Contains(ply.Account.ID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.Account.Name;
}
///
diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs
index 07662b2b..757fa6f7 100644
--- a/TShockAPI/DB/UserManager.cs
+++ b/TShockAPI/DB/UserManager.cs
@@ -28,16 +28,16 @@ using System.Security.Cryptography;
namespace TShockAPI.DB
{
- /// UserManager - Methods for dealing with database users and other user functionality within TShock.
- public class UserManager
+ /// UserAccountManager - Methods for dealing with database user accounts and other related functionality within TShock.
+ public class UserAccountManager
{
/// database - The database object to use for connections.
private IDbConnection _database;
- /// Creates a UserManager object. During instantiation, this method will verify the table structure against the format below.
+ /// Creates a UserAccountManager object. During instantiation, this method will verify the table structure against the format below.
/// The database to connect to.
- /// A UserManager object.
- public UserManager(IDbConnection db)
+ /// A UserAccountManager object.
+ public UserAccountManager(IDbConnection db)
{
_database = db;
@@ -59,145 +59,145 @@ namespace TShockAPI.DB
}
///
- /// Adds a given username to the database
+ /// Adds the given user account to the database
///
- /// User user
- public void AddUser(User user)
+ /// The user account to be added
+ public void AddUserAccount(UserAccount account)
{
- if (!TShock.Groups.GroupExists(user.Group))
- throw new GroupNotExistsException(user.Group);
+ if (!TShock.Groups.GroupExists(account.Group))
+ throw new GroupNotExistsException(account.Group);
int ret;
try
{
- ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", user.Name,
- user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s"));
+ ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", account.Name,
+ account.Password, account.UUID, account.Group, DateTime.UtcNow.ToString("s"));
}
catch (Exception ex)
{
// Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions
if (Regex.IsMatch(ex.Message, "Username.*not unique"))
- throw new UserExistsException(user.Name);
- throw new UserManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex);
+ throw new UserAccountExistsException(account.Name);
+ throw new UserAccountManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex);
}
if (1 > ret)
- throw new UserExistsException(user.Name);
+ throw new UserAccountExistsException(account.Name);
- Hooks.AccountHooks.OnAccountCreate(user);
+ Hooks.AccountHooks.OnAccountCreate(account);
}
///
- /// Removes a given username from the database
+ /// Removes all user accounts from the database whose usernames match the given user account
///
- /// User user
- public void RemoveUser(User user)
+ /// The user account
+ public void RemoveUserAccount(UserAccount account)
{
try
{
- var tempuser = GetUser(user);
- int affected = _database.Query("DELETE FROM Users WHERE Username=@0", user.Name);
+ var tempuser = GetUserAccount(account);
+ int affected = _database.Query("DELETE FROM Users WHERE Username=@0", account.Name);
if (affected < 1)
- throw new UserNotExistException(user.Name);
+ throw new UserAccountNotExistException(account.Name);
Hooks.AccountHooks.OnAccountDelete(tempuser);
}
catch (Exception ex)
{
- throw new UserManagerException("RemoveUser SQL returned an error", ex);
+ throw new UserAccountManagerException("RemoveUser SQL returned an error", ex);
}
}
///
/// Sets the Hashed Password for a given username
///
- /// User user
- /// string password
- public void SetUserPassword(User user, string password)
+ /// The user account
+ /// The user account password to be set
+ public void SetUserAccountPassword(UserAccount account, string password)
{
try
{
- user.CreateBCryptHash(password);
+ account.CreateBCryptHash(password);
if (
- _database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", user.Password,
- user.Name) == 0)
- throw new UserNotExistException(user.Name);
+ _database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", account.Password,
+ account.Name) == 0)
+ throw new UserAccountNotExistException(account.Name);
}
catch (Exception ex)
{
- throw new UserManagerException("SetUserPassword SQL returned an error", ex);
+ throw new UserAccountManagerException("SetUserPassword SQL returned an error", ex);
}
}
///
/// Sets the UUID for a given username
///
- /// User user
- /// string uuid
- public void SetUserUUID(User user, string uuid)
+ /// The user account
+ /// The user account uuid to be set
+ public void SetUserAccountUUID(UserAccount account, string uuid)
{
try
{
if (
_database.Query("UPDATE Users SET UUID = @0 WHERE Username = @1;", uuid,
- user.Name) == 0)
- throw new UserNotExistException(user.Name);
+ account.Name) == 0)
+ throw new UserAccountNotExistException(account.Name);
}
catch (Exception ex)
{
- throw new UserManagerException("SetUserUUID SQL returned an error", ex);
+ throw new UserAccountManagerException("SetUserUUID SQL returned an error", ex);
}
}
///
/// Sets the group for a given username
///
- /// User user
- /// string group
- public void SetUserGroup(User user, string group)
+ /// The user account
+ /// The user account group to be set
+ public void SetUserGroup(UserAccount account, string group)
{
Group grp = TShock.Groups.GetGroupByName(group);
if (null == grp)
throw new GroupNotExistsException(group);
- if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, user.Name) == 0)
- throw new UserNotExistException(user.Name);
+ if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, account.Name) == 0)
+ throw new UserAccountNotExistException(account.Name);
try
{
// Update player group reference for any logged in player
- foreach (var player in TShock.Players.Where(p => p != null && p.User != null && p.User.Name == user.Name))
+ foreach (var player in TShock.Players.Where(p => p != null && p.Account != null && p.Account.Name == account.Name))
{
player.Group = grp;
}
}
catch (Exception ex)
{
- throw new UserManagerException("SetUserGroup SQL returned an error", ex);
+ throw new UserAccountManagerException("SetUserGroup SQL returned an error", ex);
}
}
- /// Updates the last accessed time for a database user to the current time.
- /// The user object to modify.
- public void UpdateLogin(User user)
+ /// Updates the last accessed time for a database user account to the current time.
+ /// The user account object to modify.
+ public void UpdateLogin(UserAccount account)
{
try
{
- if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), user.KnownIps, user.Name) == 0)
- throw new UserNotExistException(user.Name);
+ if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), account.KnownIps, account.Name) == 0)
+ throw new UserAccountNotExistException(account.Name);
}
catch (Exception ex)
{
- throw new UserManagerException("UpdateLogin SQL returned an error", ex);
+ throw new UserAccountManagerException("UpdateLogin SQL returned an error", ex);
}
}
- /// Gets the database ID of a given user object from the database.
- /// The username of the user to query for.
- /// The user's ID
- public int GetUserID(string username)
+ /// Gets the database ID of a given user account object from the database.
+ /// The username of the user account to query for.
+ /// The user account ID
+ public int GetUserAccountID(string username)
{
try
{
@@ -216,55 +216,55 @@ namespace TShockAPI.DB
return -1;
}
- /// Gets a user object by name.
+ /// Gets a user account object by name.
/// The user's name.
- /// The user object returned from the search.
- public User GetUserByName(string name)
+ /// The user account object returned from the search.
+ public UserAccount GetUserAccountByName(string name)
{
try
{
- return GetUser(new User {Name = name});
+ return GetUserAccount(new UserAccount {Name = name});
}
- catch (UserManagerException)
+ catch (UserAccountManagerException)
{
return null;
}
}
- /// Gets a user object by their user ID.
+ /// Gets a user account object by their user account ID.
/// The user's ID.
- /// The user object returned from the search.
- public User GetUserByID(int id)
+ /// The user account object returned from the search.
+ public UserAccount GetUserAccountByID(int id)
{
try
{
- return GetUser(new User {ID = id});
+ return GetUserAccount(new UserAccount {ID = id});
}
- catch (UserManagerException)
+ catch (UserAccountManagerException)
{
return null;
}
}
- /// Gets a user object by a user object.
- /// The user object to search by.
+ /// Gets a user account object by a user account object.
+ /// The user account object to search by.
/// The user object that is returned from the search.
- public User GetUser(User user)
+ public UserAccount GetUserAccount(UserAccount account)
{
bool multiple = false;
string query;
string type;
object arg;
- if (0 != user.ID)
+ if (account.ID != 0)
{
query = "SELECT * FROM Users WHERE ID=@0";
- arg = user.ID;
+ arg = account.ID;
type = "id";
}
else
{
query = "SELECT * FROM Users WHERE Username=@0";
- arg = user.Name;
+ arg = account.Name;
type = "name";
}
@@ -274,38 +274,38 @@ namespace TShockAPI.DB
{
if (result.Read())
{
- user = LoadUserFromResult(user, result);
+ account = LoadUserAccountFromResult(account, result);
// Check for multiple matches
if (!result.Read())
- return user;
+ return account;
multiple = true;
}
}
}
catch (Exception ex)
{
- throw new UserManagerException("GetUser SQL returned an error (" + ex.Message + ")", ex);
+ throw new UserAccountManagerException("GetUser SQL returned an error (" + ex.Message + ")", ex);
}
if (multiple)
- throw new UserManagerException(String.Format("Multiple users found for {0} '{1}'", type, arg));
+ throw new UserAccountManagerException(String.Format("Multiple user accounts found for {0} '{1}'", type, arg));
- throw new UserNotExistException(user.Name);
+ throw new UserAccountNotExistException(account.Name);
}
- /// Gets all users from the database.
- /// The users from the database.
- public List GetUsers()
+ /// Gets all the user accounts from the database.
+ /// The user accounts from the database.
+ public List GetUserAccounts()
{
try
{
- List users = new List();
+ List accounts = new List();
using (var reader = _database.QueryReader("SELECT * FROM Users"))
{
while (reader.Read())
{
- users.Add(LoadUserFromResult(new User(), reader));
+ accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
}
- return users;
+ return accounts;
}
}
catch (Exception ex)
@@ -316,26 +316,26 @@ namespace TShockAPI.DB
}
///
- /// Gets all users from the database with a username that starts with or contains
+ /// Gets all user accounts from the database with a username that starts with or contains
///
/// Rough username search. "n" will match "n", "na", "nam", "name", etc
/// If is not the first part of the username. If true then "name" would match "name", "username", "wordsnamewords", etc
/// Matching users or null if exception is thrown
- public List GetUsersByName(string username, bool notAtStart = false)
+ public List GetUserAccountsByName(string username, bool notAtStart = false)
{
try
{
- List users = new List();
+ List accounts = new List();
string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username);
using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0",
search))
{
while (reader.Read())
{
- users.Add(LoadUserFromResult(new User(), reader));
+ accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
}
}
- return users;
+ return accounts;
}
catch (Exception ex)
{
@@ -344,61 +344,61 @@ namespace TShockAPI.DB
return null;
}
- /// Fills out the fields of a User object with the results from a QueryResult object.
- /// The user to add data to.
+ /// Fills out the fields of a User account object with the results from a QueryResult object.
+ /// The user account to add data to.
/// The QueryResult object to add data from.
/// The 'filled out' user object.
- private User LoadUserFromResult(User user, QueryResult result)
+ private UserAccount LoadUserAccountFromResult(UserAccount account, QueryResult result)
{
- user.ID = result.Get("ID");
- user.Group = result.Get("Usergroup");
- user.Password = result.Get("Password");
- user.UUID = result.Get("UUID");
- user.Name = result.Get("Username");
- user.Registered = result.Get("Registered");
- user.LastAccessed = result.Get("LastAccessed");
- user.KnownIps = result.Get("KnownIps");
- return user;
+ account.ID = result.Get("ID");
+ account.Group = result.Get("Usergroup");
+ account.Password = result.Get("Password");
+ account.UUID = result.Get("UUID");
+ account.Name = result.Get("Username");
+ account.Registered = result.Get("Registered");
+ account.LastAccessed = result.Get("LastAccessed");
+ account.KnownIps = result.Get("KnownIps");
+ return account;
}
}
- /// A database user.
- public class User : IEquatable
+ /// A database user account.
+ public class UserAccount : IEquatable
{
- /// The database ID of the user.
+ /// The database ID of the user account.
public int ID { get; set; }
/// The user's name.
public string Name { get; set; }
- /// The hashed password for the user.
+ /// The hashed password for the user account.
public string Password { get; internal set; }
/// The user's saved Univerally Unique Identifier token.
public string UUID { get; set; }
-
- /// The group object that the user is a part of.
+
+ /// The group object that the user account is a part of.
public string Group { get; set; }
- /// The unix epoch corresponding to the registration date of the user.
+ /// The unix epoch corresponding to the registration date of the user account.
public string Registered { get; set; }
- /// The unix epoch corresponding to the last access date of the user.
+ /// The unix epoch corresponding to the last access date of the user account.
public string LastAccessed { get; set; }
- /// A JSON serialized list of known IP addresses for a user.
+ /// A JSON serialized list of known IP addresses for a user account.
public string KnownIps { get; set; }
- /// Constructor for the user object, assuming you define everything yourself.
+ /// Constructor for the user account object, assuming you define everything yourself.
/// The user's name.
/// The user's password hash.
/// The user's UUID.
/// The user's group name.
/// The unix epoch for the registration date.
/// The unix epoch for the last access date.
- /// The known IPs for the user, serialized as a JSON object
- /// A completed user object.
- public User(string name, string pass, string uuid, string group, string registered, string last, string known)
+ /// The known IPs for the user account, serialized as a JSON object
+ /// A completed user account object.
+ public UserAccount(string name, string pass, string uuid, string group, string registered, string last, string known)
{
Name = name;
Password = pass;
@@ -409,9 +409,9 @@ namespace TShockAPI.DB
KnownIps = known;
}
- /// Default constructor for a user object; holds no data.
- /// A user object.
- public User()
+ /// Default constructor for a user account object; holds no data.
+ /// A user account object.
+ public UserAccount()
{
Name = "";
Password = "";
@@ -428,7 +428,7 @@ namespace TShockAPI.DB
/// If the password is stored using BCrypt, it will be re-saved if the work factor in the config
/// is greater than the existing work factor with the new work factor.
///
- /// The password to check against the user object.
+ /// The password to check against the user account object.
/// bool true, if the password matched, or false, if it didn't.
public bool VerifyPassword(string password)
{
@@ -459,7 +459,7 @@ namespace TShockAPI.DB
}
/// Upgrades a password to BCrypt, from an insecure hashing algorithm.
- /// The raw user password (unhashed) to upgrade
+ /// The raw user account password (unhashed) to upgrade
protected void UpgradePasswordToBCrypt(string password)
{
// Save the old password, in the event that we have to revert changes.
@@ -467,9 +467,9 @@ namespace TShockAPI.DB
try
{
- TShock.Users.SetUserPassword(this, password);
+ TShock.UserAccounts.SetUserAccountPassword(this, password);
}
- catch (UserManagerException e)
+ catch (UserAccountManagerException e)
{
TShock.Log.ConsoleError(e.ToString());
Password = oldpassword; // Revert changes
@@ -477,7 +477,7 @@ namespace TShockAPI.DB
}
/// Upgrades a password to the highest work factor available in the config.
- /// The raw user password (unhashed) to upgrade
+ /// The raw user account password (unhashed) to upgrade
protected void UpgradePasswordWorkFactor(string password)
{
// If the destination work factor is not greater, we won't upgrade it or re-hash it
@@ -496,16 +496,16 @@ namespace TShockAPI.DB
{
try
{
- TShock.Users.SetUserPassword(this, password);
+ TShock.UserAccounts.SetUserAccountPassword(this, password);
}
- catch (UserManagerException e)
+ catch (UserAccountManagerException e)
{
TShock.Log.ConsoleError(e.ToString());
}
}
}
- /// Creates a BCrypt hash for a user and stores it in this object.
+ /// Creates a BCrypt hash for a user account and stores it in this object.
/// The plain text password to hash
public void CreateBCryptHash(string password)
{
@@ -524,7 +524,7 @@ namespace TShockAPI.DB
}
}
- /// Creates a BCrypt hash for a user and stores it in this object.
+ /// Creates a BCrypt hash for a user account and stores it in this object.
/// The plain text password to hash
/// The work factor to use in generating the password hash
public void CreateBCryptHash(string password, int workFactor)
@@ -583,29 +583,29 @@ namespace TShockAPI.DB
#region IEquatable
- /// Indicates whether the current is equal to another .
- /// true if the is equal to the parameter; otherwise, false.
- /// An to compare with this .
- public bool Equals(User other)
+ /// Indicates whether the current is equal to another .
+ /// true if the is equal to the parameter; otherwise, false.
+ /// An to compare with this .
+ public bool Equals(UserAccount other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return ID == other.ID && string.Equals(Name, other.Name);
}
- /// Indicates whether the current is equal to another object.
- /// true if the is equal to the parameter; otherwise, false.
- /// An to compare with this .
+ /// Indicates whether the current is equal to another object.
+ /// true if the is equal to the parameter; otherwise, false.
+ /// An to compare with this .
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
- return Equals((User)obj);
+ return Equals((UserAccount)obj);
}
/// Serves as the hash function.
- /// A hash code for the current .
+ /// A hash code for the current .
public override int GetHashCode()
{
unchecked
@@ -615,86 +615,87 @@ namespace TShockAPI.DB
}
///
- /// Compares equality of two objects.
+ /// Compares equality of two objects.
///
/// Left hand of the comparison.
/// Right hand of the comparison.
- /// true if the objects are equal; otherwise, false.
- public static bool operator ==(User left, User right)
+ /// true if the objects are equal; otherwise, false.
+ public static bool operator ==(UserAccount left, UserAccount right)
{
return Equals(left, right);
}
///
- /// Compares equality of two objects.
+ /// Compares equality of two objects.
///
/// Left hand of the comparison.
/// Right hand of the comparison.
- /// true if the objects aren't equal; otherwise, false.
- public static bool operator !=(User left, User right)
+ /// true if the objects aren't equal; otherwise, false.
+ public static bool operator !=(UserAccount left, UserAccount right)
{
return !Equals(left, right);
}
#endregion
- public override string ToString()
- {
- return Name;
- }
+ ///
+ /// Converts the UserAccount to it's string representation
+ ///
+ /// Returns the UserAccount string representation
+ public override string ToString() => Name;
}
- /// UserManagerException - An exception generated by the user manager.
+ /// UserAccountManagerException - An exception generated by the user account manager.
[Serializable]
- public class UserManagerException : Exception
+ public class UserAccountManagerException : Exception
{
- /// Creates a new UserManagerException object.
+ /// Creates a new UserAccountManagerException object.
/// The message for the object.
- /// A new UserManagerException object.
- public UserManagerException(string message)
+ /// A new UserAccountManagerException object.
+ public UserAccountManagerException(string message)
: base(message)
{
}
- /// Creates a new UserManagerObject with an internal exception.
+ /// Creates a new UserAccountManager Object with an internal exception.
/// The message for the object.
/// The inner exception for the object.
- /// A new UserManagerException with a defined inner exception.
- public UserManagerException(string message, Exception inner)
+ /// A new UserAccountManagerException with a defined inner exception.
+ public UserAccountManagerException(string message, Exception inner)
: base(message, inner)
{
}
}
- /// A UserExistsException object, used when a user already exists when attempting to create a new one.
+ /// A UserExistsException object, used when a user account already exists when attempting to create a new one.
[Serializable]
- public class UserExistsException : UserManagerException
+ public class UserAccountExistsException : UserAccountManagerException
{
- /// Creates a new UserExistsException object.
- /// The name of the user that already exists.
- /// A UserExistsException object with the user's name passed in the message.
- public UserExistsException(string name)
- : base("User '" + name + "' already exists")
+ /// Creates a new UserAccountExistsException object.
+ /// The name of the user account that already exists.
+ /// A UserAccountExistsException object with the user's name passed in the message.
+ public UserAccountExistsException(string name)
+ : base("User account '" + name + "' already exists")
{
}
}
/// A UserNotExistException, used when a user does not exist and a query failed as a result of it.
[Serializable]
- public class UserNotExistException : UserManagerException
+ public class UserAccountNotExistException : UserAccountManagerException
{
- /// Creates a new UserNotExistException object, with the user's name in the message.
- /// The user's name to be pasesd in the message.
- /// A new UserNotExistException object with a message containing the user's name that does not exist.
- public UserNotExistException(string name)
- : base("User '" + name + "' does not exist")
+ /// Creates a new UserAccountNotExistException object, with the user account name in the message.
+ /// The user account name to be pasesd in the message.
+ /// A new UserAccountNotExistException object with a message containing the user account name that does not exist.
+ public UserAccountNotExistException(string name)
+ : base("User account '" + name + "' does not exist")
{
}
}
/// A GroupNotExistsException, used when a group does not exist.
[Serializable]
- public class GroupNotExistsException : UserManagerException
+ public class GroupNotExistsException : UserAccountManagerException
{
/// Creates a new GroupNotExistsException object with the group's name in the message.
/// The group name.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 2fa9cbd0..17d27519 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1518,7 +1518,7 @@ namespace TShockAPI
private static bool HandleConnecting(GetDataHandlerArgs args)
{
- var user = TShock.Users.GetUserByName(args.Player.Name);
+ var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
args.Player.DataWhenJoined = new PlayerData(args.Player);
args.Player.DataWhenJoined.CopyCharacter(args.Player);
@@ -1536,7 +1536,7 @@ namespace TShockAPI
args.Player.Group = group;
args.Player.tempGroup = null;
- args.Player.User = user;
+ args.Player.Account = user;
args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none";
@@ -1592,7 +1592,7 @@ namespace TShockAPI
if (Hooks.PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, password))
return true;
- var user = TShock.Users.GetUserByName(args.Player.Name);
+ var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
if (user != null && !TShock.Config.DisableLoginBeforeJoin)
{
if (user.VerifyPassword(password))
@@ -1608,7 +1608,7 @@ namespace TShockAPI
args.Player.Group = group;
args.Player.tempGroup = null;
- args.Player.User = user;
+ args.Player.Account = user;
args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none";
@@ -1632,7 +1632,7 @@ namespace TShockAPI
args.Player.SendMessage("Authenticated as " + args.Player.Name + " successfully.", Color.LimeGreen);
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + ".");
- TShock.Users.SetUserUUID(user, args.Player.UUID);
+ TShock.UserAccounts.SetUserAccountUUID(user, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
return true;
}
@@ -2963,9 +2963,9 @@ namespace TShockAPI
if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn)
{
- if (TShock.CharacterDB.RemovePlayer(args.Player.User.ID))
+ if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID))
{
- TShock.CharacterDB.SeedInitialData(args.Player.User);
+ TShock.CharacterDB.SeedInitialData(args.Player.Account);
}
}
@@ -3029,9 +3029,9 @@ namespace TShockAPI
if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn)
{
- if (TShock.CharacterDB.RemovePlayer(args.Player.User.ID))
+ if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID))
{
- TShock.CharacterDB.SeedInitialData(args.Player.User);
+ TShock.CharacterDB.SeedInitialData(args.Player.Account);
}
}
diff --git a/TShockAPI/Hooks/AccountHooks.cs b/TShockAPI/Hooks/AccountHooks.cs
index 1a7e1cc8..86aebbc6 100644
--- a/TShockAPI/Hooks/AccountHooks.cs
+++ b/TShockAPI/Hooks/AccountHooks.cs
@@ -21,9 +21,9 @@ namespace TShockAPI.Hooks
{
public class AccountDeleteEventArgs
{
- public User User { get; private set; }
+ public UserAccount User { get; private set; }
- public AccountDeleteEventArgs(User user)
+ public AccountDeleteEventArgs(UserAccount user)
{
this.User = user;
}
@@ -31,9 +31,9 @@ namespace TShockAPI.Hooks
public class AccountCreateEventArgs
{
- public User User { get; private set; }
+ public UserAccount User { get; private set; }
- public AccountCreateEventArgs(User user)
+ public AccountCreateEventArgs(UserAccount user)
{
this.User = user;
}
@@ -44,7 +44,7 @@ namespace TShockAPI.Hooks
public delegate void AccountCreateD(AccountCreateEventArgs e);
public static event AccountCreateD AccountCreate;
- public static void OnAccountCreate(User u)
+ public static void OnAccountCreate(UserAccount u)
{
if (AccountCreate == null)
return;
@@ -55,7 +55,7 @@ namespace TShockAPI.Hooks
public delegate void AccountDeleteD(AccountDeleteEventArgs e);
public static event AccountDeleteD AccountDelete;
- public static void OnAccountDelete(User u)
+ public static void OnAccountDelete(UserAccount u)
{
if (AccountDelete == null)
return;
diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs
index 9c2c818a..f22462b2 100644
--- a/TShockAPI/Rest/RestManager.cs
+++ b/TShockAPI/Rest/RestManager.cs
@@ -482,7 +482,7 @@ namespace TShockAPI
[Token]
private object UserActiveListV2(RestRequestArgs args)
{
- return new RestObject() { { "activeusers", string.Join("\t", TShock.Players.Where(p => null != p && null != p.User && p.Active).Select(p => p.User.Name)) } };
+ return new RestObject() { { "activeusers", string.Join("\t", TShock.Players.Where(p => null != p && null != p.Account && p.Active).Select(p => p.Account.Name)) } };
}
[Description("Lists all user accounts in the TShock database.")]
@@ -491,7 +491,7 @@ namespace TShockAPI
[Token]
private object UserListV2(RestRequestArgs args)
{
- return new RestObject() { { "users", TShock.Users.GetUsers().Select(p => new Dictionary(){
+ return new RestObject() { { "users", TShock.UserAccounts.GetUserAccounts().Select(p => new Dictionary(){
{"name", p.Name},
{"id", p.ID},
{"group", p.Group},
@@ -520,11 +520,11 @@ namespace TShockAPI
return RestMissingParam("password");
// NOTE: ip can be blank
- User user = new User(username, "", "", group, "", "", "");
+ UserAccount user = new UserAccount(username, "", "", group, "", "", "");
try
{
user.CreateBCryptHash(password);
- TShock.Users.AddUser(user);
+ TShock.UserAccounts.AddUserAccount(user);
}
catch (Exception e)
{
@@ -553,13 +553,13 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password))
return RestMissingParam("group", "password");
- User user = (User)ret;
+ UserAccount user = (UserAccount)ret;
var response = new RestObject();
if (!string.IsNullOrWhiteSpace(password))
{
try
{
- TShock.Users.SetUserPassword(user, password);
+ TShock.UserAccounts.SetUserAccountPassword(user, password);
response.Add("password-response", "Password updated successfully");
}
catch (Exception e)
@@ -572,7 +572,7 @@ namespace TShockAPI
{
try
{
- TShock.Users.SetUserGroup(user, group);
+ TShock.UserAccounts.SetUserGroup(user, group);
response.Add("group-response", "Group updated successfully");
}
catch (Exception e)
@@ -598,7 +598,7 @@ namespace TShockAPI
try
{
- TShock.Users.RemoveUser((User)ret);
+ TShock.UserAccounts.RemoveUserAccount((UserAccount)ret);
}
catch (Exception e)
{
@@ -620,7 +620,7 @@ namespace TShockAPI
if (ret is RestObject)
return ret;
- User user = (User)ret;
+ UserAccount user = (UserAccount)ret;
return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } };
}
@@ -938,10 +938,10 @@ namespace TShockAPI
return new RestObject()
{
{"nickname", player.Name},
- {"username", player.User?.Name},
+ {"username", player.Account?.Name},
{"ip", player.IP},
{"group", player.Group.Name},
- {"registered", player.User?.Registered},
+ {"registered", player.Account?.Registered},
{"muted", player.mute },
{"position", player.TileX + "," + player.TileY},
{"inventory", string.Join(", ", inventory.Select(p => (p.Name + ":" + p.stack)))},
@@ -979,10 +979,10 @@ namespace TShockAPI
return new RestObject
{
{"nickname", player.Name},
- {"username", player.User?.Name},
+ {"username", player.Account?.Name},
{"ip", player.IP},
{"group", player.Group.Name},
- {"registered", player.User?.Registered},
+ {"registered", player.Account?.Registered},
{"muted", player.mute },
{"position", player.TileX + "," + player.TileY},
{"items", items},
@@ -1283,7 +1283,7 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(name))
return RestMissingParam("user");
- User user;
+ UserAccount user;
string type = parameters["type"];
try
{
@@ -1292,10 +1292,10 @@ namespace TShockAPI
case null:
case "name":
type = "name";
- user = TShock.Users.GetUserByName(name);
+ user = TShock.UserAccounts.GetUserAccountByName(name);
break;
case "id":
- user = TShock.Users.GetUserByID(Convert.ToInt32(name));
+ user = TShock.UserAccounts.GetUserAccountByID(Convert.ToInt32(name));
break;
default:
return RestError("Invalid Type: '" + type + "'");
@@ -1359,7 +1359,7 @@ namespace TShockAPI
var player = new Dictionary
{
{"nickname", tsPlayer.Name},
- {"username", tsPlayer.User == null ? "" : tsPlayer.User.Name},
+ {"username", tsPlayer.Account == null ? "" : tsPlayer.Account.Name},
{"group", tsPlayer.Group.Name},
{"active", tsPlayer.Active},
{"state", tsPlayer.State},
diff --git a/TShockAPI/Rest/SecureRest.cs b/TShockAPI/Rest/SecureRest.cs
index ee76fd67..4000efab 100644
--- a/TShockAPI/Rest/SecureRest.cs
+++ b/TShockAPI/Rest/SecureRest.cs
@@ -131,7 +131,7 @@ namespace Rests
tokenBucket.Add(context.RemoteEndPoint.Address.ToString(), 1); // First time request, set to one and process request
}
- User userAccount = TShock.Users.GetUserByName(username);
+ UserAccount userAccount = TShock.UserAccounts.GetUserAccountByName(username);
if (userAccount == null)
{
AddTokenToBucket(context.RemoteEndPoint.Address.ToString());
@@ -216,4 +216,4 @@ namespace Rests
return result;
}
}
-}
\ No newline at end of file
+}
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index e2eedd1a..c43669f7 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -218,10 +218,10 @@ namespace TShockAPI
public Vector2 LastNetPosition = Vector2.Zero;
///
- /// User object associated with the player.
+ /// UserAccount object associated with the player.
/// Set when the player logs in.
///
- public User User { get; set; }
+ public UserAccount Account { get; set; }
///
/// Whether the player performed a valid login attempt (i.e. entered valid user name and password) but is still blocked
@@ -448,7 +448,7 @@ namespace TShockAPI
{
if (HasPermission(Permissions.bypassssc))
{
- TShock.Log.ConsoleInfo("Skipping SSC Backup for " + User.Name); // Debug Code
+ TShock.Log.ConsoleInfo("Skipping SSC Backup for " + Account.Name); // Debug Code
return true;
}
PlayerData.CopyCharacter(this);
@@ -656,7 +656,7 @@ namespace TShockAPI
{
tempGroupTimer.Stop();
}
- User = null;
+ Account = null;
IsLoggedIn = false;
}
diff --git a/TShockAPI/TSServerPlayer.cs b/TShockAPI/TSServerPlayer.cs
index b811e9a8..b9906c6a 100644
--- a/TShockAPI/TSServerPlayer.cs
+++ b/TShockAPI/TSServerPlayer.cs
@@ -36,7 +36,7 @@ namespace TShockAPI
: base("Server")
{
Group = new SuperAdminGroup();
- User = new User { Name = AccountName };
+ Account = new UserAccount { Name = AccountName };
}
public override void SendErrorMessage(string msg)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index e4fdf0ff..df3f58c8 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -94,7 +94,7 @@ namespace TShockAPI
/// Groups - Static reference to the group manager for accessing the group system.
public static GroupManager Groups;
/// Users - Static reference to the user manager for accessing the user database system.
- public static UserManager Users;
+ public static UserAccountManager UserAccounts;
/// Itembans - Static reference to the item ban system.
public static ItemManager Itembans;
/// ProjectileBans - Static reference to the projectile ban system.
@@ -312,7 +312,7 @@ namespace TShockAPI
Bans = new BanManager(DB);
Warps = new WarpManager(DB);
Regions = new RegionManager(DB);
- Users = new UserManager(DB);
+ UserAccounts = new UserAccountManager(DB);
Groups = new GroupManager(DB);
Itembans = new ItemManager(DB);
ProjectileBans = new ProjectileManagager(DB);
@@ -391,7 +391,7 @@ namespace TShockAPI
{
foreach (TSPlayer player in TShock.Players)
{
- player.User = null;
+ player.Account = null;
}
}
@@ -447,9 +447,9 @@ namespace TShockAPI
private void OnPlayerLogin(PlayerPostLoginEventArgs args)
{
List KnownIps = new List();
- if (!string.IsNullOrWhiteSpace(args.Player.User.KnownIps))
+ if (!string.IsNullOrWhiteSpace(args.Player.Account.KnownIps))
{
- KnownIps = JsonConvert.DeserializeObject>(args.Player.User.KnownIps);
+ KnownIps = JsonConvert.DeserializeObject>(args.Player.Account.KnownIps);
}
if (KnownIps.Count == 0)
@@ -470,16 +470,16 @@ namespace TShockAPI
}
}
- args.Player.User.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented);
- Users.UpdateLogin(args.Player.User);
+ args.Player.Account.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented);
+ UserAccounts.UpdateLogin(args.Player.Account);
- Ban potentialBan = Bans.GetBanByAccountName(args.Player.User.Name);
+ Ban potentialBan = Bans.GetBanByAccountName(args.Player.Account.Name);
if (potentialBan != null)
{
// A user just signed in successfully despite being banned by account name.
// We should fix the ban database so that all of their ban info is up to date.
- Bans.AddBan2(args.Player.IP, args.Player.Name, args.Player.UUID, args.Player.User.Name,
+ Bans.AddBan2(args.Player.IP, args.Player.Name, args.Player.UUID, args.Player.Account.Name,
potentialBan.Reason, false, potentialBan.BanningUser, potentialBan.Expiration);
// And then get rid of them.
@@ -507,7 +507,7 @@ namespace TShockAPI
/// args - The AccountCreateEventArgs object.
private void OnAccountCreate(Hooks.AccountCreateEventArgs args)
{
- CharacterDB.SeedInitialData(Users.GetUser(args.User));
+ CharacterDB.SeedInitialData(UserAccounts.GetUserAccount(args.User));
}
/// OnPlayerPreLogin - Internal hook fired when on player pre login.
@@ -535,7 +535,7 @@ namespace TShockAPI
}
if (player.IsLoggedIn)
{
- var ips = JsonConvert.DeserializeObject>(player.User.KnownIps);
+ var ips = JsonConvert.DeserializeObject>(player.Account.KnownIps);
if (ips.Contains(ip))
{
Netplay.Clients[player.Index].PendingTermination = true;
@@ -857,7 +857,7 @@ namespace TShockAPI
}
// Disable the auth system if "auth.lck" is present or a superadmin exists
- if (File.Exists(Path.Combine(SavePath, "auth.lck")) || Users.GetUsers().Exists(u => u.Group == new SuperAdminGroup().Name))
+ if (File.Exists(Path.Combine(SavePath, "auth.lck")) || UserAccounts.GetUserAccounts().Exists(u => u.Group == new SuperAdminGroup().Name))
{
AuthToken = 0;
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 9626d556..050515a6 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -90,7 +90,7 @@ namespace TShockAPI
{
if (includeIDs)
{
- players.Add(String.Format("{0} (IX: {1}{2})", ply.Name, ply.Index, ply.User != null ? ", ID: " + ply.User.ID : ""));
+ players.Add(String.Format("{0} (IX: {1}{2})", ply.Name, ply.Index, ply.Account != null ? ", ID: " + ply.Account.ID : ""));
}
else
{
From 5c24ba6f8df1477352cc2579f0834b9d4a195076 Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Fri, 8 Dec 2017 01:43:13 +0100
Subject: [PATCH 094/430] missed UserAccount declarations
---
TShockAPI/Rest/RestManager.cs | 26 +++++++++++++-------------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs
index f22462b2..01341d46 100644
--- a/TShockAPI/Rest/RestManager.cs
+++ b/TShockAPI/Rest/RestManager.cs
@@ -520,11 +520,11 @@ namespace TShockAPI
return RestMissingParam("password");
// NOTE: ip can be blank
- UserAccount user = new UserAccount(username, "", "", group, "", "", "");
+ UserAccount account = new UserAccount(username, "", "", group, "", "", "");
try
{
- user.CreateBCryptHash(password);
- TShock.UserAccounts.AddUserAccount(user);
+ account.CreateBCryptHash(password);
+ TShock.UserAccounts.AddUserAccount(account);
}
catch (Exception e)
{
@@ -553,13 +553,13 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password))
return RestMissingParam("group", "password");
- UserAccount user = (UserAccount)ret;
+ UserAccount account = (UserAccount)ret;
var response = new RestObject();
if (!string.IsNullOrWhiteSpace(password))
{
try
{
- TShock.UserAccounts.SetUserAccountPassword(user, password);
+ TShock.UserAccounts.SetUserAccountPassword(account, password);
response.Add("password-response", "Password updated successfully");
}
catch (Exception e)
@@ -572,7 +572,7 @@ namespace TShockAPI
{
try
{
- TShock.UserAccounts.SetUserGroup(user, group);
+ TShock.UserAccounts.SetUserGroup(account, group);
response.Add("group-response", "Group updated successfully");
}
catch (Exception e)
@@ -620,8 +620,8 @@ namespace TShockAPI
if (ret is RestObject)
return ret;
- UserAccount user = (UserAccount)ret;
- return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } };
+ UserAccount account = (UserAccount)ret;
+ return new RestObject() { { "group", account.Group }, { "id", account.ID.ToString() }, { "name", account.Name } };
}
#endregion
@@ -1283,7 +1283,7 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(name))
return RestMissingParam("user");
- UserAccount user;
+ UserAccount account;
string type = parameters["type"];
try
{
@@ -1292,10 +1292,10 @@ namespace TShockAPI
case null:
case "name":
type = "name";
- user = TShock.UserAccounts.GetUserAccountByName(name);
+ account = TShock.UserAccounts.GetUserAccountByName(name);
break;
case "id":
- user = TShock.UserAccounts.GetUserAccountByID(Convert.ToInt32(name));
+ account = TShock.UserAccounts.GetUserAccountByID(Convert.ToInt32(name));
break;
default:
return RestError("Invalid Type: '" + type + "'");
@@ -1306,10 +1306,10 @@ namespace TShockAPI
return RestError(e.Message);
}
- if (null == user)
+ if (null == account)
return RestError(String.Format("User {0} '{1}' doesn't exist", type, name));
- return user;
+ return account;
}
private object BanFind(IParameterCollection parameters)
From 07da3d5f5813731be9bbdcba04392f3fde7791d0 Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Fri, 8 Dec 2017 01:48:08 +0100
Subject: [PATCH 095/430] missed some more declarations
---
TShockAPI/DB/CharacterManager.cs | 4 ++--
TShockAPI/GetDataHandlers.cs | 30 +++++++++++++++---------------
TShockAPI/Hooks/AccountHooks.cs | 12 ++++++------
TShockAPI/TShock.cs | 4 ++--
4 files changed, 25 insertions(+), 25 deletions(-)
diff --git a/TShockAPI/DB/CharacterManager.cs b/TShockAPI/DB/CharacterManager.cs
index 132ab6ef..1a399da8 100644
--- a/TShockAPI/DB/CharacterManager.cs
+++ b/TShockAPI/DB/CharacterManager.cs
@@ -120,7 +120,7 @@ namespace TShockAPI.DB
return playerData;
}
- public bool SeedInitialData(UserAccount user)
+ public bool SeedInitialData(UserAccount account)
{
var inventory = new StringBuilder();
@@ -132,7 +132,7 @@ namespace TShockAPI.DB
try
{
database.Query("INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, spawnX, spawnY, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8);",
- user.ID,
+ account.ID,
TShock.ServerSideCharacterConfig.StartingHealth,
TShock.ServerSideCharacterConfig.StartingHealth,
TShock.ServerSideCharacterConfig.StartingMana,
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 17d27519..f3dc33e5 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1518,25 +1518,25 @@ namespace TShockAPI
private static bool HandleConnecting(GetDataHandlerArgs args)
{
- var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
+ var account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
args.Player.DataWhenJoined = new PlayerData(args.Player);
args.Player.DataWhenJoined.CopyCharacter(args.Player);
- if (user != null && !TShock.Config.DisableUUIDLogin)
+ if (account != null && !TShock.Config.DisableUUIDLogin)
{
- if (user.UUID == args.Player.UUID)
+ if (account.UUID == args.Player.UUID)
{
if (args.Player.State == 1)
args.Player.State = 2;
NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index);
- args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID);
+ args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
- var group = TShock.Utils.GetGroup(user.Group);
+ var group = TShock.Utils.GetGroup(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
- args.Player.Account = user;
+ args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none";
@@ -1557,13 +1557,13 @@ namespace TShockAPI
if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IgnoreActionsForDisabledArmor = "none";
- args.Player.SendSuccessMessage("Authenticated as " + user.Name + " successfully.");
+ args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + ".");
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
return true;
}
}
- else if (user != null && !TShock.Config.DisableLoginBeforeJoin)
+ else if (account != null && !TShock.Config.DisableLoginBeforeJoin)
{
args.Player.RequiresPassword = true;
NetMessage.SendData((int)PacketTypes.PasswordRequired, args.Player.Index);
@@ -1592,23 +1592,23 @@ namespace TShockAPI
if (Hooks.PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, password))
return true;
- var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
- if (user != null && !TShock.Config.DisableLoginBeforeJoin)
+ var account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
+ if (account != null && !TShock.Config.DisableLoginBeforeJoin)
{
- if (user.VerifyPassword(password))
+ if (account.VerifyPassword(password))
{
args.Player.RequiresPassword = false;
- args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID);
+ args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
if (args.Player.State == 1)
args.Player.State = 2;
NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index);
- var group = TShock.Utils.GetGroup(user.Group);
+ var group = TShock.Utils.GetGroup(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
- args.Player.Account = user;
+ args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none";
@@ -1632,7 +1632,7 @@ namespace TShockAPI
args.Player.SendMessage("Authenticated as " + args.Player.Name + " successfully.", Color.LimeGreen);
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + ".");
- TShock.UserAccounts.SetUserAccountUUID(user, args.Player.UUID);
+ TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
return true;
}
diff --git a/TShockAPI/Hooks/AccountHooks.cs b/TShockAPI/Hooks/AccountHooks.cs
index 86aebbc6..356a90c1 100644
--- a/TShockAPI/Hooks/AccountHooks.cs
+++ b/TShockAPI/Hooks/AccountHooks.cs
@@ -21,21 +21,21 @@ namespace TShockAPI.Hooks
{
public class AccountDeleteEventArgs
{
- public UserAccount User { get; private set; }
+ public UserAccount Account { get; private set; }
- public AccountDeleteEventArgs(UserAccount user)
+ public AccountDeleteEventArgs(UserAccount account)
{
- this.User = user;
+ this.Account = account;
}
}
public class AccountCreateEventArgs
{
- public UserAccount User { get; private set; }
+ public UserAccount Account { get; private set; }
- public AccountCreateEventArgs(UserAccount user)
+ public AccountCreateEventArgs(UserAccount account)
{
- this.User = user;
+ this.Account = account;
}
}
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index df3f58c8..ee403eab 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -500,14 +500,14 @@ namespace TShockAPI
/// args - The AccountDeleteEventArgs object.
private void OnAccountDelete(Hooks.AccountDeleteEventArgs args)
{
- CharacterDB.RemovePlayer(args.User.ID);
+ CharacterDB.RemovePlayer(args.Account.ID);
}
/// OnAccountCreate - Internal hook fired on account creation.
/// args - The AccountCreateEventArgs object.
private void OnAccountCreate(Hooks.AccountCreateEventArgs args)
{
- CharacterDB.SeedInitialData(UserAccounts.GetUserAccount(args.User));
+ CharacterDB.SeedInitialData(UserAccounts.GetUserAccount(args.Account));
}
/// OnPlayerPreLogin - Internal hook fired when on player pre login.
From 914782ab9ebb6f00b76e324b2fe00779ff625b51 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 7 Dec 2017 21:43:33 -0700
Subject: [PATCH 096/430] Create hook PlaceObject; move anti-hack to Bouncer
---
TShockAPI/Bouncer.cs | 136 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 132 +++++++++++-----------------------
2 files changed, 179 insertions(+), 89 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 5199dcb0..d11cac4d 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -27,6 +27,7 @@ using OTAPI.Tile;
using TShockAPI.Localization;
using static TShockAPI.GetDataHandlers;
using TerrariaApi.Server;
+using Terraria.ObjectData;
namespace TShockAPI
@@ -40,11 +41,138 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlaceObject.Register(OnPlaceObject);
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnPlaceObject(object sender, GetDataHandlers.PlaceObjectEventArgs args)
+ {
+ short x = args.X;
+ short y = args.Y;
+ short type = args.Type;
+ short style = args.Style;
+ byte alternate = args.Alternate;
+ bool direction = args.Direction;
+
+ if (type < 0 || type >= Main.maxTileSets)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (x < 0 || x >= Main.maxTilesX)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (y < 0 || y >= Main.maxTilesY)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ //style 52 and 53 are used by ItemID.Fake_newchest1 and ItemID.Fake_newchest2
+ //These two items cause localised lag and rendering issues
+ if (type == TileID.FakeContainers && (style == 52 || style == 53))
+ {
+ args.Player.SendTileSquare(x, y, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.TileBans.TileIsBanned(type, args.Player))
+ {
+ args.Player.SendTileSquare(x, y, 1);
+ args.Player.SendErrorMessage("You do not have permission to place this tile.");
+ args.Handled = true;
+ return;
+ }
+
+ if (!TShock.Utils.TilePlacementValid(x, y))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.Dead && TShock.Config.PreventDeadModification)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendTileSquare(x, y, 4);
+ args.Handled = true;
+ return;
+ }
+
+ // This is neccessary to check in order to prevent special tiles such as
+ // queen bee larva, paintings etc that use this packet from being placed
+ // without selecting the right item.
+ if (type != args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].createTile)
+ {
+ args.Player.SendTileSquare(x, y, 4);
+ args.Handled = true;
+ return;
+ }
+
+ TileObjectData tileData = TileObjectData.GetTileData(type, style, 0);
+ if (tileData == null)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ x -= tileData.Origin.X;
+ y -= tileData.Origin.Y;
+
+ for (int i = x; i < x + tileData.Width; i++)
+ {
+ for (int j = y; j < y + tileData.Height; j++)
+ {
+ if (TShock.CheckTilePermission(args.Player, i, j, type, EditAction.PlaceTile))
+ {
+ args.Player.SendTileSquare(i, j, 4);
+ args.Handled = true;
+ return;
+ }
+ }
+ }
+
+ // Ignore rope placement range
+ if ((type != TileID.Rope
+ || type != TileID.SilkRope
+ || type != TileID.VineRope
+ || type != TileID.WebRope)
+ && TShock.CheckRangePermission(args.Player, x, y))
+ {
+ args.Player.SendTileSquare(x, y, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.TilePlaceThreshold >= TShock.Config.TilePlaceThreshold)
+ {
+ args.Player.Disable("Reached TilePlace threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(x, y, 4);
+ args.Handled = true;
+ return;
+ }
+
+ if (!args.Player.HasPermission(Permissions.ignoreplacetiledetection))
+ {
+ args.Player.TilePlaceThreshold++;
+ var coords = new Vector2(x, y);
+ lock (args.Player.TilesCreated)
+ if (!args.Player.TilesCreated.ContainsKey(coords))
+ args.Player.TilesCreated.Add(coords, Main.tile[x, y]);
+ }
+ }
+
internal void OnTileEdit(object sender, GetDataHandlers.TileEditEventArgs args)
{
EditAction action = args.Action;
@@ -64,14 +192,22 @@ namespace TShockAPI
}
if (!TShock.Utils.TilePlacementValid(tileX, tileY))
+ {
args.Handled = true;
return;
+ }
+
if (action == EditAction.KillTile && Main.tile[tileX, tileY].type == TileID.MagicalIceBlock)
+ {
args.Handled = false;
return;
+ }
+
if (args.Player.Dead && TShock.Config.PreventDeadModification)
+ {
args.Handled = true;
return;
+ }
if (args.Player.AwaitingName)
{
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 7fbfd560..1997c554 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -613,9 +613,51 @@ namespace TShockAPI
TileX = tilex,
TileY = tiley,
};
+
SendTileSquare.Invoke(null, args);
return args.Handled;
}
+
+ public class PlaceObjectEventArgs : HandledEventArgs
+ {
+ public TSPlayer Player { get; set; }
+
+ public short X { get; set ; }
+
+ public short Y { get; set; }
+
+ public short Type { get; set; }
+
+ public short Style { get; set; }
+
+ public byte Alternate { get; set; }
+
+ public bool Direction { get; set; }
+ }
+
+ public static HandlerList PlaceObject;
+
+ private static bool OnPlaceObject(TSPlayer player, short x, short y, short type, short style, byte alternate, bool direction)
+ {
+ if (PlaceObject == null)
+ return false;
+
+ var args = new PlaceObjectEventArgs
+ {
+ Player = player,
+ X = x,
+ Y = y,
+ Type = type,
+ Style = style,
+ Alternate = alternate,
+ Direction = direction
+ };
+
+ PlaceObject.Invoke(null, args);
+ return args.Handled;
+ }
+
+
///
/// For use in a NewProjectile event
///
@@ -1826,7 +1868,6 @@ namespace TShockAPI
return false;
}
-
///
/// Handle PlaceObject event
///
@@ -1839,96 +1880,9 @@ namespace TShockAPI
byte alternate = args.Data.ReadInt8();
bool direction = args.Data.ReadBoolean();
- if (type < 0 || type >= Main.maxTileSets)
+ if (OnPlaceObject(args.Player, x, y, type, style, alternate, direction))
return true;
- if (x < 0 || x >= Main.maxTilesX)
- return true;
-
- if (y < 0 || y >= Main.maxTilesY)
- return true;
-
- //style 52 and 53 are used by ItemID.Fake_newchest1 and ItemID.Fake_newchest2
- //These two items cause localised lag and rendering issues
- if (type == TileID.FakeContainers && (style == 52 || style == 53))
- {
- args.Player.SendTileSquare(x, y, 4);
- return true;
- }
-
- if (TShock.TileBans.TileIsBanned(type, args.Player))
- {
- args.Player.SendTileSquare(x, y, 1);
- args.Player.SendErrorMessage("You do not have permission to place this tile.");
- return true;
- }
-
- if (!TShock.Utils.TilePlacementValid(x, y))
- return true;
- if (args.Player.Dead && TShock.Config.PreventDeadModification)
- return true;
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendTileSquare(x, y, 4);
- return true;
- }
-
- // This is neccessary to check in order to prevent special tiles such as
- // queen bee larva, paintings etc that use this packet from being placed
- // without selecting the right item.
- if (type != args.TPlayer.inventory[args.TPlayer.selectedItem].createTile)
- {
- args.Player.SendTileSquare(x, y, 4);
- return true;
- }
-
- TileObjectData tileData = TileObjectData.GetTileData(type, style, 0);
- if (tileData == null)
- return true;
-
- x -= tileData.Origin.X;
- y -= tileData.Origin.Y;
-
- for (int i = x; i < x + tileData.Width; i++)
- {
- for (int j = y; j < y + tileData.Height; j++)
- {
- if (TShock.CheckTilePermission(args.Player, i, j, type, EditAction.PlaceTile))
- {
- args.Player.SendTileSquare(i, j, 4);
- return true;
- }
- }
- }
-
- // Ignore rope placement range
- if ((type != TileID.Rope
- || type != TileID.SilkRope
- || type != TileID.VineRope
- || type != TileID.WebRope)
- && TShock.CheckRangePermission(args.Player, x, y))
- {
- args.Player.SendTileSquare(x, y, 4);
- return true;
- }
-
- if (args.Player.TilePlaceThreshold >= TShock.Config.TilePlaceThreshold)
- {
- args.Player.Disable("Reached TilePlace threshold.", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(x, y, 4);
- return true;
- }
-
- if (!args.Player.HasPermission(Permissions.ignoreplacetiledetection))
- {
- args.Player.TilePlaceThreshold++;
- var coords = new Vector2(x, y);
- lock (args.Player.TilesCreated)
- if (!args.Player.TilesCreated.ContainsKey(coords))
- args.Player.TilesCreated.Add(coords, Main.tile[x, y]);
- }
-
return false;
}
From b5a40a4472e9a3d4e33d527559f6fb8a74a7cc77 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 7 Dec 2017 21:46:45 -0700
Subject: [PATCH 097/430] Comment OnPlaceObject related hook stuff
---
TShockAPI/GetDataHandlers.cs | 20 +++++++++++++++++++-
1 file changed, 19 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 1997c554..99c3e8be 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -613,30 +613,48 @@ namespace TShockAPI
TileX = tilex,
TileY = tiley,
};
-
+
SendTileSquare.Invoke(null, args);
return args.Handled;
}
+ /// The arguments to the PlaceObject hook.
public class PlaceObjectEventArgs : HandledEventArgs
{
+ /// The calling Player.
public TSPlayer Player { get; set; }
+ /// The X location where the object was placed.
public short X { get; set ; }
+ /// The Y location where the object was placed.
public short Y { get; set; }
+ /// The type of object that was placed.
public short Type { get; set; }
+ /// The style of the object was placed.
public short Style { get; set; }
+ /// Alternate variation of the object placed.
public byte Alternate { get; set; }
+ /// The direction the object was placed.
public bool Direction { get; set; }
}
+ /// Fired when an object is placed in the world.
public static HandlerList PlaceObject;
+ /// Fires the PlaceObject hook. To be called when an object is placed in the world.
+ /// The originating player.
+ /// The x position where the object is placed.
+ /// The y position where the object is placed.
+ /// The type of object.
+ /// The object's style data.
+ /// The object's alternate data.
+ /// The direction of the object.
+ /// bool
private static bool OnPlaceObject(TSPlayer player, short x, short y, short type, short style, byte alternate, bool direction)
{
if (PlaceObject == null)
From eda2870bb10713db2f6182d13a6769d6c813d8c1 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 8 Dec 2017 07:50:40 -0700
Subject: [PATCH 098/430] chore: Update Probot config to support @hakusaro's
update docs
---
.github/config.yml | 10 ++++++++++
1 file changed, 10 insertions(+)
create mode 100644 .github/config.yml
diff --git a/.github/config.yml b/.github/config.yml
new file mode 100644
index 00000000..c39fdab9
--- /dev/null
+++ b/.github/config.yml
@@ -0,0 +1,10 @@
+updateDocsComment: >
+ Thanks for the pull request! TShock's maintainers would like you to go ahead and give yourself credit by updating the `CHANGELOG.md` file before this gets merged. This helps us document changes to TShock, as well as give you credit for your work. You deserve it! :sparkles:
+
+updateDocsWhiteList:
+ - bug
+ - chore
+
+updateDocsTargetFiles:
+ - README
+ - CHANGELOG.md
\ No newline at end of file
From c4129cf6450719120480e2ae4f43724d27f8185c Mon Sep 17 00:00:00 2001
From: Chris
Date: Sat, 9 Dec 2017 15:19:34 +1030
Subject: [PATCH 099/430] Updates the commandline parser to not be broken. It
should now correctly parse a commandline such as `["", "-flag", "-flag",
"arg" ... "etc" ]`
---
TShockAPI/CLI/CommandLineParser.cs | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/CLI/CommandLineParser.cs b/TShockAPI/CLI/CommandLineParser.cs
index 7106abbe..d84a7732 100644
--- a/TShockAPI/CLI/CommandLineParser.cs
+++ b/TShockAPI/CLI/CommandLineParser.cs
@@ -165,10 +165,16 @@ namespace TShockAPI.CLI
{
_source = source;
- for (int i = 0; i < (source.Length - 1 == 0 ? 1 : source.Length - 1); i++)
+ for (int i = 0; i < (source.Length - 1 == 0 ? 1 : source.Length); i++)
{
string flag = source[i].ToLowerInvariant();
string argument = null;
+
+ if (string.IsNullOrWhiteSpace(flag))
+ {
+ continue;
+ }
+
if (i + 1 < source.Length)
{
argument = source[i + 1];
From c1e72bbc251ebdd8ce20b1b1a8482348a4d2f641 Mon Sep 17 00:00:00 2001
From: Chris
Date: Sat, 9 Dec 2017 15:30:57 +1030
Subject: [PATCH 100/430] Changelog update
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14bce826..08b19051 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed /savessc not bothering to save ssc data for people who bypass ssc. (@hakusaro)
* Default permission sets for new databases are more modern. (@hakusaro)
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
+* Fixed a bug in the CommandLineParser which caused some command lines to fail (@QuicM)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From c891a81f67cc85b3cba43526399b942742b92475 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:19:05 -0700
Subject: [PATCH 101/430] Move NewProjectile into Bouncer
---
TShockAPI/Bouncer.cs | 107 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 95 ++-----------------------------
2 files changed, 112 insertions(+), 90 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index d11cac4d..3e16c10a 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -41,12 +41,119 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.NewProjectile.Register(OnNewProjectile);
GetDataHandlers.PlaceObject.Register(OnPlaceObject);
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnNewProjectile(object sender, GetDataHandlers.NewProjectileEventArgs args)
+ {
+ short ident = args.Identity;
+ Vector2 pos = args.Position;
+ Vector2 vel = args.Velocity;
+ float knockback = args.Knockback;
+ short dmg = args.Damage;
+ byte owner = args.Owner;
+ short type = args.Type;
+ int index = args.Index;
+
+ if (index > Main.maxProjectiles || index < 0)
+ {
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.ProjectileBans.ProjectileIsBanned(type, args.Player))
+ {
+ args.Player.Disable("Player does not have permission to create that projectile.", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendErrorMessage("You do not have permission to create that projectile.");
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ if (dmg > TShock.Config.MaxProjDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
+ {
+ args.Player.Disable(String.Format("Projectile damage is higher than {0}.", TShock.Config.MaxProjDamage), DisableFlags.WriteToLogAndConsole);
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ bool hasPermission = !TShock.CheckProjectilePermission(args.Player, index, type);
+ if (!TShock.Config.IgnoreProjUpdate && !hasPermission && !args.Player.HasPermission(Permissions.ignoreprojectiledetection))
+ {
+ if (type == ProjectileID.BlowupSmokeMoonlord
+ || type == ProjectileID.PhantasmalEye
+ || type == ProjectileID.CultistBossIceMist
+ || (type >= ProjectileID.MoonlordBullet && type <= ProjectileID.MoonlordTurretLaser)
+ || type == ProjectileID.DeathLaser || type == ProjectileID.Landmine
+ || type == ProjectileID.BulletDeadeye || type == ProjectileID.BoulderStaffOfEarth
+ || (type > ProjectileID.ConfettiMelee && type < ProjectileID.SpiritHeal)
+ || (type >= ProjectileID.FlamingWood && type <= ProjectileID.GreekFire3)
+ || (type >= ProjectileID.PineNeedleHostile && type <= ProjectileID.Spike)
+ || (type >= ProjectileID.MartianTurretBolt && type <= ProjectileID.RayGunnerLaser)
+ || type == ProjectileID.CultistBossLightningOrb)
+ {
+ TShock.Log.Debug("Certain projectiles have been ignored for cheat detection.");
+ }
+ else
+ {
+ args.Player.Disable(String.Format("Does not have projectile permission to update projectile. ({0})", type), DisableFlags.WriteToLogAndConsole);
+ args.Player.RemoveProjectile(ident, owner);
+ }
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.ProjectileThreshold >= TShock.Config.ProjectileThreshold)
+ {
+ args.Player.Disable("Reached projectile update threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.RemoveProjectile(ident, owner);
+ args.Handled = true;
+ return;
+ }
+
+ if (!args.Player.HasPermission(Permissions.ignoreprojectiledetection))
+ {
+ if (type == ProjectileID.CrystalShard && TShock.Config.ProjIgnoreShrapnel) // Ignore crystal shards
+ {
+ TShock.Log.Debug("Ignoring shrapnel per config..");
+ }
+ else if (!Main.projectile[index].active)
+ {
+ args.Player.ProjectileThreshold++; // Creating new projectile
+ }
+ }
+
+ if (hasPermission &&
+ (type == ProjectileID.Bomb
+ || type == ProjectileID.Dynamite
+ || type == ProjectileID.StickyBomb
+ || type == ProjectileID.StickyDynamite))
+ {
+ // Denotes that the player has recently set a fuse - used for cheat detection.
+ args.Player.RecentFuse = 10;
+ }
+ }
+
internal void OnPlaceObject(object sender, GetDataHandlers.PlaceObjectEventArgs args)
{
short x = args.X;
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 99c3e8be..bde25e27 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -681,6 +681,8 @@ namespace TShockAPI
///
public class NewProjectileEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the new projectile.
+ public TSPlayer Player { get; set; }
///
/// ???
///
@@ -719,7 +721,7 @@ namespace TShockAPI
///
public static HandlerList NewProjectile;
- private static bool OnNewProjectile(short ident, Vector2 pos, Vector2 vel, float knockback, short dmg, byte owner, short type, int index)
+ private static bool OnNewProjectile(short ident, Vector2 pos, Vector2 vel, float knockback, short dmg, byte owner, short type, int index, TSPlayer player)
{
if (NewProjectile == null)
return false;
@@ -734,6 +736,7 @@ namespace TShockAPI
Owner = owner,
Type = type,
Index = index,
+ Player = player,
};
NewProjectile.Invoke(null, args);
return args.Handled;
@@ -2261,97 +2264,9 @@ namespace TShockAPI
var index = TShock.Utils.SearchProjectile(ident, owner);
- if (OnNewProjectile(ident, pos, vel, knockback, dmg, owner, type, index))
+ if (OnNewProjectile(ident, pos, vel, knockback, dmg, owner, type, index, args.Player))
return true;
- if (index > Main.maxProjectiles || index < 0)
- {
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- if (TShock.ProjectileBans.ProjectileIsBanned(type, args.Player))
- {
- args.Player.Disable("Player does not have permission to create that projectile.", DisableFlags.WriteToLogAndConsole);
- args.Player.SendErrorMessage("You do not have permission to create that projectile.");
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- if (dmg > TShock.Config.MaxProjDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
- {
- args.Player.Disable(String.Format("Projectile damage is higher than {0}.", TShock.Config.MaxProjDamage), DisableFlags.WriteToLogAndConsole);
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- bool hasPermission = !TShock.CheckProjectilePermission(args.Player, index, type);
- if (!TShock.Config.IgnoreProjUpdate && !hasPermission && !args.Player.HasPermission(Permissions.ignoreprojectiledetection))
- {
- if (type == ProjectileID.BlowupSmokeMoonlord
- || type == ProjectileID.PhantasmalEye
- || type == ProjectileID.CultistBossIceMist
- || (type >= ProjectileID.MoonlordBullet && type <= ProjectileID.MoonlordTurretLaser)
- || type == ProjectileID.DeathLaser || type == ProjectileID.Landmine
- || type == ProjectileID.BulletDeadeye || type == ProjectileID.BoulderStaffOfEarth
- || (type > ProjectileID.ConfettiMelee && type < ProjectileID.SpiritHeal)
- || (type >= ProjectileID.FlamingWood && type <= ProjectileID.GreekFire3)
- || (type >= ProjectileID.PineNeedleHostile && type <= ProjectileID.Spike)
- || (type >= ProjectileID.MartianTurretBolt && type <= ProjectileID.RayGunnerLaser)
- || type == ProjectileID.CultistBossLightningOrb)
- {
- TShock.Log.Debug("Certain projectiles have been ignored for cheat detection.");
- }
- else
- {
- args.Player.Disable(String.Format("Does not have projectile permission to update projectile. ({0})", type), DisableFlags.WriteToLogAndConsole);
- args.Player.RemoveProjectile(ident, owner);
- }
- return true;
- }
-
- if (args.Player.ProjectileThreshold >= TShock.Config.ProjectileThreshold)
- {
- args.Player.Disable("Reached projectile update threshold.", DisableFlags.WriteToLogAndConsole);
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
- if (!args.Player.HasPermission(Permissions.ignoreprojectiledetection))
- {
- if (type == ProjectileID.CrystalShard && TShock.Config.ProjIgnoreShrapnel) // Ignore crystal shards
- {
- TShock.Log.Debug("Ignoring shrapnel per config..");
- }
- else if (!Main.projectile[index].active)
- {
- args.Player.ProjectileThreshold++; // Creating new projectile
- }
- }
-
- if (hasPermission &&
- (type == ProjectileID.Bomb
- || type == ProjectileID.Dynamite
- || type == ProjectileID.StickyBomb
- || type == ProjectileID.StickyDynamite))
- {
- // Denotes that the player has recently set a fuse - used for cheat detection.
- args.Player.RecentFuse = 10;
- //return true;
- }
-
return false;
}
From 46617e61d02a885097e0fcfcf09050e592041f3e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:29:23 -0700
Subject: [PATCH 102/430] Update changelog re. new hook changes
---
CHANGELOG.md | 3 +++
TShockAPI/GetDataHandlers.cs | 1 -
2 files changed, 3 insertions(+), 1 deletion(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14bce826..46bfb0bb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,9 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed /savessc not bothering to save ssc data for people who bypass ssc. (@hakusaro)
* Default permission sets for new databases are more modern. (@hakusaro)
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
+* `GetDataHandlers.SendTileSquare` hook now sends a `TSPlayer` and a `MemoryStream` of raw data. (@hakusaro)
+* Added `GetDataHandlers.HealOtherPlayer` hook. (@hakusaro)
+* Added `GetDataHandlers.PlaceObject` hook. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index bde25e27..0cf305a0 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2261,7 +2261,6 @@ namespace TShockAPI
ai[i] = 0f;
}
-
var index = TShock.Utils.SearchProjectile(ident, owner);
if (OnNewProjectile(ident, pos, vel, knockback, dmg, owner, type, index, args.Player))
From cdfb05690304d7b7df4c25bcd72ea35b19d5ff42 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:31:40 -0700
Subject: [PATCH 103/430] Include feedback from @bartico6 on a magic number
---
TShockAPI/Bouncer.cs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 3e16c10a..4a4df270 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -655,6 +655,8 @@ namespace TShockAPI
return;
}
+ // Why 0.2?
+ // @bartico6: Because heal other player only happens when you are using the spectre armor with the hood, and the healing you can do with that is 20% of your damage.
if (amount > TShock.Config.MaxDamage * 0.2)
{
args.Player.Disable("HealOtherPlayer cheat attempt!", DisableFlags.WriteToLogAndConsole);
From eed7b3fad234e81db0b8922d8f85bd880951d686 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:35:27 -0700
Subject: [PATCH 104/430] Document what TSPlayer.SendTileSquare does
---
TShockAPI/TSPlayer.cs | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index e2eedd1a..39dbb551 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -808,6 +808,15 @@ namespace TShockAPI
}
}
+ /// Sends a tile square at a location with a given size.
+ /// Typically used to revert changes by Bouncer through sending the
+ /// "old" version of modified data back to a client.
+ /// Prevents desync issues.
+ ///
+ /// The x coordinate to send.
+ /// The y coordinate to send.
+ /// The size square set of tiles to send.
+ /// Status if the tile square was sent successfully (i.e. no exceptions).
public virtual bool SendTileSquare(int x, int y, int size = 10)
{
try
From ce822caf2a5f75d0c9be602b3044ce385d14c735 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:39:54 -0700
Subject: [PATCH 105/430] Implement re-transmit of data if event handled in
OnTilEdit
Thanks to the suggestion of @bartico6, we now re-transmit packets
of world data to prevent desync issues with respect to stopping a
server action but not fixing the client's view of the world.
---
TShockAPI/Bouncer.cs | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 4a4df270..adbfd759 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -300,6 +300,7 @@ namespace TShockAPI
if (!TShock.Utils.TilePlacementValid(tileX, tileY))
{
+ args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
return;
}
@@ -312,6 +313,7 @@ namespace TShockAPI
if (args.Player.Dead && TShock.Config.PreventDeadModification)
{
+ args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
return;
}
@@ -377,6 +379,7 @@ namespace TShockAPI
return;
}
+ // TODO: REMOVE. This does NOT look like Bouncer code.
if (args.Player.AwaitingTempPoint > 0)
{
args.Player.TempPoints[args.Player.AwaitingTempPoint - 1].X = tileX;
@@ -656,7 +659,8 @@ namespace TShockAPI
}
// Why 0.2?
- // @bartico6: Because heal other player only happens when you are using the spectre armor with the hood, and the healing you can do with that is 20% of your damage.
+ // @bartico6: Because heal other player only happens when you are using the spectre armor with the hood,
+ // and the healing you can do with that is 20% of your damage.
if (amount > TShock.Config.MaxDamage * 0.2)
{
args.Player.Disable("HealOtherPlayer cheat attempt!", DisableFlags.WriteToLogAndConsole);
From aa527496dc87a47a81430f28780de17c3feb515d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:48:43 -0700
Subject: [PATCH 106/430] Replace a coule TileID magic numbers with direc
Tcalls.
Thanks @mistzzt & @QuiCM!
---
TShockAPI/Bouncer.cs | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index adbfd759..6d0bfe20 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -28,6 +28,7 @@ using TShockAPI.Localization;
using static TShockAPI.GetDataHandlers;
using TerrariaApi.Server;
using Terraria.ObjectData;
+using Terraria.ID;
namespace TShockAPI
@@ -333,6 +334,8 @@ namespace TShockAPI
persistentMode = true;
}
+
+ // TODO: REMOVE. This does NOT look like Bouncer code.
List outputRegions = new List();
foreach (Region region in TShock.Regions.Regions.OrderBy(r => r.Z).Reverse())
{
@@ -483,7 +486,7 @@ namespace TShockAPI
args.Handled = true;
return;
}
- if (action == EditAction.PlaceTile && (editData == 29 || editData == 97) && Main.ServerSideCharacter)
+ if (action == EditAction.PlaceTile && (editData == TileID.PiggyBank || editData == TileID.Safes) && Main.ServerSideCharacter)
{
args.Player.SendErrorMessage("You cannot place this tile because server side characters are enabled.");
args.Player.SendTileSquare(tileX, tileY, 3);
From 760f5518da6a38e81224b4726238386ace501688 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 01:50:58 -0700
Subject: [PATCH 107/430] More patching to fix potential desync (thanks
@bartico6)!
---
TShockAPI/Bouncer.cs | 2 ++
1 file changed, 2 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 6d0bfe20..c37db4ab 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -201,12 +201,14 @@ namespace TShockAPI
if (!TShock.Utils.TilePlacementValid(x, y))
{
+ args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
return;
}
if (args.Player.Dead && TShock.Config.PreventDeadModification)
{
+ args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
return;
}
From a5cbeb166b0fe034c63372af7d99454d5485008f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 02:15:31 -0700
Subject: [PATCH 108/430] Fix some SendTileSquare calls with proper args
---
TShockAPI/Bouncer.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index c37db4ab..f472b40b 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -201,14 +201,14 @@ namespace TShockAPI
if (!TShock.Utils.TilePlacementValid(x, y))
{
- args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Player.SendTileSquare(x, y, 4);
args.Handled = true;
return;
}
if (args.Player.Dead && TShock.Config.PreventDeadModification)
{
- args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Player.SendTileSquare(x, y, 4);
args.Handled = true;
return;
}
From 6a6133f3f7d4c7e8da53fe0b9ff832acd6a60ecc Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Sat, 9 Dec 2017 11:35:31 +0100
Subject: [PATCH 109/430] Add xml comments and DateTime datatype support for
SQL
---
TShockAPI/DB/IQueryBuilder.cs | 219 +++++++++++++++++++++++++++++++---
TShockAPI/DB/SqlColumn.cs | 21 +++-
TShockAPI/Extensions/DbExt.cs | 9 +-
3 files changed, 233 insertions(+), 16 deletions(-)
diff --git a/TShockAPI/DB/IQueryBuilder.cs b/TShockAPI/DB/IQueryBuilder.cs
index 7b202aaf..614b38bc 100644
--- a/TShockAPI/DB/IQueryBuilder.cs
+++ b/TShockAPI/DB/IQueryBuilder.cs
@@ -19,42 +19,110 @@ along with this program. If not, see .
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Runtime.Serialization;
using System.Text;
using MySql.Data.MySqlClient;
using TShockAPI.Extensions;
namespace TShockAPI.DB
{
+ ///
+ /// Interface for various SQL related utilities.
+ ///
public interface IQueryBuilder
{
+ ///
+ /// Creates a table from a SqlTable object.
+ ///
+ /// The SqlTable to create the table from
+ /// The sql query for the table creation.
string CreateTable(SqlTable table);
+ ///
+ /// Alter a table from source to destination
+ ///
+ /// Must have name and column names. Column types are not required
+ /// Must have column names and column types.
+ /// The SQL Query
string AlterTable(SqlTable from, SqlTable to);
+ ///
+ /// Converts the MySqlDbType enum to it's string representation.
+ ///
+ /// The MySqlDbType type
+ /// The length of the datatype
+ /// The string representation
string DbTypeToString(MySqlDbType type, int? length);
+ ///
+ /// A UPDATE Query
+ ///
+ /// The table to update
+ /// The values to change
+ ///
+ /// The SQL query
string UpdateValue(string table, List values, List wheres);
+ ///
+ /// A INSERT query
+ ///
+ /// The table to insert to
+ ///
+ /// The SQL Query
string InsertValues(string table, List values);
+ ///
+ /// A SELECT query to get all columns
+ ///
+ /// The table to select from
+ ///
+ /// The SQL query
string ReadColumn(string table, List wheres);
+ ///
+ /// Deletes row(s).
+ ///
+ /// The table to delete the row from
+ ///
+ /// The SQL query
string DeleteRow(string table, List wheres);
+ ///
+ /// Renames the given table.
+ ///
+ /// Old name of the table
+ /// New name of the table
+ /// The sql query for renaming the table.
string RenameTable(string from, string to);
}
+ ///
+ /// Query Creator for Sqlite
+ ///
public class SqliteQueryCreator : GenericQueryCreator, IQueryBuilder
{
+ ///
+ /// Creates a table from a SqlTable object.
+ ///
+ /// The SqlTable to create the table from
+ /// The sql query for the table creation.
public override string CreateTable(SqlTable table)
{
+ SqlColumnErrorCheck(table.Columns);
var columns =
table.Columns.Select(
c =>
- "'{0}' {1} {2} {3} {4}".SFormat(c.Name,
+ "'{0}' {1} {2} {3} {4} {5}".SFormat(c.Name,
DbTypeToString(c.Type, c.Length),
c.Primary ? "PRIMARY KEY" : "",
c.AutoIncrement ? "AUTOINCREMENT" : "",
- c.NotNull ? "NOT NULL" : ""));
+ c.NotNull ? "NOT NULL" : "",
+ c.DefaultCurrentTimestamp ? "DEFAULT CURRENT_TIMESTAMP" : ""));
var uniques = table.Columns.Where(c => c.Unique).Select(c => c.Name);
return "CREATE TABLE {0} ({1} {2})".SFormat(EscapeTableName(table.Name),
string.Join(", ", columns),
uniques.Count() > 0 ? ", UNIQUE({0})".SFormat(string.Join(", ", uniques)) : "");
}
+ ///
+ /// Renames the given table.
+ ///
+ /// Old name of the table
+ /// New name of the table
+ /// The sql query for renaming the table.
public override string RenameTable(string from, string to)
{
return "ALTER TABLE {0} RENAME TO {1}".SFormat(from, to);
@@ -73,8 +141,15 @@ namespace TShockAPI.DB
{ MySqlDbType.Int32, "INTEGER" },
{ MySqlDbType.Blob, "BLOB" },
{ MySqlDbType.Int64, "BIGINT"},
+ { MySqlDbType.DateTime, "DATETIME"},
};
+ ///
+ /// Converts the MySqlDbType enum to it's string representation.
+ ///
+ /// The MySqlDbType type
+ /// The length of the datatype
+ /// The string representation
public string DbTypeToString(MySqlDbType type, int? length)
{
string ret;
@@ -83,21 +158,38 @@ namespace TShockAPI.DB
throw new NotImplementedException(Enum.GetName(typeof(MySqlDbType), type));
}
+ ///
+ /// Escapes the table name
+ ///
+ /// The name of the table to be escaped
+ ///
protected override string EscapeTableName(string table)
{
return table.SFormat("'{0}'", table);
}
}
+ ///
+ /// Query Creator for MySQL
+ ///
public class MysqlQueryCreator : GenericQueryCreator, IQueryBuilder
{
+ ///
+ /// Creates a table from a SqlTable object.
+ ///
+ /// The SqlTable to create the table from
+ /// The sql query for the table creation.
public override string CreateTable(SqlTable table)
{
+ SqlColumnErrorCheck(table.Columns);
var columns =
table.Columns.Select(
c =>
- "{0} {1} {2} {3} {4}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "",
- c.AutoIncrement ? "AUTO_INCREMENT" : "", c.NotNull ? "NOT NULL" : ""));
+ "{0} {1} {2} {3} {4} {5}".SFormat(c.Name, DbTypeToString(c.Type, c.Length),
+ c.Primary ? "PRIMARY KEY" : "",
+ c.AutoIncrement ? "AUTO_INCREMENT" : "",
+ c.NotNull ? "NOT NULL" : "",
+ c.DefaultCurrentTimestamp ? "DEFAULT CURRENT_TIMESTAMP" : ""));
var uniques = table.Columns.Where(c => c.Unique).Select(c => c.Name);
return "CREATE TABLE {0} ({1} {2})".SFormat(EscapeTableName(table.Name), string.Join(", ", columns),
uniques.Count() > 0
@@ -105,6 +197,12 @@ namespace TShockAPI.DB
: "");
}
+ ///
+ /// Renames the given table.
+ ///
+ /// Old name of the table
+ /// New name of the table
+ /// The sql query for renaming the table.
public override string RenameTable(string from, string to)
{
return "RENAME TABLE {0} TO {1}".SFormat(from, to);
@@ -122,8 +220,15 @@ namespace TShockAPI.DB
{ MySqlDbType.Double, "DOUBLE" },
{ MySqlDbType.Int32, "INT" },
{ MySqlDbType.Int64, "BIGINT"},
+ { MySqlDbType.DateTime, "DATETIME"},
};
+ ///
+ /// Converts the MySqlDbType enum to it's string representation.
+ ///
+ /// The MySqlDbType type
+ /// The length of the datatype
+ /// The string representation
public string DbTypeToString(MySqlDbType type, int? length)
{
string ret;
@@ -132,17 +237,41 @@ namespace TShockAPI.DB
throw new NotImplementedException(Enum.GetName(typeof(MySqlDbType), type));
}
+ ///
+ /// Escapes the table name
+ ///
+ /// The name of the table to be escaped
+ ///
protected override string EscapeTableName(string table)
{
return table.SFormat("`{0}`", table);
}
}
+ ///
+ /// A Generic Query Creator (abstract)
+ ///
public abstract class GenericQueryCreator
{
protected static Random rand = new Random();
+ ///
+ /// Escapes the table name
+ ///
+ /// The name of the table to be escaped
+ ///
protected abstract string EscapeTableName(string table);
+ ///
+ /// Creates a table from a SqlTable object.
+ ///
+ /// The SqlTable to create the table from
+ /// The sql query for the table creation.
public abstract string CreateTable(SqlTable table);
+ ///
+ /// Renames the given table.
+ ///
+ /// Old name of the table
+ /// New name of the table
+ /// The sql query for renaming the table.
public abstract string RenameTable(string from, string to);
///
@@ -150,18 +279,9 @@ namespace TShockAPI.DB
///
/// Must have name and column names. Column types are not required
/// Must have column names and column types.
- ///
+ /// The SQL Query
public string AlterTable(SqlTable from, SqlTable to)
{
- /*
- * Any example outpuf from this looks like:-
- ALTER TABLE "main"."Bans" RENAME TO "oXHFcGcd04oXHFcGcd04_Bans"
- CREATE TABLE "main"."Bans" ("IP" TEXT PRIMARY KEY ,"Name" TEXT)
- INSERT INTO "main"."Bans" SELECT "IP","Name" FROM "main"."oXHFcGcd04oXHFcGcd04_Bans"
- DROP TABLE "main"."oXHFcGcd04oXHFcGcd04_Bans"
- *
- * Twitchy - Oh. I get it!
- */
var rstr = rand.NextString(20);
var escapedTable = EscapeTableName(from.Name);
var tmpTable = EscapeTableName("{0}_{1}".SFormat(rstr, from.Name));
@@ -175,11 +295,41 @@ namespace TShockAPI.DB
return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop);
}
+ ///
+ /// Check for errors in the columns.
+ ///
+ ///
+ /// description
+ public void SqlColumnErrorCheck(List columns)
+ {
+ columns.ForEach(x =>
+ {
+ if(x.DefaultCurrentTimestamp && x.Type != MySqlDbType.DateTime)
+ {
+ throw new SqlColumnExcepcion("Can't set to true SqlColumn.DefaultCurrentTimestamp " +
+ "when the MySqlDbType is not DateTime");
+ }
+ });
+ }
+
+ ///
+ /// Deletes row(s).
+ ///
+ /// The table to delete the row from
+ ///
+ /// The SQL query
public string DeleteRow(string table, List wheres)
{
return "DELETE FROM {0} {1}".SFormat(EscapeTableName(table), BuildWhere(wheres));
}
+ ///
+ /// A UPDATE Query
+ ///
+ /// The table to update
+ /// The values to change
+ ///
+ /// The SQL query
public string UpdateValue(string table, List values, List wheres)
{
if (0 == values.Count)
@@ -188,11 +338,23 @@ namespace TShockAPI.DB
return "UPDATE {0} SET {1} {2}".SFormat(EscapeTableName(table), string.Join(", ", values.Select(v => v.Name + " = " + v.Value)), BuildWhere(wheres));
}
+ ///
+ /// A SELECT query to get all columns
+ ///
+ /// The table to select from
+ ///
+ /// The SQL query
public string ReadColumn(string table, List wheres)
{
return "SELECT * FROM {0} {1}".SFormat(EscapeTableName(table), BuildWhere(wheres));
}
+ ///
+ /// A INSERT query
+ ///
+ /// The table to insert to
+ ///
+ /// The SQL Query
public string InsertValues(string table, List values)
{
var sbnames = new StringBuilder();
@@ -214,6 +376,11 @@ namespace TShockAPI.DB
return "INSERT INTO {0} ({1}) VALUES ({2})".SFormat(EscapeTableName(table), sbnames, sbvalues);
}
+ ///
+ /// Builds the SQL WHERE clause
+ ///
+ ///
+ ///
protected static string BuildWhere(List wheres)
{
if (0 == wheres.Count)
@@ -222,4 +389,28 @@ namespace TShockAPI.DB
return "WHERE {0}".SFormat(string.Join(", ", wheres.Select(v => v.Name + " = " + v.Value)));
}
}
+
+ ///
+ /// An excepcion generated by the Column check.
+ ///
+ [Serializable]
+ public class SqlColumnExcepcion : Exception
+ {
+ public SqlColumnExcepcion()
+ {
+ }
+
+ public SqlColumnExcepcion(string message)
+ : base(message)
+ {
+ }
+
+ public SqlColumnExcepcion(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+
+ protected SqlColumnExcepcion(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ }
+ }
}
diff --git a/TShockAPI/DB/SqlColumn.cs b/TShockAPI/DB/SqlColumn.cs
index 8a6c6bdf..cef6b3d8 100644
--- a/TShockAPI/DB/SqlColumn.cs
+++ b/TShockAPI/DB/SqlColumn.cs
@@ -28,11 +28,30 @@ namespace TShockAPI.DB
//Optional
+ ///
+ /// Sets/Gets if it's unique
+ ///
public bool Unique { get; set; }
+ ///
+ /// Sets/Gets if it's primary key
+ ///
public bool Primary { get; set; }
+ ///
+ /// Sets/Gets if it autoincrements
+ ///
public bool AutoIncrement { get; set; }
+ ///
+ /// Sets/Gets if it can be or not null
+ ///
public bool NotNull { get; set; }
+ ///
+ /// Sets the default value
+ ///
public string DefaultValue { get; set; }
+ ///
+ /// Use on DateTime only, if true, sets the default value to the current date when creating the row.
+ ///
+ public bool DefaultCurrentTimestamp { get; set; }
///
/// Length of the data type, null = default
@@ -51,4 +70,4 @@ namespace TShockAPI.DB
Length = length;
}
}
-}
\ No newline at end of file
+}
diff --git a/TShockAPI/Extensions/DbExt.cs b/TShockAPI/Extensions/DbExt.cs
index 3db75ec6..b623cae1 100644
--- a/TShockAPI/Extensions/DbExt.cs
+++ b/TShockAPI/Extensions/DbExt.cs
@@ -23,6 +23,9 @@ using System.Diagnostics.CodeAnalysis;
namespace TShockAPI.DB
{
+ ///
+ /// Database extensions
+ ///
public static class DbExt
{
///
@@ -189,6 +192,10 @@ namespace TShockAPI.DB
typeof (double?),
(s, i) => s.IsDBNull(i) ? null : (object)s.GetDouble(i)
},
+ {
+ typeof (DateTime),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetDateTime(i)
+ },
{
typeof (object),
(s, i) => s.GetValue(i)
@@ -272,4 +279,4 @@ namespace TShockAPI.DB
return Reader.Get(Reader.GetOrdinal(column));
}
}
-}
\ No newline at end of file
+}
From 83f02e49aa662871e0bb812218e5280f0aeca35f Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Sat, 9 Dec 2017 16:04:27 +0100
Subject: [PATCH 110/430] Format better
---
TShockAPI/Extensions/DbExt.cs | 162 +++++++++++++++++-----------------
1 file changed, 81 insertions(+), 81 deletions(-)
diff --git a/TShockAPI/Extensions/DbExt.cs b/TShockAPI/Extensions/DbExt.cs
index b623cae1..fbed21f7 100644
--- a/TShockAPI/Extensions/DbExt.cs
+++ b/TShockAPI/Extensions/DbExt.cs
@@ -106,7 +106,7 @@ namespace TShockAPI.DB
public static IDbConnection CloneEx(this IDbConnection conn)
{
- var clone = (IDbConnection) Activator.CreateInstance(conn.GetType());
+ var clone = (IDbConnection)Activator.CreateInstance(conn.GetType());
clone.ConnectionString = conn.ConnectionString;
return clone;
}
@@ -123,84 +123,84 @@ namespace TShockAPI.DB
private static readonly Dictionary> ReadFuncs = new Dictionary
>
- {
- {
- typeof (bool),
- (s, i) => s.GetBoolean(i)
- },
- {
- typeof (bool?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetBoolean(i)
- },
- {
- typeof (byte),
- (s, i) => s.GetByte(i)
- },
- {
- typeof (byte?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetByte(i)
- },
- {
- typeof (Int16),
- (s, i) => s.GetInt16(i)
- },
- {
- typeof (Int16?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt16(i)
- },
- {
- typeof (Int32),
- (s, i) => s.GetInt32(i)
- },
- {
- typeof (Int32?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt32(i)
- },
- {
- typeof (Int64),
- (s, i) => s.GetInt64(i)
- },
- {
- typeof (Int64?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt64(i)
- },
- {
- typeof (string),
- (s, i) => s.GetString(i)
- },
- {
- typeof (decimal),
- (s, i) => s.GetDecimal(i)
- },
- {
- typeof (decimal?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetDecimal(i)
- },
- {
- typeof (float),
- (s, i) => s.GetFloat(i)
- },
- {
- typeof (float?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetFloat(i)
- },
- {
- typeof (double),
- (s, i) => s.GetDouble(i)
- },
- {
- typeof (double?),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetDouble(i)
- },
- {
- typeof (DateTime),
- (s, i) => s.IsDBNull(i) ? null : (object)s.GetDateTime(i)
- },
- {
- typeof (object),
- (s, i) => s.GetValue(i)
- },
- };
+ {
+ {
+ typeof (bool),
+ (s, i) => s.GetBoolean(i)
+ },
+ {
+ typeof (bool?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetBoolean(i)
+ },
+ {
+ typeof (byte),
+ (s, i) => s.GetByte(i)
+ },
+ {
+ typeof (byte?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetByte(i)
+ },
+ {
+ typeof (Int16),
+ (s, i) => s.GetInt16(i)
+ },
+ {
+ typeof (Int16?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt16(i)
+ },
+ {
+ typeof (Int32),
+ (s, i) => s.GetInt32(i)
+ },
+ {
+ typeof (Int32?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt32(i)
+ },
+ {
+ typeof (Int64),
+ (s, i) => s.GetInt64(i)
+ },
+ {
+ typeof (Int64?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetInt64(i)
+ },
+ {
+ typeof (string),
+ (s, i) => s.GetString(i)
+ },
+ {
+ typeof (decimal),
+ (s, i) => s.GetDecimal(i)
+ },
+ {
+ typeof (decimal?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetDecimal(i)
+ },
+ {
+ typeof (float),
+ (s, i) => s.GetFloat(i)
+ },
+ {
+ typeof (float?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetFloat(i)
+ },
+ {
+ typeof (double),
+ (s, i) => s.GetDouble(i)
+ },
+ {
+ typeof (double?),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetDouble(i)
+ },
+ {
+ typeof (DateTime),
+ (s, i) => s.IsDBNull(i) ? null : (object)s.GetDateTime(i)
+ },
+ {
+ typeof (object),
+ (s, i) => s.GetValue(i)
+ },
+ };
public static T Get(this IDataReader reader, string column)
{
@@ -212,8 +212,8 @@ namespace TShockAPI.DB
if (reader.IsDBNull(column))
return default(T);
- if (ReadFuncs.ContainsKey(typeof (T)))
- return (T) ReadFuncs[typeof (T)](reader, column);
+ if (ReadFuncs.ContainsKey(typeof(T)))
+ return (T)ReadFuncs[typeof(T)](reader, column);
throw new NotImplementedException();
}
From 5770be0ac30444ef4bc29c2082f280a8bc4f46ba Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sat, 9 Dec 2017 16:20:52 +0100
Subject: [PATCH 111/430] Update CHANGELOG.md
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14bce826..2999805e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed /savessc not bothering to save ssc data for people who bypass ssc. (@hakusaro)
* Default permission sets for new databases are more modern. (@hakusaro)
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
+* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 4575792987f031a36f7849aac7ea84154cebef95 Mon Sep 17 00:00:00 2001
From: Edgar Luque
Date: Sat, 9 Dec 2017 16:45:31 +0100
Subject: [PATCH 112/430] Formatted a bit better and moved SqlColumnException
to SqlColumn.cs
---
TShockAPI/DB/IQueryBuilder.cs | 60 ++++++++++++++---------------------
TShockAPI/DB/SqlColumn.cs | 16 ++++++++++
2 files changed, 39 insertions(+), 37 deletions(-)
diff --git a/TShockAPI/DB/IQueryBuilder.cs b/TShockAPI/DB/IQueryBuilder.cs
index 614b38bc..917f634d 100644
--- a/TShockAPI/DB/IQueryBuilder.cs
+++ b/TShockAPI/DB/IQueryBuilder.cs
@@ -16,12 +16,12 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
+using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
-using MySql.Data.MySqlClient;
using TShockAPI.Extensions;
namespace TShockAPI.DB
@@ -37,6 +37,7 @@ namespace TShockAPI.DB
/// The SqlTable to create the table from
/// The sql query for the table creation.
string CreateTable(SqlTable table);
+
///
/// Alter a table from source to destination
///
@@ -44,6 +45,7 @@ namespace TShockAPI.DB
/// Must have column names and column types.
/// The SQL Query
string AlterTable(SqlTable from, SqlTable to);
+
///
/// Converts the MySqlDbType enum to it's string representation.
///
@@ -51,6 +53,7 @@ namespace TShockAPI.DB
/// The length of the datatype
/// The string representation
string DbTypeToString(MySqlDbType type, int? length);
+
///
/// A UPDATE Query
///
@@ -59,6 +62,7 @@ namespace TShockAPI.DB
///
/// The SQL query
string UpdateValue(string table, List values, List wheres);
+
///
/// A INSERT query
///
@@ -66,6 +70,7 @@ namespace TShockAPI.DB
///
/// The SQL Query
string InsertValues(string table, List values);
+
///
/// A SELECT query to get all columns
///
@@ -73,6 +78,7 @@ namespace TShockAPI.DB
///
/// The SQL query
string ReadColumn(string table, List wheres);
+
///
/// Deletes row(s).
///
@@ -80,6 +86,7 @@ namespace TShockAPI.DB
///
/// The SQL query
string DeleteRow(string table, List wheres);
+
///
/// Renames the given table.
///
@@ -101,18 +108,18 @@ namespace TShockAPI.DB
/// The sql query for the table creation.
public override string CreateTable(SqlTable table)
{
- SqlColumnErrorCheck(table.Columns);
+ ValidateSqlColumnType(table.Columns);
var columns =
table.Columns.Select(
c =>
- "'{0}' {1} {2} {3} {4} {5}".SFormat(c.Name,
- DbTypeToString(c.Type, c.Length),
+ "'{0}' {1} {2} {3} {4} {5}".SFormat(c.Name,
+ DbTypeToString(c.Type, c.Length),
c.Primary ? "PRIMARY KEY" : "",
- c.AutoIncrement ? "AUTOINCREMENT" : "",
+ c.AutoIncrement ? "AUTOINCREMENT" : "",
c.NotNull ? "NOT NULL" : "",
c.DefaultCurrentTimestamp ? "DEFAULT CURRENT_TIMESTAMP" : ""));
var uniques = table.Columns.Where(c => c.Unique).Select(c => c.Name);
- return "CREATE TABLE {0} ({1} {2})".SFormat(EscapeTableName(table.Name),
+ return "CREATE TABLE {0} ({1} {2})".SFormat(EscapeTableName(table.Name),
string.Join(", ", columns),
uniques.Count() > 0 ? ", UNIQUE({0})".SFormat(string.Join(", ", uniques)) : "");
}
@@ -140,7 +147,7 @@ namespace TShockAPI.DB
{ MySqlDbType.Double, "REAL" },
{ MySqlDbType.Int32, "INTEGER" },
{ MySqlDbType.Blob, "BLOB" },
- { MySqlDbType.Int64, "BIGINT"},
+ { MySqlDbType.Int64, "BIGINT"},
{ MySqlDbType.DateTime, "DATETIME"},
};
@@ -181,7 +188,7 @@ namespace TShockAPI.DB
/// The sql query for the table creation.
public override string CreateTable(SqlTable table)
{
- SqlColumnErrorCheck(table.Columns);
+ ValidateSqlColumnType(table.Columns);
var columns =
table.Columns.Select(
c =>
@@ -219,7 +226,7 @@ namespace TShockAPI.DB
{ MySqlDbType.Float, "FLOAT" },
{ MySqlDbType.Double, "DOUBLE" },
{ MySqlDbType.Int32, "INT" },
- { MySqlDbType.Int64, "BIGINT"},
+ { MySqlDbType.Int64, "BIGINT"},
{ MySqlDbType.DateTime, "DATETIME"},
};
@@ -254,18 +261,21 @@ namespace TShockAPI.DB
public abstract class GenericQueryCreator
{
protected static Random rand = new Random();
+
///
/// Escapes the table name
///
/// The name of the table to be escaped
///
protected abstract string EscapeTableName(string table);
+
///
/// Creates a table from a SqlTable object.
///
/// The SqlTable to create the table from
/// The sql query for the table creation.
public abstract string CreateTable(SqlTable table);
+
///
/// Renames the given table.
///
@@ -299,14 +309,14 @@ namespace TShockAPI.DB
/// Check for errors in the columns.
///
///
- /// description
- public void SqlColumnErrorCheck(List columns)
+ ///
+ public void ValidateSqlColumnType(List columns)
{
columns.ForEach(x =>
{
- if(x.DefaultCurrentTimestamp && x.Type != MySqlDbType.DateTime)
+ if (x.DefaultCurrentTimestamp && x.Type != MySqlDbType.DateTime)
{
- throw new SqlColumnExcepcion("Can't set to true SqlColumn.DefaultCurrentTimestamp " +
+ throw new SqlColumnException("Can't set to true SqlColumn.DefaultCurrentTimestamp " +
"when the MySqlDbType is not DateTime");
}
});
@@ -389,28 +399,4 @@ namespace TShockAPI.DB
return "WHERE {0}".SFormat(string.Join(", ", wheres.Select(v => v.Name + " = " + v.Value)));
}
}
-
- ///
- /// An excepcion generated by the Column check.
- ///
- [Serializable]
- public class SqlColumnExcepcion : Exception
- {
- public SqlColumnExcepcion()
- {
- }
-
- public SqlColumnExcepcion(string message)
- : base(message)
- {
- }
-
- public SqlColumnExcepcion(string message, Exception innerException) : base(message, innerException)
- {
- }
-
- protected SqlColumnExcepcion(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
- }
}
diff --git a/TShockAPI/DB/SqlColumn.cs b/TShockAPI/DB/SqlColumn.cs
index cef6b3d8..d61501d6 100644
--- a/TShockAPI/DB/SqlColumn.cs
+++ b/TShockAPI/DB/SqlColumn.cs
@@ -17,6 +17,7 @@ along with this program. If not, see .
*/
using MySql.Data.MySqlClient;
+using System;
namespace TShockAPI.DB
{
@@ -70,4 +71,19 @@ namespace TShockAPI.DB
Length = length;
}
}
+
+ ///
+ /// Used when a SqlColumn has validation errors.
+ ///
+ [Serializable]
+ public class SqlColumnException : Exception
+ {
+ ///
+ /// Creates a new SqlColumnException with the given message.
+ ///
+ ///
+ public SqlColumnException(string message) : base(message)
+ {
+ }
+ }
}
From 055d25330c65ba9445aee989029978de9c2bc0af Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sat, 9 Dec 2017 17:57:33 +0100
Subject: [PATCH 113/430] update otapi
---
TShockAPI/TShockAPI.csproj | 9 ++++-----
TShockAPI/packages.config | 2 +-
TerrariaServerAPI | 2 +-
3 files changed, 6 insertions(+), 7 deletions(-)
diff --git a/TShockAPI/TShockAPI.csproj b/TShockAPI/TShockAPI.csproj
index 08e9323d..957f805b 100644
--- a/TShockAPI/TShockAPI.csproj
+++ b/TShockAPI/TShockAPI.csproj
@@ -68,9 +68,8 @@
..\packages\MySql.Data.6.9.8\lib\net45\MySql.Data.dll
True
-
- ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll
- True
+
+ ..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll
False
@@ -206,7 +205,7 @@
-
+
-
+
\ No newline at end of file
diff --git a/TShockAPI/packages.config b/TShockAPI/packages.config
index cc9c5276..691052d5 100644
--- a/TShockAPI/packages.config
+++ b/TShockAPI/packages.config
@@ -2,5 +2,5 @@
-
+
\ No newline at end of file
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index bc9f7c69..de13bb0c 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit bc9f7c69becb60816fc1e4587bbca15991231317
+Subproject commit de13bb0c5fd7e255e12d7fd1171a071323664b78
From 6d0a729e5a520cc632684f7d2dead6dd5a20ce22 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sat, 9 Dec 2017 18:09:20 +0100
Subject: [PATCH 114/430] checkout submodule
---
TerrariaServerAPI | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index de13bb0c..e76b7d18 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit de13bb0c5fd7e255e12d7fd1171a071323664b78
+Subproject commit e76b7d18175163cc9375361494ca6283113c4389
From b794fae21d10566e7e679a608895fcc73667458f Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sat, 9 Dec 2017 18:13:47 +0100
Subject: [PATCH 115/430] update release script
---
scripts/create_release.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/scripts/create_release.py b/scripts/create_release.py
index 735c664c..1bc823d6 100755
--- a/scripts/create_release.py
+++ b/scripts/create_release.py
@@ -47,7 +47,7 @@ mysql_bin = os.path.join(cur_wd, "packages", "MySql.Data.6.9.8", "lib", "net45",
sqlite_dep = os.path.join(cur_wd, "prebuilts", sqlite_dep_name)
sqlite_bin = os.path.join(cur_wd, "prebuilts", sqlite_bin_name)
http_bin = os.path.join(cur_wd, "prebuilts", http_bin_name)
-json_bin = os.path.join(cur_wd, "packages", "Newtonsoft.Json.9.0.1", "lib", "net45", json_bin_name)
+json_bin = os.path.join(cur_wd, "packages", "Newtonsoft.Json.10.0.3", "lib", "net45", json_bin_name)
bcrypt_bin = os.path.join(cur_wd, "packages", "BCrypt.Net.0.1.0", "lib", "net35", bcrypt_bin_name)
geoip_db = os.path.join(cur_wd, "prebuilts", geoip_db_name)
release_bin = os.path.join(cur_wd, "TShockAPI", "bin", "Release", tshock_bin_name)
From a146e9bc387c72ae088f777d8107a70b851e6839 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sat, 9 Dec 2017 18:14:42 +0100
Subject: [PATCH 116/430] update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2999805e..71d26eb7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Default permission sets for new databases are more modern. (@hakusaro)
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki)
+* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 436e91c1f11654f625e5bdf21273f6a5ba130773 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 10:30:20 -0700
Subject: [PATCH 117/430] Change STS to 1 tile for @bartico6's quality of life
changes
Since these reverts are on a per-tile basis, we only need to revert
the first block not surrounding ones.
Note: May cause problems with dropped sand because of gravity.
---
TShockAPI/Bouncer.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index f472b40b..ed1caba1 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -201,7 +201,7 @@ namespace TShockAPI
if (!TShock.Utils.TilePlacementValid(x, y))
{
- args.Player.SendTileSquare(x, y, 4);
+ args.Player.SendTileSquare(x, y, 1);
args.Handled = true;
return;
}
@@ -303,7 +303,7 @@ namespace TShockAPI
if (!TShock.Utils.TilePlacementValid(tileX, tileY))
{
- args.Player.SendTileSquare(tileX, tileY, 4);
+ args.Player.SendTileSquare(tileX, tileY, 1);
args.Handled = true;
return;
}
From dd7ffe2d3a6453368eff0d562d9c507ee32fde69 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 13:46:45 -0700
Subject: [PATCH 118/430] Move PlayerKillMeV2 anti-crash to Bouncer
Removed PacketTypes.PlayerKillMe since it's out of the protocol.
Removed handler method for PlayerKillMe since it's out of the
protocol.
Updated changelog to reflect new hook changes.
---
CHANGELOG.md | 2 +-
TShockAPI/Bouncer.cs | 34 ++++++++++++-
TShockAPI/GetDataHandlers.cs | 93 ++++--------------------------------
3 files changed, 42 insertions(+), 87 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d08b8527..dc1a0b01 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,7 +26,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* `GetDataHandlers.SendTileSquare` hook now sends a `TSPlayer` and a `MemoryStream` of raw data. (@hakusaro)
* Added `GetDataHandlers.HealOtherPlayer` hook. (@hakusaro)
* Added `GetDataHandlers.PlaceObject` hook. (@hakusaro)
-
+* `GetDataHandlers.KillMe` now sends a `TSPlayer` and a `PlayerDeathReason`. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index ed1caba1..6fc7f640 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -29,7 +29,7 @@ using static TShockAPI.GetDataHandlers;
using TerrariaApi.Server;
using Terraria.ObjectData;
using Terraria.ID;
-
+using Terraria.DataStructures;
namespace TShockAPI
{
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.KillMe.Register(OnKillMe);
GetDataHandlers.NewProjectile.Register(OnNewProjectile);
GetDataHandlers.PlaceObject.Register(OnPlaceObject);
GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
@@ -49,6 +50,37 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnKillMe(object sender, GetDataHandlers.KillMeEventArgs args)
+ {
+ short dmg = args.Damage;
+ short id = args.PlayerId;
+ PlayerDeathReason playerDeathReason = args.PlayerDeathReason;
+
+ if (dmg > 20000) //Abnormal values have the potential to cause infinite loops in the server.
+ {
+ TShock.Utils.ForceKick(args.Player, "Crash Exploit Attempt", true);
+ TShock.Log.ConsoleError("Death Exploit Attempt: Damage {0}", dmg);
+ args.Handled = true;
+ return;
+ }
+
+ if (id >= Main.maxPlayers)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (playerDeathReason != null)
+ {
+ if (playerDeathReason.GetDeathText(TShock.Players[id].Name).ToString().Length > 500)
+ {
+ TShock.Utils.Kick(TShock.Players[id], "Crash attempt", true);
+ args.Handled = true;
+ return;
+ }
+ }
+ }
+
internal void OnNewProjectile(object sender, GetDataHandlers.NewProjectileEventArgs args)
{
short ident = args.Identity;
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 0d59a7ec..c57ab351 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -389,6 +389,8 @@ namespace TShockAPI
///
public class KillMeEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
///
/// The Terraria playerID of the player
///
@@ -405,23 +407,27 @@ namespace TShockAPI
/// Player's current pvp setting
///
public bool Pvp { get; set; }
+ /// The reason the player died.
+ public PlayerDeathReason PlayerDeathReason { get; set; }
}
///
/// KillMe - Terraria's crappy way of handling damage from players
///
public static HandlerList KillMe;
- private static bool OnKillMe(byte plr, byte direction, short damage, bool pvp)
+ private static bool OnKillMe(TSPlayer player, byte plr, byte direction, short damage, bool pvp, PlayerDeathReason playerDeathReason)
{
if (KillMe == null)
return false;
var args = new KillMeEventArgs
{
+ Player = player,
PlayerId = plr,
Direction = direction,
Damage = damage,
Pvp = pvp,
+ PlayerDeathReason = playerDeathReason,
};
KillMe.Invoke(null, args);
return args.Handled;
@@ -1341,7 +1347,6 @@ namespace TShockAPI
{ PacketTypes.TogglePvp, HandleTogglePvp },
{ PacketTypes.PlayerTeam, HandlePlayerTeam },
{ PacketTypes.TileKill, HandleTileKill },
- { PacketTypes.PlayerKillMe, HandlePlayerKillMe },
{ PacketTypes.LiquidSet, HandleLiquidSet },
{ PacketTypes.PlayerSpawn, HandleSpawn },
{ PacketTypes.ChestGetContents, HandleChestOpen },
@@ -2315,71 +2320,6 @@ namespace TShockAPI
return false;
}
- private static bool HandlePlayerKillMe(GetDataHandlerArgs args)
- {
- var id = args.Data.ReadInt8();
- var direction = (byte)(args.Data.ReadInt8() - 1);
- var dmg = args.Data.ReadInt16();
- var pvp = args.Data.ReadInt8() == 0;
- var text = args.Data.ReadString();
- if (dmg > 20000) //Abnormal values have the potential to cause infinite loops in the server.
- {
- TShock.Utils.ForceKick(args.Player, "Crash Exploit Attempt", true);
- TShock.Log.ConsoleError("Death Exploit Attempt: Damage {0}", dmg);
- return false;
- }
-
- if (id >= Main.maxPlayers)
- {
- return true;
- }
-
- if (OnKillMe(id, direction, dmg, pvp))
- return true;
-
- if (text.Length > 500)
- {
- TShock.Utils.Kick(TShock.Players[id], "Crash attempt", true);
- return true;
- }
-
- args.Player.Dead = true;
- args.Player.RespawnTimer = TShock.Config.RespawnSeconds;
-
- foreach (NPC npc in Main.npc)
- {
- if (npc.active && (npc.boss || npc.type == 13 || npc.type == 14 || npc.type == 15) &&
- Math.Abs(args.TPlayer.Center.X - npc.Center.X) + Math.Abs(args.TPlayer.Center.Y - npc.Center.Y) < 4000f)
- {
- args.Player.RespawnTimer = TShock.Config.RespawnBossSeconds;
- break;
- }
- }
-
- if (args.TPlayer.difficulty == 2 && (TShock.Config.KickOnHardcoreDeath || TShock.Config.BanOnHardcoreDeath))
- {
- if (TShock.Config.BanOnHardcoreDeath)
- {
- if (!TShock.Utils.Ban(args.Player, TShock.Config.HardcoreBanReason, false, "hardcore-death"))
- TShock.Utils.ForceKick(args.Player, "Death results in a ban, but you are immune to bans.", true);
- }
- else
- {
- TShock.Utils.ForceKick(args.Player, TShock.Config.HardcoreKickReason, true, false);
- }
- }
-
- if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn)
- {
- if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID))
- {
- TShock.CharacterDB.SeedInitialData(args.Player.Account);
- }
- }
-
- return false;
- }
-
private static bool HandlePlayerKillMeV2(GetDataHandlerArgs args)
{
var id = args.Data.ReadInt8();
@@ -2388,26 +2328,9 @@ namespace TShockAPI
var direction = (byte)(args.Data.ReadInt8() - 1);
BitsByte bits = (BitsByte)args.Data.ReadByte();
bool pvp = bits[0];
- if (dmg > 20000) //Abnormal values have the potential to cause infinite loops in the server.
- {
- TShock.Utils.ForceKick(args.Player, "Crash Exploit Attempt", true);
- TShock.Log.ConsoleError("Death Exploit Attempt: Damage {0}", dmg);
- return false;
- }
- if (id >= Main.maxPlayers)
- {
+ if (OnKillMe(args.Player, id, direction, dmg, pvp, playerDeathReason))
return true;
- }
-
- if (OnKillMe(id, direction, dmg, pvp))
- return true;
-
- if (playerDeathReason.GetDeathText(TShock.Players[id].Name).ToString().Length > 500)
- {
- TShock.Utils.Kick(TShock.Players[id], "Crash attempt", true);
- return true;
- }
args.Player.Dead = true;
args.Player.RespawnTimer = TShock.Config.RespawnSeconds;
From 63179deaa57b06429623a1b2673645fd2c80d9f7 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 15:54:51 -0700
Subject: [PATCH 119/430] Adds /dumpdata which dumps the permission table & ref
data.
---
TShockAPI/Commands.cs | 12 ++++++++++++
TShockAPI/Permissions.cs | 3 +++
TShockAPI/Utils.cs | 1 -
3 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 592177cf..d682c8e6 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -616,6 +616,10 @@ namespace TShockAPI
{
HelpText = "Sends a PM to a player."
});
+ add(new Command(Permissions.createdumps, CreateDumps, "datadump")
+ {
+ HelpText = "Creates a reference tables for Terraria data types and the TShock permission system in the server folder."
+ });
#endregion
add(new Command(Aliases, "aliases")
@@ -5178,6 +5182,14 @@ namespace TShockAPI
args.Player.SendErrorMessage("No command or command alias matching \"{0}\" found.", givenCommandName);
}
+ private static void CreateDumps(CommandArgs args)
+ {
+ TShock.Utils.DumpPermissionMatrix("PermissionMatrix.txt");
+ TShock.Utils.Dump();
+ args.Player.SendSuccessMessage("Your reference dumps have been created in the server folder.");
+ return;
+ }
+
#endregion General Commands
#region Cheat Commands
diff --git a/TShockAPI/Permissions.cs b/TShockAPI/Permissions.cs
index 37340e48..a02b3ff7 100644
--- a/TShockAPI/Permissions.cs
+++ b/TShockAPI/Permissions.cs
@@ -103,6 +103,9 @@ namespace TShockAPI
[Description("User can get other users' info.")]
public static readonly string userinfo = "tshock.admin.userinfo";
+ [Description("User can create reference files of Terraria IDs and the permission matrix in the server folder.")]
+ public static readonly string createdumps = "tshock.admin.createdumps";
+
// tshock.buff nodes
[Description("User can buff self.")]
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 050515a6..b899276a 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1204,7 +1204,6 @@ namespace TShockAPI
Permissions.DumpDescriptions();
ServerSideCharacters.ServerSideConfig.DumpDescriptions();
RestManager.DumpDescriptions();
- DumpPermissionMatrix("PermissionMatrix.txt");
DumpBuffs("BuffList.txt");
DumpItems("Items-1_0.txt", -48, 235);
DumpItems("Items-1_1.txt", 235, 604);
From 419b5415dae1c60daaa24c907a5bf59e905d9884 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 15:57:57 -0700
Subject: [PATCH 120/430] Updated the changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 71d26eb7..01660564 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki)
* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
+* Added the `/dumpdata` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From bdabf020d21d305f9eec5ef680ab7fbe609e7cd6 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 15:58:42 -0700
Subject: [PATCH 121/430] tshock.admin.createdumps is now a default owner level
permission
---
TShockAPI/DB/GroupManager.cs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/DB/GroupManager.cs b/TShockAPI/DB/GroupManager.cs
index f952fee2..56c4ef15 100644
--- a/TShockAPI/DB/GroupManager.cs
+++ b/TShockAPI/DB/GroupManager.cs
@@ -172,7 +172,8 @@ namespace TShockAPI.DB
Permissions.serverinfo,
Permissions.settempgroup,
Permissions.spawnrate,
- Permissions.tpoverride));
+ Permissions.tpoverride,
+ Permissions.createdumps));
}
// Load Permissions from the DB
From aa2f040787fbe6434389f5c2664bfcbe2294689c Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 16:03:12 -0700
Subject: [PATCH 122/430] Change command /datadump to /dump-reference-data
---
CHANGELOG.md | 2 +-
TShockAPI/Commands.cs | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01660564..b5e80c67 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +23,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki)
* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
-* Added the `/dumpdata` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
+* Added the `/dump-reference-data` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index d682c8e6..7eea0927 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -616,7 +616,7 @@ namespace TShockAPI
{
HelpText = "Sends a PM to a player."
});
- add(new Command(Permissions.createdumps, CreateDumps, "datadump")
+ add(new Command(Permissions.createdumps, CreateDumps, "dump-reference-data")
{
HelpText = "Creates a reference tables for Terraria data types and the TShock permission system in the server folder."
});
From 2e64d65910683d44227b407a45093ad4be50d936 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 16:09:53 -0700
Subject: [PATCH 123/430] Modify call to Utils.Dump() from the server context
to not stop
---
TShockAPI/Commands.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 7eea0927..b2f08d5f 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -5185,7 +5185,7 @@ namespace TShockAPI
private static void CreateDumps(CommandArgs args)
{
TShock.Utils.DumpPermissionMatrix("PermissionMatrix.txt");
- TShock.Utils.Dump();
+ TShock.Utils.Dump(false);
args.Player.SendSuccessMessage("Your reference dumps have been created in the server folder.");
return;
}
From 985dcebda9cd87f3bf93407fe8e5a3bfcff28414 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 17:14:59 -0700
Subject: [PATCH 124/430] Comment what DumpPermissionMatrix does
---
TShockAPI/Utils.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index b899276a..a587788d 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1225,8 +1225,8 @@ namespace TShockAPI
Main.recipe[i] = new Recipe();
}
- // Dumps a matrix of all permissions and all groups in markdown format
- // Hard coded to default groups because apparently we have poor querying tools
+ /// Dumps a matrix of all permissions & all groups in Markdown table format.
+ /// The save destination.
public void DumpPermissionMatrix(string path)
{
StringBuilder output = new StringBuilder();
From 14c071350ccb32ccb2c49ac2b5d56471305d25d3 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 17:15:21 -0700
Subject: [PATCH 125/430] Mark Utils.DumpPemrissionMatrix as internal
---
TShockAPI/Utils.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index a587788d..73ea56af 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1227,7 +1227,7 @@ namespace TShockAPI
/// Dumps a matrix of all permissions & all groups in Markdown table format.
/// The save destination.
- public void DumpPermissionMatrix(string path)
+ internal void DumpPermissionMatrix(string path)
{
StringBuilder output = new StringBuilder();
output.Append("|Permission|");
From 4638b85adc53eff55f4b0d4b6fec19172f54b225 Mon Sep 17 00:00:00 2001
From: Zaicon Kiroshu
Date: Sat, 9 Dec 2017 18:48:40 -0600
Subject: [PATCH 126/430] Fixed IndexOutOfRange exception
---
TShockAPI/Utils.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 050515a6..286d50c1 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1206,7 +1206,7 @@ namespace TShockAPI
RestManager.DumpDescriptions();
DumpPermissionMatrix("PermissionMatrix.txt");
DumpBuffs("BuffList.txt");
- DumpItems("Items-1_0.txt", -48, 235);
+ DumpItems("Items-1_0.txt", 1, 235);
DumpItems("Items-1_1.txt", 235, 604);
DumpItems("Items-1_2.txt", 604, 2749);
DumpItems("Items-1_3.txt", 2749, Main.maxItemTypes);
From 82f53addd75fb1c06bd29f0cbaa89e226fe37753 Mon Sep 17 00:00:00 2001
From: Zaicon
Date: Sat, 9 Dec 2017 20:12:12 -0600
Subject: [PATCH 127/430] Update CHANGELOG.md
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 71d26eb7..0c877cf3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro)
* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki)
* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
+* Fixed DumpItems() from trying to dump older versions of certain items (negative item IDs). (@Zaicon)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 691a3684257c99055ba0875eedc511070566bf2a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 9 Dec 2017 20:42:47 -0700
Subject: [PATCH 128/430] Change permission node to tshock.cfg.createdumps
---
TShockAPI/Permissions.cs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/TShockAPI/Permissions.cs b/TShockAPI/Permissions.cs
index a02b3ff7..bad4148f 100644
--- a/TShockAPI/Permissions.cs
+++ b/TShockAPI/Permissions.cs
@@ -103,9 +103,6 @@ namespace TShockAPI
[Description("User can get other users' info.")]
public static readonly string userinfo = "tshock.admin.userinfo";
- [Description("User can create reference files of Terraria IDs and the permission matrix in the server folder.")]
- public static readonly string createdumps = "tshock.admin.createdumps";
-
// tshock.buff nodes
[Description("User can buff self.")]
@@ -131,6 +128,9 @@ namespace TShockAPI
[Description("User can download updates to plugins that are currently running.")]
public static readonly string updateplugins = "tshock.cfg.updateplugins";
+ [Description("User can create reference files of Terraria IDs and the permission matrix in the server folder.")]
+ public static readonly string createdumps = "tshock.cfg.createdumps";
+
// tshock.ignore nodes
[Description("Prevents you from being reverted by kill tile abuse detection.")]
From 7d98e3db774700e4bc853bbf65cbaf48c1b51214 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Sun, 10 Dec 2017 09:39:20 +0100
Subject: [PATCH 129/430] update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1a85365..346f73dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
* Fixed DumpItems() from trying to dump older versions of certain items (negative item IDs). (@Zaicon)
* Added the `/dump-reference-data` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
+* Added DateTime datatype support for both MySQL and SQLite. (@Ryozuki)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 79802cd9e06f54fdfa5e278462754aaa05f04bac Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 08:54:32 -0700
Subject: [PATCH 130/430] Comment more things in Bouncer
---
TShockAPI/Bouncer.cs | 24 ++++++++++++++++++------
1 file changed, 18 insertions(+), 6 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 6fc7f640..d1810c38 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -50,6 +50,9 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Bouncer's KillMe hook stops crash exploits from out of bounds values.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnKillMe(object sender, GetDataHandlers.KillMeEventArgs args)
{
short dmg = args.Damage;
@@ -81,6 +84,9 @@ namespace TShockAPI
}
}
+ /// Bouncer's projectile trigger hook stops world damaging projectiles from destroying the world.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnNewProjectile(object sender, GetDataHandlers.NewProjectileEventArgs args)
{
short ident = args.Identity;
@@ -187,6 +193,9 @@ namespace TShockAPI
}
}
+ /// Bouncer's PlaceObject hook reverts malicious tile placement.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnPlaceObject(object sender, GetDataHandlers.PlaceObjectEventArgs args)
{
short x = args.X;
@@ -315,6 +324,9 @@ namespace TShockAPI
}
}
+ /// Bouncer's TileEdit hook is used to revert malicious tile changes.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnTileEdit(object sender, GetDataHandlers.TileEditEventArgs args)
{
EditAction action = args.Action;
@@ -681,9 +693,9 @@ namespace TShockAPI
}
}
- /// The handler for the HealOther events in Bouncer
- /// sender
- /// args
+ /// Bouncer's HealOther handler prevents gross misuse of HealOther packets by hackers.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnHealOtherPlayer(object sender, GetDataHandlers.HealOtherPlayerEventArgs args)
{
short amount = args.Amount;
@@ -723,9 +735,9 @@ namespace TShockAPI
return;
}
- /// The handler for SendTileSquare events in Bouncer
- /// sender
- /// args
+ /// Bouncer's SendTileSquare hook halts large scope world destruction.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnSendTileSquare(object sender, GetDataHandlers.SendTileSquareEventArgs args)
{
short size = args.Size;
From 949d0e0ffa7452c1ad0dc0cedbdf588a713612a4 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 08:56:17 -0700
Subject: [PATCH 131/430] More remove notes
---
TShockAPI/Bouncer.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index d1810c38..3d5d5ebe 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -232,6 +232,7 @@ namespace TShockAPI
return;
}
+ // TODO: REMOVE. This does NOT look like Bouncer code.
if (TShock.TileBans.TileIsBanned(type, args.Player))
{
args.Player.SendTileSquare(x, y, 1);
From d3c566db83d1b273b8108d3f177337fc3f901633 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 10:04:27 -0700
Subject: [PATCH 132/430] Move a large majority of OnPlayerUpdate to Bouncer
I really really don't understand why we're doing Terraria's data
sync for them (see HandlePlayerUpdate). Someone know why?
---
TShockAPI/Bouncer.cs | 104 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 98 +++++----------------------------
2 files changed, 119 insertions(+), 83 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 3d5d5ebe..e99233a9 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlayerUpdate.Register(OnPlayerUpdate);
GetDataHandlers.KillMe.Register(OnKillMe);
GetDataHandlers.NewProjectile.Register(OnNewProjectile);
GetDataHandlers.PlaceObject.Register(OnPlaceObject);
@@ -50,6 +51,109 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles disabling enforcement & minor anti-exploit stuff
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnPlayerUpdate(object sender, GetDataHandlers.PlayerUpdateEventArgs args)
+ {
+ byte plr = args.PlayerId;
+ BitsByte control = args.Control;
+ BitsByte pulley = args.Pulley;
+ byte item = args.Item;
+ var pos = args.Position;
+ var vel = args.Velocity;
+
+ if (pos.X < 0 || pos.Y < 0 || pos.X >= Main.maxTilesX * 16 - 16 || pos.Y >= Main.maxTilesY * 16 - 16)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (item < 0 || item >= args.Player.TPlayer.inventory.Length)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.LastNetPosition == Vector2.Zero)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (!pos.Equals(args.Player.LastNetPosition))
+ {
+ float distance = Vector2.Distance(new Vector2(pos.X / 16f, pos.Y / 16f),
+ new Vector2(args.Player.LastNetPosition.X / 16f, args.Player.LastNetPosition.Y / 16f));
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ // If the player has moved outside the disabled zone...
+ if (distance > TShock.Config.MaxRangeForDisabled)
+ {
+ // We need to tell them they were disabled and why, then revert the change.
+ if (args.Player.IgnoreActionsForCheating != "none")
+ {
+ args.Player.SendErrorMessage("Disabled for cheating: " + args.Player.IgnoreActionsForCheating);
+ }
+ else if (args.Player.IgnoreActionsForDisabledArmor != "none")
+ {
+ args.Player.SendErrorMessage("Disabled for banned armor: " + args.Player.IgnoreActionsForDisabledArmor);
+ }
+ else if (args.Player.IgnoreActionsForInventory != "none")
+ {
+ args.Player.SendErrorMessage("Disabled for Server Side Inventory: " + args.Player.IgnoreActionsForInventory);
+ }
+ else if (TShock.Config.RequireLogin && !args.Player.IsLoggedIn)
+ {
+ args.Player.SendErrorMessage("Please /register or /login to play!");
+ }
+ else if (args.Player.IgnoreActionsForClearingTrashCan)
+ {
+ args.Player.SendErrorMessage("You need to rejoin to ensure your trash can is cleared!");
+ }
+
+ // ??
+ var lastTileX = args.Player.LastNetPosition.X;
+ var lastTileY = args.Player.LastNetPosition.Y - 48;
+ if (!args.Player.Teleport(lastTileX, lastTileY))
+ {
+ args.Player.Spawn();
+ }
+ args.Handled = true;
+ return;
+ }
+ args.Handled = true;
+ return;
+ }
+
+ // Corpses don't move
+ if (args.Player.Dead)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ // Noclip detection
+ if (!args.Player.HasPermission(Permissions.ignorenoclipdetection) &&
+ TSCheckNoclip(pos, args.Player.TPlayer.width, args.Player.TPlayer.height - (args.Player.TPlayer.mount.Active ? args.Player.TPlayer.mount.HeightBoost : 0)) && !TShock.Config.IgnoreNoClip
+ && !args.Player.TPlayer.tongued)
+ {
+ var lastTileX = args.Player.LastNetPosition.X;
+ var lastTileY = args.Player.LastNetPosition.Y;
+ if (!args.Player.Teleport(lastTileX, lastTileY))
+ {
+ args.Player.SendErrorMessage("You got stuck in a solid object, Sent to spawn point.");
+ args.Player.Spawn();
+ }
+ args.Handled = true;
+ return;
+ }
+ }
+
+ return;
+ }
+
/// Bouncer's KillMe hook stops crash exploits from out of bounds values.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index c57ab351..fb1ac16b 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -438,16 +438,18 @@ namespace TShockAPI
///
public class PlayerUpdateEventArgs : HandledEventArgs
{
+ /// The TSPlayer object that triggered the event
+ public TSPlayer Player { get; set; }
///
/// The Terraria playerID of the player
///
public byte PlayerId { get; set; }
///
- /// ???
+ /// Control direction (BitFlags)
///
public byte Control { get; set; }
///
- /// Current item?
+ /// Selected item
///
public byte Item { get; set; }
///
@@ -458,7 +460,7 @@ namespace TShockAPI
/// Velocity of the player
///
public Vector2 Velocity { get; set; }
-
+ /// Pulley update (BitFlags)
public byte Pulley { get; set; }
}
///
@@ -466,14 +468,15 @@ namespace TShockAPI
///
public static HandlerList PlayerUpdate;
- private static bool OnPlayerUpdate(byte player, byte control, byte item, Vector2 position, Vector2 velocity, byte pulley)
+ private static bool OnPlayerUpdate(TSPlayer player, byte plr, byte control, byte item, Vector2 position, Vector2 velocity, byte pulley)
{
if (PlayerUpdate == null)
return false;
var args = new PlayerUpdateEventArgs
{
- PlayerId = player,
+ Player = player,
+ PlayerId = plr,
Control = control,
Item = item,
Position = position,
@@ -2034,6 +2037,9 @@ namespace TShockAPI
{
if (args.Player == null || args.TPlayer == null || args.Data == null)
{
+ // Is this really the best option?
+ // If we're getting a packet that doesn't have a player or a TPlayer or data...
+ // Should we really let it through?
return false;
}
@@ -2046,86 +2052,12 @@ namespace TShockAPI
if (pulley[2])
vel = new Vector2(args.Data.ReadSingle(), args.Data.ReadSingle());
- if (OnPlayerUpdate(plr, control, item, pos, vel, pulley))
+ if (OnPlayerUpdate(args.Player, plr, control, item, pos, vel, pulley))
return true;
- if (pos.X < 0 || pos.Y < 0 || pos.X >= Main.maxTilesX * 16 - 16 || pos.Y >= Main.maxTilesY * 16 - 16)
- {
- return true;
- }
-
- if (item < 0 || item >= args.TPlayer.inventory.Length)
- {
- return true;
- }
-
- if (args.Player.LastNetPosition == Vector2.Zero)
- {
- return true;
- }
-
- if (!pos.Equals(args.Player.LastNetPosition))
- {
- float distance = Vector2.Distance(new Vector2(pos.X / 16f, pos.Y / 16f),
- new Vector2(args.Player.LastNetPosition.X / 16f, args.Player.LastNetPosition.Y / 16f));
- if (TShock.CheckIgnores(args.Player))
- {
- if (distance > TShock.Config.MaxRangeForDisabled)
- {
- if (args.Player.IgnoreActionsForCheating != "none")
- {
- args.Player.SendErrorMessage("Disabled for cheating: " + args.Player.IgnoreActionsForCheating);
- }
- else if (args.Player.IgnoreActionsForDisabledArmor != "none")
- {
- args.Player.SendErrorMessage("Disabled for banned armor: " + args.Player.IgnoreActionsForDisabledArmor);
- }
- else if (args.Player.IgnoreActionsForInventory != "none")
- {
- args.Player.SendErrorMessage("Disabled for Server Side Inventory: " + args.Player.IgnoreActionsForInventory);
- }
- else if (TShock.Config.RequireLogin && !args.Player.IsLoggedIn)
- {
- args.Player.SendErrorMessage("Please /register or /login to play!");
- }
- else if (args.Player.IgnoreActionsForClearingTrashCan)
- {
- args.Player.SendErrorMessage("You need to rejoin to ensure your trash can is cleared!");
- }
- var lastTileX = args.Player.LastNetPosition.X;
- var lastTileY = args.Player.LastNetPosition.Y - 48;
- if (!args.Player.Teleport(lastTileX, lastTileY))
- {
- args.Player.Spawn();
- }
- return true;
- }
- return true;
- }
-
- if (args.Player.Dead)
- {
- return true;
- }
-
- if (!args.Player.HasPermission(Permissions.ignorenoclipdetection) &&
- TSCheckNoclip(pos, args.TPlayer.width, args.TPlayer.height - (args.TPlayer.mount.Active ? args.Player.TPlayer.mount.HeightBoost : 0)) && !TShock.Config.IgnoreNoClip
- && !args.TPlayer.tongued)
- {
- var lastTileX = args.Player.LastNetPosition.X;
- var lastTileY = args.Player.LastNetPosition.Y;
- if (!args.Player.Teleport(lastTileX, lastTileY))
- {
- args.Player.SendErrorMessage("You got stuck in a solid object, Sent to spawn point.");
- args.Player.Spawn();
- }
- return true;
- }
- args.Player.LastNetPosition = pos;
- }
-
if (control[5])
{
+ // ItemBan system
string itemName = args.TPlayer.inventory[item].Name;
if (TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(args.TPlayer.inventory[item].netID), args.Player))
{
@@ -2134,6 +2066,7 @@ namespace TShockAPI
args.Player.SendErrorMessage("You cannot use {0} on this server. Your actions are being ignored.", itemName);
}
+ // Reimplementation of normal Terraria stuff?
if (args.TPlayer.inventory[item].Name == "Mana Crystal" && args.Player.TPlayer.statManaMax <= 180)
{
args.Player.TPlayer.statMana += 20;
@@ -2154,6 +2087,7 @@ namespace TShockAPI
}
}
+ // Where we rebuild sync data for Terraria?
args.TPlayer.selectedItem = item;
args.TPlayer.position = pos;
args.TPlayer.oldVelocity = args.TPlayer.velocity;
@@ -2210,7 +2144,6 @@ namespace TShockAPI
args.TPlayer.direction = -1;
}
-
if (args.Player.Confused && Main.ServerSideCharacter && args.Player.IsLoggedIn)
{
if (args.TPlayer.controlUp)
@@ -2235,7 +2168,6 @@ namespace TShockAPI
args.TPlayer.controlLeft = true;
}
-
args.TPlayer.Update(args.TPlayer.whoAmI);
NetMessage.SendData((int)PacketTypes.PlayerUpdate, -1, -1, NetworkText.Empty, args.Player.Index);
return true;
From 2cfa633df4d1a5ad3b059a26c0567d91b91c3d71 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 11:26:01 -0700
Subject: [PATCH 133/430] Remove commented out code from HandleProjectileKill
---
TShockAPI/GetDataHandlers.cs | 8 --------
1 file changed, 8 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index fb1ac16b..888bce64 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2220,14 +2220,6 @@ namespace TShockAPI
var type = Main.projectile[index].type;
- // Players can no longer destroy projectiles that are not theirs as of 1.1.2
- /*if (args.Player.Index != Main.projectile[index].owner && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill) // workaround for skeletron prime projectiles
- {
- args.Player.Disable(String.Format("Owner ({0}) and player ID ({1}) does not match to kill projectile of type: {3}", Main.projectile[index].owner, args.Player.Index, type));
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }*/
-
if (TShock.CheckIgnores(args.Player))
{
args.Player.RemoveProjectile(ident, owner);
From 740ad4d6c3226e69122f901a9736d23e821de267 Mon Sep 17 00:00:00 2001
From: Patrikk
Date: Sun, 10 Dec 2017 20:14:54 +0100
Subject: [PATCH 134/430] Add missing "if handled - return" code.
---
TShockAPI/TShock.cs | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index ee403eab..5d59dc8a 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -522,6 +522,11 @@ namespace TShockAPI
/// args - The NameCollisionEventArgs object.
private void NetHooks_NameCollision(NameCollisionEventArgs args)
{
+ if (args.Handled)
+ {
+ return;
+ }
+
string ip = Utils.GetRealIP(Netplay.Clients[args.Who].Socket.GetRemoteAddress().ToString());
var player = Players.First(p => p != null && p.Name == args.Name && p.Index != args.Who);
From 7181757dd3014f0f07bdfbcba1b8b1eabbb4275f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 12:26:54 -0700
Subject: [PATCH 135/430] Changelog bot message is more prodding
If people keep ignoring the bot, I'm going to make it block merging too.
---
.github/config.yml | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/.github/config.yml b/.github/config.yml
index c39fdab9..34b33fce 100644
--- a/.github/config.yml
+++ b/.github/config.yml
@@ -1,5 +1,5 @@
updateDocsComment: >
- Thanks for the pull request! TShock's maintainers would like you to go ahead and give yourself credit by updating the `CHANGELOG.md` file before this gets merged. This helps us document changes to TShock, as well as give you credit for your work. You deserve it! :sparkles:
+ Thanks for the pull request! TShock's maintainers would like you to go ahead and give yourself credit by updating the `CHANGELOG.md` as soon as you can. Your pull request will likely not be accepted without this. This both helps us document changes to TShock, as well as give you credit for your work. You deserve it, so go take credit! :sparkles:
updateDocsWhiteList:
- bug
@@ -7,4 +7,4 @@ updateDocsWhiteList:
updateDocsTargetFiles:
- README
- - CHANGELOG.md
\ No newline at end of file
+ - CHANGELOG.md
From 6f044b2123c744e5673d63e883958be15770c91d Mon Sep 17 00:00:00 2001
From: Patrikk
Date: Sun, 10 Dec 2017 20:37:59 +0100
Subject: [PATCH 136/430] Adding missing Changelog.
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1a85365..e50ee4a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
This is the rolling changelog for TShock for Terraria. Use past tense when adding new entries; sign your name off when you add or change something. This should primarily be things like user changes, not necessarily codebase changes unless it's really relevant or large.
## Upcoming Changes
+* API: Added return in OnNameCollision if hook has been handled. (@Patrikkk)
* API: Added hooks for item, projectile and tile bans (@deadsurgeon42)
* API: Changed `PlayerHooks` permission hook mechanisms to allow negation from hooks (@deadsurgeon42)
* API: New WorldGrassSpread hook which shold allow corruption/crimson/hallow creep config options to work (@DeathCradle)
From 1f79e14bd7d4296c859b74514f7cd64c445aaaeb Mon Sep 17 00:00:00 2001
From: quake1337 <3310937+bartico6@users.noreply.github.com>
Date: Mon, 11 Dec 2017 01:12:27 +0100
Subject: [PATCH 137/430] Make TShock pull OTAPI from the correct folder on
build
---
TShockAPI/TShockAPI.csproj | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/TShockAPI/TShockAPI.csproj b/TShockAPI/TShockAPI.csproj
index 957f805b..a612f444 100644
--- a/TShockAPI/TShockAPI.csproj
+++ b/TShockAPI/TShockAPI.csproj
@@ -71,11 +71,9 @@
..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll
-
+
False
- ..\TerrariaServerAPI\TerrariaServerAPI\bin\Debug\OTAPI.dll
- ..\TerrariaServerAPI\TerrariaServerAPI\bin\Release\OTAPI.dll
- ..\TerrariaServerAPI\TerrariaServerAPI\bin\$(Configuration)\OTAPI.dll
+ ..\TerrariaServerAPI\TerrariaServerAPI\bin\$(ConfigurationName)\OTAPI.dll
From a5e196178e31d9a444ed9b7f2fc542c84f7e7989 Mon Sep 17 00:00:00 2001
From: quake1337 <3310937+bartico6@users.noreply.github.com>
Date: Mon, 11 Dec 2017 01:16:10 +0100
Subject: [PATCH 138/430] Add credit
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e50ee4a5..d4eafb1d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Update OTAPI to 2.0.0.31, which also updates Newtonsoft.Json to 10.0.3 (@Ryozuki)
* Fixed DumpItems() from trying to dump older versions of certain items (negative item IDs). (@Zaicon)
* Added the `/dump-reference-data` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
+* Fixed builds to not require a specific version of OTAPI and to not fail when in Release mode (@bartico6)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From c5f9a518023bd1d3f2803a38b0f87b8d9cfe871b Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 23:05:50 -0700
Subject: [PATCH 139/430] Move most of HandleProjectileKill to Bouncer
Added GetDataHandlers.ProjectileKill hook and related arguments.
Fired when a projectile kill packet is accepted by the server.
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 28 ++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 56 +++++++++++++++++++++++++++---------
3 files changed, 71 insertions(+), 14 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 010e16e7..7359fbfb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added `GetDataHandlers.HealOtherPlayer` hook. (@hakusaro)
* Added `GetDataHandlers.PlaceObject` hook. (@hakusaro)
* `GetDataHandlers.KillMe` now sends a `TSPlayer` and a `PlayerDeathReason`. (@hakusaro)
+* Added `GetDataHandlers.ProjectileKill` hook. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index e99233a9..87ea3c72 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.ProjectileKill.Register(OnProjectileKill);
GetDataHandlers.PlayerUpdate.Register(OnPlayerUpdate);
GetDataHandlers.KillMe.Register(OnKillMe);
GetDataHandlers.NewProjectile.Register(OnNewProjectile);
@@ -51,6 +52,33 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles ProjectileKill events for throttling & out of bounds projectiles.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnProjectileKill(object sender, GetDataHandlers.ProjectileKillEventArgs args)
+ {
+ if (args.ProjectileIndex > Main.maxProjectiles || args.ProjectileIndex < 0)
+ {
+ // TODO: Should this be /true/ to stop the server from processing it?
+ args.Handled = false;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.RemoveProjectile(args.ProjectileIdentity, args.ProjectileOwner);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.RemoveProjectile(args.ProjectileIdentity, args.ProjectileOwner);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles disabling enforcement & minor anti-exploit stuff
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 888bce64..3eb03926 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -384,6 +384,45 @@ namespace TShockAPI
return args.Handled;
}
+ /// The arguments to the ProjectileKill packet.
+ public class ProjectileKillEventArgs : HandledEventArgs
+ {
+ /// The TSPlayer that fired the event.
+ public TSPlayer Player;
+ /// The projectile's identity...?
+ public int ProjectileIdentity;
+ /// The the player index of the projectile's owner (Main.players).
+ public byte ProjectileOwner;
+ /// The index of the projectile in Main.projectile.
+ public int ProjectileIndex;
+ }
+
+ /// The event fired when a projectile kill packet is received.
+ public static HandlerList ProjectileKill;
+
+ /// Fires the ProjectileKill event.
+ /// The TSPlayer that caused the event.
+ /// The projectile identity (from the packet).
+ /// The projectile's owner (from the packet).
+ /// The projectile's index (from Main.projectiles).
+ /// bool
+ private static bool OnProjectileKill(TSPlayer player, int identity, byte owner, int index)
+ {
+ if (ProjectileKill == null)
+ return false;
+
+ var args = new ProjectileKillEventArgs
+ {
+ Player = player,
+ ProjectileIdentity = identity,
+ ProjectileOwner = owner,
+ ProjectileIndex = index,
+ };
+
+ ProjectileKill.Invoke(null, args);
+ return args.Handled;
+ }
+
///
/// For use in a KillMe event
///
@@ -2213,19 +2252,14 @@ namespace TShockAPI
owner = (byte)args.Player.Index;
var index = TShock.Utils.SearchProjectile(ident, owner);
- if (index > Main.maxProjectiles || index < 0)
+ if (OnProjectileKill(args.Player, ident, owner, index))
{
- return false;
+ return true;
}
var type = Main.projectile[index].type;
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
+ // TODO: This needs to be moved somewhere else.
if (TShock.CheckProjectilePermission(args.Player, index, type) && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill)
{
args.Player.Disable("Does not have projectile permission to kill projectile.", DisableFlags.WriteToLogAndConsole);
@@ -2233,12 +2267,6 @@ namespace TShockAPI
return true;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.RemoveProjectile(ident, owner);
- return true;
- }
-
args.Player.LastKilledProjectile = type;
return false;
From ba851d3570f6efae73aa8a8c953ffa3775133efc Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 10 Dec 2017 23:36:16 -0700
Subject: [PATCH 140/430] Remove TShock.CheckProjectilePermission
Add TSPlayer.HasProjectilePermission() and its inverse:
TSPlayer.LacksProjectilePermission()
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 2 +-
TShockAPI/GetDataHandlers.cs | 2 +-
TShockAPI/TSPlayer.cs | 51 ++++++++++++++++++++++++++++++++++++
TShockAPI/TShock.cs | 35 -------------------------
5 files changed, 54 insertions(+), 37 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7359fbfb..2327f753 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added `GetDataHandlers.PlaceObject` hook. (@hakusaro)
* `GetDataHandlers.KillMe` now sends a `TSPlayer` and a `PlayerDeathReason`. (@hakusaro)
* Added `GetDataHandlers.ProjectileKill` hook. (@hakusaro)
+* Removed `TShock.CheckProjectilePermission` and replaced it with `TSPlayer.HasProjectilePermission` and `TSPlayer.LacksProjectilePermission` respectively. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 87ea3c72..dd1257db 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -261,7 +261,7 @@ namespace TShockAPI
return;
}
- bool hasPermission = !TShock.CheckProjectilePermission(args.Player, index, type);
+ bool hasPermission = args.Player.HasProjectilePermission(index, type);
if (!TShock.Config.IgnoreProjUpdate && !hasPermission && !args.Player.HasPermission(Permissions.ignoreprojectiledetection))
{
if (type == ProjectileID.BlowupSmokeMoonlord
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 3eb03926..2545a2f0 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2260,7 +2260,7 @@ namespace TShockAPI
var type = Main.projectile[index].type;
// TODO: This needs to be moved somewhere else.
- if (TShock.CheckProjectilePermission(args.Player, index, type) && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill)
+ if (args.Player.LacksProjectilePermission(index, type) && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill)
{
args.Player.Disable("Does not have projectile permission to kill projectile.", DisableFlags.WriteToLogAndConsole);
args.Player.RemoveProjectile(ident, owner);
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 78d3ef74..73a2bce0 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -789,6 +789,57 @@ namespace TShockAPI
}
}
+ /// Checks to see if this player object lacks access rights to a given projectile. Used by projectile bans.
+ /// The projectile index from Main.projectiles (NOT from a packet directly).
+ /// The type of projectile, from Main.projectiles.
+ /// If the player has lacks access rights to the projectile.
+ public bool LacksProjectilePermission(int index, int type)
+ {
+ return !HasProjectilePermission(index, type);
+ }
+
+ /// Checks to see if this player object has access rights to a given projectile. Used by projectile bans.
+ /// The projectile index from Main.projectiles (NOT from a packet directly).
+ /// The type of projectile, from Main.projectiles.
+ /// If the player has access rights to the projectile.
+ public bool HasProjectilePermission(int index, int type)
+ {
+ // Players never have the rights to tombstones.
+ if (type == ProjectileID.Tombstone)
+ {
+ return false;
+ }
+
+ // Dirt balls are the projectiles from dirt rods.
+ // If the dirt rod item is banned, they probably shouldn't have this projectile.
+ if (type == ProjectileID.DirtBall && TShock.Itembans.ItemIsBanned("Dirt Rod", this))
+ {
+ return false;
+ }
+
+ // If the sandgun is banned, block sand bullets.
+ if (TShock.Itembans.ItemIsBanned("Sandgun", this))
+ {
+ if (type == ProjectileID.SandBallGun
+ || type == ProjectileID.EbonsandBallGun
+ || type == ProjectileID.PearlSandBallGun)
+ {
+ return false;
+ }
+ }
+
+ // If the projectile is hostile, block it?
+ Projectile tempProjectile = new Projectile();
+ tempProjectile.SetDefaults(type);
+
+ if (Main.projHostile[type])
+ {
+ return false;
+ }
+
+ return true;
+ }
+
///
/// Removes the projectile with the given index and owner.
///
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 40003217..a4245e09 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1772,41 +1772,6 @@ namespace TShockAPI
Main.StartInvasion(type);
}
- /// CheckProjectilePermission - Checks if a projectile is banned.
- /// player - The TSPlayer object that created the projectile.
- /// index - The projectile index.
- /// type - The projectile type.
- /// bool - True if the player does not have permission to use a projectile.
- public static bool CheckProjectilePermission(TSPlayer player, int index, int type)
- {
- if (type == 43)
- {
- return true;
- }
-
- if (type == 17 && Itembans.ItemIsBanned("Dirt Rod", player))
- //Dirt Rod Projectile
- {
- return true;
- }
-
- if ((type == 42 || type == 65 || type == 68) && Itembans.ItemIsBanned("Sandgun", player)) //Sandgun Projectiles
- {
- return true;
- }
-
- Projectile proj = new Projectile();
- proj.SetDefaults(type);
-
- if (Main.projHostile[type])
- {
- //player.SendMessage( proj.name, Color.Yellow);
- return true;
- }
-
- return false;
- }
-
/// CheckRangePermission - Checks if a player has permission to modify a tile dependent on range checks.
/// player - The TSPlayer object.
/// x - The x coordinate of the tile.
From 4b08d616733fa6350442d2b46ce161820c6c0a9d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 00:17:58 -0700
Subject: [PATCH 141/430] Change null check to return true in
HandlePlayerUpdate
After confirming with @QuiCM on this, we couldn't figure out why
this was set to false in the first place. As a result, we changed
it to true to conform with usual logic (bad stuff? reject it.).
---
TShockAPI/GetDataHandlers.cs | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 2545a2f0..0ef703af 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2076,10 +2076,7 @@ namespace TShockAPI
{
if (args.Player == null || args.TPlayer == null || args.Data == null)
{
- // Is this really the best option?
- // If we're getting a packet that doesn't have a player or a TPlayer or data...
- // Should we really let it through?
- return false;
+ return true;
}
byte plr = args.Data.ReadInt8();
From 6ed110f862cfc600ceb6ad874579b8d08ae95ef5 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 00:28:08 -0700
Subject: [PATCH 142/430] Change a bounds check to handle a packet instead of
letting it go.
This change reverts mod to line 1525 of GetDataHandlers.cs in
672d360e9dbe6c93997f4d17ac0f5e2c987db6ea by Deathamx.
We couldn't think of a reason why a bounds check would ever return
false, thus not handling the packet and letting the server accept
it. Therefore, it's now true.
In the future, we need to document handling better.
---
TShockAPI/Bouncer.cs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index dd1257db..5b802cef 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -59,8 +59,7 @@ namespace TShockAPI
{
if (args.ProjectileIndex > Main.maxProjectiles || args.ProjectileIndex < 0)
{
- // TODO: Should this be /true/ to stop the server from processing it?
- args.Handled = false;
+ args.Handled = true;
return;
}
From 1e233d15e72c1441029a59574e8da7dc708dae0d Mon Sep 17 00:00:00 2001
From: quake1337 <3310937+bartico6@users.noreply.github.com>
Date: Mon, 11 Dec 2017 15:33:53 +0100
Subject: [PATCH 143/430] Update submodule
---
TerrariaServerAPI | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index e76b7d18..faa3b956 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit e76b7d18175163cc9375361494ca6283113c4389
+Subproject commit faa3b95697bbf675503b2823c5f59593cf825bb3
From e19fd22fe0a5600af0c47c07eade94aff119f343 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 08:18:23 -0700
Subject: [PATCH 144/430] Change Utils.SearchProjectile to return -1 in error
Thanks for checking this out, @bartico6. Fixes #1549.
Note: this method only returns 1 because the game won't allocate
more identity/index combo. Apparently, according to RL.
---
TShockAPI/Utils.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 0ad2d0ad..3451f5f1 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -943,7 +943,7 @@ namespace TShockAPI
///
/// identity
/// owner
- /// projectile ID
+ /// projectile ID or -1 if not found
public int SearchProjectile(short identity, int owner)
{
for (int i = 0; i < Main.maxProjectiles; i++)
@@ -951,7 +951,7 @@ namespace TShockAPI
if (Main.projectile[i].identity == identity && Main.projectile[i].owner == owner)
return i;
}
- return 1000;
+ return -1;
}
///
From 5c9d2ed870c1254d4d2d38f062d22b6ceb504321 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 08:23:36 -0700
Subject: [PATCH 145/430] Simpler check (thanks @bartico6) on OPK's nullcheck.
---
TShockAPI/Bouncer.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 5b802cef..48613832 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -57,7 +57,7 @@ namespace TShockAPI
/// The packet arguments that the event has.
internal void OnProjectileKill(object sender, GetDataHandlers.ProjectileKillEventArgs args)
{
- if (args.ProjectileIndex > Main.maxProjectiles || args.ProjectileIndex < 0)
+ if (args.ProjectileIndex < 0)
{
args.Handled = true;
return;
From c1c57160068b5569aac9dc7fa801b41134198383 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Mon, 11 Dec 2017 16:26:19 +0100
Subject: [PATCH 146/430] update assembly company to Pryaxis
---
TShockAPI/Properties/AssemblyInfo.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Properties/AssemblyInfo.cs b/TShockAPI/Properties/AssemblyInfo.cs
index c5fc1426..9ebbdb5f 100644
--- a/TShockAPI/Properties/AssemblyInfo.cs
+++ b/TShockAPI/Properties/AssemblyInfo.cs
@@ -26,7 +26,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyTitle("TShock for Terraria")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Nyx Studios & TShock Contributors")]
+[assembly: AssemblyCompany("Pryaxis & TShock Contributors")]
[assembly: AssemblyProduct("TShockAPI")]
[assembly: AssemblyCopyright("Copyright © Nyx Studios 2011-2017")]
[assembly: AssemblyTrademark("")]
From bbabec6003bb17d5c140c470c20db9d2f8f7edc1 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Mon, 11 Dec 2017 16:29:37 +0100
Subject: [PATCH 147/430] update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d4eafb1d..d3ce77d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Fixed DumpItems() from trying to dump older versions of certain items (negative item IDs). (@Zaicon)
* Added the `/dump-reference-data` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
* Fixed builds to not require a specific version of OTAPI and to not fail when in Release mode (@bartico6)
+* Update Assembly Company to Pryaxis (@Ryozuki)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 903b5b124ecaaef164e1dec182bc3c8f4971395e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 10:04:21 -0700
Subject: [PATCH 148/430] Remove more randomly commented out code with no
apparent reason
---
TShockAPI/GetDataHandlers.cs | 10 ----------
1 file changed, 10 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 0ef703af..205bf0b7 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -3097,16 +3097,6 @@ namespace TShockAPI
{
var buff = args.Data.ReadInt8();
- /*if (TShock.Itembans.ItemBans.Any(s =>
- {
- Item item = new Item();
- item.SetDefaults(s.Name);
- return item.buffType == buff;
- }))
- {
- buff = 0;
- }*/
-
if (buff == 10 && TShock.Config.DisableInvisPvP && args.TPlayer.hostile)
buff = 0;
From b3928905519abaccfdbe9cd735ee13ed2fe0ba30 Mon Sep 17 00:00:00 2001
From: Ryozuki
Date: Mon, 11 Dec 2017 23:09:07 +0100
Subject: [PATCH 149/430] update copyright notice
---
TShockAPI/Properties/AssemblyInfo.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Properties/AssemblyInfo.cs b/TShockAPI/Properties/AssemblyInfo.cs
index 9ebbdb5f..f4030480 100644
--- a/TShockAPI/Properties/AssemblyInfo.cs
+++ b/TShockAPI/Properties/AssemblyInfo.cs
@@ -28,7 +28,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pryaxis & TShock Contributors")]
[assembly: AssemblyProduct("TShockAPI")]
-[assembly: AssemblyCopyright("Copyright © Nyx Studios 2011-2017")]
+[assembly: AssemblyCopyright("Copyright © Pryaxis & TShock Contributors 2011-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
From 4ea7d10482ee68a150339ae4f7c1f40c7a9cf52d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 15:45:23 -0700
Subject: [PATCH 150/430] Remove stupid updates permission. Fixes #1540.
---
TShockAPI/Permissions.cs | 3 ---
1 file changed, 3 deletions(-)
diff --git a/TShockAPI/Permissions.cs b/TShockAPI/Permissions.cs
index bad4148f..d4fb9229 100644
--- a/TShockAPI/Permissions.cs
+++ b/TShockAPI/Permissions.cs
@@ -125,9 +125,6 @@ namespace TShockAPI
[Description("User can reload the configurations file.")]
public static readonly string cfgreload = "tshock.cfg.reload";
- [Description("User can download updates to plugins that are currently running.")]
- public static readonly string updateplugins = "tshock.cfg.updateplugins";
-
[Description("User can create reference files of Terraria IDs and the permission matrix in the server folder.")]
public static readonly string createdumps = "tshock.cfg.createdumps";
From 611fb6b418d807e8539d19ac7068e7d24d93f11c Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 15:45:42 -0700
Subject: [PATCH 151/430] Remove /restart command. Fixes #1454.
---
TShockAPI/Commands.cs | 23 -----------------------
1 file changed, 23 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index b2f08d5f..4f2cba4c 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -366,10 +366,6 @@ namespace TShockAPI
{
HelpText = "Reloads the server configuration file."
});
- add(new Command(Permissions.maintenance, Restart, "restart")
- {
- HelpText = "Restarts the server."
- });
add(new Command(Permissions.cfgpassword, ServerPassword, "serverpassword")
{
HelpText = "Changes the server password."
@@ -1902,25 +1898,6 @@ namespace TShockAPI
TShock.Utils.StopServer(true, reason);
}
- private static void Restart(CommandArgs args)
- {
- if (TShock.NoRestart)
- {
- args.Player.SendErrorMessage("This command has been disabled.");
- return;
- }
-
- if (ServerApi.RunningMono)
- {
- TShock.Log.ConsoleInfo("Sorry, this command has not yet been implemented in Mono.");
- }
- else
- {
- string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
- TShock.Utils.RestartServer(true, reason);
- }
- }
-
private static void OffNoSave(CommandArgs args)
{
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
From 9cf949cc600841b1f129d00d047598654334b1f2 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 15:47:05 -0700
Subject: [PATCH 152/430] Update changelog
---
CHANGELOG.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3ce77d8..5b1e69d1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,8 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Added the `/dump-reference-data` command, which when run, runs Utils.Dump() and outputs Terraria reference data to the server folder. (@hakusaro)
* Fixed builds to not require a specific version of OTAPI and to not fail when in Release mode (@bartico6)
* Update Assembly Company to Pryaxis (@Ryozuki)
+* Removed `/restart` command. (@hakusaro)
+* Removed `Permissions.updateplugins` permission. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 12701e54bab1409fe4133a13544b4c457dceffb7 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 15:53:34 -0700
Subject: [PATCH 153/430] Update submodule again?
---
TerrariaServerAPI | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index bc9f7c69..faa3b956 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit bc9f7c69becb60816fc1e4587bbca15991231317
+Subproject commit faa3b95697bbf675503b2823c5f59593cf825bb3
From 3bed40ec65cc1066ca37ba52cb295bea70631d16 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 16:01:09 -0700
Subject: [PATCH 154/430] Remove Utils.RestartServer (thanks @QuiCM!)
---
TShockAPI/Utils.cs | 18 ------------------
1 file changed, 18 deletions(-)
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index e99aadd6..8314de92 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -580,24 +580,6 @@ namespace TShockAPI
Netplay.disconnect = true;
}
- ///
- /// Stops the server after kicking all players with a reason message, and optionally saving the world then attempts to
- /// restart it.
- ///
- /// bool perform a world save before stop (default: true)
- /// string reason (default: "Server shutting down!")
- public void RestartServer(bool save = true, string reason = "Server shutting down!")
- {
- if (Main.ServerSideCharacter)
- foreach (TSPlayer player in TShock.Players)
- if (player != null && player.IsLoggedIn && !player.IgnoreActionsForClearingTrashCan)
- TShock.CharacterDB.InsertPlayerData(player);
-
- StopServer(true, reason);
- System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
- Environment.Exit(0);
- }
-
///
/// Reloads all configuration settings, groups, regions and raises the reload event.
///
From 69eda3d38e4106bce65a320e7b136beb8706e670 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 16:09:03 -0700
Subject: [PATCH 155/430] Remove server restart rest routes
---
CHANGELOG.md | 1 +
TShockAPI/Rest/RestManager.cs | 21 ---------------------
2 files changed, 1 insertion(+), 21 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b1e69d1..fe9a120f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Update Assembly Company to Pryaxis (@Ryozuki)
* Removed `/restart` command. (@hakusaro)
* Removed `Permissions.updateplugins` permission. (@hakusaro)
+* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs
index 01341d46..636e0407 100644
--- a/TShockAPI/Rest/RestManager.cs
+++ b/TShockAPI/Rest/RestManager.cs
@@ -205,7 +205,6 @@ namespace TShockAPI
Rest.RegisterRedirect("/server/broadcast", "/v2/server/broadcast");
Rest.RegisterRedirect("/server/reload", "/v2/server/reload");
Rest.RegisterRedirect("/server/off", "/v2/server/off");
- Rest.RegisterRedirect("/server/restart", "/v3/server/restart");
Rest.RegisterRedirect("/server/rawcmd", "/v3/server/rawcmd");
//user commands
@@ -247,7 +246,6 @@ namespace TShockAPI
Rest.Register(new SecureRestCommand("/v2/server/broadcast", ServerBroadcast));
Rest.Register(new SecureRestCommand("/v3/server/reload", ServerReload, RestPermissions.restcfg));
Rest.Register(new SecureRestCommand("/v2/server/off", ServerOff, RestPermissions.restmaintenance));
- Rest.Register(new SecureRestCommand("/v3/server/restart", ServerRestart, RestPermissions.restmaintenance));
Rest.Register(new SecureRestCommand("/v3/server/rawcmd", ServerCommandV3, RestPermissions.restrawcommand));
Rest.Register(new SecureRestCommand("/tokentest", ServerTokenTest));
@@ -335,25 +333,6 @@ namespace TShockAPI
return RestResponse("The server is shutting down");
}
- [Description("Attempt to restart the server.")]
- [Route("/v3/server/restart")]
- [Permission(RestPermissions.restmaintenance)]
- [Noun("confirm", true, "Confirm that you actually want to restart the server", typeof(bool))]
- [Noun("message", false, "The shutdown message.", typeof(String))]
- [Noun("nosave", false, "Shutdown without saving.", typeof(bool))]
- [Token]
- private object ServerRestart(RestRequestArgs args)
- {
- if (!GetBool(args.Parameters["confirm"], false))
- return RestInvalidParam("confirm");
-
- // Inform players the server is shutting down
- var reason = string.IsNullOrWhiteSpace(args.Parameters["message"]) ? "Server is restarting" : args.Parameters["message"];
- TShock.Utils.RestartServer(!GetBool(args.Parameters["nosave"], false), reason);
-
- return RestResponse("The server is shutting down and will attempt to restart");
- }
-
[Description("Reload config files for the server.")]
[Route("/v3/server/reload")]
[Permission(RestPermissions.restcfg)]
From 98aa01c620137ee73c084dc4f41f7e8163f9fa0e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Mon, 11 Dec 2017 19:07:53 -0700
Subject: [PATCH 156/430] Add note about crash check & change reaosn on
OnKillMe
---
TShockAPI/Bouncer.cs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 48613832..2710fbd4 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -204,11 +204,12 @@ namespace TShockAPI
return;
}
+ // This was formerly marked as a crash check; does not actually crash on this specific packet.
if (playerDeathReason != null)
{
if (playerDeathReason.GetDeathText(TShock.Players[id].Name).ToString().Length > 500)
{
- TShock.Utils.Kick(TShock.Players[id], "Crash attempt", true);
+ TShock.Utils.Kick(TShock.Players[id], "Death reason outside of normal bounds.", true);
args.Handled = true;
return;
}
From 270cc4c481577abbed4b539ddb9a0733d823f3ae Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 12 Dec 2017 03:18:44 -0700
Subject: [PATCH 157/430] Update changelog for critical crash fix
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe9a120f..4f47ae8a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed `/restart` command. (@hakusaro)
* Removed `Permissions.updateplugins` permission. (@hakusaro)
* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
+* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
From 74eb680bffa737434ba622a64cac3e14c6feb316 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 12 Dec 2017 03:31:05 -0700
Subject: [PATCH 158/430] Really update the changelog properly this time
---
CHANGELOG.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f47ae8a..b3c1b788 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,8 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed `/restart` command. (@hakusaro)
* Removed `Permissions.updateplugins` permission. (@hakusaro)
* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
+
+## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
## TShock 4.3.24
From 45579e04b876f79a0f02d4db6cb0eabda2a1aa1d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Tue, 12 Dec 2017 22:29:02 -0700
Subject: [PATCH 159/430] Use svg for travis badge so we have retina images on
retina
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 2ad38b13..0f39a5d5 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
-
+
From 7d8a3c9b14e461d4bbc990c6673081297475632f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 18:28:35 -0700
Subject: [PATCH 160/430] Why does anyone use TShock?
---
README.md | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 0f39a5d5..defdb0fa 100644
--- a/README.md
+++ b/README.md
@@ -4,10 +4,17 @@
-[](#backers)
-[](#sponsors)
+TShock is a toolbox for Terraria servers and communities. TShock is trusted by hundreds of server owners to provide exploit patches, game updates, and more in a reliable and timely fashion.
-TShock is a server modification for Terraria, written in C#, and based upon the [Terraria Server API](https://github.com/NyxStudios/TerrariaAPI-Server). It uses JSON for configuration management, and offers several features not present in the Terraria Server normally.
+Why do people love TShock?
+
+* Server-side characters.
+ * Players can't cheat and hack-in items. They have to earn everything on the server.
+* Groups & Permissions
+ * Categorize who can do what. Give your donors special abilities, like infinite sand.
+* Customizable world settings
+ * Make Terraria your own with custom difficulty, spawn rates, regions, and more.
+* Fast acting bans and exploit defense make hackers have a bad time.
## :star: Quick Start
From 4fd525f839adfc93e896a9ec3c95517cf64a0869 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 18:53:20 -0700
Subject: [PATCH 161/430] Add basic new to tshock section
(The markdown preview system I'm using seems to be lying to me,
so I want to see what this looks like with gfm for one commit).
---
README.md | 60 ++++++++++++++++++++++++++++++++++---------------------
1 file changed, 37 insertions(+), 23 deletions(-)
diff --git a/README.md b/README.md
index defdb0fa..458bfb0c 100644
--- a/README.md
+++ b/README.md
@@ -1,36 +1,51 @@
-
-TShock is a toolbox for Terraria servers and communities. TShock is trusted by hundreds of server owners to provide exploit patches, game updates, and more in a reliable and timely fashion.
+TShock is a toolbox for Terraria servers and communities. That toolbox is jam packed with anti-cheat tools, server-side characters, groups, permissions, item bans, tons of commands, and limitless potential. It's one of a kind.
-Why do people love TShock?
+* Download: [Stable](https://github.com/TShock/TShock/releases) or [Experimental](https://travis.tshock.co/).
+* Read [the documentation](https://tshock.readme.io/) to quickly get up to speed.
+* Join [Discord](https://discord.gg/XUJdH58) to get help, chat, and enjoy some swell Australian company.
+* Download [other plugins](https://tshock.co/xf/index.php?resources/) to supercharge your server.
-* Server-side characters.
- * Players can't cheat and hack-in items. They have to earn everything on the server.
-* Groups & Permissions
- * Categorize who can do what. Give your donors special abilities, like infinite sand.
-* Customizable world settings
- * Make Terraria your own with custom difficulty, spawn rates, regions, and more.
-* Fast acting bans and exploit defense make hackers have a bad time.
+----
-## :star: Quick Start
+## Table of Contents
-https://tshock.readme.io/docs/getting-started
+ * New to TShock?(#new-to-tshock)
+ * Code of conduct(#code-of-conduct)
-## Features
+## New to TShock?
-* MySQL support
-* Permissions
-* Multiple administrators
-* Anti-cheat
-* User registration
-* Reserved slots
-* User punishment (kicking, banning, muting)
-* Server side characters
-* JSON based configuration management
+1. Download [the latest stable version](https://github.com/TShock/TShock/releases) and `unzip` the folder using your favorite unzip tool. Make sure that all of the files in the zip get into one folder. This is where your server will be stored. The file structure looks like this:
+
+
+ GeoIP.dat
+ Newtonsoft.Json.dll
+ OTAPI.dll
+ ServerPlugins\
+ |------BCrypt.Net.dll
+ |------HttpServer.dll
+ |------Mono.Data.Sqlite.dll
+ |------MySql.Data.dll
+ |------TShockAPI.dll
+ TerrariaServer.exe
+ sqlite3.dll
+
+
+1. Start `TerrariaServer.exe` and TShock will boot. Answer the startup questions, and you should be ready to roll. In the background, TShock made some folders for you. We'll come back to those later.
+
+1. Startup Terraria. Connect to a `multiplayer` server via IP and enter `localhost` if you're doing this on your local computer. If you're doing it on another computer, you need its IP address.
+
+1. Look at the server console for the _auth code_. Type `/auth [code]` (example: `/auth 12345`), then a space, then the code you see in the console in your game chat. Instead of chatting, you'll run a command on the server. This one makes you temporary admin. All commands are prefixed with `/` or `!` (to make them silent).
+
+1. Use the in-game command `/user add [username] [password] owner` (example: `/user add shank ashes owner`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later.
+
+1. Login to your newly created account with `/login [username] [password]` (example: `/login shank ashes`). You should see a login success message.
+
+1. Turn off the backdoor with `/auth` and your server is setup for initial use!
## Community
@@ -50,7 +65,6 @@ Please see the contributing file before sending pull requests.
## Download
-* [Github Releases](https://github.com/TShock/TShock/releases)
* [Development Builds](https://travis.tshock.co/)
* [Plugins](https://tshock.co/xf/index.php?resources/)
* [Very, very old versions of TShock](https://github.com/TShock/TShock/downloads)
From 486c6280197fbb6bceea76108c3f8ae3e1e7ae7c Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 18:55:07 -0700
Subject: [PATCH 162/430] How do Markdown links work?
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 458bfb0c..c7cff81c 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,8 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
## Table of Contents
- * New to TShock?(#new-to-tshock)
- * Code of conduct(#code-of-conduct)
+ * [New to TShock?](#new-to-tshock)
+ * [Code of Conduct](#code-of-conduct)
## New to TShock?
From 71bf0ed084f42210e68ba8dcaa014129578acf81 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 19:53:04 -0700
Subject: [PATCH 163/430] Segregate out code of conduct; commit temporary
changes for preview
---
.github/CODE_OF_CONDUCT.md | 3 +
README.md | 111 +++++++++++--------------------------
2 files changed, 34 insertions(+), 80 deletions(-)
create mode 100644 .github/CODE_OF_CONDUCT.md
diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md
new file mode 100644
index 00000000..4eacbbc4
--- /dev/null
+++ b/.github/CODE_OF_CONDUCT.md
@@ -0,0 +1,3 @@
+By participating in the TShock for Terraria community, all members will adhere to maintaining decorum with respect to all humans, in and out of the community. Members will not engage in discussion that inappropriately disparages or marginalizes any group of people or any individual. Members will not attempt to further or advance an agenda to the point of being overbearing or close minded (such as through spreading FUD). Members will not abuse services provided to them and will follow the guidance of community leaders on a situational basis about what abuse consists of. Members will adhere to United States and international law. If members notice a violation of this code of conduct, they will not engage but will instead contact the leadership team on either the forums or Discord.
+
+Do not attempt to circumvent or bypass the code of conduct by using clever logic or reasoning (e.g., insulting Facepunch members, because they weren't directly mentioned here).
\ No newline at end of file
diff --git a/README.md b/README.md
index c7cff81c..19307d5a 100644
--- a/README.md
+++ b/README.md
@@ -15,10 +15,12 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
## Table of Contents
* [New to TShock?](#new-to-tshock)
- * [Code of Conduct](#code-of-conduct)
+ * [Developer's Guide](#developers-guide)
## New to TShock?
+_These instructions assume Windows. If you're setting up on Linux or macOS, please refer to [the in-depth guide](https://tshock.readme.io/docs/getting-started) (and don't forget to install the *latest version* of `mono-complete` on Linux)._
+
1. Download [the latest stable version](https://github.com/TShock/TShock/releases) and `unzip` the folder using your favorite unzip tool. Make sure that all of the files in the zip get into one folder. This is where your server will be stored. The file structure looks like this:
@@ -41,100 +43,49 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
1. Look at the server console for the _auth code_. Type `/auth [code]` (example: `/auth 12345`), then a space, then the code you see in the console in your game chat. Instead of chatting, you'll run a command on the server. This one makes you temporary admin. All commands are prefixed with `/` or `!` (to make them silent).
-1. Use the in-game command `/user add [username] [password] owner` (example: `/user add shank ashes owner`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later.
+1. Use the in-game command `/register [password]` (example: `/register lovely-ashes`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later. Your `character name` is your `account name`.
1. Login to your newly created account with `/login [username] [password]` (example: `/login shank ashes`). You should see a login success message.
-1. Turn off the backdoor with `/auth` and your server is setup for initial use!
+1. Turn off the backdoor with `/auth-verify` and your server is setup for initial use. TShock also created several files inside a new `tshock` folder. These files include `config.json` (our big configuration file), `sscconfig.json` (the server side characters configuration file), and `tshock.sqlite`. Don't lose your `tshock.sqlite` or you'll have to re-setup TShock all over again.
-## Community
+1. You can now [customize your configuration](https://tshock.readme.io/docs/config-settings), build groups, ban items, and install more plugins.
-Feeling like helping out? Want to find an awesome server? Some awesome plugins?
+## Developer's Guide
-* [Website & Forums](https://tshock.co/xf/)
-* [Contribute to our docs on readme.io](https://tshock.readme.io/)
-* [Join our Discord chat (supports Android, iOS, Web, Mac, and Windows)](https://discord.gg/XUJdH58)
+Whether you want to contribute to TShock by sending a pull request, customize it to suit your own elfish desires, or want to build your own plugin, this is the best starting point. By the end of this, you'll be able to build TShock from source, start to finish. More than that, though, you'll know how to start on the path of becoming an expert TShock developer.
-### Code of Conduct
+But first, you need some background.
-> By participating in the TShock for Terraria community, all members will adhere to maintaining decorum with respect to all humans, in and out of the community. Members will not engage in discussion that inappropriately disparages or marginalizes any group of people or any individual. Members will not attempt to further or advance an agenda to the point of being overbearing or close minded (such as through spreading FUD). Members will not abuse services provided to them and will follow the guidance of community leaders on a situational basis about what abuse consists of. Members will adhere to United States and international law. If members notice a violation of this code of conduct, they will not engage but will instead contact the leadership team on either the forums or Discord.
+### Background
-> Do not attempt to circumvent or bypass the code of conduct by using clever logic or reasoning (e.g., insulting Facepunch members, because they weren't directly mentioned here).
+Terraria is a C# application written on the .NET framework using the XNA game framework. TShock is a mod for Terraria's server, which is also written in C# on the .NET framework. Some might compare TShock to hMod in the Minecraft world (the precursor to Bukkit and its server, CraftBukkit). This is a good comparison to make in how the underlying build process works. When the project started, TShock was injected directly into the decompiled source code for Terraria. Unlike Minecraft, Terraria is not obfuscated, which means that many variable names and inner workings are sanely-named out of the box. Now, TShock uses advanced techniques to operate.
-Please see the contributing file before sending pull requests.
+TShock is, first and foremost, a plugin written for the server variant of the Terraria API, an unofficial construct originally built by `bladecoding`. `TShock` has been colloquially used to refer to both the plugin as well as the server and plugin together. Similarly, the Terraria API's client version was abandoned long ago, and development of the `Server` API led to the abbreviation `TSAPI`, for `Terraria Server API`. The plugin `TShock` is executed by the [Terraria Server API](https://github.com/Pryaxis/TerrariaAPI-Server), which is in turn bound to the `Open Terraria API`, more commonly `OTAPI`. The [Open Terraria API](https://github.com/DeathCradle/Open-Terraria-API) is maintained by [DeathCradle](https://github.com/DeathCradle).
-## Download
+Now, the way that `TShock` runs on `TSAPI` through `OTAPI` can be summarized as the following:
-* [Development Builds](https://travis.tshock.co/)
-* [Plugins](https://tshock.co/xf/index.php?resources/)
-* [Very, very old versions of TShock](https://github.com/TShock/TShock/downloads)
+1. The Open Terraria API deeply integrates with Terraria by modifying the official server's binary directly. This is done through rewriting the Terraria bytecode, the [CIL code](https://en.wikipedia.org/wiki/Common_Intermediate_Language), using a patching tool designed by DeathCradle and tools from the Mono project. For `TSAPI`, additional modifications are done to support TSAPI specific features. This done through the `TShock Mintaka Patcher`.
+2. The `Terraria Server API` uses hooks provided by `OTAPI` to provide higher level hooks as well as legacy hooks for existing TSAPI applications.
+3. `TShock` is executed by `TSAPI`, uses hooks provided by both `TSAPI` and `OTAPI`, and provides even higher level hooks and support tools to other `TSAPI` plugins.
-## Backers
+With all of this in mind, the primary goal when compiling TShock is to remember that only the second and third layers are required to be interacted with. The first layer, `OTAPI`, is provided pre-compiled through NuGet. The second layer, `TSAPI`, is provided in the `TShock` repository through a git submodule.
-Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/tshock#backer)]
+Let's get started.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+## Building
-## Sponsors
+You need to get the source code. Using git, [clone this repository](https://help.github.com/articles/cloning-a-repository/).
-Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/tshock#sponsor)]
+The next set of instructions are the technical details to setup both the Terraria Server API and TShock. More importantly, the Terraria API steps here are written under the assumption that you are building TShock primarily. Before you start, you need to **initialize the git submodules** and then **update them**. You can do this in a graphical git client, or use the following commands.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ $ git submodule init
+ $ git submodule update
+
+### On Windows
+
+#### The Terraria Server API
+
+
+
+####
From 142c338c1a7a59eb090a759cea9a1f02c35e280a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 19:58:29 -0700
Subject: [PATCH 164/430] It turns out "elvish" is spelled "elvish" not
"elfish"
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 19307d5a..989869fc 100644
--- a/README.md
+++ b/README.md
@@ -53,7 +53,7 @@ _These instructions assume Windows. If you're setting up on Linux or macOS, plea
## Developer's Guide
-Whether you want to contribute to TShock by sending a pull request, customize it to suit your own elfish desires, or want to build your own plugin, this is the best starting point. By the end of this, you'll be able to build TShock from source, start to finish. More than that, though, you'll know how to start on the path of becoming an expert TShock developer.
+Whether you want to contribute to TShock by sending a pull request, customize it to suit your own elvish desires, or want to build your own plugin, this is the best starting point. By the end of this, you'll be able to build TShock from source, start to finish. More than that, though, you'll know how to start on the path of becoming an expert TShock developer.
But first, you need some background.
@@ -69,7 +69,7 @@ Now, the way that `TShock` runs on `TSAPI` through `OTAPI` can be summarized as
2. The `Terraria Server API` uses hooks provided by `OTAPI` to provide higher level hooks as well as legacy hooks for existing TSAPI applications.
3. `TShock` is executed by `TSAPI`, uses hooks provided by both `TSAPI` and `OTAPI`, and provides even higher level hooks and support tools to other `TSAPI` plugins.
-With all of this in mind, the primary goal when compiling TShock is to remember that only the second and third layers are required to be interacted with. The first layer, `OTAPI`, is provided pre-compiled through NuGet. The second layer, `TSAPI`, is provided in the `TShock` repository through a git submodule.
+With all of this in mind, the primary goal when compiling TShock is to remember that only the second and third layers are required to be interacted with. The first layer, `OTAPI`, is provided pre-compiled through NuGet. The second layer, `TSAPI`, is provided in the `TShock` repository through a git submodule. It's primary home is the [Terraria Server API repository](https://github.com/Pryaxis/TerrariaAPI-Server).
Let's get started.
From 7221d66dd07407bcd4c156a6946b9d2075e2c2fd Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 21:54:00 -0700
Subject: [PATCH 165/430] Update the instructions for Windows (fully!)
---
README.md | 34 +++++++++++++++++++++++++++++-----
1 file changed, 29 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index 989869fc..778f3ebd 100644
--- a/README.md
+++ b/README.md
@@ -73,19 +73,43 @@ With all of this in mind, the primary goal when compiling TShock is to remember
Let's get started.
-## Building
+### Building
You need to get the source code. Using git, [clone this repository](https://help.github.com/articles/cloning-a-repository/).
-The next set of instructions are the technical details to setup both the Terraria Server API and TShock. More importantly, the Terraria API steps here are written under the assumption that you are building TShock primarily. Before you start, you need to **initialize the git submodules** and then **update them**. You can do this in a graphical git client, or use the following commands.
+The next set of instructions are the technical details to setup both the Terraria Server API and TShock. More importantly, the Terraria API steps here are written under the assumption that you are building TShock primarily. Before you start, you need to **initialize the git submodules** and then **update them**. You need to use the following commands to do this.
$ git submodule init
$ git submodule update
-### On Windows
+If you're using [GitHub Desktop](https://desktop.github.com), you need to perform additional steps. After cloning the TShock repository, go to the `Repository` menu and select `Open in Command Prompt`. If you don't have Git (not GitHub Desktop) installed, you can follow the prompts to to install Git for your command line. Once Git is installed, use this same process to get to the command prompt. Then, run the above commands.
-#### The Terraria Server API
+#### On Windows
+On Windows, you need to install [Visual Studio Community Edition](https://www.visualstudio.com/downloads/) or a better (more expensive) version of Visual Studio.
+##### The Terraria Server API
-####
+1. Open the `TShock.4.OTAPI.sln` solution in the `TerrariaServerAPI` folder.
+
+1. Set the `TShock.Modifications.Bootstrapper` project as the StartUp project, then build the solution.
+
+1. Build the solution in either debug or release mode, depending on your preference. NuGet will automatically fetch the appropriate packages as a result of its magical powers.
+
+1. Hit the "Start" button in Visual Studio to run the `TShock Mintaka Bootstrapper`.
+
+1. Watch the output window and make sure that a non-zero number of modifications ran. When it completes, you have successfully bootstrapped `TShock Mintaka`.
+
+1. Set the `TerrariaServerAPI` project as the StartUp project.
+
+1. Build the solution in either debug or release mode, depending on your preference.
+
+1. Close `TShock.4.OTAPI.sln` in Visual Studio.
+
+You need to do re-run the patcher any time OTAPI updates. You need to rebuild `TerrariaServerAPI` any time that the submodule in `TShock` gets changed, if you're doing this from inside the TShock repo. You also need to update the submodules (`git submodule update`) if they're out of date on a pull too.
+
+##### TShock
+
+1. Open the `TShockAPI.sln` solution in the root of the repository.
+
+1. Build the solution. It should correctly download NuGet packages automatically and build against the aforementioned `TerrariaServerAPI` project you just built.
From e4fdee317cb56ebaedb0b8179f345b04e47051bb Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 22:30:00 -0700
Subject: [PATCH 166/430] Commit changes before switching branches
---
README.md | 50 +++++++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 45 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index 778f3ebd..472a0dfd 100644
--- a/README.md
+++ b/README.md
@@ -45,9 +45,9 @@ _These instructions assume Windows. If you're setting up on Linux or macOS, plea
1. Use the in-game command `/register [password]` (example: `/register lovely-ashes`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later. Your `character name` is your `account name`.
-1. Login to your newly created account with `/login [username] [password]` (example: `/login shank ashes`). You should see a login success message.
+1. Login to your newly created account with `/login [account name] [password]` (example: `/login shank lovely-ashes`). You should see a login success message.
-1. Turn off the backdoor with `/auth-verify` and your server is setup for initial use. TShock also created several files inside a new `tshock` folder. These files include `config.json` (our big configuration file), `sscconfig.json` (the server side characters configuration file), and `tshock.sqlite`. Don't lose your `tshock.sqlite` or you'll have to re-setup TShock all over again.
+1. Turn off the setup system with `/auth-verify` and your server is setup for initial use. TShock also created several files inside a new `tshock` folder. These files include `config.json` (our big configuration file), `sscconfig.json` (the server side characters configuration file), and `tshock.sqlite`. Don't lose your `tshock.sqlite` or you'll have to re-setup TShock.
1. You can now [customize your configuration](https://tshock.readme.io/docs/config-settings), build groups, ban items, and install more plugins.
@@ -69,7 +69,7 @@ Now, the way that `TShock` runs on `TSAPI` through `OTAPI` can be summarized as
2. The `Terraria Server API` uses hooks provided by `OTAPI` to provide higher level hooks as well as legacy hooks for existing TSAPI applications.
3. `TShock` is executed by `TSAPI`, uses hooks provided by both `TSAPI` and `OTAPI`, and provides even higher level hooks and support tools to other `TSAPI` plugins.
-With all of this in mind, the primary goal when compiling TShock is to remember that only the second and third layers are required to be interacted with. The first layer, `OTAPI`, is provided pre-compiled through NuGet. The second layer, `TSAPI`, is provided in the `TShock` repository through a git submodule. It's primary home is the [Terraria Server API repository](https://github.com/Pryaxis/TerrariaAPI-Server).
+With all of this in mind, the primary goal when compiling TShock is to remember that only the second and third layers are required to be interacted with. The first layer, `OTAPI`, is provided pre-compiled through NuGet. The second layer, `TSAPI`, is provided in the `TShock` repository through a git submodule. Its primary home is the [Terraria Server API repository](https://github.com/Pryaxis/TerrariaAPI-Server).
Let's get started.
@@ -92,7 +92,7 @@ On Windows, you need to install [Visual Studio Community Edition](https://www.vi
1. Open the `TShock.4.OTAPI.sln` solution in the `TerrariaServerAPI` folder.
-1. Set the `TShock.Modifications.Bootstrapper` project as the StartUp project, then build the solution.
+1. Set the `TShock.Modifications.Bootstrapper` project as the StartUp project.
1. Build the solution in either debug or release mode, depending on your preference. NuGet will automatically fetch the appropriate packages as a result of its magical powers.
@@ -106,10 +106,50 @@ On Windows, you need to install [Visual Studio Community Edition](https://www.vi
1. Close `TShock.4.OTAPI.sln` in Visual Studio.
-You need to do re-run the patcher any time OTAPI updates. You need to rebuild `TerrariaServerAPI` any time that the submodule in `TShock` gets changed, if you're doing this from inside the TShock repo. You also need to update the submodules (`git submodule update`) if they're out of date on a pull too.
+You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `TerrariaServerAPI` any time that the submodule in `TShock` gets changed, if you're doing this from inside the TShock repo. You also need to update the submodules (`git submodule update`) if they're out of date on a pull too.
##### TShock
1. Open the `TShockAPI.sln` solution in the root of the repository.
1. Build the solution. It should correctly download NuGet packages automatically and build against the aforementioned `TerrariaServerAPI` project you just built.
+
+#### On macOS
+
+1. Install [Homebrew](https://brew.sh) if you haven't already.
+
+1. Install mono:
+
+ $ brew install mono
+
+1. Verify that mono is available:
+
+ $ mono --version
+
+ Mono JIT compiler version 5.0.1.1 (2017-02/5077205 Sun Sep 17 18:29:46 BST 2017)
+ ...
+
+1. Proceed to the [unix build steps](#unix-build-steps) to continue.
+
+#### On Linux
+
+1. **DO NOT** just install mono from your package manager unless told to do so. If you do and it's out of date, you probably won't be able to successfully develop for TShock.
+
+1. Follow the [official install instructions for mono](http://www.mono-project.com/download/). **DO** install `mono-complete` or you're missing components.
+
+#### On Unix
+
+1. You need to get NuGet. Download the latest `nuget.exe` from [NuGet](https://www.nuget.org/downloads).
+
+1. Make a `~/bin` folder if you don't have one.
+
+ $ mkdir ~/bin/
+
+##### The Terraria Server API
+
+1. Move into the `TerrariaServerAPI` project and then perform a NuGet restore.
+
+ $ cd ./TerrariaServerAPI/
+ $ mono ~/bin/nuget.exe restore
+
+1.
\ No newline at end of file
From 8451ef9fb77d76cf63da4c67263d8f9d5dcca99b Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 22:38:44 -0700
Subject: [PATCH 167/430] Switch the "auth system" to "initial system"
everywhere.
This is better verbiage. If you think about it, you never really
want the "authentication system" to shut off. Doesn't that mean
that the server doesn't authenticate people anymore?
---
TShockAPI/Commands.cs | 36 ++++++++++++++++++------------------
TShockAPI/TShock.cs | 40 ++++++++++++++++++++--------------------
2 files changed, 38 insertions(+), 38 deletions(-)
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 4f2cba4c..1d8545ca 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -220,7 +220,7 @@ namespace TShockAPI
ChatCommands.Add(cmd);
};
- add(new Command(AuthToken, "auth")
+ add(new Command(SetupToken, "setup")
{
AllowServer = false,
HelpText = "Used to authenticate as superadmin when first setting up TShock."
@@ -4736,7 +4736,7 @@ namespace TShockAPI
}
IEnumerable cmdNames = from cmd in ChatCommands
- where cmd.CanRun(args.Player) && (cmd.Name != "auth" || TShock.AuthToken != 0)
+ where cmd.CanRun(args.Player) && (cmd.Name != "auth" || TShock.SetupToken != 0)
select Specifier + cmd.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames),
@@ -4829,17 +4829,17 @@ namespace TShockAPI
);
}
- private static void AuthToken(CommandArgs args)
+ private static void SetupToken(CommandArgs args)
{
- if (TShock.AuthToken == 0)
+ if (TShock.SetupToken == 0)
{
if (args.Player.Group.Name == new SuperAdminGroup().Name)
- args.Player.SendInfoMessage("The auth system is already disabled.");
+ args.Player.SendInfoMessage("The initial setup system is already disabled.");
else
{
- args.Player.SendWarningMessage("The auth system is disabled. This incident has been logged.");
- TShock.Utils.ForceKick(args.Player, "Auth system is disabled.", true, true);
- TShock.Log.Warn("{0} attempted to use {1}auth even though it's disabled.", args.Player.IP, Specifier);
+ args.Player.SendWarningMessage("The initial setup system is disabled. This incident has been logged.");
+ TShock.Utils.ForceKick(args.Player, "The initial setup system is disabled.", true, true);
+ TShock.Log.Warn("{0} attempted to use the initial setup system even though it's disabled.", args.Player.IP);
return;
}
}
@@ -4847,28 +4847,28 @@ namespace TShockAPI
// If the user account is already a superadmin (permanent), disable the system
if (args.Player.IsLoggedIn && args.Player.tempGroup == null && args.Player.Group.Name == new SuperAdminGroup().Name)
{
- args.Player.SendSuccessMessage("Your new account has been verified, and the {0}auth system has been turned off.", Specifier);
+ args.Player.SendSuccessMessage("Your new account has been verified, and the {0}setup system has been turned off.", Specifier);
args.Player.SendSuccessMessage("You can always use the {0}user command to manage players.", Specifier);
- args.Player.SendSuccessMessage("The auth system will remain disabled as long as a superadmin exists (even if you delete auth.lck).");
+ args.Player.SendSuccessMessage("The setup system will remain disabled as long as a superadmin exists (even if you delete setup.lock).");
args.Player.SendSuccessMessage("Share your server, talk with other admins, and more on our forums -- https://tshock.co/");
args.Player.SendSuccessMessage("Thank you for using TShock for Terraria!");
- FileTools.CreateFile(Path.Combine(TShock.SavePath, "auth.lck"));
- File.Delete(Path.Combine(TShock.SavePath, "authcode.txt"));
- TShock.AuthToken = 0;
+ FileTools.CreateFile(Path.Combine(TShock.SavePath, "setup.lock"));
+ File.Delete(Path.Combine(TShock.SavePath, "setup-code.txt"));
+ TShock.SetupToken = 0;
return;
}
if (args.Parameters.Count == 0)
{
- args.Player.SendErrorMessage("You must provide an auth code!");
+ args.Player.SendErrorMessage("You must provide a setup code!");
return;
}
int givenCode;
- if (!Int32.TryParse(args.Parameters[0], out givenCode) || givenCode != TShock.AuthToken)
+ if (!Int32.TryParse(args.Parameters[0], out givenCode) || givenCode != TShock.SetupToken)
{
- args.Player.SendErrorMessage("Incorrect auth code. This incident has been logged.");
- TShock.Log.Warn(args.Player.IP + " attempted to use an incorrect auth code.");
+ args.Player.SendErrorMessage("Incorrect setup code. This incident has been logged.");
+ TShock.Log.Warn(args.Player.IP + " attempted to use an incorrect setup code.");
return;
}
@@ -4880,7 +4880,7 @@ namespace TShockAPI
args.Player.SendInfoMessage("{0}user add owner", Specifier);
args.Player.SendInfoMessage("Creates: with the password as part of the owner group.");
args.Player.SendInfoMessage("Please use {0}login after this process.", Specifier);
- args.Player.SendInfoMessage("If you understand, please {0}login now, and then type {0}auth.", Specifier);
+ args.Player.SendInfoMessage("If you understand, please {0}login now, and then type {0}setup.", Specifier);
return;
}
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 5d59dc8a..405cd887 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -841,8 +841,8 @@ namespace TShockAPI
CliParser.ParseFromSource(parms);
}
- /// AuthToken - The auth token used by the /auth system to grant temporary superadmin access to new admins.
- public static int AuthToken = -1;
+ /// SetupToken - The auth token used by the setup system to grant temporary superadmin access to new admins.
+ public static int SetupToken = -1;
private string _cliPassword = null;
/// OnPostInit - Fired when the server loads a map, to perform world specific operations.
@@ -861,41 +861,41 @@ namespace TShockAPI
Config.ServerPassword = _cliPassword;
}
- // Disable the auth system if "auth.lck" is present or a superadmin exists
- if (File.Exists(Path.Combine(SavePath, "auth.lck")) || UserAccounts.GetUserAccounts().Exists(u => u.Group == new SuperAdminGroup().Name))
+ // Disable the auth system if "setup.lock" is present or a superadmin exists
+ if (File.Exists(Path.Combine(SavePath, "setup.lock")) || UserAccounts.GetUserAccounts().Exists(u => u.Group == new SuperAdminGroup().Name))
{
- AuthToken = 0;
+ SetupToken = 0;
- if (File.Exists(Path.Combine(SavePath, "authcode.txt")))
+ if (File.Exists(Path.Combine(SavePath, "setup-code.txt")))
{
- Log.ConsoleInfo("A superadmin account has been detected in the user database, but authcode.txt is still present.");
- Log.ConsoleInfo("TShock will now disable the auth system and remove authcode.txt as it is no longer needed.");
- File.Delete(Path.Combine(SavePath, "authcode.txt"));
+ Log.ConsoleInfo("A superadmin account has been detected in the user database, but setup-code.txt is still present.");
+ Log.ConsoleInfo("TShock will now disable the initial setup system and remove setup-code.txt as it is no longer needed.");
+ File.Delete(Path.Combine(SavePath, "setup-code.txt"));
}
- if (!File.Exists(Path.Combine(SavePath, "auth.lck")))
+ if (!File.Exists(Path.Combine(SavePath, "setup.lock")))
{
// This avoids unnecessary database work, which can get ridiculously high on old servers as all users need to be fetched
- File.Create(Path.Combine(SavePath, "auth.lck"));
+ File.Create(Path.Combine(SavePath, "setup.lock"));
}
}
- else if (!File.Exists(Path.Combine(SavePath, "authcode.txt")))
+ else if (!File.Exists(Path.Combine(SavePath, "setup-code.txt")))
{
var r = new Random((int)DateTime.Now.ToBinary());
- AuthToken = r.Next(100000, 10000000);
+ SetupToken = r.Next(100000, 10000000);
Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("TShock Notice: To become SuperAdmin, join the game and type {0}auth {1}", Commands.Specifier, AuthToken);
- Console.WriteLine("This token will display until disabled by verification. ({0}auth)", Commands.Specifier);
+ Console.WriteLine("To setup the server, join the game and type {0}setup {1}", Commands.Specifier, SetupToken);
+ Console.WriteLine("This token will display until disabled by verification. ({0}setup)", Commands.Specifier);
Console.ResetColor();
- File.WriteAllText(Path.Combine(SavePath, "authcode.txt"), AuthToken.ToString());
+ File.WriteAllText(Path.Combine(SavePath, "setup-code.txt"), SetupToken.ToString());
}
else
{
- AuthToken = Convert.ToInt32(File.ReadAllText(Path.Combine(SavePath, "authcode.txt")));
+ SetupToken = Convert.ToInt32(File.ReadAllText(Path.Combine(SavePath, "setup-code.txt")));
Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used.");
- Console.WriteLine("To become superadmin, join the game and type {0}auth {1}", Commands.Specifier, AuthToken);
- Console.WriteLine("This token will display until disabled by verification. ({0}auth)", Commands.Specifier);
+ Console.WriteLine("TShock Notice: setup-code.txt is still present, and the code located in that file will be used.");
+ Console.WriteLine("To setup the server, join the game and type {0}setup {1}", Commands.Specifier, SetupToken);
+ Console.WriteLine("This token will display until disabled by verification. ({0}setup)", Commands.Specifier);
Console.ResetColor();
}
From 0826a37fe8f88775f6c75b62814bf9161a5951bd Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 22:41:00 -0700
Subject: [PATCH 168/430] Update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3c1b788..ad484a17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed `/restart` command. (@hakusaro)
* Removed `Permissions.updateplugins` permission. (@hakusaro)
* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
+* The "auth system" is now referred to as the initial setup system (what it actually is). This is better verbiage for basically all situations. Who really wants to turn off the "authentication system?" In addition, the system now makes it more clear what the point of it is, rather than that it grants permissions. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
From ffdcd34c9109df66a2ca920c35251fc5b0e174d3 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 22:45:41 -0700
Subject: [PATCH 169/430] Fix issue where setup system could re-enable itself
The current initial setup system would re-enable if setup.lock
was removed even if an account was in the database. This is
because when we switched to "owner" being the primary target
of the setup system, we failed to anticipate that an account with
superadmin would never exist in the database in an ideal
condition.
---
TShockAPI/TShock.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 405cd887..eeec18c1 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -861,8 +861,8 @@ namespace TShockAPI
Config.ServerPassword = _cliPassword;
}
- // Disable the auth system if "setup.lock" is present or a superadmin exists
- if (File.Exists(Path.Combine(SavePath, "setup.lock")) || UserAccounts.GetUserAccounts().Exists(u => u.Group == new SuperAdminGroup().Name))
+ // Disable the auth system if "setup.lock" is present or a user account already exists
+ if (File.Exists(Path.Combine(SavePath, "setup.lock")) || (UserAccounts.GetUserAccounts().Count() > 0))
{
SetupToken = 0;
From d6dfbe4e7d1bd1e70de63f854a5989f43bea85ef Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 23:07:03 -0700
Subject: [PATCH 170/430] Updated readme with new setup system stuff
---
README.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 472a0dfd..11126856 100644
--- a/README.md
+++ b/README.md
@@ -41,13 +41,13 @@ _These instructions assume Windows. If you're setting up on Linux or macOS, plea
1. Startup Terraria. Connect to a `multiplayer` server via IP and enter `localhost` if you're doing this on your local computer. If you're doing it on another computer, you need its IP address.
-1. Look at the server console for the _auth code_. Type `/auth [code]` (example: `/auth 12345`), then a space, then the code you see in the console in your game chat. Instead of chatting, you'll run a command on the server. This one makes you temporary admin. All commands are prefixed with `/` or `!` (to make them silent).
+1. Look at the server console for the _setup code_. Type `/setup [code]` (example: `/setup 12345`), then a space, then the code you see in the console in your game chat. Instead of chatting, you'll run a command on the server. This one makes you temporary admin. All commands are prefixed with `/` or `!` (to make them silent).
1. Use the in-game command `/register [password]` (example: `/register lovely-ashes`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later. Your `character name` is your `account name`.
1. Login to your newly created account with `/login [account name] [password]` (example: `/login shank lovely-ashes`). You should see a login success message.
-1. Turn off the setup system with `/auth-verify` and your server is setup for initial use. TShock also created several files inside a new `tshock` folder. These files include `config.json` (our big configuration file), `sscconfig.json` (the server side characters configuration file), and `tshock.sqlite`. Don't lose your `tshock.sqlite` or you'll have to re-setup TShock.
+1. Turn off the setup system with `/setup` and your server is setup for initial use. TShock also created several files inside a new `tshock` folder. These files include `config.json` (our big configuration file), `sscconfig.json` (the server side characters configuration file), and `tshock.sqlite`. Don't lose your `tshock.sqlite` or you'll have to re-setup TShock.
1. You can now [customize your configuration](https://tshock.readme.io/docs/config-settings), build groups, ban items, and install more plugins.
From b6bc57745f883f91fdf82f9150d5fcc61989a602 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 23:08:43 -0700
Subject: [PATCH 171/430] Alnitak is a star in the constellation Orion, part of
Orion's Belt
---
TShockAPI/TShock.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 5d59dc8a..43d1e56c 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -57,7 +57,7 @@ namespace TShockAPI
/// VersionNum - The version number the TerrariaAPI will return back to the API. We just use the Assembly info.
public static readonly Version VersionNum = Assembly.GetExecutingAssembly().GetName().Version;
/// VersionCodename - The version codename is displayed when the server starts. Inspired by software codenames conventions.
- public static readonly string VersionCodename = "Mintaka";
+ public static readonly string VersionCodename = "Alnitak";
/// SavePath - This is the path TShock saves its data in. This path is relative to the TerrariaServer.exe (not in ServerPlugins).
public static string SavePath = "tshock";
From 3188f5d1eac362cd2311add63300336b4a05cef9 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 23:40:48 -0700
Subject: [PATCH 172/430] Finish dev docs for building; need to check anchor
links live
---
README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 50 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 11126856..932d508a 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,16 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
* [New to TShock?](#new-to-tshock)
* [Developer's Guide](#developers-guide)
+ * [Background](#background)
+ * [Building](#building)
+ * [On Windows](#on-windows)
+ * [The Terraria Server API](#the-terraria-server-api-1)
+ * [TShock](#tshock-1)
+ * [On macOS](#on-macos)
+ * [On Linux](#on-linux)
+ * [On Unix](#on-unix)
+ * [The Terraria Server API](#the-terraria-server-api-2)
+ * [TShock](#tshock-2)
## New to TShock?
@@ -145,11 +155,48 @@ You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `Te
$ mkdir ~/bin/
+1. Set an environment variable to store if you plan to build in debug or release.
+
+ $ export BUILD_MODE=Debug
+
+ or
+
+ $ export BUILD_MODE=Release
+
+
##### The Terraria Server API
-1. Move into the `TerrariaServerAPI` project and then perform a NuGet restore.
+1. Perform a NuGet restore in the directory above `TerrariaServerAPI`.
+
+ $ mono ~/bin/nuget.exe restore ./TerrariaServerAPI/
+
+1. Build the `TShock.4.OTAPI.sln` solution the configuration you chose:
+
+ $ xbuild ./TerrariaServerAPI/TShock.4.OTAPI.sln /p:Configuration=$BUILD_MODE
+
+1. Run the `TShock Mintaka Bootstrapper` with the TShock modifications. If you don't use `/bin/bash` as your primary shell, you might want to temporarily switch to it, or the bootstrapper may fail.
+
+ $ cd ./TerrariaServerAPI/TShock.Modifications.Bootstrapper/bin/$BUILD_MODE/
+ $ mono TShock.Modifications.Bootstrapper.exe -in=OTAPI.dll \
+ -mod=../../../TShock.Modifications.**/bin/$BUILD_MODE/TShock.Modifications.*.dll \
+ -o=Output/OTAPI.dll
+
+1. Verify that non-zero modifications ran successfully. Then, build the Terraria Server API executable.
+
+ $ cd ./../../../
+ $ xbuild ./TerrariaServerAPI/TerrariaServerAPI/TerrariaServerAPI.csproj \
+ /p:Configuration=$BUILD_MODE
+
+You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `TerrariaServerAPI` any time that the submodule in `TShock` gets changed, if you're doing this from inside the TShock repo. You also need to update the submodules (`git submodule update`) if they're out of date on a pull too.
+
+##### TShock
+
+1. Perform a NuGet restore in `TShockAPI` folder that contains `TShockAPI.sln`.
- $ cd ./TerrariaServerAPI/
$ mono ~/bin/nuget.exe restore
-1.
\ No newline at end of file
+1. Build TShock in the `BUILD_MODE` you set earlier.
+
+ $ xbuild ./TShockAPI.sln /p:Configuration=
+
+You're done!
\ No newline at end of file
From 25c67c5d7cdff8634a9599301bcd457aa6132a12 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 23:42:38 -0700
Subject: [PATCH 173/430] Fix anchors on the readme
---
README.md | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/README.md b/README.md
index 932d508a..d6e4c018 100644
--- a/README.md
+++ b/README.md
@@ -19,13 +19,13 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
* [Background](#background)
* [Building](#building)
* [On Windows](#on-windows)
- * [The Terraria Server API](#the-terraria-server-api-1)
- * [TShock](#tshock-1)
+ * [The Terraria Server API](#the-terraria-server-api)
+ * [TShock](#tshock)
* [On macOS](#on-macos)
* [On Linux](#on-linux)
* [On Unix](#on-unix)
- * [The Terraria Server API](#the-terraria-server-api-2)
- * [TShock](#tshock-2)
+ * [The Terraria Server API](#the-terraria-server-api-1)
+ * [TShock](#tshock-1)
## New to TShock?
@@ -197,6 +197,6 @@ You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `Te
1. Build TShock in the `BUILD_MODE` you set earlier.
- $ xbuild ./TShockAPI.sln /p:Configuration=
+ $ xbuild ./TShockAPI.sln /p:Configuration=$BUILD_MODE
You're done!
\ No newline at end of file
From 2bd4636446d0c6dc6259f9ce3ab19a617b96dd7a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 13 Dec 2017 23:55:35 -0700
Subject: [PATCH 174/430] Finalize readme update; prepare for code review
---
README.md | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index d6e4c018..063f30a3 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
* [On Unix](#on-unix)
* [The Terraria Server API](#the-terraria-server-api-1)
* [TShock](#tshock-1)
+ * [Working with Terraria](#working-with-terraria)
## New to TShock?
@@ -199,4 +200,14 @@ You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `Te
$ xbuild ./TShockAPI.sln /p:Configuration=$BUILD_MODE
-You're done!
\ No newline at end of file
+You're done!
+
+### Working with Terraria
+
+Working with Terraria in TShock and in other Terraria Server API plugins is different from most other APIs. Due to the nature of how OTAPI works, you have direct access to all public fields in the `Terraria` namespace. This means that you can access Terraria member methods directly. TShock and other plugins do this quite often, mostly to modify the game world, send data, and receive data. Calls to `Main` are one such example of direct access to Terraria. This is the equivalent to `net.minecraft.server` (NMS) calls in CraftBukkit.
+
+You might find yourself wondering where these fields are. Pryaxis provides the decompiled [Sources](https://github.com/pryaxis/Sources) to Terraria's server, updated with each release. Note that these decompiled servers do not re-compile. The process of fixing the decompiles has proven to be nearly impossible in a reasonable timeframe with the modern Terraria Server.
+
+Finally, you may be interested in developing other Terraria Server API plugins. The [TShockResources](https://github.com/TShockResources) organization has several plugins you can look at and build on. TShock is itself a plugin, and most plugins are open source. This gives you ample room to figure out where to go next.
+
+Need help? Join us on [#tshock-programming in Discord](https://discord.gg/ABtrBaY).
\ No newline at end of file
From 76b5ba6af55ff0153a560b9642ade986104ab8bb Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:00:19 -0700
Subject: [PATCH 175/430] Update contributing guidelines & issue template
---
.github/CONTRIBUTING.md | 21 +++++----------------
.github/ISSUE_TEMPLATE.md | 18 ++++++++++++++----
2 files changed, 19 insertions(+), 20 deletions(-)
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 01735e16..b28f0c83 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -8,18 +8,6 @@ Please follow these simple requirements before posting a bug report:
- How to reproduce the issue
- Screenshots of the issue (if applicable)
-### To build the source
-
-Note: This includes the API by default. If you need only the API, you need to cd into that folder and do the following with the .sln file for the API. For those new to C#, the .sln and .csproj files contain the necessary definitions to do a complete source build using Microsoft or Mono build tools.
-
-- Checkout the source.
-- Initialize the submodules: ```git submodule update --init```
-- Open the source in your favorite text editor that supports .NET building and press the build button OR
-- Run ```msbuild TShock.sln``` in the root of the cloned folder on Windows in a 'Developer Command Prompt' OR
-- Run ```xbuild TShock.sln``` in the root of the cloned folder on Unix.
-
-Need help? Drop by Discord and we'll be happy to explain it with more words, step by step.
-
### TShock Additions
If something is better suited to be a plugin for TShock, rather than a TShock core feature, it should not be added! Project scope is at times questionable, though, so create an issue on Github for discussion first. If an issue is completely outside of the scope of TShock, it will be made clear in that issue what it is.
@@ -33,13 +21,13 @@ _If a person makes a suggestion in Discord, capture the suggestion as a Github i
These guidelines are for all contributors.
* Create an issue first to suggest an improvement or feature addition to TShock.
-* Active developers will then give a go/no go for implementation. This is scope related: if an issue is within the scope of TShock, it will be tagged 'pr-wanted.'
-* After 'pr-wanted' has been added, an issue should be considered workable in a pull request fashion.
-* If you, as a developer, want to claim an issue for a PR, as soon as possible start work and note that in both the original issue and the new PR. The 'pr-wanted' tag will remain but the active PR will become the center for discussion for your implementation.
+* Active developers will then give a go/no go for implementation. This is scope related: if an issue is within the scope of TShock, it will be tagged 'Contribution Wanted.'
+* After 'Contribution Wanted' has been added, an issue should be considered workable in a pull request fashion.
+* If you, as a developer, want to claim an issue for a PR, as soon as possible start work and note that in both the original issue and the new PR. The 'Contribution Wanted' tag will remain but the active PR will become the center for discussion for your implementation.
* If a TShock core developer takes an issue, they'll be assigned to the issue. If your issue was taken by a TShock developer and you were actively developing it in a PR, you should _make it clear as soon as possible that a process error has been made_ so that the your development resources and our development resources aren't wasted.
* Please send a pull request with at least a sentence description and something meaningful as the title, not just the issue number you're fixing.
-_The pr-wanted tag indicates an issue should be implemented. If an issue has a developer assigned, it indicates that they're working on it. When in doubt, ask where an issue is before starting work (so you don't waste time)!_
+_The tag indicates an issue should be implemented. If an issue has a developer assigned, it indicates that they're working on it. When in doubt, ask where an issue is before starting work (so you don't waste time)!_
Even if you have write access to the repository, follow [Github flow](https://guides.github.com/introduction/flow/) when sending commits. Don't send commits directly to either ```master``` or ```general-devel``` unless those commits modify either the deploy scripts or non-code components. If it compiles, follow Github Flow.
@@ -56,6 +44,7 @@ Required:
- When using static methods on primitives, use the CLR type. E.g. ```String.Format``` instead of ```string.Format```.
- Always use properties, not public fields.
- Document deprecations and fail compilation if they're included with ```[Obsolete("Use blah instead of blahx...", true)]```.
+- Update the `CHANGELOG.md` file.
### Dev Team Guidelines
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 2b249480..e3d2f8c4 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -1,11 +1,21 @@
+!!!!!! PLEASE FILL IN THE TEMPLATE BELOW THANK YOU VERY MUCH !!!!!!
-## TShock version
+If you don't need help, delete this template and just post an issue (feature requests and discussions and the like).
+* TShock version:
+* TShock build number (if known):
-## Any stack traces that may have happened when the issue occurred
+#### Reproduction steps (if applicable)?
+1. Some step
+2. Some other step
+3. Some bigger step
+4. This is the problem
-## Steps to reproduce
+#### Any stack traces or error messages (if known)?
+```
+PUT SUPER LONG ERROR MESSAGES IN THE TICK MARKS
+```
-## Screenshots of the problem, if applicable
+#### Any screenshots?
\ No newline at end of file
From b2939e3cad7d10b9d77478e2c7c17be4214176d7 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:02:24 -0700
Subject: [PATCH 176/430] Freshen the pull request template
---
.github/PULL_REQUEST_TEMPLATE.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 9e7b1cc8..4cf87d10 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1 +1,19 @@
+
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
+?????? HAVE YOU UPDATED THE CHANGELOG? ??????
\ No newline at end of file
From 7440995b4dd1c291e36013fb54a54796e402f35e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:03:56 -0700
Subject: [PATCH 177/430] Shuffle code of conduct a bit
---
.github/CODE_OF_CONDUCT.md | 4 ++--
README.md | 9 ++++++++-
2 files changed, 10 insertions(+), 3 deletions(-)
diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md
index 4eacbbc4..990b9ed1 100644
--- a/.github/CODE_OF_CONDUCT.md
+++ b/.github/CODE_OF_CONDUCT.md
@@ -1,3 +1,3 @@
-By participating in the TShock for Terraria community, all members will adhere to maintaining decorum with respect to all humans, in and out of the community. Members will not engage in discussion that inappropriately disparages or marginalizes any group of people or any individual. Members will not attempt to further or advance an agenda to the point of being overbearing or close minded (such as through spreading FUD). Members will not abuse services provided to them and will follow the guidance of community leaders on a situational basis about what abuse consists of. Members will adhere to United States and international law. If members notice a violation of this code of conduct, they will not engage but will instead contact the leadership team on either the forums or Discord.
+> By participating in the TShock for Terraria community, all members will adhere to maintaining decorum with respect to all humans, in and out of the community. Members will not engage in discussion that inappropriately disparages or marginalizes any group of people or any individual. Members will not attempt to further or advance an agenda to the point of being overbearing or close minded (such as through spreading FUD). Members will not abuse services provided to them and will follow the guidance of community leaders on a situational basis about what abuse consists of. Members will adhere to United States and international law. If members notice a violation of this code of conduct, they will not engage but will instead contact the leadership team on either the forums or Discord.
-Do not attempt to circumvent or bypass the code of conduct by using clever logic or reasoning (e.g., insulting Facepunch members, because they weren't directly mentioned here).
\ No newline at end of file
+> Do not attempt to circumvent or bypass the code of conduct by using clever logic or reasoning (e.g., insulting Facepunch members, because they weren't directly mentioned here).
\ No newline at end of file
diff --git a/README.md b/README.md
index 063f30a3..9dbadb9a 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,7 @@ TShock is a toolbox for Terraria servers and communities. That toolbox is jam pa
* [The Terraria Server API](#the-terraria-server-api-1)
* [TShock](#tshock-1)
* [Working with Terraria](#working-with-terraria)
+ * [Code of Conduct](#code-of-conduct)
## New to TShock?
@@ -210,4 +211,10 @@ You might find yourself wondering where these fields are. Pryaxis provides the d
Finally, you may be interested in developing other Terraria Server API plugins. The [TShockResources](https://github.com/TShockResources) organization has several plugins you can look at and build on. TShock is itself a plugin, and most plugins are open source. This gives you ample room to figure out where to go next.
-Need help? Join us on [#tshock-programming in Discord](https://discord.gg/ABtrBaY).
\ No newline at end of file
+Need help? Join us on [#tshock-programming in Discord](https://discord.gg/ABtrBaY).
+
+## Code of Conduct
+
+> By participating in the TShock for Terraria community, all members will adhere to maintaining decorum with respect to all humans, in and out of the community. Members will not engage in discussion that inappropriately disparages or marginalizes any group of people or any individual. Members will not attempt to further or advance an agenda to the point of being overbearing or close minded (such as through spreading FUD). Members will not abuse services provided to them and will follow the guidance of community leaders on a situational basis about what abuse consists of. Members will adhere to United States and international law. If members notice a violation of this code of conduct, they will not engage but will instead contact the leadership team on either the forums or Discord.
+
+> Do not attempt to circumvent or bypass the code of conduct by using clever logic or reasoning (e.g., insulting Facepunch members, because they weren't directly mentioned here).
\ No newline at end of file
From 6dc125214e6433d69ced088494c56246f5d84903 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:04:21 -0700
Subject: [PATCH 178/430] Minor tweak to issue template
---
.github/ISSUE_TEMPLATE.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index e3d2f8c4..5c4cc69f 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -18,4 +18,6 @@ If you don't need help, delete this template and just post an issue (feature req
PUT SUPER LONG ERROR MESSAGES IN THE TICK MARKS
```
-#### Any screenshots?
\ No newline at end of file
+#### Any screenshots?
+
+!!!!!! PLEASE FILL IN THE TEMPLATE ABOVE THANK YOU VERY MUCH !!!!!!
\ No newline at end of file
From 21c15da9b0bbe112f72893e1dbce516472493fe8 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:12:53 -0700
Subject: [PATCH 179/430] Redirect linux users to the unix readme
---
README.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/README.md b/README.md
index 9dbadb9a..6caab0cf 100644
--- a/README.md
+++ b/README.md
@@ -149,6 +149,8 @@ You need to re-run the patcher any time `OTAPI` updates. You need to rebuild `Te
1. Follow the [official install instructions for mono](http://www.mono-project.com/download/). **DO** install `mono-complete` or you're missing components.
+1. Proceed to the [unix build steps](#unix-build-steps) to continue.
+
#### On Unix
1. You need to get NuGet. Download the latest `nuget.exe` from [NuGet](https://www.nuget.org/downloads).
From fddc31cd6f0b05db79e016d0c3436c2ca18c2eb8 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 00:18:50 -0700
Subject: [PATCH 180/430] Update submodule to latest TSAPI rev
---
TerrariaServerAPI | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index 2c25bb68..6b52da09 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit 2c25bb68fde0e2c40a32d639ff79d614d3fb1580
+Subproject commit 6b52da09ea076c16413989664be197297c425548
From 5cd5bdaaa04aa06a22d43b3216ea211db4def91d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 07:46:29 -0700
Subject: [PATCH 181/430] Move OnLiquidSet to Bouncer
---
CHANGELOG.md | 7 +-
TShockAPI/Bouncer.cs | 141 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 119 ++---------------------------
3 files changed, 150 insertions(+), 117 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2602044a..f4bc853d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,9 +34,6 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
* The "auth system" is now referred to as the initial setup system (what it actually is). This is better verbiage for basically all situations. Who really wants to turn off the "authentication system?" In addition, the system now makes it more clear what the point of it is, rather than that it grants permissions. (@hakusaro)
-## TShock 4.3.25
-* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
-
@@ -68,6 +65,10 @@ Putting this stuff down here so things don't conflict as often.
* `GetDataHandlers.KillMe` now sends a `TSPlayer` and a `PlayerDeathReason`. (@hakusaro)
* Added `GetDataHandlers.ProjectileKill` hook. (@hakusaro)
* Removed `TShock.CheckProjectilePermission` and replaced it with `TSPlayer.HasProjectilePermission` and `TSPlayer.LacksProjectilePermission` respectively. (@hakusaro)
+* Added `TSPlayer` object to `GetDataHandlers.LiquidSetEventArgs`. (@hakusaro)
+
+## TShock 4.3.25
+* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
## TShock 4.3.24
* Updated OpenTerraria API to 1.3.5.3 (@DeathCradle)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 2710fbd4..31b31173 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.LiquidSet.Register(OnLiquidSet);
GetDataHandlers.ProjectileKill.Register(OnProjectileKill);
GetDataHandlers.PlayerUpdate.Register(OnPlayerUpdate);
GetDataHandlers.KillMe.Register(OnKillMe);
@@ -52,6 +53,146 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles Bouncer's liquid set anti-cheat.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnLiquidSet(object sender, GetDataHandlers.LiquidSetEventArgs args)
+ {
+ int tileX = args.TileX;
+ int tileY = args.TileY;
+ byte amount = args.Amount;
+ byte type = args.Type;
+
+ if (!TShock.Utils.TilePlacementValid(tileX, tileY) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (args.Player.TileLiquidThreshold >= TShock.Config.TileLiquidThreshold)
+ {
+ args.Player.Disable("Reached TileLiquid threshold.", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (!args.Player.HasPermission(Permissions.ignoreliquidsetdetection))
+ {
+ args.Player.TileLiquidThreshold++;
+ }
+
+ // Liquid anti-cheat
+ // Arguably the banned buckets bit should be in the item bans system
+ if (amount != 0)
+ {
+ int bucket = -1;
+ if (args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.EmptyBucket)
+ {
+ bucket = 0;
+ }
+ else if (args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.WaterBucket)
+ {
+ bucket = 1;
+ }
+ else if (args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.LavaBucket)
+ {
+ bucket = 2;
+ }
+ else if (args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.HoneyBucket)
+ {
+ bucket = 3;
+ }
+ else if (args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.BottomlessBucket ||
+ args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].type == ItemID.SuperAbsorbantSponge)
+ {
+ bucket = 4;
+ }
+
+ if (type == 1 && !(bucket == 2 || bucket == 0))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Spreading lava without holding a lava bucket", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (type == 1 && TShock.Itembans.ItemIsBanned("Lava Bucket", args.Player))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Using banned lava bucket without permissions", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (type == 0 && !(bucket == 1 || bucket == 0 || bucket == 4))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Spreading water without holding a water bucket", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (type == 0 && TShock.Itembans.ItemIsBanned("Water Bucket", args.Player))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Using banned water bucket without permissions", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (type == 2 && !(bucket == 3 || bucket == 0))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Spreading honey without holding a honey bucket", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (type == 2 && TShock.Itembans.ItemIsBanned("Honey Bucket", args.Player))
+ {
+ args.Player.SendErrorMessage("You do not have permission to perform this action.");
+ args.Player.Disable("Using banned honey bucket without permissions", DisableFlags.WriteToLogAndConsole);
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+
+ if (TShock.CheckTilePermission(args.Player, tileX, tileY))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, tileX, tileY, 16))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendTileSquare(tileX, tileY, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles ProjectileKill events for throttling & out of bounds projectiles.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 205bf0b7..7dca2509 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -795,6 +795,8 @@ namespace TShockAPI
///
public class LiquidSetEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
///
/// X location of the tile
///
@@ -817,13 +819,14 @@ namespace TShockAPI
///
public static HandlerList LiquidSet;
- private static bool OnLiquidSet(int tilex, int tiley, byte amount, byte type)
+ private static bool OnLiquidSet(TSPlayer player, int tilex, int tiley, byte amount, byte type)
{
if (LiquidSet == null)
return false;
var args = new LiquidSetEventArgs
{
+ Player = player,
TileX = tilex,
TileY = tiley,
Amount = amount,
@@ -2325,121 +2328,9 @@ namespace TShockAPI
byte amount = args.Data.ReadInt8();
byte type = args.Data.ReadInt8();
- if (OnLiquidSet(tileX, tileY, amount, type))
+ if (OnLiquidSet(args.Player, tileX, tileY, amount, type))
return true;
- if (!TShock.Utils.TilePlacementValid(tileX, tileY) || (args.Player.Dead && TShock.Config.PreventDeadModification))
- return true;
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (args.Player.TileLiquidThreshold >= TShock.Config.TileLiquidThreshold)
- {
- args.Player.Disable("Reached TileLiquid threshold.", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (!args.Player.HasPermission(Permissions.ignoreliquidsetdetection))
- {
- args.Player.TileLiquidThreshold++;
- }
- if (amount != 0)
- {
- int bucket = -1;
- if (args.TPlayer.inventory[args.TPlayer.selectedItem].type == 205)
- {
- bucket = 0;
- }
- else if (args.TPlayer.inventory[args.TPlayer.selectedItem].type == 206)
- {
- bucket = 1;
- }
- else if (args.TPlayer.inventory[args.TPlayer.selectedItem].type == 207)
- {
- bucket = 2;
- }
- else if (args.TPlayer.inventory[args.TPlayer.selectedItem].type == 1128)
- {
- bucket = 3;
- }
- else if (args.TPlayer.inventory[args.TPlayer.selectedItem].type == 3031 ||
- args.TPlayer.inventory[args.TPlayer.selectedItem].type == 3032)
- {
- bucket = 4;
- }
-
- if (type == 1 && !(bucket == 2 || bucket == 0))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Spreading lava without holding a lava bucket", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (type == 1 && TShock.Itembans.ItemIsBanned("Lava Bucket", args.Player))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Using banned lava bucket without permissions", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (type == 0 && !(bucket == 1 || bucket == 0 || bucket == 4))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Spreading water without holding a water bucket", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (type == 0 && TShock.Itembans.ItemIsBanned("Water Bucket", args.Player))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Using banned water bucket without permissions", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (type == 2 && !(bucket == 3 || bucket == 0))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Spreading honey without holding a honey bucket", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (type == 2 && TShock.Itembans.ItemIsBanned("Honey Bucket", args.Player))
- {
- args.Player.SendErrorMessage("You do not have permission to perform this action.");
- args.Player.Disable("Using banned honey bucket without permissions", DisableFlags.WriteToLogAndConsole);
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
- }
-
- if (TShock.CheckTilePermission(args.Player, tileX, tileY))
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, tileX, tileY, 16))
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendTileSquare(tileX, tileY, 1);
- return true;
- }
-
return false;
}
From 3f22c52698ccfe1fbffbce7b990f83c5dc4027b9 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 07:56:41 -0700
Subject: [PATCH 182/430] Move StartInvasion() out of the TShock main class
---
CHANGELOG.md | 1 +
TShockAPI/Commands.cs | 8 ++++----
TShockAPI/TShock.cs | 20 --------------------
TShockAPI/Utils.cs | 21 +++++++++++++++++++++
4 files changed, 26 insertions(+), 24 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4bc853d..d8a7890a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -66,6 +66,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `GetDataHandlers.ProjectileKill` hook. (@hakusaro)
* Removed `TShock.CheckProjectilePermission` and replaced it with `TSPlayer.HasProjectilePermission` and `TSPlayer.LacksProjectilePermission` respectively. (@hakusaro)
* Added `TSPlayer` object to `GetDataHandlers.LiquidSetEventArgs`. (@hakusaro)
+* Removed `TShock.StartInvasion` for public use (moved to Utils and marked internal). (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 1d8545ca..039d14b3 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -2044,19 +2044,19 @@ namespace TShockAPI
case "goblin":
case "goblins":
TSPlayer.All.SendInfoMessage("{0} has started a goblin army invasion.", args.Player.Name);
- TShock.StartInvasion(1);
+ TShock.Utils.StartInvasion(1);
break;
case "snowman":
case "snowmen":
TSPlayer.All.SendInfoMessage("{0} has started a snow legion invasion.", args.Player.Name);
- TShock.StartInvasion(2);
+ TShock.Utils.StartInvasion(2);
break;
case "pirate":
case "pirates":
TSPlayer.All.SendInfoMessage("{0} has started a pirate invasion.", args.Player.Name);
- TShock.StartInvasion(3);
+ TShock.Utils.StartInvasion(3);
break;
case "pumpkin":
@@ -2098,7 +2098,7 @@ namespace TShockAPI
case "martian":
case "martians":
TSPlayer.All.SendInfoMessage("{0} has started a martian invasion.", args.Player.Name);
- TShock.StartInvasion(4);
+ TShock.Utils.StartInvasion(4);
break;
}
}
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 8ad27859..232d9e36 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1755,27 +1755,7 @@ namespace TShockAPI
}
- /// StartInvasion - Starts an invasion on the server.
- /// type - The invasion type id.
- //TODO: Why is this in TShock's main class?
- public static void StartInvasion(int type)
- {
- int invasionSize = 0;
- if (Config.InfiniteInvasion)
- {
- invasionSize = 20000000;
- }
- else
- {
- invasionSize = 100 + (Config.InvasionMultiplier * Utils.ActivePlayers());
- }
-
- // Note: This is a workaround to previously providing the size as a parameter in StartInvasion
- Main.invasionSize = invasionSize;
-
- Main.StartInvasion(type);
- }
/// CheckRangePermission - Checks if a player has permission to modify a tile dependent on range checks.
/// player - The TSPlayer object.
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index 2cd87e9c..f831a249 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1457,6 +1457,27 @@ namespace TShockAPI
}
}
+ /// Starts an invasion on the server.
+ /// The invasion type id.
+ internal void StartInvasion(int type)
+ {
+ int invasionSize = 0;
+
+ if (TShock.Config.InfiniteInvasion)
+ {
+ invasionSize = 20000000;
+ }
+ else
+ {
+ invasionSize = 100 + (TShock.Config.InvasionMultiplier * ActivePlayers());
+ }
+
+ // Note: This is a workaround to previously providing the size as a parameter in StartInvasion
+ Main.invasionSize = invasionSize;
+
+ Main.StartInvasion(type);
+ }
+
/// Verifies that each stack in each chest is valid and not over the max stack count.
internal void FixChestStacks()
{
From 5f647f087ca74905ae0bc01bef9782b52dfd5534 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 08:08:57 -0700
Subject: [PATCH 183/430] (Probably) fix invasions started by TShock being
weird
TShock used to call the StartInvasion method in Main with a type
and a size, but then in some update it stopped taking a size. So
you have to change a field to change the size, but the problem is
that the field is reset when StartInavsion is called. This means
that any effort to manually change the size would have failed due
to the fact that the field is reset at the end. The order has been
changed to account for this.
In addition, the start size is now set, so the game can report
progress correctly on the current invasion.
---
CHANGELOG.md | 1 +
TShockAPI/Utils.cs | 10 ++++++++--
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d8a7890a..4c6df366 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,7 @@ Putting this stuff down here so things don't conflict as often.
* Removed `TShock.CheckProjectilePermission` and replaced it with `TSPlayer.HasProjectilePermission` and `TSPlayer.LacksProjectilePermission` respectively. (@hakusaro)
* Added `TSPlayer` object to `GetDataHandlers.LiquidSetEventArgs`. (@hakusaro)
* Removed `TShock.StartInvasion` for public use (moved to Utils and marked internal). (@hakusaro)
+* Fixed invasions started by TShock not reporting size correctly and probably not working at all. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs
index f831a249..b27bee5d 100644
--- a/TShockAPI/Utils.cs
+++ b/TShockAPI/Utils.cs
@@ -1465,6 +1465,7 @@ namespace TShockAPI
if (TShock.Config.InfiniteInvasion)
{
+ // Not really an infinite size
invasionSize = 20000000;
}
else
@@ -1472,10 +1473,15 @@ namespace TShockAPI
invasionSize = 100 + (TShock.Config.InvasionMultiplier * ActivePlayers());
}
- // Note: This is a workaround to previously providing the size as a parameter in StartInvasion
- Main.invasionSize = invasionSize;
+ // Order matters
+ // StartInvasion will reset the invasion size
Main.StartInvasion(type);
+
+ // Note: This is a workaround to previously providing the size as a parameter in StartInvasion
+ // Have to set start size to report progress correctly
+ Main.invasionSizeStart = invasionSize;
+ Main.invasionSize = invasionSize;
}
/// Verifies that each stack in each chest is valid and not over the max stack count.
From 0ac486ab5ebc5600a1c1d691d9b15ebe668bae63 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 08:33:34 -0700
Subject: [PATCH 184/430] Remove TShockRestTestPlugin
1. It hasn't been updated in 6 years.
2. Nobody is going to update it.
---
.../Properties/AssemblyInfo.cs | 54 -----
TShockRestTestPlugin/TShockRestTestPlugin.cs | 210 ------------------
.../TShockRestTestPlugin.csproj | 62 ------
3 files changed, 326 deletions(-)
delete mode 100644 TShockRestTestPlugin/Properties/AssemblyInfo.cs
delete mode 100644 TShockRestTestPlugin/TShockRestTestPlugin.cs
delete mode 100644 TShockRestTestPlugin/TShockRestTestPlugin.csproj
diff --git a/TShockRestTestPlugin/Properties/AssemblyInfo.cs b/TShockRestTestPlugin/Properties/AssemblyInfo.cs
deleted file mode 100644
index dfb6c9aa..00000000
--- a/TShockRestTestPlugin/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-TShock, a server mod for Terraria
-Copyright (C) 2011-2016 Nyx Studios (fka. The TShock Team)
-
-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.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("ClassLibrary1")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Multiplay")]
-[assembly: AssemblyProduct("ClassLibrary1")]
-[assembly: AssemblyCopyright("Copyright © Multiplay 2012")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("c6aed7ee-6282-49a2-8177-b79cad20d6d3")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/TShockRestTestPlugin/TShockRestTestPlugin.cs b/TShockRestTestPlugin/TShockRestTestPlugin.cs
deleted file mode 100644
index 250ff087..00000000
--- a/TShockRestTestPlugin/TShockRestTestPlugin.cs
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
-TShock, a server mod for Terraria
-Copyright (C) 2011-2016 Nyx Studios (fka. The TShock Team)
-
-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.Text;
-using System.Web;
-using System.Web.Script.Serialization;
-using System.Text.RegularExpressions;
-using Microsoft.VisualStudio.TestTools.WebTesting;
-using Microsoft.VisualStudio.TestTools.WebTesting.Rules;
-using Rests;
-
-namespace TshockRestTestPlugin
-{
- [DisplayName("JSON Status")]
- [Description("Checks to see the that the JSON response has the specified status response")]
- public class JsonValidateStatus : JsonValidate
- {
- public override void Validate(object sender, ValidationEventArgs e)
- {
- if (null != ValidateJson(sender, e))
- e.IsValid = true;
- }
- }
-
- [DisplayName("JSON Regexp Property")]
- [Description("Checks to see the that the JSON response contains the specified property and is matches the specified regexp")]
- public class JsonValidateRegexpProperty : JsonValidateProperty
- {
- // The name of the desired JSON property
- [DisplayName("Regexp")]
- [DefaultValue(true)]
- public new bool UseRegularExpression { get { return base.UseRegularExpression; } set { base.UseRegularExpression = value; } }
- }
-
- [DisplayName("JSON Error")]
- [Description("Checks to see the that the JSON response contains the specified error")]
- public class JsonValidateError : JsonValidateProperty
- {
- // The status of the JSON request
- [DisplayName("JSON Status")]
- [DefaultValue("400")]
- public new string JSonStatus { get { return base.JSonStatus; } set { base.JSonStatus = value; } }
-
- // The name of the desired JSON property
- [DisplayName("Property")]
- [DefaultValue("error")]
- public new string PropertyName { get { return base.PropertyName; } set { base.PropertyName = value; } }
- }
-
- [DisplayName("JSON Missing Parameter")]
- [Description("Checks to see the that the JSON response indicates a missing or invalid parameter")]
- public class JsonValidateMissingParameter : JsonValidateError
- {
- // The value of the desired JSON property
- [DisplayName("Missing Value")]
- public new string PropertyValue { get { return base.PropertyValue; } set { base.PropertyValue = String.Format("Missing or empty {0} parameter", value); } }
- }
-
- [DisplayName("JSON Invalid Parameter")]
- [Description("Checks to see the that the JSON response indicates a missing or invalid parameter")]
- public class JsonValidateInvalidParameter : JsonValidateError
- {
- // The value of the desired JSON property
- [DisplayName("Invalid Value")]
- public new string PropertyValue { get { return base.PropertyValue; } set { base.PropertyValue = String.Format("Missing or invalid {0} parameter", value); } }
- }
-
- [DisplayName("JSON Response")]
- [Description("Checks to see the that the JSON response contains the specified message")]
- public class JsonValidateResponse : JsonValidateProperty
- {
- // The name of the desired JSON property
- [DisplayName("Response")]
- [DefaultValue("response")]
- public new string PropertyName { get { return base.PropertyName; } set { base.PropertyName = value; } }
- }
-
- [DisplayName("JSON Property")]
- [Description("Checks to see the that the JSON response contains the specified property and is set to the specified value")]
- public class JsonValidateProperty : JsonValidate
- {
- // The name of the desired JSON property
- [DisplayName("Property")]
- public string PropertyName { get; set; }
-
- // The value of the desired JSON property
- [DisplayName("Value")]
- public string PropertyValue { get; set; }
-
- // Is the value a regexp of the desired JSON property
- [DisplayName("Regexp")]
- [DefaultValue(false)]
- public bool UseRegularExpression { get; set; }
-
- public override void Validate(object sender, ValidationEventArgs e)
- {
- RestObject response = ValidateJson(sender, e);
- if (null == response)
- return;
-
- if (null == response[PropertyName])
- {
- e.Message = String.Format("{0} Not Found", PropertyName);
- e.IsValid = false;
- return;
- }
-
- if (UseRegularExpression)
- {
- var re = new Regex(PropertyValue);
- if (!re.IsMatch((string)response[PropertyName]))
- {
- e.Message = String.Format("{0} => '{1}' !~ '{2}'", PropertyName, response[PropertyName], PropertyValue);
- e.IsValid = false;
- return;
- }
- }
- else
- {
- if (PropertyValue != (string)response[PropertyName])
- {
- e.Message = String.Format("{0} => '{1}' != '{2}'", PropertyName, response[PropertyName], PropertyValue);
- e.IsValid = false;
- return;
- }
- }
-
- e.IsValid = true;
- //e.WebTest.Context.Add(ContextParameterName, propertyValue);
- }
- }
-
- [DisplayName("JSON Has Properties")]
- [Description("Checks to see the that the JSON response contains the specified properties (comma seperated)")]
- public class JsonHasProperties : JsonValidate
- {
- // The name of the desired JSON properties to check
- [DisplayName("Properties")]
- [Description("A comma seperated list of property names to check exist")]
- public string PropertyNames { get; set; }
-
- //---------------------------------------------------------------------
- public override void Validate(object sender, ValidationEventArgs e)
- {
- RestObject response = ValidateJson(sender, e);
- if (null == response)
- return;
- foreach (var p in PropertyNames.Split(','))
- {
- if (null == response[p])
- {
- e.Message = String.Format("'{0}' Not Found", p);
- e.IsValid = false;
- return;
- }
- }
- e.IsValid = true;
-
- //e.WebTest.Context.Add(ContextParameterName, propertyValue);
- }
- }
-
- public abstract class JsonValidate : ValidationRule
- {
- // The status of the JSON request
- [DisplayName("JSON Status")]
- [DefaultValue("200")]
- public string JSonStatus { get; set; }
-
- public RestObject ValidateJson(object sender, ValidationEventArgs e)
- {
- if (string.IsNullOrWhiteSpace(e.Response.BodyString))
- {
- e.IsValid = false;
- e.Message = String.Format("Empty or null response {0}", e.Response.StatusCode);
- return null;
- }
- JavaScriptSerializer serialiser = new JavaScriptSerializer();
- //dynamic data = serialiser.Deserialize(e.Response.BodyString);
- RestObject response = serialiser.Deserialize(e.Response.BodyString);
-
- if (JSonStatus != response.Status)
- {
- e.IsValid = false;
- e.Message = String.Format("Response Status '{0}' not '{1}'", response.Status, JSonStatus);
- return null;
- }
-
- return response;
- }
- }
-}
\ No newline at end of file
diff --git a/TShockRestTestPlugin/TShockRestTestPlugin.csproj b/TShockRestTestPlugin/TShockRestTestPlugin.csproj
deleted file mode 100644
index e315c7d3..00000000
--- a/TShockRestTestPlugin/TShockRestTestPlugin.csproj
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-
- Debug
- AnyCPU
- 8.0.30703
- 2.0
- {F2FEDAFB-58DE-4611-9168-A86112C346C7}
- Library
- Properties
- TshockRestTestPlugin
- TshockRestTestPlugin
- v4.0
- 512
-
-
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {49606449-072B-4CF5-8088-AA49DA586694}
- TShockAPI
-
-
-
-
-
\ No newline at end of file
From 9f8db9618841786c25e79c104ee6a1b61c9dd876 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 09:18:44 -0700
Subject: [PATCH 185/430] Make death in hardcore sting a little more
---
TShockAPI/GetDataHandlers.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 7dca2509..624e6285 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2314,6 +2314,7 @@ namespace TShockAPI
{
if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID))
{
+ args.Player.SendErrorMessage("You have fallen in hardcore mode, and your items have been lost forever.");
TShock.CharacterDB.SeedInitialData(args.Player.Account);
}
}
From 6d7c8aa01999b8de23faeeb9f6cac1c7efa127a8 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:13:25 -0700
Subject: [PATCH 186/430] TileKill -> PlaceChest (hook changed, so did packet);
+Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 56 +++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 74 ++++++++++--------------------------
3 files changed, 77 insertions(+), 54 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c6df366..11b1dad9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -68,6 +68,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` object to `GetDataHandlers.LiquidSetEventArgs`. (@hakusaro)
* Removed `TShock.StartInvasion` for public use (moved to Utils and marked internal). (@hakusaro)
* Fixed invasions started by TShock not reporting size correctly and probably not working at all. (@hakusaro)
+* Removed `GetDataHandlers.TileKill` and replaced it with `GetDataHandlers.PlaceChest` as the packet originally designated as tile kill is now only used for chests. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 31b31173..17bd69ef 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlaceChest.Register(OnPlaceChest);
GetDataHandlers.LiquidSet.Register(OnLiquidSet);
GetDataHandlers.ProjectileKill.Register(OnProjectileKill);
GetDataHandlers.PlayerUpdate.Register(OnPlayerUpdate);
@@ -53,6 +54,61 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnPlaceChest(object sender, GetDataHandlers.PlaceChestEventArgs args)
+ {
+ int tileX = args.TileX;
+ int tileY = args.TileY;
+ int flag = args.Flag;
+
+ if (!TShock.Utils.TilePlacementValid(tileX, tileY) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ args.Handled = true;
+ return;
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+
+ if (flag != 0 && flag != 4 // if no container or container2 placement
+ && Main.tile[tileX, tileY].type != TileID.Containers
+ && Main.tile[tileX, tileY].type != TileID.Dressers
+ && Main.tile[tileX, tileY].type != TileID.Containers2
+ && (!TShock.Utils.MaxChests() && Main.tile[tileX, tileY].type != TileID.Dirt)) //Chest
+ {
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+
+ if (flag == 2) //place dresser
+ {
+ if ((TShock.Utils.TilePlacementValid(tileX, tileY + 1) && Main.tile[tileX, tileY + 1].type == TileID.Teleporter) ||
+ (TShock.Utils.TilePlacementValid(tileX + 1, tileY + 1) && Main.tile[tileX + 1, tileY + 1].type == TileID.Teleporter))
+ {
+ //Prevent a dresser from being placed on a teleporter, as this can cause client and server crashes.
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+ }
+
+ if (TShock.CheckTilePermission(args.Player, tileX, tileY))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, tileX, tileY))
+ {
+ args.Player.SendTileSquare(tileX, tileY, 3);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles Bouncer's liquid set anti-cheat.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 624e6285..a519bc23 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -352,35 +352,41 @@ namespace TShockAPI
}
///
- /// For use in a TileKill event
+ /// For use in a PlaceChest event
///
- public class TileKillEventArgs : HandledEventArgs
+ public class PlaceChestEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event
+ public TSPlayer Player { get; set; }
+ /// What the packet is doing (see MP packet docs).
+ public int Flag { get; set; }
///
- /// The X coordinate that is being killed
+ /// The X coordinate
///
public int TileX { get; set; }
///
- /// The Y coordinate that is being killed
+ /// The Y coordinate
///
public int TileY { get; set; }
}
///
- /// TileKill - When a tile is removed from the world
+ /// When a chest is added or removed from the world.
///
- public static HandlerList TileKill;
+ public static HandlerList PlaceChest;
- private static bool OnTileKill(int tilex, int tiley)
+ private static bool OnPlaceChest(TSPlayer player, int flag, int tilex, int tiley)
{
- if (TileKill == null)
+ if (PlaceChest == null)
return false;
- var args = new TileKillEventArgs
+ var args = new PlaceChestEventArgs
{
+ Player = player,
+ Flag = flag,
TileX = tilex,
TileY = tiley,
};
- TileKill.Invoke(null, args);
+ PlaceChest.Invoke(null, args);
return args.Handled;
}
@@ -1391,7 +1397,7 @@ namespace TShockAPI
{ PacketTypes.ProjectileNew, HandleProjectileNew },
{ PacketTypes.TogglePvp, HandleTogglePvp },
{ PacketTypes.PlayerTeam, HandlePlayerTeam },
- { PacketTypes.TileKill, HandleTileKill },
+ { PacketTypes.TileKill, HandlePlaceChest },
{ PacketTypes.LiquidSet, HandleLiquidSet },
{ PacketTypes.PlayerSpawn, HandleSpawn },
{ PacketTypes.ChestGetContents, HandleChestOpen },
@@ -2335,56 +2341,16 @@ namespace TShockAPI
return false;
}
- private static bool HandleTileKill(GetDataHandlerArgs args)
+ private static bool HandlePlaceChest(GetDataHandlerArgs args)
{
int flag = args.Data.ReadByte();
int tileX = args.Data.ReadInt16();
int tileY = args.Data.ReadInt16();
args.Data.ReadInt16(); // Ignore style
- if (OnTileKill(tileX, tileY))
+ if (OnPlaceChest(args.Player, flag, tileX, tileY))
return true;
- if (!TShock.Utils.TilePlacementValid(tileX, tileY) || (args.Player.Dead && TShock.Config.PreventDeadModification))
- return true;
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
-
- if (flag != 0 && flag != 4 // if no container or container2 placement
- && Main.tile[tileX, tileY].type != TileID.Containers
- && Main.tile[tileX, tileY].type != TileID.Dressers
- && Main.tile[tileX, tileY].type != TileID.Containers2
- && (!TShock.Utils.MaxChests() && Main.tile[tileX, tileY].type != TileID.Dirt)) //Chest
- {
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
-
- if (flag == 2) //place dresser
- {
- if ((TShock.Utils.TilePlacementValid(tileX, tileY + 1) && Main.tile[tileX, tileY + 1].type == TileID.Teleporter) ||
- (TShock.Utils.TilePlacementValid(tileX + 1, tileY + 1) && Main.tile[tileX + 1, tileY + 1].type == TileID.Teleporter))
- {
- //Prevent a dresser from being placed on a teleporter, as this can cause client and server crashes.
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
- }
-
- if (TShock.CheckTilePermission(args.Player, tileX, tileY))
- {
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, tileX, tileY))
- {
- args.Player.SendTileSquare(tileX, tileY, 3);
- return true;
- }
+
return false;
}
From a6d1d9ab49c4bed07168d7ccd1db9cac6d78ec77 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:19:53 -0700
Subject: [PATCH 187/430] Update submodule; PacketTypes.TileKill -> PlaceChest
---
TShockAPI/GetDataHandlers.cs | 2 +-
TerrariaServerAPI | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index f3dc33e5..3fa71b4d 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1230,7 +1230,7 @@ namespace TShockAPI
{ PacketTypes.ProjectileNew, HandleProjectileNew },
{ PacketTypes.TogglePvp, HandleTogglePvp },
{ PacketTypes.PlayerTeam, HandlePlayerTeam },
- { PacketTypes.TileKill, HandleTileKill },
+ { PacketTypes.PlaceChest, HandleTileKill },
{ PacketTypes.PlayerKillMe, HandlePlayerKillMe },
{ PacketTypes.LiquidSet, HandleLiquidSet },
{ PacketTypes.PlayerSpawn, HandleSpawn },
diff --git a/TerrariaServerAPI b/TerrariaServerAPI
index 6b52da09..28200f7d 160000
--- a/TerrariaServerAPI
+++ b/TerrariaServerAPI
@@ -1 +1 @@
-Subproject commit 6b52da09ea076c16413989664be197297c425548
+Subproject commit 28200f7d4447ee275e85856f97eee58fa156ffc4
From 863fa706c2e24c7cb1316f3d0163e1855d9bad5b Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:28:50 -0700
Subject: [PATCH 188/430] Document OnPlaceChest in Bouncer
---
TShockAPI/Bouncer.cs | 3 +++
1 file changed, 3 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 17bd69ef..6e9bdbf1 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -54,6 +54,9 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// The place chest event that Bouncer hooks to prevent accidental damage.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnPlaceChest(object sender, GetDataHandlers.PlaceChestEventArgs args)
{
int tileX = args.TileX;
From be8cffddfd02e254a717607e036dc7facd0f19a0 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:31:54 -0700
Subject: [PATCH 189/430] Move OnChestOpen to Bouncer
---
TShockAPI/Bouncer.cs | 26 ++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 18 ------------------
2 files changed, 26 insertions(+), 18 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 6e9bdbf1..30268f41 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.ChestOpen.Register(OnChestOpen);
GetDataHandlers.PlaceChest.Register(OnPlaceChest);
GetDataHandlers.LiquidSet.Register(OnLiquidSet);
GetDataHandlers.ProjectileKill.Register(OnProjectileKill);
@@ -54,6 +55,31 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnChestOpen(object sender, GetDataHandlers.ChestOpenEventArgs args)
+ {
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, args.X, args.Y))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, args.X, args.Y) && TShock.Config.RegionProtectChests)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ int id = Chest.FindChest(args.X, args.Y);
+ args.Player.ActiveChest = id;
+ }
+
/// The place chest event that Bouncer hooks to prevent accidental damage.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index da75b529..5606c50b 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2413,24 +2413,6 @@ namespace TShockAPI
if (OnChestOpen(x, y, args.Player))
return true;
- if (TShock.CheckIgnores(args.Player))
- {
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, x, y))
- {
- return true;
- }
-
- if (TShock.CheckTilePermission(args.Player, x, y) && TShock.Config.RegionProtectChests)
- {
- return true;
- }
-
- int id = Chest.FindChest(x, y);
- args.Player.ActiveChest = id;
-
return false;
}
From 943f86615a5f893630f64963e71aab27192bdd5f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:46:26 -0700
Subject: [PATCH 190/430] Move UpdateNPCHome to Bouncer
---
TShockAPI/Bouncer.cs | 35 ++++++++++++++++++++++++++++++++++-
TShockAPI/GetDataHandlers.cs | 23 +++++------------------
2 files changed, 39 insertions(+), 19 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 30268f41..8bb255a0 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.NPCHome.Register(OnUpdateNPCHome);
GetDataHandlers.ChestOpen.Register(OnChestOpen);
GetDataHandlers.PlaceChest.Register(OnPlaceChest);
GetDataHandlers.LiquidSet.Register(OnLiquidSet);
@@ -55,9 +56,41 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// The Bouncer handler for when an NPC is rehomed.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnUpdateNPCHome(object sender, GetDataHandlers.NPCHomeChangeEventArgs args)
+ {
+ int id = args.ID;
+ short x = args.X;
+ short y = args.Y;
+ byte homeless = args.Homeless;
+
+ // Calls to TShock.CheckTilePermission need to be broken up into different subsystems
+ // In particular, this handles both regions and other things. Ouch.
+ if (TShock.CheckTilePermission(args.Player, x, y))
+ {
+ args.Player.SendErrorMessage("You do not have access to modify this area.");
+ args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
+ Convert.ToByte(Main.npc[id].homeless));
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, x, y))
+ {
+ args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
+ Convert.ToByte(Main.npc[id].homeless));
+ args.Handled = true;
+ return;
+ }
+ }
+
+ /// The Bouncer handler for when chests are opened.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnChestOpen(object sender, GetDataHandlers.ChestOpenEventArgs args)
{
-
if (TShock.CheckIgnores(args.Player))
{
args.Handled = true;
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 5606c50b..dead02ec 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1008,6 +1008,8 @@ namespace TShockAPI
///
public class NPCHomeChangeEventArgs : HandledEventArgs
{
+ /// The TSPlayer that caused the event.
+ public TSPlayer Player { get; set; }
///
/// The Terraria playerID of the player
///
@@ -1030,13 +1032,14 @@ namespace TShockAPI
///
public static HandlerList NPCHome;
- private static bool OnUpdateNPCHome(short id, short x, short y, byte homeless)
+ private static bool OnUpdateNPCHome(TSPlayer player, short id, short x, short y, byte homeless)
{
if (NPCHome == null)
return false;
var args = new NPCHomeChangeEventArgs
{
+ Player = player,
ID = id,
X = x,
Y = y,
@@ -2514,7 +2517,7 @@ namespace TShockAPI
var y = args.Data.ReadInt16();
var homeless = args.Data.ReadInt8();
- if (OnUpdateNPCHome(id, x, y, homeless))
+ if (OnUpdateNPCHome(args.Player, id, x, y, homeless))
return true;
if (!args.Player.HasPermission(Permissions.movenpc))
@@ -2524,22 +2527,6 @@ namespace TShockAPI
Convert.ToByte(Main.npc[id].homeless));
return true;
}
-
- if (TShock.CheckTilePermission(args.Player, x, y))
- {
- args.Player.SendErrorMessage("You do not have access to modify this area.");
- args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
- Convert.ToByte(Main.npc[id].homeless));
- return true;
- }
-
- //removed until NPC Home packet actually sends their home coords.
- /*if (TShock.CheckRangePermission(args.Player, x, y))
- {
- args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
- Convert.ToByte(Main.npc[id].homeless));
- return true;
- }*/
return false;
}
From bcc18160715ca36e1d33fdcb5c05a4889c50f52c Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Thu, 14 Dec 2017 20:54:04 -0700
Subject: [PATCH 191/430] Update changelog
---
CHANGELOG.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 11b1dad9..4673edc0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -69,6 +69,7 @@ Putting this stuff down here so things don't conflict as often.
* Removed `TShock.StartInvasion` for public use (moved to Utils and marked internal). (@hakusaro)
* Fixed invasions started by TShock not reporting size correctly and probably not working at all. (@hakusaro)
* Removed `GetDataHandlers.TileKill` and replaced it with `GetDataHandlers.PlaceChest` as the packet originally designated as tile kill is now only used for chests. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.NPCHome`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
From 845fc3b7c80d7df870dd241681abfce2ea9a41c9 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 12:12:21 -0700
Subject: [PATCH 192/430] Move OnChestItemChange to Bouncer
Fix issue where TShock didn't properly do anti-cheat on chest
item changes.
---
CHANGELOG.md | 2 ++
TShockAPI/Bouncer.cs | 35 +++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 30 ++++++------------------------
3 files changed, 43 insertions(+), 24 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4673edc0..b627f6c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -70,6 +70,8 @@ Putting this stuff down here so things don't conflict as often.
* Fixed invasions started by TShock not reporting size correctly and probably not working at all. (@hakusaro)
* Removed `GetDataHandlers.TileKill` and replaced it with `GetDataHandlers.PlaceChest` as the packet originally designated as tile kill is now only used for chests. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.NPCHome`. (@hakusaro)
+* Added a `TSPlayer` to `GetDataHandlers.ChestItemChanged`. (@hakusaro)
+* Fixed chest item changes not triggering any range checks, tile checks, or correct chest checks. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 8bb255a0..1aa6b22e 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.ChestItemChange.Register(OnChestItemChange);
GetDataHandlers.NPCHome.Register(OnUpdateNPCHome);
GetDataHandlers.ChestOpen.Register(OnChestOpen);
GetDataHandlers.PlaceChest.Register(OnPlaceChest);
@@ -56,6 +57,40 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnChestItemChange(object sender, GetDataHandlers.ChestItemEventArgs args)
+ {
+ short id = args.ID;
+ byte slot = args.Slot;
+ short stacks = args.Stacks;
+ byte prefix = args.Prefix;
+ short type = args.Type;
+
+ if (args.Player.TPlayer.chest != id)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.ChestItem, "", id, slot);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, Main.chest[id].x, Main.chest[id].y) && TShock.Config.RegionProtectChests)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, Main.chest[id].x, Main.chest[id].y))
+ {
+ args.Handled = true;
+ return;
+ }
+ }
+
/// The Bouncer handler for when an NPC is rehomed.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index dead02ec..8431a27d 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -922,6 +922,8 @@ namespace TShockAPI
///
public class ChestItemEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
///
/// ChestID
///
@@ -948,13 +950,14 @@ namespace TShockAPI
///
public static HandlerList ChestItemChange;
- private static bool OnChestItemChange(short id, byte slot, short stacks, byte prefix, short type)
+ private static bool OnChestItemChange(TSPlayer player, short id, byte slot, short stacks, byte prefix, short type)
{
if (ChestItemChange == null)
return false;
var args = new ChestItemEventArgs
{
+ Player = player,
ID = id,
Slot = slot,
Stacks = stacks,
@@ -2452,35 +2455,14 @@ namespace TShockAPI
var prefix = args.Data.ReadInt8();
var type = args.Data.ReadInt16();
- if (OnChestItemChange(id, slot, stacks, prefix, type))
+ if (OnChestItemChange(args.Player, id, slot, stacks, prefix, type))
return true;
- if (args.TPlayer.chest != id)
- {
- return false;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.ChestItem, "", id, slot);
- return true;
- }
-
Item item = new Item();
item.netDefaults(type);
if (stacks > item.maxStack || TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(item.type), args.Player))
{
- return false;
- }
-
- if (TShock.CheckTilePermission(args.Player, Main.chest[id].x, Main.chest[id].y) && TShock.Config.RegionProtectChests)
- {
- return false;
- }
-
- if (TShock.CheckRangePermission(args.Player, Main.chest[id].x, Main.chest[id].y))
- {
- return false;
+ return true;
}
return false;
From c9955a74ec4e471e5aaf51b367018540155d23c7 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 12:14:10 -0700
Subject: [PATCH 193/430] Document OnChestItemChange
---
TShockAPI/Bouncer.cs | 3 +++
1 file changed, 3 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 1aa6b22e..5dbf22db 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -57,6 +57,9 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles when a chest item is changed.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnChestItemChange(object sender, GetDataHandlers.ChestItemEventArgs args)
{
short id = args.ID;
From 5cdb38675cacc231932820516a695c02b822a9cc Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 17:51:16 -0700
Subject: [PATCH 194/430] Move OnPlayerBuff logic to Bouncer
---
CHANGELOG.md | 3 +-
TShockAPI/Bouncer.cs | 58 ++++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 42 +++-----------------------
3 files changed, 64 insertions(+), 39 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b627f6c6..a84786df 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -70,8 +70,9 @@ Putting this stuff down here so things don't conflict as often.
* Fixed invasions started by TShock not reporting size correctly and probably not working at all. (@hakusaro)
* Removed `GetDataHandlers.TileKill` and replaced it with `GetDataHandlers.PlaceChest` as the packet originally designated as tile kill is now only used for chests. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.NPCHome`. (@hakusaro)
-* Added a `TSPlayer` to `GetDataHandlers.ChestItemChanged`. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.ChestItemChanged`. (@hakusaro)
* Fixed chest item changes not triggering any range checks, tile checks, or correct chest checks. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.PlayerBuff`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 5dbf22db..59eab38e 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlayerBuff.Register(OnPlayerBuff);
GetDataHandlers.ChestItemChange.Register(OnChestItemChange);
GetDataHandlers.NPCHome.Register(OnUpdateNPCHome);
GetDataHandlers.ChestOpen.Register(OnChestOpen);
@@ -57,6 +58,63 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles Buff events.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnPlayerBuff(object sender, GetDataHandlers.PlayerBuffEventArgs args)
+ {
+ byte id = args.ID;
+ byte type = args.Type;
+ int time = args.Time;
+
+ if (TShock.Players[id] == null)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (id >= Main.maxPlayers)
+ {
+ args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (!TShock.Players[id].TPlayer.hostile || !Main.pvpBuff[type])
+ {
+ args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, TShock.Players[id].TileX, TShock.Players[id].TileY, 50))
+ {
+ args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (WhitelistBuffMaxTime[type] > 0 && time <= WhitelistBuffMaxTime[type])
+ {
+ args.Handled = false;
+ return;
+ }
+ }
+
/// Handles when a chest item is changed.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 8431a27d..25115035 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1057,6 +1057,7 @@ namespace TShockAPI
///
public class PlayerBuffEventArgs : HandledEventArgs
{
+ public TSPlayer Player { get; set; }
///
/// The Terraria playerID of the player
///
@@ -1075,13 +1076,14 @@ namespace TShockAPI
///
public static HandlerList PlayerBuff;
- private static bool OnPlayerBuff(byte id, byte type, int time)
+ private static bool OnPlayerBuff(TSPlayer player, byte id, byte type, int time)
{
if (PlayerBuff == null)
return false;
var args = new PlayerBuffEventArgs
{
+ Player = player,
ID = id,
Type = type,
Time = time
@@ -2518,45 +2520,9 @@ namespace TShockAPI
var type = args.Data.ReadInt8();
var time = args.Data.ReadInt32();
- if (OnPlayerBuff(id, type, time))
+ if (OnPlayerBuff(args.Player, id, type, time))
return true;
- if (TShock.Players[id] == null)
- return false;
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
- return true;
- }
-
- if (id >= Main.maxPlayers)
- {
- args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
- return true;
- }
-
- if (!TShock.Players[id].TPlayer.hostile || !Main.pvpBuff[type])
- {
- args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
- return true;
- }
- if (TShock.CheckRangePermission(args.Player, TShock.Players[id].TileX, TShock.Players[id].TileY, 50))
- {
- args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
- return true;
- }
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
- return true;
- }
-
- if (WhitelistBuffMaxTime[type] > 0 && time <= WhitelistBuffMaxTime[type])
- {
- return false;
- }
-
args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
return true;
}
From 82e2ecb66247db7fd6145c48c24abf78c5f9906d Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 18:11:35 -0700
Subject: [PATCH 195/430] Move OnItemDrop to Bouncer
---
TShockAPI/Bouncer.cs | 91 ++++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 59 -----------------------
2 files changed, 91 insertions(+), 59 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 59eab38e..90b2e461 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.ItemDrop.Register(OnItemDrop);
GetDataHandlers.PlayerBuff.Register(OnPlayerBuff);
GetDataHandlers.ChestItemChange.Register(OnChestItemChange);
GetDataHandlers.NPCHome.Register(OnUpdateNPCHome);
@@ -58,6 +59,96 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Registered when items fall to the ground to prevent cheating.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnItemDrop(object sender, GetDataHandlers.ItemDropEventArgs args)
+ {
+ short id = args.ID;
+ Vector2 pos = args.Position;
+ Vector2 vel = args.Velocity;
+ short stacks = args.Stacks;
+ short prefix = args.Prefix;
+ bool noDelay = args.NoDelay;
+ short type = args.Type;
+
+ // player is attempting to crash clients
+ if (type < -48 || type >= Main.maxItemTypes)
+ {
+ // Causes item duplications. Will be re added later if necessary
+ //args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ //make sure the prefix is a legit value
+ if (prefix > PrefixID.Count)
+ {
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ //Item removed, let client do this to prevent item duplication
+ // client side (but only if it passed the range check)
+ if (type == 0)
+ {
+ if (TShock.CheckRangePermission(args.Player, (int)(Main.item[id].position.X / 16f), (int)(Main.item[id].position.Y / 16f)))
+ {
+ // Causes item duplications. Will be re added if necessary
+ //args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, (int)(pos.X / 16f), (int)(pos.Y / 16f)))
+ {
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ // stop the client from changing the item type of a drop but
+ // only if the client isn't picking up the item
+ if (Main.item[id].active && Main.item[id].netID != type)
+ {
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ Item item = new Item();
+ item.netDefaults(type);
+ if ((stacks > item.maxStack || stacks <= 0) || (TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(item.type), args.Player) && !args.Player.HasPermission(Permissions.allowdroppingbanneditems)))
+ {
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ // TODO: Remove item ban part of this check
+ if ((Main.ServerSideCharacter) && (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond - args.Player.LoginMS < TShock.ServerSideCharacterConfig.LogonDiscardThreshold))
+ {
+ //Player is probably trying to sneak items onto the server in their hands!!!
+ TShock.Log.ConsoleInfo("Player {0} tried to sneak {1} onto the server!", args.Player.Name, item.Name);
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.ItemDrop, "", id);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles Buff events.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 25115035..cc472d38 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2540,65 +2540,6 @@ namespace TShockAPI
if (OnItemDrop(args.Player, id, pos, vel, stacks, prefix, noDelay, type))
return true;
- // player is attempting to crash clients
- if (type < -48 || type >= Main.maxItemTypes)
- {
- // Causes item duplications. Will be re added later if necessary
- //args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
- if (prefix > PrefixID.Count) //make sure the prefix is a legit value
- {
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
- if (type == 0) //Item removed, let client do this to prevent item duplication client side (but only if it passed the range check)
- {
- if (TShock.CheckRangePermission(args.Player, (int)(Main.item[id].position.X / 16f), (int)(Main.item[id].position.Y / 16f)))
- {
- // Causes item duplications. Will be re added if necessary
- //args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
- return false;
- }
-
- if (TShock.CheckRangePermission(args.Player, (int)(pos.X / 16f), (int)(pos.Y / 16f)))
- {
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
- if (Main.item[id].active && Main.item[id].netID != type) //stop the client from changing the item type of a drop but only if the client isn't picking up the item
- {
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
- Item item = new Item();
- item.netDefaults(type);
- if ((stacks > item.maxStack || stacks <= 0) || (TShock.Itembans.ItemIsBanned(EnglishLanguage.GetItemNameById(item.type), args.Player) && !args.Player.HasPermission(Permissions.allowdroppingbanneditems)))
- {
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
- if ((Main.ServerSideCharacter) && (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond - args.Player.LoginMS < TShock.ServerSideCharacterConfig.LogonDiscardThreshold))
- {
- //Player is probably trying to sneak items onto the server in their hands!!!
- TShock.Log.ConsoleInfo("Player {0} tried to sneak {1} onto the server!", args.Player.Name, item.Name);
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
-
- }
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.ItemDrop, "", id);
- return true;
- }
-
return false;
}
From 01d865fddca261075ecc37e4b3fb786536925b08 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 18:27:55 -0700
Subject: [PATCH 196/430] Move OnPlayerDamage to Bouncer
Remove reference to PlayerDamage v1 hook
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 76 +++++++++++++++++++--
TShockAPI/GetDataHandlers.cs | 129 ++---------------------------------
3 files changed, 80 insertions(+), 126 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a84786df..ba907aad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` to `GetDataHandlers.ChestItemChanged`. (@hakusaro)
* Fixed chest item changes not triggering any range checks, tile checks, or correct chest checks. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.PlayerBuff`. (@hakusaro)
+* Added `TSPlayer` and `PlayerDeathReason` to `GetDataHandlers.PlayerDamage`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 90b2e461..dfc53968 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -28,7 +28,6 @@ using TShockAPI.Localization;
using static TShockAPI.GetDataHandlers;
using TerrariaApi.Server;
using Terraria.ObjectData;
-using Terraria.ID;
using Terraria.DataStructures;
namespace TShockAPI
@@ -36,7 +35,7 @@ namespace TShockAPI
/// Bouncer is the TShock anti-hack and build guardian system
internal sealed class Bouncer
{
- /// Constructor call initializes Bouncer & related functionality.
+ /// Constructor call initializes Bouncer and related functionality.
/// A new Bouncer.
internal Bouncer(TerrariaPlugin pluginInstance)
{
@@ -59,6 +58,75 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Called when a player is damaged.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnPlayerDamage(object sender, GetDataHandlers.PlayerDamageEventArgs args)
+ {
+ byte id = args.ID;
+ short dmg = args.Damage;
+ bool pvp = args.PVP;
+ bool crit = args.Critical;
+ byte direction = args.Direction;
+
+ if (id >= Main.maxPlayers || TShock.Players[id] == null)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap) && id != args.Player.Index)
+ {
+ if (TShock.Config.KickOnDamageThresholdBroken)
+ {
+ TShock.Utils.Kick(args.Player, string.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage));
+ args.Handled = true;
+ return;
+ }
+ else
+ {
+ args.Player.Disable(String.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage), DisableFlags.WriteToLogAndConsole);
+ }
+ args.Player.SendData(PacketTypes.PlayerHp, "", id);
+ args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (!TShock.Players[id].TPlayer.hostile && pvp && id != args.Player.Index)
+ {
+ args.Player.SendData(PacketTypes.PlayerHp, "", id);
+ args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.PlayerHp, "", id);
+ args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, TShock.Players[id].TileX, TShock.Players[id].TileY, 100))
+ {
+ args.Player.SendData(PacketTypes.PlayerHp, "", id);
+ args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendData(PacketTypes.PlayerHp, "", id);
+ args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ }
+
/// Registered when items fall to the ground to prevent cheating.
/// The object that triggered the event.
/// The packet arguments that the event has.
@@ -498,7 +566,7 @@ namespace TShockAPI
}
}
- /// Handles ProjectileKill events for throttling & out of bounds projectiles.
+ /// Handles ProjectileKill events for throttling and out of bounds projectiles.
/// The object that triggered the event.
/// The packet arguments that the event has.
internal void OnProjectileKill(object sender, GetDataHandlers.ProjectileKillEventArgs args)
@@ -524,7 +592,7 @@ namespace TShockAPI
}
}
- /// Handles disabling enforcement & minor anti-exploit stuff
+ /// Handles disabling enforcement and minor anti-exploit stuff
/// The object that triggered the event.
/// The packet arguments that the event has.
internal void OnPlayerUpdate(object sender, GetDataHandlers.PlayerUpdateEventArgs args)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index cc472d38..27bd2dd8 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1161,6 +1161,7 @@ namespace TShockAPI
///
public class PlayerDamageEventArgs : HandledEventArgs
{
+ public TSPlayer Player { get; set; }
///
/// The Terraria playerID of the player
///
@@ -1181,24 +1182,28 @@ namespace TShockAPI
/// Is the damage critical?
///
public bool Critical { get; set; }
+ /// The reason the player took damage and/or died.
+ public PlayerDeathReason PlayerDeathReason { get; set; }
}
///
/// PlayerDamage - Called when a player is damaged
///
public static HandlerList PlayerDamage;
- private static bool OnPlayerDamage(byte id, byte dir, short dmg, bool pvp, bool crit)
+ private static bool OnPlayerDamage(TSPlayer player, byte id, byte dir, short dmg, bool pvp, bool crit, PlayerDeathReason playerDeathReason)
{
if (PlayerDamage == null)
return false;
var args = new PlayerDamageEventArgs
{
+ Player = player,
ID = id,
Direction = dir,
Damage = dmg,
PVP = pvp,
Critical = crit,
+ PlayerDeathReason = playerDeathReason,
};
PlayerDamage.Invoke(null, args);
return args.Handled;
@@ -1421,7 +1426,6 @@ namespace TShockAPI
{ PacketTypes.ItemOwner, HandleItemOwner },
{ PacketTypes.PlayerHp, HandlePlayerHp },
{ PacketTypes.PlayerMana, HandlePlayerMana },
- { PacketTypes.PlayerDamage, HandlePlayerDamage },
{ PacketTypes.NpcStrike, HandleNpcStrike },
{ PacketTypes.NpcSpecial, HandleSpecial },
{ PacketTypes.PlayerAnimation, HandlePlayerAnimation },
@@ -2560,76 +2564,6 @@ namespace TShockAPI
return false;
}
- private static bool HandlePlayerDamage(GetDataHandlerArgs args)
- {
- var id = args.Data.ReadInt8();
- var direction = (byte)(args.Data.ReadInt8() - 1);
- var dmg = args.Data.ReadInt16();
- args.Data.ReadString(); // don't store damage text
- var bits = (BitsByte)args.Data.ReadInt8();
- var pvp = bits[0];
- var crit = bits[1];
-
- if (OnPlayerDamage(id, direction, dmg, pvp, crit))
- return true;
-
- if (id >= Main.maxPlayers || TShock.Players[id] == null)
- {
- return true;
- }
-
- if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap) && id != args.Player.Index)
- {
- if (TShock.Config.KickOnDamageThresholdBroken)
- {
- TShock.Utils.Kick(args.Player, string.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage));
- return true;
- }
- else
- {
- args.Player.Disable(String.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage), DisableFlags.WriteToLogAndConsole);
- }
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (!TShock.Players[id].TPlayer.hostile && pvp && id != args.Player.Index)
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, TShock.Players[id].TileX, TShock.Players[id].TileY, 100))
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (TShock.Players[id].GodMode)
- {
- TShock.Players[id].Heal(args.TPlayer.statLifeMax);
- }
-
- return false;
- }
-
private static bool HandlePlayerDamageV2(GetDataHandlerArgs args)
{
var id = args.Data.ReadInt8();
@@ -2640,58 +2574,9 @@ namespace TShockAPI
var crit = bits[0];
var pvp = bits[1];
- if (OnPlayerDamage(id, direction, dmg, pvp, crit))
+ if (OnPlayerDamage(args.Player, id, direction, dmg, pvp, crit, playerDeathReason))
return true;
- if (id >= Main.maxPlayers || TShock.Players[id] == null)
- {
- return true;
- }
-
- if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap) && id != args.Player.Index)
- {
- if (TShock.Config.KickOnDamageThresholdBroken)
- {
- TShock.Utils.Kick(args.Player, string.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage));
- return true;
- }
- else
- {
- args.Player.Disable(String.Format("Player damage exceeded {0}.", TShock.Config.MaxDamage), DisableFlags.WriteToLogAndConsole);
- }
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (!TShock.Players[id].TPlayer.hostile && pvp && id != args.Player.Index)
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, TShock.Players[id].TileX, TShock.Players[id].TileY, 100))
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendData(PacketTypes.PlayerHp, "", id);
- args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
- return true;
- }
-
if (TShock.Players[id].GodMode)
{
TShock.Players[id].Heal(args.TPlayer.statLifeMax);
From 007c685c19f627cd0b9957d1af61882bfdd7bfc8 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 21:42:20 -0700
Subject: [PATCH 197/430] Move OnNPCStrike to Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 58 ++++++++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 44 ++++-----------------------
3 files changed, 64 insertions(+), 39 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 907240f0..abd236ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -75,6 +75,7 @@ Putting this stuff down here so things don't conflict as often.
* Fixed chest item changes not triggering any range checks, tile checks, or correct chest checks. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.PlayerBuff`. (@hakusaro)
* Added `TSPlayer` and `PlayerDeathReason` to `GetDataHandlers.PlayerDamage`. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.NPCStrike`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index dfc53968..5a759abd 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -41,6 +41,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.NPCStrike.Register(OnNPCStrike);
GetDataHandlers.ItemDrop.Register(OnItemDrop);
GetDataHandlers.PlayerBuff.Register(OnPlayerBuff);
GetDataHandlers.ChestItemChange.Register(OnChestItemChange);
@@ -58,6 +59,63 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles the NPC Strike event for Bouncer.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnNPCStrike(object sender, GetDataHandlers.NPCStrikeEventArgs args)
+ {
+ short id = args.ID;
+ byte direction = args.Direction;
+ short dmg = args.Damage;
+ float knockback = args.Knockback;
+ byte crit = args.Critical;
+
+ if (Main.npc[id] == null)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
+ {
+ if (TShock.Config.KickOnDamageThresholdBroken)
+ {
+ TShock.Utils.Kick(args.Player, string.Format("NPC damage exceeded {0}.", TShock.Config.MaxDamage));
+ args.Handled = true;
+ return;
+ }
+ else
+ {
+ args.Player.Disable(String.Format("NPC damage exceeded {0}.", TShock.Config.MaxDamage), DisableFlags.WriteToLogAndConsole);
+ }
+ args.Player.SendData(PacketTypes.NpcUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.NpcUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.Config.RangeChecks &&
+ TShock.CheckRangePermission(args.Player, (int)(Main.npc[id].position.X / 16f), (int)(Main.npc[id].position.Y / 16f), 128))
+ {
+ args.Player.SendData(PacketTypes.NpcUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendData(PacketTypes.NpcUpdate, "", id);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Called when a player is damaged.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 27bd2dd8..e6555cc3 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1214,6 +1214,8 @@ namespace TShockAPI
///
public class NPCStrikeEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
///
/// ???
///
@@ -1240,13 +1242,14 @@ namespace TShockAPI
///
public static HandlerList NPCStrike;
- private static bool OnNPCStrike(short id, byte dir, short dmg, float knockback, byte crit)
+ private static bool OnNPCStrike(TSPlayer player, short id, byte dir, short dmg, float knockback, byte crit)
{
if (NPCStrike == null)
return false;
var args = new NPCStrikeEventArgs
{
+ Player = player,
ID = id,
Direction = dir,
Damage = dmg,
@@ -2593,33 +2596,9 @@ namespace TShockAPI
var direction = (byte)(args.Data.ReadInt8() - 1);
var crit = args.Data.ReadInt8();
- if (OnNPCStrike(id, direction, dmg, knockback, crit))
+ if (OnNPCStrike(args.Player, id, direction, dmg, knockback, crit))
return true;
- if (Main.npc[id] == null)
- return true;
-
- if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
- {
- if (TShock.Config.KickOnDamageThresholdBroken)
- {
- TShock.Utils.Kick(args.Player, string.Format("NPC damage exceeded {0}.", TShock.Config.MaxDamage));
- return true;
- }
- else
- {
- args.Player.Disable(String.Format("NPC damage exceeded {0}.", TShock.Config.MaxDamage), DisableFlags.WriteToLogAndConsole);
- }
- args.Player.SendData(PacketTypes.NpcUpdate, "", id);
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.NpcUpdate, "", id);
- return true;
- }
-
if (Main.npc[id].townNPC && !args.Player.HasPermission(Permissions.hurttownnpc))
{
args.Player.SendErrorMessage("You do not have permission to hurt this NPC.");
@@ -2627,19 +2606,6 @@ namespace TShockAPI
return true;
}
- if (TShock.Config.RangeChecks &&
- TShock.CheckRangePermission(args.Player, (int)(Main.npc[id].position.X / 16f), (int)(Main.npc[id].position.Y / 16f), 128))
- {
- args.Player.SendData(PacketTypes.NpcUpdate, "", id);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendData(PacketTypes.NpcUpdate, "", id);
- return true;
- }
-
return false;
}
From d03e899452847e0a387ff305adf8db79f4c21146 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 21:43:21 -0700
Subject: [PATCH 198/430] dmg -> damage
---
TShockAPI/Bouncer.cs | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 5a759abd..f1e62ab8 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -66,7 +66,7 @@ namespace TShockAPI
{
short id = args.ID;
byte direction = args.Direction;
- short dmg = args.Damage;
+ short damage = args.Damage;
float knockback = args.Knockback;
byte crit = args.Critical;
@@ -76,7 +76,7 @@ namespace TShockAPI
return;
}
- if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
+ if (damage > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
{
if (TShock.Config.KickOnDamageThresholdBroken)
{
@@ -122,7 +122,7 @@ namespace TShockAPI
internal void OnPlayerDamage(object sender, GetDataHandlers.PlayerDamageEventArgs args)
{
byte id = args.ID;
- short dmg = args.Damage;
+ short damage = args.Damage;
bool pvp = args.PVP;
bool crit = args.Critical;
byte direction = args.Direction;
@@ -133,7 +133,7 @@ namespace TShockAPI
return;
}
- if (dmg > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap) && id != args.Player.Index)
+ if (damage > TShock.Config.MaxDamage && !args.Player.HasPermission(Permissions.ignoredamagecap) && id != args.Player.Index)
{
if (TShock.Config.KickOnDamageThresholdBroken)
{
@@ -758,14 +758,14 @@ namespace TShockAPI
/// The packet arguments that the event has.
internal void OnKillMe(object sender, GetDataHandlers.KillMeEventArgs args)
{
- short dmg = args.Damage;
+ short damage = args.Damage;
short id = args.PlayerId;
PlayerDeathReason playerDeathReason = args.PlayerDeathReason;
- if (dmg > 20000) //Abnormal values have the potential to cause infinite loops in the server.
+ if (damage > 20000) //Abnormal values have the potential to cause infinite loops in the server.
{
TShock.Utils.ForceKick(args.Player, "Crash Exploit Attempt", true);
- TShock.Log.ConsoleError("Death Exploit Attempt: Damage {0}", dmg);
+ TShock.Log.ConsoleError("Death Exploit Attempt: Damage {0}", damage);
args.Handled = true;
return;
}
@@ -797,7 +797,7 @@ namespace TShockAPI
Vector2 pos = args.Position;
Vector2 vel = args.Velocity;
float knockback = args.Knockback;
- short dmg = args.Damage;
+ short damage = args.Damage;
byte owner = args.Owner;
short type = args.Type;
int index = args.Index;
@@ -818,7 +818,7 @@ namespace TShockAPI
return;
}
- if (dmg > TShock.Config.MaxProjDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
+ if (damage > TShock.Config.MaxProjDamage && !args.Player.HasPermission(Permissions.ignoredamagecap))
{
args.Player.Disable(String.Format("Projectile damage is higher than {0}.", TShock.Config.MaxProjDamage), DisableFlags.WriteToLogAndConsole);
args.Player.RemoveProjectile(ident, owner);
From cdba07c62e0fd268c2a3e9549f9072ef1f44f73e Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 21:50:20 -0700
Subject: [PATCH 199/430] Move OnPlayerAnimation to Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 23 ++++++++++++++++++++++-
TShockAPI/GetDataHandlers.cs | 23 ++++++++---------------
3 files changed, 31 insertions(+), 16 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index abd236ca..83383492 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,6 +76,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` to `GetDataHandlers.PlayerBuff`. (@hakusaro)
* Added `TSPlayer` and `PlayerDeathReason` to `GetDataHandlers.PlayerDamage`. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.NPCStrike`. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.PlayerAnimation`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index f1e62ab8..ab291c3a 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -41,6 +41,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlayerAnimation.Register(OnPlayerAnimation);
GetDataHandlers.NPCStrike.Register(OnNPCStrike);
GetDataHandlers.ItemDrop.Register(OnItemDrop);
GetDataHandlers.PlayerBuff.Register(OnPlayerBuff);
@@ -59,6 +60,26 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles basic animation throttling for disabled players.
+ /// sender
+ /// args
+ internal void OnPlayerAnimation(object sender, GetDataHandlers.PlayerAnimationEventArgs args)
+ {
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
+ args.Handled = true;
+ return;
+ }
+
+ if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ {
+ args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles the NPC Strike event for Bouncer.
/// The object that triggered the event.
/// The packet arguments that the event has.
@@ -69,7 +90,7 @@ namespace TShockAPI
short damage = args.Damage;
float knockback = args.Knockback;
byte crit = args.Critical;
-
+
if (Main.npc[id] == null)
{
args.Handled = true;
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index e6555cc3..b6d182b7 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1298,6 +1298,8 @@ namespace TShockAPI
///
public class PlayerAnimationEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
}
///
@@ -1305,12 +1307,15 @@ namespace TShockAPI
///
public static HandlerList PlayerAnimation;
- private static bool OnPlayerAnimation()
+ private static bool OnPlayerAnimation(TSPlayer player)
{
if (PlayerAnimation == null)
return false;
- var args = new PlayerAnimationEventArgs { };
+ var args = new PlayerAnimationEventArgs
+ {
+ Player = player,
+ };
PlayerAnimation.Invoke(null, args);
return args.Handled;
}
@@ -2635,21 +2640,9 @@ namespace TShockAPI
private static bool HandlePlayerAnimation(GetDataHandlerArgs args)
{
- if (OnPlayerAnimation())
+ if (OnPlayerAnimation(args.Player))
return true;
- if (TShock.CheckIgnores(args.Player))
- {
- args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
- return true;
- }
-
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
- {
- args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
- return true;
- }
-
return false;
}
From 681f2a2432b84e0dc9c3bbd60dbd862c6f329d13 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 22:15:17 -0700
Subject: [PATCH 200/430] Add & move OnMassWireOperation hook to Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 37 ++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 73 +++++++++++++++++++++++-------------
3 files changed, 85 insertions(+), 26 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 83383492..574c1962 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -77,6 +77,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` and `PlayerDeathReason` to `GetDataHandlers.PlayerDamage`. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.NPCStrike`. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.PlayerAnimation`. (@hakusaro)
+* Added `GetDataHandlers.MassWireOperation` hook and related arguments. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index ab291c3a..f7e1628e 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -60,6 +60,43 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ internal void OnMassWireOperation(object sender, GetDataHandlers.MassWireOperationEventArgs args)
+ {
+ short startX = args.StartX;
+ short startY = args.StartY;
+ short endX = args.EndX;
+ short endY = args.EndY;
+
+ List points = Utils.Instance.GetMassWireOperationRange(
+ new Point(startX, startY),
+ new Point(endX, endY),
+ args.Player.TPlayer.direction == 1);
+
+ int x;
+ int y;
+ foreach (Point p in points)
+ {
+ /* Perform similar checks to TileKill
+ * The server-side nature of this packet removes the need to use SendTileSquare
+ * Range checks are currently ignored here as the items that send this seem to have infinite range */
+
+ x = p.X;
+ y = p.Y;
+
+ if (!TShock.Utils.TilePlacementValid(x, y) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ args.Handled = true;
+ return;
+
+ if (TShock.CheckIgnores(args.Player))
+ args.Handled = true;
+ return;
+
+ if (TShock.CheckTilePermission(args.Player, x, y))
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles basic animation throttling for disabled players.
/// sender
/// args
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index b6d182b7..eb7aa572 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1260,6 +1260,50 @@ namespace TShockAPI
return args.Handled;
}
+ /// The arguments to the MassWireOperation event.
+ public class MassWireOperationEventArgs : HandledEventArgs
+ {
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
+
+ /// The start X point in the operation.
+ public short StartX { get; set; }
+
+ /// The start Y point in the operation.
+ public short StartY { get; set; }
+
+ /// The end X point in the operation.
+ public short EndX { get; set; }
+
+ /// The end Y point in the operation.
+ public short EndY { get; set; }
+
+ /// ToolMode
+ public byte ToolMode { get; set; }
+ }
+
+ /// Fired on a mass wire edit operation.
+ public static HandlerList MassWireOperation;
+
+ private static bool OnMassWireOperation(TSPlayer player, short startX, short startY, short endX, short endY, byte toolMode)
+ {
+ if (MassWireOperation == null)
+ return false;
+
+ var args = new MassWireOperationEventArgs
+ {
+ Player = player,
+ StartX = startX,
+ StartY = startY,
+ EndX = endX,
+ EndY = endY,
+ ToolMode = toolMode,
+ };
+
+ MassWireOperation.Invoke(null, args);
+ return args.Handled;
+ }
+
///
/// For use with a NPCSpecial event
///
@@ -2987,33 +3031,10 @@ namespace TShockAPI
short startY = args.Data.ReadInt16();
short endX = args.Data.ReadInt16();
short endY = args.Data.ReadInt16();
- args.Data.ReadByte(); // Ignore toolmode
+ byte toolMode = (byte) args.Data.ReadByte();
- List points = Utils.Instance.GetMassWireOperationRange(
- new Point(startX, startY),
- new Point(endX, endY),
- args.Player.TPlayer.direction == 1);
-
- int x;
- int y;
- foreach (Point p in points)
- {
- /* Perform similar checks to TileKill
- * The server-side nature of this packet removes the need to use SendTileSquare
- * Range checks are currently ignored here as the items that send this seem to have infinite range */
-
- x = p.X;
- y = p.Y;
-
- if (!TShock.Utils.TilePlacementValid(x, y) || (args.Player.Dead && TShock.Config.PreventDeadModification))
- return true;
-
- if (TShock.CheckIgnores(args.Player))
- return true;
-
- if (TShock.CheckTilePermission(args.Player, x, y))
- return true;
- }
+ if (OnMassWireOperation(args.Player, startX, startY, endX, endY, toolMode))
+ return true;
return false;
}
From 64facfc10cffe9e84f4c148fe791dd94c2b49ac9 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 22:29:52 -0700
Subject: [PATCH 201/430] Document internal mass wire op in Bouncer
---
TShockAPI/Bouncer.cs | 3 +++
1 file changed, 3 insertions(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index f7e1628e..731abbda 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -60,6 +60,9 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles validation of of basic anti-cheat on mass wire operations.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
internal void OnMassWireOperation(object sender, GetDataHandlers.MassWireOperationEventArgs args)
{
short startX = args.StartX;
From de017f2d416c20fc573445be5be2511369f58521 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 22:51:07 -0700
Subject: [PATCH 202/430] Create & move OnPlaceTileEntity to Bouncer; fix
unreachable code
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 33 ++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 60 ++++++++++++++++++++++++++----------
3 files changed, 78 insertions(+), 16 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 574c1962..9b591efc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -78,6 +78,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` to `GetDataHandlers.NPCStrike`. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.PlayerAnimation`. (@hakusaro)
* Added `GetDataHandlers.MassWireOperation` hook and related arguments. (@hakusaro)
+* Added `GetDataHandlers.PlaceTileEntity` hook and related arguments. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 731abbda..b8df3ddb 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -41,6 +41,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlaceTileEntity.Register(OnPlaceTileEntity);
GetDataHandlers.PlayerAnimation.Register(OnPlayerAnimation);
GetDataHandlers.NPCStrike.Register(OnNPCStrike);
GetDataHandlers.ItemDrop.Register(OnItemDrop);
@@ -60,6 +61,30 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Fired when a PlaceTileEntity occurs for basic anti-cheat on perms and range.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnPlaceTileEntity(object sender, GetDataHandlers.PlaceTileEntityEventArgs args)
+ {
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, args.X, args.Y))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, args.X, args.Y))
+ {
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles validation of of basic anti-cheat on mass wire operations.
/// The object that triggered the event.
/// The packet arguments that the event has.
@@ -87,16 +112,22 @@ namespace TShockAPI
y = p.Y;
if (!TShock.Utils.TilePlacementValid(x, y) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ {
args.Handled = true;
return;
+ }
if (TShock.CheckIgnores(args.Player))
+ {
args.Handled = true;
return;
+ }
if (TShock.CheckTilePermission(args.Player, x, y))
+ {
args.Handled = true;
return;
+ }
}
}
@@ -497,8 +528,10 @@ namespace TShockAPI
int flag = args.Flag;
if (!TShock.Utils.TilePlacementValid(tileX, tileY) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ {
args.Handled = true;
return;
+ }
if (TShock.CheckIgnores(args.Player))
{
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index eb7aa572..6721d5a1 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -1304,6 +1304,42 @@ namespace TShockAPI
return args.Handled;
}
+ /// For use in a PlaceTileEntity event.
+ public class PlaceTileEntityEventArgs : HandledEventArgs
+ {
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
+
+ /// The X coordinate of the event.
+ public short X { get; set; }
+
+ /// The Y coordinate of the event.
+ public short Y { get; set; }
+
+ /// The Type of event.
+ public byte Type { get; set; }
+ }
+
+ /// Fired when a PlaceTileEntity event occurs.
+ public static HandlerList PlaceTileEntity;
+
+ private static bool OnPlaceTileEntity(TSPlayer player, short x, short y, byte type)
+ {
+ if (PlaceTileEntity == null)
+ return false;
+
+ var args = new PlaceTileEntityEventArgs
+ {
+ Player = player,
+ X = x,
+ Y = y,
+ Type = type
+ };
+
+ PlaceTileEntity.Invoke(null, args);
+ return args.Handled;
+ }
+
///
/// For use with a NPCSpecial event
///
@@ -3175,7 +3211,14 @@ namespace TShockAPI
{
var x = args.Data.ReadInt16();
var y = args.Data.ReadInt16();
- var type = args.Data.ReadByte();
+ var type = (byte) args.Data.ReadByte();
+
+ if (OnPlaceTileEntity(args.Player, x, y, type))
+ {
+ return true;
+ }
+
+ // ItemBan subsystem
if (TShock.TileBans.TileIsBanned((short)TileID.LogicSensor, args.Player))
{
@@ -3184,21 +3227,6 @@ namespace TShockAPI
return true;
}
- if (TShock.CheckIgnores(args.Player))
- {
- return true;
- }
-
- if (TShock.CheckTilePermission(args.Player, x, y))
- {
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, x, y))
- {
- return true;
- }
-
return false;
}
From 748d7f7fab0e9cc3d25c82ae2bf2c74e8543fc60 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 22:58:41 -0700
Subject: [PATCH 203/430] Move OnGemLockToggle -> Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 31 +++++++++++++++++++++++++++++++
TShockAPI/GetDataHandlers.cs | 32 +++++++-------------------------
3 files changed, 39 insertions(+), 25 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b591efc..e48fd0cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -79,6 +79,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `TSPlayer` to `GetDataHandlers.PlayerAnimation`. (@hakusaro)
* Added `GetDataHandlers.MassWireOperation` hook and related arguments. (@hakusaro)
* Added `GetDataHandlers.PlaceTileEntity` hook and related arguments. (@hakusaro)
+* Added `TSPlayer` to `GetDataHandlers.GemLockToggle`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index b8df3ddb..d29b94ae 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -41,6 +41,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.GemLockToggle.Register(OnGemLockToggle);
GetDataHandlers.PlaceTileEntity.Register(OnPlaceTileEntity);
GetDataHandlers.PlayerAnimation.Register(OnPlayerAnimation);
GetDataHandlers.NPCStrike.Register(OnNPCStrike);
@@ -61,6 +62,36 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Handles the anti-cheat components of gem lock toggles.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnGemLockToggle(object sender, GetDataHandlers.GemLockToggleEventArgs args)
+ {
+ if (args.X < 0 || args.Y < 0 || args.X >= Main.maxTilesX || args.Y >= Main.maxTilesY)
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (!TShock.Utils.TilePlacementValid(args.X, args.Y) || (args.Player.Dead && TShock.Config.PreventDeadModification))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckIgnores(args.Player))
+ {
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, args.X, args.Y))
+ {
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Fired when a PlaceTileEntity occurs for basic anti-cheat on perms and range.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 6721d5a1..8e10eb98 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -3080,14 +3080,16 @@ namespace TShockAPI
///
public class GemLockToggleEventArgs : HandledEventArgs
{
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
///
/// X Location
///
- public Int32 X { get; set; }
+ public short X { get; set; }
///
/// Y Location
///
- public Int32 Y { get; set; }
+ public short Y { get; set; }
///
/// On status
///
@@ -3099,7 +3101,7 @@ namespace TShockAPI
///
public static HandlerList GemLockToggle;
- private static bool OnGemLockToggle(Int32 x, Int32 y, bool on)
+ private static bool OnGemLockToggle(short x, short y, bool on)
{
if (GemLockToggle == null)
return false;
@@ -3116,15 +3118,10 @@ namespace TShockAPI
private static bool HandleGemLockToggle(GetDataHandlerArgs args)
{
- var x = (int)args.Data.ReadInt16();
- var y = (int)args.Data.ReadInt16();
+ var x = args.Data.ReadInt16();
+ var y = args.Data.ReadInt16();
var on = args.Data.ReadBoolean();
- if (x < 0 || y < 0 || x >= Main.maxTilesX || y >= Main.maxTilesY)
- {
- return true;
- }
-
if (OnGemLockToggle(x, y, on))
{
return true;
@@ -3135,21 +3132,6 @@ namespace TShockAPI
return false;
}
- if (!TShock.Utils.TilePlacementValid(x, y) || (args.Player.Dead && TShock.Config.PreventDeadModification))
- {
- return true;
- }
-
- if (TShock.CheckIgnores(args.Player))
- {
- return true;
- }
-
- if (TShock.CheckTilePermission(args.Player, x, y))
- {
- return true;
- }
-
return false;
}
From 9f7c3ead09bb090e686c59430297f7c328619a42 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Fri, 15 Dec 2017 23:15:43 -0700
Subject: [PATCH 204/430] Add & move OnPlaceItemFrame to Bouncer
---
CHANGELOG.md | 1 +
TShockAPI/Bouncer.cs | 29 +++++++++++++++++
TShockAPI/GetDataHandlers.cs | 63 ++++++++++++++++++++++++++++--------
3 files changed, 79 insertions(+), 14 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e48fd0cc..226bcfe0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -80,6 +80,7 @@ Putting this stuff down here so things don't conflict as often.
* Added `GetDataHandlers.MassWireOperation` hook and related arguments. (@hakusaro)
* Added `GetDataHandlers.PlaceTileEntity` hook and related arguments. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.GemLockToggle`. (@hakusaro)
+* Added `GetDataHandlers.PlaceItemFrame` hook and related arguments. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index d29b94ae..ae522e19 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -29,6 +29,7 @@ using static TShockAPI.GetDataHandlers;
using TerrariaApi.Server;
using Terraria.ObjectData;
using Terraria.DataStructures;
+using Terraria.Localization;
namespace TShockAPI
{
@@ -41,6 +42,7 @@ namespace TShockAPI
{
// Setup hooks
+ GetDataHandlers.PlaceItemFrame.Register(OnPlaceItemFrame);
GetDataHandlers.GemLockToggle.Register(OnGemLockToggle);
GetDataHandlers.PlaceTileEntity.Register(OnPlaceTileEntity);
GetDataHandlers.PlayerAnimation.Register(OnPlayerAnimation);
@@ -62,6 +64,33 @@ namespace TShockAPI
GetDataHandlers.TileEdit.Register(OnTileEdit);
}
+ /// Fired when an item frame is placed for anti-cheat detection.
+ /// The object that triggered the event.
+ /// The packet arguments that the event has.
+ internal void OnPlaceItemFrame(object sender, GetDataHandlers.PlaceItemFrameEventArgs args)
+ {
+ if (TShock.CheckIgnores(args.Player))
+ {
+ NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, args.ItemFrame.ID, 0, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckTilePermission(args.Player, args.X, args.Y))
+ {
+ NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, args.ItemFrame.ID, 0, 1);
+ args.Handled = true;
+ return;
+ }
+
+ if (TShock.CheckRangePermission(args.Player, args.X, args.Y))
+ {
+ NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, args.ItemFrame.ID, 0, 1);
+ args.Handled = true;
+ return;
+ }
+ }
+
/// Handles the anti-cheat components of gem lock toggles.
/// The object that triggered the event.
/// The packet arguments that the event has.
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 8e10eb98..82ef08c4 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -3075,6 +3075,54 @@ namespace TShockAPI
return false;
}
+ /// The arguments to the PlaceItemFrame event.
+ public class PlaceItemFrameEventArgs : HandledEventArgs
+ {
+ /// The TSPlayer that triggered the event.
+ public TSPlayer Player { get; set; }
+
+ /// The X coordinate of the item frame.
+ public short X { get; set; }
+
+ /// The Y coordinate of the item frame.
+ public short Y { get; set; }
+
+ /// The ItemID of the item frame.
+ public short ItemID { get; set; }
+
+ /// The prefix.
+ public byte Prefix { get; set; }
+
+ /// The stack.
+ public short Stack { get; set; }
+
+ /// The ItemFrame object associated with this event.
+ public TEItemFrame ItemFrame { get; set; }
+ }
+
+ /// Fired when an ItemFrame is placed.
+ public static HandlerList PlaceItemFrame;
+
+ private static bool OnPlaceItemFrame(TSPlayer player, short x, short y, short itemID, byte prefix, short stack, TEItemFrame itemFrame)
+ {
+ if (PlaceItemFrame == null)
+ return false;
+
+ var args = new PlaceItemFrameEventArgs
+ {
+ Player = player,
+ X = x,
+ Y = y,
+ ItemID = itemID,
+ Prefix = prefix,
+ Stack = stack,
+ ItemFrame = itemFrame,
+ };
+
+ PlaceItemFrame.Invoke(null, args);
+ return args.Handled;
+ }
+
///
/// For use with a ToggleGemLock event
///
@@ -3221,21 +3269,8 @@ namespace TShockAPI
var stack = args.Data.ReadInt16();
var itemFrame = (TEItemFrame)TileEntity.ByID[TEItemFrame.Find(x, y)];
- if (TShock.CheckIgnores(args.Player))
+ if (OnPlaceItemFrame(args.Player, x, y, itemID, prefix, stack, itemFrame))
{
- NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, itemFrame.ID, 0, 1);
- return true;
- }
-
- if (TShock.CheckTilePermission(args.Player, x, y))
- {
- NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, itemFrame.ID, 0, 1);
- return true;
- }
-
- if (TShock.CheckRangePermission(args.Player, x, y))
- {
- NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, itemFrame.ID, 0, 1);
return true;
}
From 1bee289dafd82e6e8c9822b77ff2c2229e96c740 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 01:03:05 -0700
Subject: [PATCH 205/430] Move TShock.CheckIgnores(TSPlayer) ->
TSPlayer.CheckIgnores()
Note: This method really sucks and needs to be rebuilt anyway.
---
TShockAPI/Bouncer.cs | 40 ++++++++++++++++++++--------------------
TShockAPI/TSPlayer.cs | 8 ++++++++
TShockAPI/TShock.cs | 12 ++----------
3 files changed, 30 insertions(+), 30 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index ae522e19..38769b06 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -69,7 +69,7 @@ namespace TShockAPI
/// The packet arguments that the event has.
internal void OnPlaceItemFrame(object sender, GetDataHandlers.PlaceItemFrameEventArgs args)
{
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
NetMessage.SendData((int)PacketTypes.UpdateTileEntity, -1, -1, NetworkText.Empty, args.ItemFrame.ID, 0, 1);
args.Handled = true;
@@ -108,7 +108,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Handled = true;
return;
@@ -126,7 +126,7 @@ namespace TShockAPI
/// The packet arguments that the event has.
internal void OnPlaceTileEntity(object sender, GetDataHandlers.PlaceTileEntityEventArgs args)
{
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Handled = true;
return;
@@ -177,7 +177,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Handled = true;
return;
@@ -196,7 +196,7 @@ namespace TShockAPI
/// args
internal void OnPlayerAnimation(object sender, GetDataHandlers.PlayerAnimationEventArgs args)
{
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
args.Handled = true;
@@ -245,7 +245,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.NpcUpdate, "", id);
args.Handled = true;
@@ -311,7 +311,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.PlayerHp, "", id);
args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
@@ -419,7 +419,7 @@ namespace TShockAPI
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.ItemDrop, "", id);
args.Handled = true;
@@ -442,7 +442,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
args.Handled = true;
@@ -501,7 +501,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendData(PacketTypes.ChestItem, "", id, slot);
args.Handled = true;
@@ -556,7 +556,7 @@ namespace TShockAPI
/// The packet arguments that the event has.
internal void OnChestOpen(object sender, GetDataHandlers.ChestOpenEventArgs args)
{
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Handled = true;
return;
@@ -593,7 +593,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendTileSquare(tileX, tileY, 3);
args.Handled = true;
@@ -654,7 +654,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendTileSquare(tileX, tileY, 1);
args.Handled = true;
@@ -789,7 +789,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.RemoveProjectile(args.ProjectileIdentity, args.ProjectileOwner);
args.Handled = true;
@@ -839,7 +839,7 @@ namespace TShockAPI
float distance = Vector2.Distance(new Vector2(pos.X / 16f, pos.Y / 16f),
new Vector2(args.Player.LastNetPosition.X / 16f, args.Player.LastNetPosition.Y / 16f));
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
// If the player has moved outside the disabled zone...
if (distance > TShock.Config.MaxRangeForDisabled)
@@ -980,7 +980,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.RemoveProjectile(ident, owner);
args.Handled = true;
@@ -1113,7 +1113,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendTileSquare(x, y, 4);
args.Handled = true;
@@ -1467,7 +1467,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
@@ -1583,7 +1583,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player) || (DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.CheckIgnores() || (DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
{
args.Handled = true;
return;
@@ -1624,7 +1624,7 @@ namespace TShockAPI
return;
}
- if (TShock.CheckIgnores(args.Player))
+ if (args.Player.CheckIgnores())
{
args.Player.SendTileSquare(tileX, tileY, size);
args.Handled = true;
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 73a2bce0..5c732457 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -285,6 +285,14 @@ namespace TShockAPI
public bool IgnoreActionsForClearingTrashCan;
+ /// CheckIgnores - Checks a players ignores...?
+ /// player - The TSPlayer object.
+ /// bool - True if any ignore is not none, false, or login state differs from the required state.
+ public bool CheckIgnores()
+ {
+ return IgnoreActionsForInventory != "none" || IgnoreActionsForCheating != "none" || IgnoreActionsForDisabledArmor != "none" || IgnoreActionsForClearingTrashCan || !IsLoggedIn && TShock.Config.RequireLogin;
+ }
+
///
/// The player's server side inventory data.
///
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 232d9e36..6f8b54e4 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -1080,7 +1080,7 @@ namespace TShockAPI
if (Main.ServerSideCharacter && !player.IsLoggedIn)
{
- if (CheckIgnores(player))
+ if (player.CheckIgnores())
{
player.Disable(flags: flags);
}
@@ -1160,7 +1160,7 @@ namespace TShockAPI
}
player.IgnoreActionsForDisabledArmor = check;
- if (CheckIgnores(player))
+ if (player.CheckIgnores())
{
player.Disable(flags: flags);
}
@@ -2142,14 +2142,6 @@ namespace TShockAPI
return check;
}
- /// CheckIgnores - Checks a players ignores...?
- /// player - The TSPlayer object.
- /// bool - True if any ignore is not none, false, or login state differs from the required state.
- public static bool CheckIgnores(TSPlayer player)
- {
- return player.IgnoreActionsForInventory != "none" || player.IgnoreActionsForCheating != "none" || player.IgnoreActionsForDisabledArmor != "none" || player.IgnoreActionsForClearingTrashCan || !player.IsLoggedIn && Config.RequireLogin;
- }
-
/// OnConfigRead - Fired when the config file has been read.
/// file - The config file object.
public void OnConfigRead(ConfigFile file)
From 0260530848aa90228a406da1802e91aaf98f2f84 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 01:06:41 -0700
Subject: [PATCH 206/430] Change Bouncer initialization to a more permanent
home
---
TShockAPI/Bouncer.cs | 4 ++--
TShockAPI/TShock.cs | 5 ++++-
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 38769b06..b0f110ab 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -33,12 +33,12 @@ using Terraria.Localization;
namespace TShockAPI
{
- /// Bouncer is the TShock anti-hack and build guardian system
+ /// Bouncer is the TShock anti-hack and anti-cheat system.
internal sealed class Bouncer
{
/// Constructor call initializes Bouncer and related functionality.
/// A new Bouncer.
- internal Bouncer(TerrariaPlugin pluginInstance)
+ internal Bouncer()
{
// Setup hooks
diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs
index 6f8b54e4..9766b93d 100644
--- a/TShockAPI/TShock.cs
+++ b/TShockAPI/TShock.cs
@@ -138,6 +138,9 @@ namespace TShockAPI
///
public static Dictionary RESTStartupTokens = new Dictionary();
+ /// The TShock anti-cheat/anti-exploit system.
+ internal Bouncer Bouncer;
+
///
/// Called after TShock is initialized. Useful for plugins that needs hooks before tshock but also depend on tshock being loaded.
///
@@ -322,6 +325,7 @@ namespace TShockAPI
RestApi = new SecureRest(Netplay.ServerIP, Config.RestApiPort);
RestManager = new RestManager(RestApi);
RestManager.RegisterRestfulCommands();
+ Bouncer = new Bouncer();
var geoippath = "GeoIP.dat";
if (Config.EnableGeoIP && File.Exists(geoippath))
@@ -379,7 +383,6 @@ namespace TShockAPI
Log.ConsoleInfo("TShock comes with no warranty & is free software.");
Log.ConsoleInfo("You can modify & distribute it under the terms of the GNU GPLv3.");
- Bouncer b = new Bouncer(this);
}
catch (Exception ex)
{
From 1e9532a3162179aa9664502421cd4cdd7ed2fbd4 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 01:14:39 -0700
Subject: [PATCH 207/430] Create TSPlayer.IsBouncerThrottled() to avoid code
copypasta
---
TShockAPI/Bouncer.cs | 20 ++++++++++----------
TShockAPI/GetDataHandlers.cs | 8 ++++----
TShockAPI/TSPlayer.cs | 7 +++++++
3 files changed, 21 insertions(+), 14 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index b0f110ab..57b4554e 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -203,7 +203,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendData(PacketTypes.PlayerAnimation, "", args.Player.Index);
args.Handled = true;
@@ -260,7 +260,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendData(PacketTypes.NpcUpdate, "", id);
args.Handled = true;
@@ -327,7 +327,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendData(PacketTypes.PlayerHp, "", id);
args.Player.SendData(PacketTypes.PlayerUpdate, "", id);
@@ -470,7 +470,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendData(PacketTypes.PlayerAddBuff, "", id);
args.Handled = true;
@@ -770,7 +770,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendTileSquare(tileX, tileY, 1);
args.Handled = true;
@@ -796,7 +796,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.RemoveProjectile(args.ProjectileIdentity, args.ProjectileOwner);
args.Handled = true;
@@ -1021,7 +1021,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.RemoveProjectile(ident, owner);
args.Handled = true;
@@ -1516,7 +1516,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendTileSquare(tileX, tileY, 4);
args.Handled = true;
@@ -1583,7 +1583,7 @@ namespace TShockAPI
return;
}
- if (args.Player.CheckIgnores() || (DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.CheckIgnores() || args.Player.IsBouncerThrottled())
{
args.Handled = true;
return;
@@ -1617,7 +1617,7 @@ namespace TShockAPI
return;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
args.Player.SendTileSquare(tileX, tileY, size);
args.Handled = true;
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 82ef08c4..d21c0e36 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2761,7 +2761,7 @@ namespace TShockAPI
private static bool HandleSpawnBoss(GetDataHandlerArgs args)
{
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
return true;
}
@@ -2896,7 +2896,7 @@ namespace TShockAPI
return true;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000 ||
+ if (args.Player.IsBouncerThrottled() ||
TShock.CheckTilePermission(args.Player, x, y, true) ||
TShock.CheckRangePermission(args.Player, x, y))
{
@@ -2940,7 +2940,7 @@ namespace TShockAPI
return true;
}
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000 ||
+ if (args.Player.IsBouncerThrottled() ||
TShock.CheckTilePermission(args.Player, x, y, true) ||
TShock.CheckRangePermission(args.Player, x, y))
{
@@ -3320,7 +3320,7 @@ namespace TShockAPI
private static bool HandleOldOnesArmy(GetDataHandlerArgs args)
{
- if ((DateTime.UtcNow - args.Player.LastThreat).TotalMilliseconds < 5000)
+ if (args.Player.IsBouncerThrottled())
{
return true;
}
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index 5c732457..aae8ace8 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -285,6 +285,13 @@ namespace TShockAPI
public bool IgnoreActionsForClearingTrashCan;
+ /// Checks to see if active throttling is happening on events by Bouncer. Rejects repeated events by malicious clients in a short window.
+ /// If the player is currently being throttled by Bouncer, or not.
+ public bool IsBouncerThrottled()
+ {
+ return (DateTime.UtcNow - LastThreat).TotalMilliseconds < 5000;
+ }
+
/// CheckIgnores - Checks a players ignores...?
/// player - The TSPlayer object.
/// bool - True if any ignore is not none, false, or login state differs from the required state.
From cff91f39e8fc3edb43e8180429e8c4ec69152f14 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 01:18:22 -0700
Subject: [PATCH 208/430] Update the changelog
---
CHANGELOG.md | 28 ++--------------------------
1 file changed, 2 insertions(+), 26 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 226bcfe0..30241bbb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,32 +34,6 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin
* Removed `Permissions.updateplugins` permission. (@hakusaro)
* Removed REST `/v3/server/restart/` route and `/server/restart/` route. (@hakusaro)
* The "auth system" is now referred to as the initial setup system (what it actually is). This is better verbiage for basically all situations. Who really wants to turn off the "authentication system?" In addition, the system now makes it more clear what the point of it is, rather than that it grants permissions. (@hakusaro)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## Bouncer changes
-
-Putting this stuff down here so things don't conflict as often.
-
* `GetDataHandlers.SendTileSquare` hook now sends a `TSPlayer` and a `MemoryStream` of raw data. (@hakusaro)
* Added `GetDataHandlers.HealOtherPlayer` hook. (@hakusaro)
* Added `GetDataHandlers.PlaceObject` hook. (@hakusaro)
@@ -81,6 +55,8 @@ Putting this stuff down here so things don't conflict as often.
* Added `GetDataHandlers.PlaceTileEntity` hook and related arguments. (@hakusaro)
* Added `TSPlayer` to `GetDataHandlers.GemLockToggle`. (@hakusaro)
* Added `GetDataHandlers.PlaceItemFrame` hook and related arguments. (@hakusaro)
+* Added `TSPlayer.IsBouncerThrottled()`. (@hakusaro)
+* Added `TSPlayer.CheckIgnores()` and removed `TShock.CheckIgnores(TSPlayer)`. (@hakusaro)
## TShock 4.3.25
* Fixed a critical exploit in the Terraria protocol that could cause massive unpreventable world corruption as well as a number of other problems. Thanks to @bartico6 for reporting. Fixed by the efforts of @QuiCM, @hakusaro, and tips in the right directioon from @bartico6.
From 9d0c84fd13b0a9825f8683a7f774175b0881accb Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 10:37:44 -0700
Subject: [PATCH 209/430] Fix handler registration in Bouncer init constructor
---
TShockAPI/Bouncer.cs | 40 ++++++++++++++++++++--------------------
1 file changed, 20 insertions(+), 20 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 57b4554e..91e3d6e8 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -42,26 +42,26 @@ namespace TShockAPI
{
// Setup hooks
- GetDataHandlers.PlaceItemFrame.Register(OnPlaceItemFrame);
- GetDataHandlers.GemLockToggle.Register(OnGemLockToggle);
- GetDataHandlers.PlaceTileEntity.Register(OnPlaceTileEntity);
- GetDataHandlers.PlayerAnimation.Register(OnPlayerAnimation);
- GetDataHandlers.NPCStrike.Register(OnNPCStrike);
- GetDataHandlers.ItemDrop.Register(OnItemDrop);
- GetDataHandlers.PlayerBuff.Register(OnPlayerBuff);
- GetDataHandlers.ChestItemChange.Register(OnChestItemChange);
- GetDataHandlers.NPCHome.Register(OnUpdateNPCHome);
- GetDataHandlers.ChestOpen.Register(OnChestOpen);
- GetDataHandlers.PlaceChest.Register(OnPlaceChest);
- GetDataHandlers.LiquidSet.Register(OnLiquidSet);
- GetDataHandlers.ProjectileKill.Register(OnProjectileKill);
- GetDataHandlers.PlayerUpdate.Register(OnPlayerUpdate);
- GetDataHandlers.KillMe.Register(OnKillMe);
- GetDataHandlers.NewProjectile.Register(OnNewProjectile);
- GetDataHandlers.PlaceObject.Register(OnPlaceObject);
- GetDataHandlers.SendTileSquare.Register(OnSendTileSquare);
- GetDataHandlers.HealOtherPlayer.Register(OnHealOtherPlayer);
- GetDataHandlers.TileEdit.Register(OnTileEdit);
+ GetDataHandlers.PlaceItemFrame += OnPlaceItemFrame;
+ GetDataHandlers.GemLockToggle += OnGemLockToggle;
+ GetDataHandlers.PlaceTileEntity += OnPlaceTileEntity;
+ GetDataHandlers.PlayerAnimation += OnPlayerAnimation;
+ GetDataHandlers.NPCStrike += OnNPCStrike;
+ GetDataHandlers.ItemDrop += OnItemDrop;
+ GetDataHandlers.PlayerBuff += OnPlayerBuff;
+ GetDataHandlers.ChestItemChange += OnChestItemChange;
+ GetDataHandlers.NPCHome += OnUpdateNPCHome;
+ GetDataHandlers.ChestOpen += OnChestOpen;
+ GetDataHandlers.PlaceChest += OnPlaceChest;
+ GetDataHandlers.LiquidSet += OnLiquidSet;
+ GetDataHandlers.ProjectileKill += OnProjectileKill;
+ GetDataHandlers.PlayerUpdate += OnPlayerUpdate;
+ GetDataHandlers.KillMe += OnKillMe;
+ GetDataHandlers.NewProjectile += OnNewProjectile;
+ GetDataHandlers.PlaceObject += OnPlaceObject;
+ GetDataHandlers.SendTileSquare += OnSendTileSquare;
+ GetDataHandlers.HealOtherPlayer += OnHealOtherPlayer;
+ GetDataHandlers.TileEdit += OnTileEdit;
}
/// Fired when an item frame is placed for anti-cheat detection.
From b71458b293d82b0dd18270f8e7b48fe497aebb4a Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sat, 16 Dec 2017 20:37:43 -0700
Subject: [PATCH 210/430] Fix /setup not working with owner groups; update
readme
---
README.md | 2 +-
TShockAPI/Commands.cs | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 6caab0cf..303f89c9 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ _These instructions assume Windows. If you're setting up on Linux or macOS, plea
1. Look at the server console for the _setup code_. Type `/setup [code]` (example: `/setup 12345`), then a space, then the code you see in the console in your game chat. Instead of chatting, you'll run a command on the server. This one makes you temporary admin. All commands are prefixed with `/` or `!` (to make them silent).
-1. Use the in-game command `/register [password]` (example: `/register lovely-ashes`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later. Your `character name` is your `account name`.
+1. Use the in-game command `/user add [account name] [password] owner` (example: `/user add shank lovely-ashes owner`) to create an account. This gives you owner rights on your server, which you can configure more to your liking later.
1. Login to your newly created account with `/login [account name] [password]` (example: `/login shank lovely-ashes`). You should see a login success message.
diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs
index 1d8545ca..1964d071 100644
--- a/TShockAPI/Commands.cs
+++ b/TShockAPI/Commands.cs
@@ -4845,7 +4845,7 @@ namespace TShockAPI
}
// If the user account is already a superadmin (permanent), disable the system
- if (args.Player.IsLoggedIn && args.Player.tempGroup == null && args.Player.Group.Name == new SuperAdminGroup().Name)
+ if (args.Player.IsLoggedIn && args.Player.tempGroup == null)
{
args.Player.SendSuccessMessage("Your new account has been verified, and the {0}setup system has been turned off.", Specifier);
args.Player.SendSuccessMessage("You can always use the {0}user command to manage players.", Specifier);
From 3f79a904daa43f13159502de05b6371f2f9c5192 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 17 Dec 2017 00:39:11 -0700
Subject: [PATCH 211/430] Bouncer: Handle case where prefix < 1
---
TShockAPI/Bouncer.cs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 91e3d6e8..3e460013 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -360,7 +360,7 @@ namespace TShockAPI
}
//make sure the prefix is a legit value
- if (prefix > PrefixID.Count)
+ if (prefix > PrefixID.Count || prefix < 1)
{
args.Player.SendData(PacketTypes.ItemDrop, "", id);
args.Handled = true;
From 14a6338b73152bf58ad3974db70f115982383eee Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 17 Dec 2017 00:44:19 -0700
Subject: [PATCH 212/430] Add a "remove from bouncer" todo item
---
TShockAPI/Bouncer.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 3e460013..4f4e6419 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -1224,6 +1224,7 @@ namespace TShockAPI
return;
}
+ // TODO: Remove from bouncer (does't look like Bouncer code)
if (args.Player.AwaitingName)
{
bool includeUnprotected = false;
From c1de974e16fc08d03482221798e584903304592f Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 17 Dec 2017 01:04:47 -0700
Subject: [PATCH 213/430] Remove happiness.
http://rubyonrails.org/doctrine
The problem with most programmers is that they refuse to see any
logic in thinking about a problem from the other side, even just
once. You can't argue with someone over what opinionated "programmer
happiness" things are because logically you'll always be outmatched
with "well you can just do it this other way."
Take this example. How is !args.Player.HasProjectilePermission any
easier to understand than args.Player.LacksProjectilePermission?
-> One is direct: it focuses on what a player doesn't have.
-> The other is indirect: it's the inverse of have.
You can read one in a sentence and think "so if a player lacks a
permission then this happens" whereas the other is like "invert
if a player has a permission." In this soupy mess of a codebase
where you're trying to sort out what 300 magic numbers mean and
what everything else is trying to do, then it's kinda nice to
be able to read something and understand it immediately.
---
TShockAPI/GetDataHandlers.cs | 2 +-
TShockAPI/TSPlayer.cs | 9 ---------
2 files changed, 1 insertion(+), 10 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index d21c0e36..959ec454 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -2366,7 +2366,7 @@ namespace TShockAPI
var type = Main.projectile[index].type;
// TODO: This needs to be moved somewhere else.
- if (args.Player.LacksProjectilePermission(index, type) && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill)
+ if (!args.Player.HasProjectilePermission(index, type) && type != 102 && type != 100 && !TShock.Config.IgnoreProjKill)
{
args.Player.Disable("Does not have projectile permission to kill projectile.", DisableFlags.WriteToLogAndConsole);
args.Player.RemoveProjectile(ident, owner);
diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs
index aae8ace8..868f20b2 100644
--- a/TShockAPI/TSPlayer.cs
+++ b/TShockAPI/TSPlayer.cs
@@ -804,15 +804,6 @@ namespace TShockAPI
}
}
- /// Checks to see if this player object lacks access rights to a given projectile. Used by projectile bans.
- /// The projectile index from Main.projectiles (NOT from a packet directly).
- /// The type of projectile, from Main.projectiles.
- /// If the player has lacks access rights to the projectile.
- public bool LacksProjectilePermission(int index, int type)
- {
- return !HasProjectilePermission(index, type);
- }
-
/// Checks to see if this player object has access rights to a given projectile. Used by projectile bans.
/// The projectile index from Main.projectiles (NOT from a packet directly).
/// The type of projectile, from Main.projectiles.
From 263c0bc402414d5440e1b6153271c0ca86e15dad Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 17 Dec 2017 12:25:23 -0700
Subject: [PATCH 214/430] Revert "Bouncer: Handle case where prefix < 1"
This reverts commit 3f79a904daa43f13159502de05b6371f2f9c5192.
If prefix is < 1 and we block this event, clients can no longer
delete picked up items. This is what caused what Joshwoo reported.
---
TShockAPI/Bouncer.cs | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 4f4e6419..65d1865f 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -359,8 +359,10 @@ namespace TShockAPI
return;
}
- //make sure the prefix is a legit value
- if (prefix > PrefixID.Count || prefix < 1)
+ // make sure the prefix is a legit value
+ // Note: Not checking if prefix is less than 1 because if it is, this check
+ // will break item pickups on the client.
+ if (prefix > PrefixID.Count)
{
args.Player.SendData(PacketTypes.ItemDrop, "", id);
args.Handled = true;
From 713dd2614a66255e7aea10237b95036e8b62208b Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Sun, 17 Dec 2017 12:40:24 -0700
Subject: [PATCH 215/430] Fix regression where Bouncer would create dupe items
on drop
---
TShockAPI/Bouncer.cs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/TShockAPI/Bouncer.cs b/TShockAPI/Bouncer.cs
index 65d1865f..a65f840c 100644
--- a/TShockAPI/Bouncer.cs
+++ b/TShockAPI/Bouncer.cs
@@ -370,7 +370,7 @@ namespace TShockAPI
}
//Item removed, let client do this to prevent item duplication
- // client side (but only if it passed the range check)
+ // client side (but only if it passed the range check) (i.e., return false)
if (type == 0)
{
if (TShock.CheckRangePermission(args.Player, (int)(Main.item[id].position.X / 16f), (int)(Main.item[id].position.Y / 16f)))
@@ -381,7 +381,7 @@ namespace TShockAPI
return;
}
- args.Handled = true;
+ args.Handled = false;
return;
}
From 3a59280834b043b1c6072975a89ce82bf167d711 Mon Sep 17 00:00:00 2001
From: Lucas Nicodemus
Date: Wed, 20 Dec 2017 12:35:42 -0700
Subject: [PATCH 216/430] Pre-initialize TShock hooks for Register method
Hooks have this fancy .Register method when they're of type
HandlerList that high made but we never bother to initialize
any of them, so .Register doesn't work because it's null.
This solves that problem by just initializing all handlers. Thus,
.Register works, and thus, you can register hooks with priorities.
---
TShockAPI/GetDataHandlers.cs | 70 ++++++++++++++++++------------------
TShockAPI/Rest/Rest.cs | 2 +-
2 files changed, 36 insertions(+), 36 deletions(-)
diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs
index 959ec454..e5336967 100644
--- a/TShockAPI/GetDataHandlers.cs
+++ b/TShockAPI/GetDataHandlers.cs
@@ -108,7 +108,7 @@ namespace TShockAPI
///
/// TileEdit - called when a tile is placed or destroyed
///
- public static HandlerList TileEdit;
+ public static HandlerList TileEdit = new HandlerList();
private static bool OnTileEdit(TSPlayer ply, int x, int y, EditAction action, EditType editDetail, short editData, byte style)
{
if (TileEdit == null)
@@ -144,7 +144,7 @@ namespace TShockAPI
///
/// TogglePvp - called when a player toggles pvp
///
- public static HandlerList TogglePvp;
+ public static HandlerList TogglePvp = new HandlerList();
private static bool OnPvpToggled(byte _id, bool _pvp)
{
if (TogglePvp == null)
@@ -176,7 +176,7 @@ namespace TShockAPI
///
/// TogglePvp - called when a player toggles pvp
///
- public static HandlerList PlayerTeam;
+ public static HandlerList PlayerTeam = new HandlerList();
private static bool OnPlayerTeam(byte _id, byte _team)
{
if (PlayerTeam == null)
@@ -220,7 +220,7 @@ namespace TShockAPI
///
/// PlayerSlot - called at a PlayerSlot event
///
- public static HandlerList PlayerSlot;
+ public static HandlerList PlayerSlot = new HandlerList();
private static bool OnPlayerSlot(byte _plr, byte _slot, short _stack, byte _prefix, short _type)
{
if (PlayerSlot == null)
@@ -259,7 +259,7 @@ namespace TShockAPI
///
/// PlayerHP - called at a PlayerHP event
///
- public static HandlerList PlayerHP;
+ public static HandlerList PlayerHP = new HandlerList();
private static bool OnPlayerHP(byte _plr, short _cur, short _max)
{
@@ -288,7 +288,7 @@ namespace TShockAPI
///
/// PlayerMana - called at a PlayerMana event
///
- public static HandlerList PlayerMana;
+ public static HandlerList PlayerMana = new HandlerList();
private static bool OnPlayerMana(byte _plr, short _cur, short _max)
{
@@ -332,7 +332,7 @@ namespace TShockAPI
/// PlayerInfo - called at a PlayerInfo event
/// If this is cancelled, the server will ForceKick the player. If this should be changed in the future, let someone know.
///
- public static HandlerList PlayerInfo;
+ public static HandlerList PlayerInfo = new HandlerList();
private static bool OnPlayerInfo(byte _plrid, byte _hair, int _style, byte _difficulty, string _name)
{
@@ -372,7 +372,7 @@ namespace TShockAPI
///
/// When a chest is added or removed from the world.
///
- public static HandlerList PlaceChest;
+ public static HandlerList PlaceChest = new HandlerList();
private static bool OnPlaceChest(TSPlayer player, int flag, int tilex, int tiley)
{
@@ -404,7 +404,7 @@ namespace TShockAPI
}
/// The event fired when a projectile kill packet is received.
- public static HandlerList ProjectileKill;
+ public static HandlerList ProjectileKill = new HandlerList();
/// Fires the ProjectileKill event.
/// The TSPlayer that caused the event.
@@ -458,7 +458,7 @@ namespace TShockAPI
///
/// KillMe - Terraria's crappy way of handling damage from players
///
- public static HandlerList KillMe;
+ public static HandlerList KillMe = new HandlerList();
private static bool OnKillMe(TSPlayer player, byte plr, byte direction, short damage, bool pvp, PlayerDeathReason playerDeathReason)
{
@@ -511,7 +511,7 @@ namespace TShockAPI
///
/// PlayerUpdate - When the player sends it's updated information to the server
///
- public static HandlerList PlayerUpdate;
+ public static HandlerList PlayerUpdate = new HandlerList();
private static bool OnPlayerUpdate(TSPlayer player, byte plr, byte control, byte item, Vector2 position, Vector2 velocity, byte pulley)
{
@@ -600,7 +600,7 @@ namespace TShockAPI
}
/// When a player heals another player
- public static HandlerList HealOtherPlayer;
+ public static HandlerList HealOtherPlayer = new HandlerList();
/// Fires the HealOtherPlayer event
/// The TSPlayer that started the event
@@ -652,7 +652,7 @@ namespace TShockAPI
///
/// When the player sends a tile square
///
- public static HandlerList SendTileSquare;
+ public static HandlerList SendTileSquare = new HandlerList();
private static bool OnSendTileSquare(TSPlayer player, MemoryStream data, short size, int tilex, int tiley)
{
@@ -698,7 +698,7 @@ namespace TShockAPI
}
/// Fired when an object is placed in the world.
- public static HandlerList PlaceObject;
+ public static HandlerList PlaceObject = new HandlerList();
/// Fires the PlaceObject hook. To be called when an object is placed in the world.
/// The originating player.
@@ -773,7 +773,7 @@ namespace TShockAPI
///
/// NewProjectile - Called when a client creates a new projectile
///
- public static HandlerList NewProjectile;
+ public static HandlerList NewProjectile = new HandlerList();
private static bool OnNewProjectile(short ident, Vector2 pos, Vector2 vel, float knockback, short dmg, byte owner, short type, int index, TSPlayer player)
{
@@ -823,7 +823,7 @@ namespace TShockAPI
///
/// LiquidSet - When ever a liquid is set
///
- public static HandlerList LiquidSet;
+ public static HandlerList LiquidSet = new HandlerList();
private static bool OnLiquidSet(TSPlayer player, int tilex, int tiley, byte amount, byte type)
{
@@ -862,7 +862,7 @@ namespace TShockAPI
///
/// PlayerSpawn - When a player spawns
///
- public static HandlerList PlayerSpawn;
+ public static HandlerList PlayerSpawn = new HandlerList();
private static bool OnPlayerSpawn(byte player, int spawnX, int spawnY)
{
@@ -900,7 +900,7 @@ namespace TShockAPI
///
/// ChestOpen - Called when any chest is opened
///
- public static HandlerList ChestOpen;
+ public static HandlerList ChestOpen = new HandlerList();
private static bool OnChestOpen(int x, int y, TSPlayer player)
{
@@ -948,7 +948,7 @@ namespace TShockAPI
///
/// ChestItemChange - Called when an item in a chest changes
///
- public static HandlerList ChestItemChange;
+ public static HandlerList ChestItemChange = new HandlerList();
private static bool OnChestItemChange(TSPlayer player, short id, byte slot, short stacks, byte prefix, short type)
{
@@ -989,7 +989,7 @@ namespace TShockAPI
///
/// Sign - Called when a sign is changed
///
- public static HandlerList Sign;
+ public static HandlerList Sign = new HandlerList();
private static bool OnSignEvent(short id, int x, int y)
{
@@ -1033,7 +1033,7 @@ namespace TShockAPI
///
/// NPCHome - Called when an NPC's home is changed
///
- public static HandlerList NPCHome;
+ public static HandlerList NPCHome = new HandlerList();
private static bool OnUpdateNPCHome(TSPlayer player, short id, short x, short y, byte homeless)
{
@@ -1074,7 +1074,7 @@ namespace TShockAPI
///
/// PlayerBuff - Called when a player is buffed
///
- public static HandlerList PlayerBuff;
+ public static HandlerList