Fix calls in TShock.cs and TSPlayer.cs

This commit is contained in:
Enerdy 2015-07-04 14:18:17 +01:00
parent 84c6d97f6d
commit b7aaf4092c
2 changed files with 143 additions and 183 deletions

View file

@ -100,13 +100,13 @@ namespace TShockAPI
/// </summary> /// </summary>
public Group Group public Group Group
{ {
get get
{ {
if (tempGroup != null) if (tempGroup != null)
return tempGroup; return tempGroup;
return group; return group;
} }
set { group = value; } set { group = value; }
} }
/// <summary> /// <summary>
@ -339,8 +339,8 @@ namespace TShockAPI
{ {
get get
{ {
return RealPlayer && return RealPlayer
(Netplay.serverSock[Index] != null && Netplay.serverSock[Index].active && !Netplay.serverSock[Index].kill); && (Netplay.Clients[Index] != null && Netplay.Clients[Index].IsActive && !Netplay.Clients[Index].PendingTermination);
} }
} }
@ -354,8 +354,8 @@ namespace TShockAPI
public int State public int State
{ {
get { return Netplay.serverSock[Index].state; } get { return Netplay.Clients[Index].State; }
set { Netplay.serverSock[Index].state = value; } set { Netplay.Clients[Index].State = value; }
} }
/// <summary> /// <summary>
@ -363,7 +363,7 @@ namespace TShockAPI
/// </summary> /// </summary>
public string UUID public string UUID
{ {
get { return RealPlayer ? Netplay.serverSock[Index].clientUUID : ""; } get { return RealPlayer ? Netplay.Clients[Index].ClientUUID : ""; }
} }
/// <summary> /// <summary>
@ -375,12 +375,10 @@ namespace TShockAPI
{ {
if (string.IsNullOrEmpty(CacheIP)) if (string.IsNullOrEmpty(CacheIP))
return return
CacheIP = CacheIP = RealPlayer ? (Netplay.Clients[Index].Socket.IsConnected()
RealPlayer ? TShock.Utils.GetRealIP(Netplay.Clients[Index].Socket.GetRemoteAddress().ToString())
? (Netplay.serverSock[Index].tcpClient.Connected : "")
? TShock.Utils.GetRealIP(Netplay.serverSock[Index].tcpClient.Client.RemoteEndPoint.ToString()) : "";
: "")
: "";
else else
return CacheIP; return CacheIP;
} }
@ -511,9 +509,9 @@ namespace TShockAPI
TilesDestroyed = new Dictionary<Vector2, Tile>(); TilesDestroyed = new Dictionary<Vector2, Tile>();
TilesCreated = new Dictionary<Vector2, Tile>(); TilesCreated = new Dictionary<Vector2, Tile>();
Index = index; Index = index;
Group = Group.DefaultGroup; Group = Group.DefaultGroup;
IceTiles = new List<Point>(); IceTiles = new List<Point>();
AwaitingResponse = new Dictionary<string, Action<object>>(); AwaitingResponse = new Dictionary<string, Action<object>>();
} }
protected TSPlayer(String playerName) protected TSPlayer(String playerName)
@ -521,9 +519,9 @@ namespace TShockAPI
TilesDestroyed = new Dictionary<Vector2, Tile>(); TilesDestroyed = new Dictionary<Vector2, Tile>();
TilesCreated = new Dictionary<Vector2, Tile>(); TilesCreated = new Dictionary<Vector2, Tile>();
Index = -1; Index = -1;
FakePlayer = new Player {name = playerName, whoAmi = -1}; FakePlayer = new Player {name = playerName, whoAmI = -1};
Group = Group.DefaultGroup; Group = Group.DefaultGroup;
AwaitingResponse = new Dictionary<string, Action<object>>(); AwaitingResponse = new Dictionary<string, Action<object>>();
} }
public virtual void Disconnect(string reason) public virtual void Disconnect(string reason)
@ -533,11 +531,11 @@ namespace TShockAPI
public virtual void Flush() public virtual void Flush()
{ {
var sock = Netplay.serverSock[Index]; var client = Netplay.Clients[Index];
if (sock == null) if (client == null)
return; return;
TShock.PacketBuffer.Flush(sock); TShock.PacketBuffer.Flush(client);
} }
@ -573,13 +571,13 @@ namespace TShockAPI
SendTileSquare((int) (x/16), (int) (y/16), 15); SendTileSquare((int) (x/16), (int) (y/16), 15);
TPlayer.Teleport(new Vector2(x, y), style); TPlayer.Teleport(new Vector2(x, y), style);
NetMessage.SendData((int)PacketTypes.Teleport, -1, -1, "", 0, TPlayer.whoAmi, x, y, style); NetMessage.SendData((int)PacketTypes.Teleport, -1, -1, "", 0, TPlayer.whoAmI, x, y, style);
return true; return true;
} }
public void Heal(int health = 600) public void Heal(int health = 600)
{ {
NetMessage.SendData((int)PacketTypes.PlayerHealOther, -1, -1, "", this.TPlayer.whoAmi, health); NetMessage.SendData((int)PacketTypes.PlayerHealOther, -1, -1, "", this.TPlayer.whoAmI, health);
} }
public void Spawn() public void Spawn()
@ -675,12 +673,12 @@ namespace TShockAPI
public bool GiveItemCheck(int type, string name, int width, int height, int stack, int prefix = 0) public bool GiveItemCheck(int type, string name, int width, int height, int stack, int prefix = 0)
{ {
if ((TShock.Itembans.ItemIsBanned(name) && TShock.Config.PreventBannedItemSpawn) && if ((TShock.Itembans.ItemIsBanned(name) && TShock.Config.PreventBannedItemSpawn) &&
(TShock.Itembans.ItemIsBanned(name, this) || !TShock.Config.AllowAllowedGroupsToSpawnBannedItems)) (TShock.Itembans.ItemIsBanned(name, this) || !TShock.Config.AllowAllowedGroupsToSpawnBannedItems))
return false; return false;
GiveItem(type,name,width,height,stack,prefix); GiveItem(type,name,width,height,stack,prefix);
return true; return true;
} }
public virtual void GiveItem(int type, string name, int width, int height, int stack, int prefix = 0) public virtual void GiveItem(int type, string name, int width, int height, int stack, int prefix = 0)
@ -703,42 +701,42 @@ namespace TShockAPI
public virtual void SendInfoMessage(string msg) public virtual void SendInfoMessage(string msg)
{ {
SendMessage(msg, Color.Yellow); SendMessage(msg, Color.Yellow);
} }
public void SendInfoMessage(string format, params object[] args) public void SendInfoMessage(string format, params object[] args)
{ {
SendInfoMessage(string.Format(format, args)); SendInfoMessage(string.Format(format, args));
} }
public virtual void SendSuccessMessage(string msg) public virtual void SendSuccessMessage(string msg)
{ {
SendMessage(msg, Color.Green); SendMessage(msg, Color.Green);
} }
public void SendSuccessMessage(string format, params object[] args) public void SendSuccessMessage(string format, params object[] args)
{ {
SendSuccessMessage(string.Format(format, args)); SendSuccessMessage(string.Format(format, args));
} }
public virtual void SendWarningMessage(string msg) public virtual void SendWarningMessage(string msg)
{ {
SendMessage(msg, Color.OrangeRed); SendMessage(msg, Color.OrangeRed);
} }
public void SendWarningMessage(string format, params object[] args) public void SendWarningMessage(string format, params object[] args)
{ {
SendWarningMessage(string.Format(format, args)); SendWarningMessage(string.Format(format, args));
} }
public virtual void SendErrorMessage(string msg) public virtual void SendErrorMessage(string msg)
{ {
SendMessage(msg, Color.Red); SendMessage(msg, Color.Red);
} }
public void SendErrorMessage(string format, params object[] args) public void SendErrorMessage(string format, params object[] args)
{ {
SendErrorMessage(string.Format(format, args)); SendErrorMessage(string.Format(format, args));
} }
public virtual void SendMessage(string msg, Color color) public virtual void SendMessage(string msg, Color color)
@ -753,7 +751,7 @@ namespace TShockAPI
public virtual void SendMessageFromPlayer(string msg, byte red, byte green, byte blue, int ply) public virtual void SendMessageFromPlayer(string msg, byte red, byte green, byte blue, int ply)
{ {
SendDataFromPlayer(PacketTypes.ChatText, ply, msg, red, green, blue, 0); SendDataFromPlayer(PacketTypes.ChatText, ply, msg, red, green, blue, 0);
} }
public virtual void DamagePlayer(int damage) public virtual void DamagePlayer(int damage)
@ -830,7 +828,7 @@ namespace TShockAPI
//Todo: Separate this into a few functions. SendTo, SendToAll, etc //Todo: Separate this into a few functions. SendTo, SendToAll, etc
public virtual void SendData(PacketTypes msgType, string text = "", int number = 0, float number2 = 0f, public virtual void SendData(PacketTypes msgType, string text = "", int number = 0, float number2 = 0f,
float number3 = 0f, float number4 = 0f, int number5 = 0) float number3 = 0f, float number4 = 0f, int number5 = 0)
{ {
if (RealPlayer && !ConnectionAlive) if (RealPlayer && !ConnectionAlive)
return; return;
@ -838,19 +836,21 @@ namespace TShockAPI
NetMessage.SendData((int) msgType, Index, -1, text, number, number2, number3, number4, number5); NetMessage.SendData((int) msgType, Index, -1, text, number, number2, number3, number4, number5);
} }
public virtual void SendDataFromPlayer(PacketTypes msgType, int ply, string text = "", float number2 = 0f, float number3 = 0f, float number4 = 0f, int number5 = 0) public virtual void SendDataFromPlayer(PacketTypes msgType, int ply, string text = "", float number2 = 0f,
{ float number3 = 0f, float number4 = 0f, int number5 = 0)
if (RealPlayer && !ConnectionAlive) {
return; if (RealPlayer && !ConnectionAlive)
return;
NetMessage.SendData((int) msgType, Index, -1, text, ply, number2, number3, number4, number5); NetMessage.SendData((int) msgType, Index, -1, text, ply, number2, number3, number4, number5);
} }
public virtual void SendRawData(byte[] data) public virtual void SendRawData(byte[] data)
{ {
if (!RealPlayer || !ConnectionAlive) if (!RealPlayer || !ConnectionAlive)
return; return;
NetMessage.SendBytes(Netplay.serverSock[Index], data, 0, data.Length, Netplay.serverSock[Index].ServerWriteCallBack, Netplay.serverSock[Index].networkStream);
Netplay.Clients[Index].Socket.AsyncSend(data, 0, data.Length, Netplay.Clients[Index].ServerWriteCallBack);
} }
/// <summary> /// <summary>
@ -860,12 +860,12 @@ namespace TShockAPI
/// <param name="callback">The method that will be executed on confirmation ie user accepts</param> /// <param name="callback">The method that will be executed on confirmation ie user accepts</param>
public void AddResponse( string name, Action<object> callback) public void AddResponse( string name, Action<object> callback)
{ {
if( AwaitingResponse.ContainsKey(name)) if( AwaitingResponse.ContainsKey(name))
{ {
AwaitingResponse.Remove(name); AwaitingResponse.Remove(name);
} }
AwaitingResponse.Add(name, callback); AwaitingResponse.Add(name, callback);
} }
} }
@ -928,30 +928,30 @@ namespace TShockAPI
public override void SendErrorMessage(string msg) public override void SendErrorMessage(string msg)
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(msg); Console.WriteLine(msg);
Console.ResetColor(); Console.ResetColor();
} }
public override void SendInfoMessage(string msg) public override void SendInfoMessage(string msg)
{ {
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(msg); Console.WriteLine(msg);
Console.ResetColor(); Console.ResetColor();
} }
public override void SendSuccessMessage(string msg) public override void SendSuccessMessage(string msg)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(msg); Console.WriteLine(msg);
Console.ResetColor(); Console.ResetColor();
} }
public override void SendWarningMessage(string msg) public override void SendWarningMessage(string msg)
{ {
Console.ForegroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine(msg); Console.WriteLine(msg);
Console.ResetColor(); Console.ResetColor();
} }
public override void SendMessage(string msg, Color color) public override void SendMessage(string msg, Color color)
@ -1031,7 +1031,7 @@ namespace TShockAPI
} }
public void SpawnNPC(int type, string name, int amount, int startTileX, int startTileY, int tileXRange = 100, public void SpawnNPC(int type, string name, int amount, int startTileX, int startTileY, int tileXRange = 100,
int tileYRange = 50) int tileYRange = 50)
{ {
for (int i = 0; i < amount; i++) for (int i = 0; i < amount; i++)
{ {
@ -1089,7 +1089,7 @@ namespace TShockAPI
public Color? shoeColor; public Color? shoeColor;
public Color? skinColor; public Color? skinColor;
public Color? eyeColor; public Color? eyeColor;
public BitsByte? hideVisuals; public bool[] hideVisuals;
public int questsCompleted; public int questsCompleted;
public PlayerData(TSPlayer player) public PlayerData(TSPlayer player)
@ -1200,9 +1200,9 @@ namespace TShockAPI
player.TPlayer.eyeColor = this.eyeColor.Value; player.TPlayer.eyeColor = this.eyeColor.Value;
if (this.hideVisuals != null) if (this.hideVisuals != null)
player.TPlayer.hideVisual = this.hideVisuals.Value; player.TPlayer.hideVisual = this.hideVisuals;
else else
player.TPlayer.hideVisual.ClearAll(); player.TPlayer.hideVisual = new bool[player.TPlayer.hideVisual.Length];
for (int i = 0; i < NetItem.MaxInventory; i++) for (int i = 0; i < NetItem.MaxInventory; i++)
{ {

View file

@ -202,7 +202,7 @@ namespace TShockAPI
{ {
logPathSetupWarning = logPathSetupWarning =
"Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex; "Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex;
ServerApi.LogWriter.PluginWriteLine(this, logPathSetupWarning, TraceLevel.Error); ServerApi.LogWriter.PluginWriteLine(this, logPathSetupWarning, TraceLevel.Error);
// Problem with the log path or format use the default // Problem with the log path or format use the default
@ -280,7 +280,7 @@ namespace TShockAPI
TileBans = new TileManager(DB); TileBans = new TileManager(DB);
RememberedPos = new RememberedPosManager(DB); RememberedPos = new RememberedPosManager(DB);
CharacterDB = new CharacterManager(DB); CharacterDB = new CharacterManager(DB);
RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort); RestApi = new SecureRest(Netplay.ServerIP, Config.RestApiPort);
RestApi.Port = Config.RestApiPort; RestApi.Port = Config.RestApiPort;
RestManager = new RestManager(RestApi); RestManager = new RestManager(RestApi);
RestManager.RegisterRestfulCommands(); RestManager.RegisterRestfulCommands();
@ -442,14 +442,14 @@ namespace TShockAPI
/// <param name="args">args - The NameCollisionEventArgs object.</param> /// <param name="args">args - The NameCollisionEventArgs object.</param>
private void NetHooks_NameCollision(NameCollisionEventArgs args) private void NetHooks_NameCollision(NameCollisionEventArgs args)
{ {
string ip = Utils.GetRealIP(Netplay.serverSock[args.Who].tcpClient.Client.RemoteEndPoint.ToString()); 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); var player = Players.First(p => p != null && p.Name == args.Name && p.Index != args.Who);
if (player != null) if (player != null)
{ {
if (player.IP == ip) if (player.IP == ip)
{ {
Netplay.serverSock[player.Index].kill = true; Netplay.Clients[player.Index].PendingTermination = true;
args.Handled = true; args.Handled = true;
return; return;
} }
@ -458,7 +458,7 @@ namespace TShockAPI
var ips = JsonConvert.DeserializeObject<List<string>>(player.User.KnownIps); var ips = JsonConvert.DeserializeObject<List<string>>(player.User.KnownIps);
if (ips.Contains(ip)) if (ips.Contains(ip))
{ {
Netplay.serverSock[player.Index].kill = true; Netplay.Clients[player.Index].PendingTermination = true;
args.Handled = true; args.Handled = true;
} }
} }
@ -506,13 +506,13 @@ namespace TShockAPI
e.ExceptionObject.ToString().Contains("Terraria.Netplay.ServerLoop")) e.ExceptionObject.ToString().Contains("Terraria.Netplay.ServerLoop"))
{ {
var sb = new List<string>(); var sb = new List<string>();
for (int i = 0; i < Netplay.serverSock.Length; i++) for (int i = 0; i < Netplay.Clients.Length; i++)
{ {
if (Netplay.serverSock[i] == null) if (Netplay.Clients[i] == null)
{ {
sb.Add("Sock[" + i + "]"); sb.Add("Client[" + i + "]");
} }
else if (Netplay.serverSock[i].tcpClient == null) else if (Netplay.Clients[i].Socket == null)
{ {
sb.Add("Tcp[" + i + "]"); sb.Add("Tcp[" + i + "]");
} }
@ -537,7 +537,7 @@ namespace TShockAPI
string path; string path;
for (int i = 0; i < parms.Length; i++) for (int i = 0; i < parms.Length; i++)
{ {
switch(parms[i].ToLower()) switch (parms[i].ToLower())
{ {
case "-configpath": case "-configpath":
path = parms[++i]; path = parms[++i];
@ -591,11 +591,11 @@ namespace TShockAPI
{ {
for (int i = 0; i < parms.Length; i++) for (int i = 0; i < parms.Length; i++)
{ {
switch(parms[i].ToLower()) switch (parms[i].ToLower())
{ {
case "-port": case "-port":
int port = Convert.ToInt32(parms[++i]); int port = Convert.ToInt32(parms[++i]);
Netplay.serverPort = port; Netplay.ListenPort = port;
Config.ServerPort = port; Config.ServerPort = port;
OverridePort = true; OverridePort = true;
Log.ConsoleInfo("Port overridden by startup argument. Set to " + port); Log.ConsoleInfo("Port overridden by startup argument. Set to " + port);
@ -632,7 +632,7 @@ namespace TShockAPI
SetConsoleTitle(false); SetConsoleTitle(false);
if (!File.Exists(Path.Combine(SavePath, "auth.lck")) && !File.Exists(Path.Combine(SavePath, "authcode.txt"))) if (!File.Exists(Path.Combine(SavePath, "auth.lck")) && !File.Exists(Path.Combine(SavePath, "authcode.txt")))
{ {
var r = new Random((int) DateTime.Now.ToBinary()); var r = new Random((int)DateTime.Now.ToBinary());
AuthToken = r.Next(100000, 10000000); AuthToken = r.Next(100000, 10000000);
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("TShock Notice: To become SuperAdmin, join the game and type {0}auth {1}", Commands.Specifier, AuthToken); Console.WriteLine("TShock Notice: To become SuperAdmin, join the game and type {0}auth {1}", Commands.Specifier, AuthToken);
@ -661,14 +661,14 @@ namespace TShockAPI
{ {
AuthToken = 0; AuthToken = 0;
} }
Regions.Reload(); Regions.Reload();
Warps.ReloadWarps(); Warps.ReloadWarps();
Lighting.lightMode = 2; Lighting.lightMode = 2;
ComputeMaxStyles(); ComputeMaxStyles();
FixChestStacks(); FixChestStacks();
UpdateManager = new UpdateManager(); UpdateManager = new UpdateManager();
StatTracker.Initialize(); StatTracker.Initialize();
} }
@ -692,7 +692,7 @@ namespace TShockAPI
} }
} }
} }
/// <summary>FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.</summary> /// <summary>FixChestStacks - Verifies that each stack in each chest is valid and not over the max stack count.</summary>
private void FixChestStacks() private void FixChestStacks()
{ {
@ -761,7 +761,7 @@ namespace TShockAPI
break; break;
} }
} }
foreach (TSPlayer player in Players) foreach (TSPlayer player in Players)
{ {
if (player != null && player.Active) if (player != null && player.Active)
@ -795,14 +795,14 @@ namespace TShockAPI
{ {
player.TilePlaceThreshold = 0; player.TilePlaceThreshold = 0;
} }
if (player.RecentFuse >0) if (player.RecentFuse > 0)
player.RecentFuse--; player.RecentFuse--;
if ((Main.ServerSideCharacter) && (player.TPlayer.SpawnX > 0) &&(player.sX != player.TPlayer.SpawnX)) if ((Main.ServerSideCharacter) && (player.TPlayer.SpawnX > 0) && (player.sX != player.TPlayer.SpawnX))
{ {
player.sX=player.TPlayer.SpawnX; player.sX = player.TPlayer.SpawnX;
player.sY=player.TPlayer.SpawnY; player.sY = player.TPlayer.SpawnY;
} }
if ((Main.ServerSideCharacter) && (player.sX > 0) && (player.sY > 0) && (player.TPlayer.SpawnX < 0)) if ((Main.ServerSideCharacter) && (player.sX > 0) && (player.sY > 0) && (player.TPlayer.SpawnX < 0))
@ -811,20 +811,20 @@ namespace TShockAPI
player.TPlayer.SpawnY = player.sY; player.TPlayer.SpawnY = player.sY;
} }
if (player.RPPending >0) if (player.RPPending > 0)
{ {
if (player.RPPending == 1) if (player.RPPending == 1)
{ {
var pos = RememberedPos.GetLeavePos(player.Name, player.IP); var pos = RememberedPos.GetLeavePos(player.Name, player.IP);
player.Teleport(pos.X*16, pos.Y*16 ); player.Teleport(pos.X * 16, pos.Y * 16);
player.RPPending = 0; player.RPPending = 0;
} }
else else
{ {
player.RPPending--; player.RPPending--;
} }
} }
if (player.TileLiquidThreshold >= Config.TileLiquidThreshold) if (player.TileLiquidThreshold >= Config.TileLiquidThreshold)
{ {
player.Disable("Reached TileLiquid threshold"); player.Disable("Reached TileLiquid threshold");
@ -877,7 +877,7 @@ namespace TShockAPI
player.SetBuff(30, 120); //Bleeding player.SetBuff(30, 120); //Bleeding
player.SetBuff(36, 120); //Broken Armor player.SetBuff(36, 120); //Broken Armor
check = "Remove armor/accessory " + item.name; check = "Remove armor/accessory " + item.name;
player.SendErrorMessage("You are wearing banned equipment. {0}", check); player.SendErrorMessage("You are wearing banned equipment. {0}", check);
break; break;
} }
@ -916,10 +916,10 @@ namespace TShockAPI
/// <param name="empty">empty - True/false if the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.</param> /// <param name="empty">empty - True/false if the server is empty; determines if we should use Utils.ActivePlayers() for player count or 0.</param>
private void SetConsoleTitle(bool empty) private void SetConsoleTitle(bool empty)
{ {
Console.Title = string.Format("{0}{1}/{2} @ {3}:{4} (TShock for Terraria v{5})", Console.Title = string.Format("{0}{1}/{2} @ {3}:{4} (TShock for Terraria v{5})",
!string.IsNullOrWhiteSpace(Config.ServerName) ? Config.ServerName + " - " : "", !string.IsNullOrWhiteSpace(Config.ServerName) ? Config.ServerName + " - " : "",
empty ? 0 : Utils.ActivePlayers(), empty ? 0 : Utils.ActivePlayers(),
Config.MaxSlots, Netplay.serverListenIP, Netplay.serverPort, Version); Config.MaxSlots, Netplay.ServerIPText, Netplay.ListenPort, Version);
} }
/// <summary>OnHardUpdate - Fired when a hardmode tile update event happens.</summary> /// <summary>OnHardUpdate - Fired when a hardmode tile update event happens.</summary>
@ -930,8 +930,8 @@ namespace TShockAPI
return; return;
if (!Config.AllowCrimsonCreep && (args.Type == 0 || args.Type == 199 || args.Type == 200 || args.Type == 203 if (!Config.AllowCrimsonCreep && (args.Type == 0 || args.Type == 199 || args.Type == 200 || args.Type == 203
|| args.Type == 234)) || args.Type == 234))
{ {
args.Handled = true; args.Handled = true;
return; return;
} }
@ -944,7 +944,7 @@ namespace TShockAPI
} }
if (!Config.AllowHallowCreep && (args.Type == 109 || args.Type == 117 || args.Type == 116 || args.Type == 115 if (!Config.AllowHallowCreep && (args.Type == 109 || args.Type == 117 || args.Type == 116 || args.Type == 115
|| args.Type == 164)) || args.Type == 164))
{ {
args.Handled = true; args.Handled = true;
} }
@ -1011,7 +1011,7 @@ namespace TShockAPI
args.Handled = true; args.Handled = true;
return; return;
} }
if (Config.KickEmptyUUID && String.IsNullOrWhiteSpace(player.UUID)) if (Config.KickEmptyUUID && String.IsNullOrWhiteSpace(player.UUID))
{ {
Utils.ForceKick(player, "Your client did not send a UUID, this server is not configured to accept such a client.", true); Utils.ForceKick(player, "Your client did not send a UUID, this server is not configured to accept such a client.", true);
@ -1039,9 +1039,9 @@ namespace TShockAPI
if (ban != null) if (ban != null)
{ {
if (!Utils.HasBanExpired(ban)) if (!Utils.HasBanExpired(ban))
{ {
DateTime exp; DateTime exp;
if (!DateTime.TryParse(ban.Expiration, out exp)) if (!DateTime.TryParse(ban.Expiration, out exp))
{ {
player.Disconnect("You are banned forever: " + ban.Reason); player.Disconnect("You are banned forever: " + ban.Reason);
@ -1058,7 +1058,7 @@ namespace TShockAPI
else if (ts.Days > 0) else if (ts.Days > 0)
{ {
player.Disconnect(String.Format("You are banned for {0} day{1} and {2} hour{3}: {4}", player.Disconnect(String.Format("You are banned for {0} day{1} and {2} hour{3}: {4}",
ts.Days, ts.Days == 1 ? "": "s", ts.Hours, ts.Hours == 1 ? "" : "s", ban.Reason)); ts.Days, ts.Days == 1 ? "" : "s", ts.Hours, ts.Hours == 1 ? "" : "s", ban.Reason));
} }
else if (ts.Hours > 0) else if (ts.Hours > 0)
{ {
@ -1077,8 +1077,8 @@ namespace TShockAPI
} }
} }
args.Handled = true; args.Handled = true;
} }
} }
} }
/// <summary>OnLeave - Called when a player leaves the server.</summary> /// <summary>OnLeave - Called when a player leaves the server.</summary>
@ -1102,7 +1102,7 @@ namespace TShockAPI
if (Config.RememberLeavePos && !tsplr.LoginHarassed) if (Config.RememberLeavePos && !tsplr.LoginHarassed)
{ {
RememberedPos.InsertLeavePos(tsplr.Name, tsplr.IP, (int) (tsplr.X/16), (int) (tsplr.Y/16)); RememberedPos.InsertLeavePos(tsplr.Name, tsplr.IP, (int)(tsplr.X / 16), (int)(tsplr.Y / 16));
} }
if (tsplr.tempGroupTimer != null) if (tsplr.tempGroupTimer != null)
@ -1147,7 +1147,7 @@ namespace TShockAPI
return; return;
} }
if ((args.Text.StartsWith(Config.CommandSpecifier) || args.Text.StartsWith(Config.CommandSilentSpecifier)) if ((args.Text.StartsWith(Config.CommandSpecifier) || args.Text.StartsWith(Config.CommandSilentSpecifier))
&& !string.IsNullOrWhiteSpace(args.Text.Substring(1))) && !string.IsNullOrWhiteSpace(args.Text.Substring(1)))
{ {
try try
@ -1174,7 +1174,7 @@ namespace TShockAPI
else if (!TShock.Config.EnableChatAboveHeads) else if (!TShock.Config.EnableChatAboveHeads)
{ {
var text = String.Format(Config.ChatFormat, tsplr.Group.Name, tsplr.Group.Prefix, tsplr.Name, tsplr.Group.Suffix, var text = String.Format(Config.ChatFormat, tsplr.Group.Name, tsplr.Group.Prefix, tsplr.Name, tsplr.Group.Suffix,
args.Text); args.Text);
Hooks.PlayerHooks.OnPlayerChat(tsplr, args.Text, ref text); Hooks.PlayerHooks.OnPlayerChat(tsplr, args.Text, ref text);
Utils.Broadcast(text, tsplr.Group.R, tsplr.Group.G, tsplr.Group.B); Utils.Broadcast(text, tsplr.Group.R, tsplr.Group.G, tsplr.Group.B);
args.Handled = true; args.Handled = true;
@ -1245,10 +1245,10 @@ namespace TShockAPI
{ {
if (e.Handled) if (e.Handled)
return; return;
PacketTypes type = e.MsgID; PacketTypes type = e.MsgID;
Debug.WriteLine("Recv: {0:X}: {2} ({1:XX})", e.Msg.whoAmI, (byte) type, type); Debug.WriteLine("Recv: {0:X}: {2} ({1:XX})", e.Msg.whoAmI, (byte)type, type);
var player = Players[e.Msg.whoAmI]; var player = Players[e.Msg.whoAmI];
if (player == null || !player.ConnectionAlive) if (player == null || !player.ConnectionAlive)
@ -1263,8 +1263,8 @@ namespace TShockAPI
return; return;
} }
if ((player.State < 10 || player.Dead) && (int) type > 12 && (int) type != 16 && (int) type != 42 && (int) type != 50 && if ((player.State < 10 || player.Dead) && (int)type > 12 && (int)type != 16 && (int)type != 42 && (int)type != 50 &&
(int) type != 38 && (int) type != 21 && (int) type != 22) (int)type != 38 && (int)type != 21 && (int)type != 22)
{ {
e.Handled = true; e.Handled = true;
return; return;
@ -1375,75 +1375,37 @@ namespace TShockAPI
e.Object.SetDefaults(0); e.Object.SetDefaults(0);
} }
/// <summary>
/// Send bytes to client using packetbuffering if available
/// </summary>
/// <param name="client">socket to send to</param>
/// <param name="bytes">bytes to send</param>
/// <returns>False on exception</returns>
public static bool SendBytes(ServerSock client, byte[] bytes)
{
if (PacketBuffer != null)
{
PacketBuffer.BufferBytes(client, bytes);
return true;
}
return SendBytesBufferless(client, bytes);
}
/// <summary>
/// Send bytes to a client ignoring the packet buffer
/// </summary>
/// <param name="client">socket to send to</param>
/// <param name="bytes">bytes to send</param>
/// <returns>False on exception</returns>
public static bool SendBytesBufferless(ServerSock client, byte[] bytes)
{
try
{
if (client.tcpClient.Connected)
client.networkStream.Write(bytes, 0, bytes.Length);
return true;
}
catch (Exception ex)
{
Log.Warn("This is a normal exception");
Log.Warn(ex.ToString());
}
return false;
}
/// <summary>NetHooks_SendData - Fired when the server sends data.</summary> /// <summary>NetHooks_SendData - Fired when the server sends data.</summary>
/// <param name="e">e - The SendDataEventArgs object.</param> /// <param name="e">e - The SendDataEventArgs object.</param>
private void NetHooks_SendData(SendDataEventArgs e) private void NetHooks_SendData(SendDataEventArgs e)
{ {
if (e.MsgId == PacketTypes.Disconnect) if (e.MsgId == PacketTypes.Disconnect)
{ {
Action<ServerSock, string> senddisconnect = (sock, str) => Action<RemoteClient, string> disconnect = (client, str) =>
{ {
if (sock == null || !sock.active) if (client == null || !client.IsActive || client.Socket.IsConnected())
return; return;
sock.kill = true; using (var ms = new MemoryStream())
using (var ms = new MemoryStream()) {
{ var msg = new DisconnectMsg() { Reason = str };
new DisconnectMsg { Reason = str }.PackFull(ms); msg.PackFull(ms);
SendBytesBufferless(sock, ms.ToArray()); client.Socket.AsyncSend(ms.ToArray(), 0, (int)ms.Length, client.ServerWriteCallBack);
} client.Socket.Close();
}; }
};
if (e.remoteClient != -1) if (e.remoteClient != -1)
{ {
senddisconnect(Netplay.serverSock[e.remoteClient], e.text); disconnect(Netplay.Clients[e.remoteClient], e.text);
} }
else else
{ {
for (int i = 0; i < Netplay.serverSock.Length; i++) for (int i = 0; i < Netplay.Clients.Length; i++)
{ {
if (e.ignoreClient != -1 && e.ignoreClient == i) if (e.ignoreClient != -1 && e.ignoreClient == i)
continue; continue;
senddisconnect(Netplay.serverSock[i], e.text); disconnect(Netplay.Clients[i], e.text);
} }
} }
e.Handled = true; e.Handled = true;
@ -1562,7 +1524,7 @@ namespace TShockAPI
} }
else else
{ {
Main.invasionSize = 100 + (Config.InvasionMultiplier*Utils.ActivePlayers()); Main.invasionSize = 100 + (Config.InvasionMultiplier * Utils.ActivePlayers());
} }
Main.invasionWarn = 0; Main.invasionWarn = 0;
@ -1586,7 +1548,7 @@ namespace TShockAPI
KillCount++; KillCount++;
Random r = new Random(); Random r = new Random();
int random = r.Next(5); int random = r.Next(5);
if (KillCount%100 == 0) if (KillCount % 100 == 0)
{ {
switch (random) switch (random)
{ {
@ -1625,7 +1587,7 @@ namespace TShockAPI
} }
if (type == 17 && Itembans.ItemIsBanned("Dirt Rod", player)) if (type == 17 && Itembans.ItemIsBanned("Dirt Rod", player))
//Dirt Rod Projectile //Dirt Rod Projectile
{ {
return true; return true;
} }
@ -1640,7 +1602,7 @@ namespace TShockAPI
if (Main.projHostile[type]) if (Main.projHostile[type])
{ {
//player.SendMessage( proj.name, Color.Yellow); //player.SendMessage( proj.name, Color.Yellow);
return true; return true;
} }
@ -1828,8 +1790,8 @@ namespace TShockAPI
{ {
float num2 = value1.X - value2.X; float num2 = value1.X - value2.X;
float num = value1.Y - value2.Y; float num = value1.Y - value2.Y;
float num3 = (num2*num2) + (num*num); float num3 = (num2 * num2) + (num * num);
return (float) Math.Sqrt(num3); return (float)Math.Sqrt(num3);
} }
/// <summary>HackedInventory - Checks to see if a user has a hacked inventory. In addition, messages players the result.</summary> /// <summary>HackedInventory - Checks to see if a user has a hacked inventory. In addition, messages players the result.</summary>
@ -1861,7 +1823,7 @@ namespace TShockAPI
} }
} }
} }
else if(i < (NetItem.MaxInventory - (NetItem.ArmorSlots + NetItem.DyeSlots))) else if (i < (NetItem.MaxInventory - (NetItem.ArmorSlots + NetItem.DyeSlots)))
{ {
Item item = new Item(); Item item = new Item();
var index = i - (NetItem.MaxInventory - (NetItem.ArmorSlots + NetItem.DyeSlots)); var index = i - (NetItem.MaxInventory - (NetItem.ArmorSlots + NetItem.DyeSlots));
@ -1925,16 +1887,14 @@ namespace TShockAPI
} }
if (!OverridePort) if (!OverridePort)
{ {
Netplay.serverPort = file.ServerPort; Netplay.ListenPort = file.ServerPort;
} }
if (file.MaxSlots > 235) if (file.MaxSlots > 235)
file.MaxSlots = 235; file.MaxSlots = 235;
Main.maxNetPlayers = file.MaxSlots + 20; Main.maxNetPlayers = file.MaxSlots + 20;
Netplay.password = ""; Netplay.ServerPassword = "";
Netplay.spamCheck = false; Netplay.spamCheck = false;
Utils.HashAlgo = file.HashAlgorithm;
} }
} }
} }