From d8b6240a522126bcffef63a831efa53d7a5671cc Mon Sep 17 00:00:00 2001 From: UnknownShadow200 Date: Thu, 8 Sep 2016 20:58:34 +1000 Subject: [PATCH] Remove unnecessary try{} catch{} --- Commands/World/CmdGoto.cs | 10 +- Levels/Level.Blocks.cs | 8 +- Levels/LevelAccess.cs | 45 ++++-- Network/Player.Networking.cs | 5 +- Player/Player.Handlers.cs | 7 +- Player/Player.Login.cs | 280 +++++++++++++++++------------------ 6 files changed, 186 insertions(+), 169 deletions(-) diff --git a/Commands/World/CmdGoto.cs b/Commands/World/CmdGoto.cs index 99470d0a6..4443deb19 100644 --- a/Commands/World/CmdGoto.cs +++ b/Commands/World/CmdGoto.cs @@ -61,13 +61,13 @@ namespace MCGalaxy.Commands.World { bool HandleGoto(Player p, string message) { Level lvl = LevelInfo.FindExact(message); if (lvl != null) { - return GoToLevel(p, lvl, message); + return GoToLevel(p, lvl); } else if (Server.AutoLoad) { // First try exactly matching unloaded levels if (LevelInfo.ExistsOffline(message)) return GotoOfflineLevel(p, message); lvl = LevelInfo.Find(message); - if (lvl != null) return GoToLevel(p, lvl, message); + if (lvl != null) return GoToLevel(p, lvl); string map = LevelInfo.FindMapMatches(p, message); if (map == null) return false; @@ -79,7 +79,7 @@ namespace MCGalaxy.Commands.World { Command.all.Find("search").Use(p, "levels " + message); return false; } - return GoToLevel(p, lvl, message); + return GoToLevel(p, lvl); } } @@ -88,7 +88,7 @@ namespace MCGalaxy.Commands.World { CmdLoad.LoadLevel(p, message, "0", true); Level lvl = LevelInfo.Find(message); if (lvl != null) { - return GoToLevel(p, lvl, message); + return GoToLevel(p, lvl); } else { Player.Message(p, "Level \"{0}\" failed to be auto-loaded.", message); return false; @@ -98,7 +98,7 @@ namespace MCGalaxy.Commands.World { return false; } - static bool GoToLevel(Player p, Level lvl, string message) { + static bool GoToLevel(Player p, Level lvl) { if (p.level == lvl) { Player.Message(p, "You are already in \"" + lvl.name + "\"."); return false; } if (!lvl.CanJoin(p)) return false; if (!Server.zombie.PlayerCanJoinLevel(p, lvl, p.level)) return false; diff --git a/Levels/Level.Blocks.cs b/Levels/Level.Blocks.cs index 364a6c3f4..7968a8996 100644 --- a/Levels/Level.Blocks.cs +++ b/Levels/Level.Blocks.cs @@ -230,9 +230,11 @@ namespace MCGalaxy { BuildAccess.CheckDetailed(p, false); p.ZoneSpam = DateTime.UtcNow.AddSeconds(2); } - - return p.level == this - ? p.AllowBuild : BuildAccess.Check(p, false); + if (p.level == this) return p.AllowBuild; + + LevelAccessResult access = BuildAccess.Check(p, false); + return access == LevelAccessResult.Whitelisted + || access == LevelAccessResult.Allowed; } public bool CheckAffectPermissions(Player p, ushort x, ushort y, ushort z, diff --git a/Levels/LevelAccess.cs b/Levels/LevelAccess.cs index 9408c0ec8..77caa1dd9 100644 --- a/Levels/LevelAccess.cs +++ b/Levels/LevelAccess.cs @@ -62,15 +62,21 @@ namespace MCGalaxy { } - /// Returns whether the given player is allowed by these access permissions. - public bool Check(Player p, bool ignoreRankPerm = false) { - if (Blacklisted.CaselessContains(p.name)) return false; - if (Whitelisted.CaselessContains(p.name) || ignoreRankPerm) return true; + /// Returns the allowed state for the given player. + public LevelAccessResult Check(Player p, bool ignoreRankPerm = false) { + if (Blacklisted.CaselessContains(p.name)) + return LevelAccessResult.Blacklisted; + if (Whitelisted.CaselessContains(p.name)) + return LevelAccessResult.Whitelisted; + if (ignoreRankPerm) + return LevelAccessResult.Allowed; - if (p.Rank < Min) return false; + if (p.Rank < Min) + return LevelAccessResult.BelowMinRank; string maxCmd = IsVisit ? "pervisitmax" : "perbuildmax"; - if (p.Rank > Max && !p.group.CanExecute(maxCmd)) return false; - return true; + if (p.Rank > Max && !p.group.CanExecute(maxCmd)) + return LevelAccessResult.AboveMaxRank; + return LevelAccessResult.Allowed; } /// Returns whether the given player is allowed for these access permissions. @@ -134,7 +140,7 @@ namespace MCGalaxy { bool CheckRank(Player p, LevelPermission perm, string target, bool newPerm) { if (p != null && perm > p.Rank) { Player.Message(p, "You cannot change the {0} of a level {1} a {0} higher than your rank.", - target, newPerm ? "to" : "with"); + target, newPerm ? "to" : "with"); return false; } return true; @@ -153,8 +159,29 @@ namespace MCGalaxy { Player[] players = PlayerInfo.Online.Items; foreach (Player p in players) { if (p.level != lvl) continue; - p.AllowBuild = lvl.BuildAccess.Check(p, false); + + LevelAccessResult access = lvl.BuildAccess.Check(p, false); + p.AllowBuild = access == LevelAccessResult.Whitelisted + || access == LevelAccessResult.Allowed; } } } + + public enum LevelAccessResult { + + /// The player is whitelisted and always allowed. + Whitelisted, + + /// The player is blacklisted and never allowed. + Blacklisted, + + /// The player is allowed (by their rank) + Allowed, + + /// The player's rank is below the minimum rank allowed. + BelowMinRank, + + /// The player's rank is above the maximum rank allowed. + AboveMaxRank, + } } \ No newline at end of file diff --git a/Network/Player.Networking.cs b/Network/Player.Networking.cs index 9dbf04381..c1987604a 100644 --- a/Network/Player.Networking.cs +++ b/Network/Player.Networking.cs @@ -319,7 +319,10 @@ namespace MCGalaxy { bool success = true; useCheckpointSpawn = false; lastCheckpointIndex = -1; - AllowBuild = level.BuildAccess.Check(this, false); + + LevelAccessResult access = level.BuildAccess.Check(this, false); + AllowBuild = access == LevelAccessResult.Whitelisted + || access == LevelAccessResult.Allowed; try { if (hasBlockDefs) { diff --git a/Player/Player.Handlers.cs b/Player/Player.Handlers.cs index a2074e23a..6a65e89b1 100644 --- a/Player/Player.Handlers.cs +++ b/Player/Player.Handlers.cs @@ -187,8 +187,8 @@ namespace MCGalaxy { byte[] remaining = new byte[buffer.Length - size]; Buffer.BlockCopy(buffer, size, remaining, 0, remaining.Length); return ProcessReceived(remaining); - } catch (Exception e) { - Server.ErrorLog(e); + } catch (Exception ex) { + Server.ErrorLog(ex); } return buffer; } @@ -441,7 +441,6 @@ return; } void HandleChat(byte[] packet) { - try { if (!loggedIn) return; byte continued = packet[1]; string text = GetString(packet, 2); @@ -518,8 +517,6 @@ return; } } CheckForMessageSpam(); - } - catch ( Exception e ) { Server.ErrorLog(e); Chat.MessageAll("An error occurred: {0}", e.Message); } } bool FilterChat(ref string text, byte continued) { diff --git a/Player/Player.Login.cs b/Player/Player.Login.cs index 73edc2161..74b0f206a 100644 --- a/Player/Player.Login.cs +++ b/Player/Player.Login.cs @@ -20,120 +20,115 @@ using MCGalaxy.Commands.World; using MCGalaxy.Games; using MCGalaxy.SQL; -namespace MCGalaxy { +namespace MCGalaxy { public sealed partial class Player : IDisposable { - + void HandleLogin(byte[] packet) { LastAction = DateTime.UtcNow; - try { - if (loggedIn) return; + if (loggedIn) return; - byte version = packet[1]; - name = enc.GetString(packet, 2, 64).Trim(); - if (name.Length > 16) { - Leave("Usernames must be 16 characters or less", true); return; + byte version = packet[1]; + name = enc.GetString(packet, 2, 64).Trim(); + if (name.Length > 16) { + Leave("Usernames must be 16 characters or less", true); return; + } + truename = name; + skinName = name; + + int altsCount = 0; + lock (pendingLock) { + DateTime now = DateTime.UtcNow; + foreach (PendingItem item in pendingNames) { + if (item.Name == truename && (now - item.Connected).TotalSeconds <= 60) + altsCount++; } - truename = name; - skinName = name; + pendingNames.Add(new PendingItem(name)); + } + if (altsCount > 0) { + Leave("Already logged in!", true); return; + } + + string verify = enc.GetString(packet, 66, 32).Trim(); + verifiedName = false; + if (Server.verify) { + byte[] hash = null; + lock (md5Lock) + hash = md5.ComputeHash(enc.GetBytes(Server.salt + truename)); - int altsCount = 0; - lock (pendingLock) { - DateTime now = DateTime.UtcNow; - foreach (PendingItem item in pendingNames) { - if (item.Name == truename && (now - item.Connected).TotalSeconds <= 60) - altsCount++; - } - pendingNames.Add(new PendingItem(name)); + string hashHex = BitConverter.ToString(hash); + if (!verify.CaselessEq(hashHex.Replace("-", ""))) { + if (!IPInPrivateRange(ip)) { + Leave("Login failed! Try signing in again.", true); return; + } + } else { + verifiedName = true; } - if (altsCount > 0) { + } + + DisplayName = name; + if (Server.ClassicubeAccountPlus) name += "+"; + isDev = Server.Devs.CaselessContains(truename); + isMod = Server.Mods.CaselessContains(truename); + + try { + Server.TempBan tBan = Server.tempBans.Find(tB => tB.name.ToLower() == name.ToLower()); + if (tBan.expiryTime < DateTime.UtcNow) { + Server.tempBans.Remove(tBan); + } else { + string reason = String.IsNullOrEmpty(tBan.reason) ? "" : + " (" + tBan.reason + ")"; + Kick("You're still temp banned!" + reason, true); + } + } catch { } + + if (!CheckWhitelist()) { Leave("This is a private server!", true); return; } + Group foundGrp = Group.findPlayerGroup(name); + + // ban check + if (Server.bannedIP.Contains(ip) && (!Server.useWhitelist || !onWhitelist)) { + Kick(Server.defaultBanMessage, true); return; + } + + if (foundGrp.Permission == LevelPermission.Banned) { + string[] data = Ban.GetBanData(name); + if (data != null) { + Kick(Ban.FormatBan(data[0], data[1]), true); + } else { + Kick(Server.defaultBanMessage, true); + } + return; + } + + // maxplayer check + if (!CheckPlayersCount(foundGrp)) return; + if (version != Server.version) { Leave("Wrong version!", true); return; } + + Player[] players = PlayerInfo.Online.Items; + foreach (Player p in players) { + if (p.name != name) continue; + + if (Server.verify) { + string reason = p.ip == ip ? "(Reconnecting)" : "(Reconnecting from a different IP)"; + p.Leave(reason); break; + } else { Leave("Already logged in!", true); return; } - - string verify = enc.GetString(packet, 66, 32).Trim(); - verifiedName = false; - if (Server.verify) { - byte[] hash = null; - lock (md5Lock) - hash = md5.ComputeHash(enc.GetBytes(Server.salt + truename)); - - string hashHex = BitConverter.ToString(hash); - if (!verify.CaselessEq(hashHex.Replace("-", ""))) { - if (!IPInPrivateRange(ip)) { - Leave("Login failed! Try signing in again.", true); return; - } - } else { - verifiedName = true; - } - } - - DisplayName = name; - if (Server.ClassicubeAccountPlus) name += "+"; - isDev = Server.Devs.CaselessContains(truename); - isMod = Server.Mods.CaselessContains(truename); - - try { - Server.TempBan tBan = Server.tempBans.Find(tB => tB.name.ToLower() == name.ToLower()); - if (tBan.expiryTime < DateTime.UtcNow) { - Server.tempBans.Remove(tBan); - } else { - string reason = String.IsNullOrEmpty(tBan.reason) ? "" : - " (" + tBan.reason + ")"; - Kick("You're still temp banned!" + reason, true); - } - } catch { } - - if (!CheckWhitelist()) { Leave("This is a private server!", true); return; } - Group foundGrp = Group.findPlayerGroup(name); - - // ban check - if (Server.bannedIP.Contains(ip) && (!Server.useWhitelist || !onWhitelist)) { - Kick(Server.defaultBanMessage, true); return; - } - - if (foundGrp.Permission == LevelPermission.Banned) { - string[] data = Ban.GetBanData(name); - if (data != null) { - Kick(Ban.FormatBan(data[0], data[1]), true); - } else { - Kick(Server.defaultBanMessage, true); - } - return; - } - - // maxplayer check - if (!CheckPlayersCount(foundGrp)) return; - if (version != Server.version) { Leave("Wrong version!", true); return; } - - Player[] players = PlayerInfo.Online.Items; - foreach (Player p in players) { - if (p.name != name) continue; - - if (Server.verify) { - string reason = p.ip == ip ? "(Reconnecting)" : "(Reconnecting from a different IP)"; - p.Leave(reason); break; - } else { - Leave("Already logged in!", true); return; - } - } - - LoadIgnores(); - byte type = packet[130]; - if (type == 0x42) { hasCpe = true; SendCpeExtensions(); } - - try { left.Remove(name.ToLower()); } - catch { } - - group = foundGrp; - Loading = true; - if (disconnected) return; - id = NextFreeId(); - - if (type != 0x42) - CompleteLoginProcess(); - } catch (Exception e) { - Server.ErrorLog(e); - Chat.MessageAll("An error occurred: {0}", e.Message); } + + LoadIgnores(); + byte type = packet[130]; + if (type == 0x42) { hasCpe = true; SendCpeExtensions(); } + + try { left.Remove(name.ToLower()); } + catch { } + + group = foundGrp; + Loading = true; + if (disconnected) return; + id = NextFreeId(); + + if (type != 0x42) + CompleteLoginProcess(); } bool CheckPlayersCount(Group foundGrp) { @@ -196,43 +191,38 @@ namespace MCGalaxy { } void CompleteLoginProcess() { - LevelPermission adminChatRank = CommandOtherPerms.FindPerm("adminchat", LevelPermission.Admin); + LevelPermission adminChatRank = CommandOtherPerms.FindPerm("adminchat", LevelPermission.Admin); - try { - SendUserMOTD(); - SendMap(null); - if (disconnected) return; - loggedIn = true; + SendUserMOTD(); + SendMap(null); + if (disconnected) return; + loggedIn = true; - PlayerInfo.Online.Add(this); - connections.Remove(this); - RemoveFromPending(); - Server.s.PlayerListUpdate(); + PlayerInfo.Online.Add(this); + connections.Remove(this); + RemoveFromPending(); + Server.s.PlayerListUpdate(); - //Test code to show when people come back with different accounts on the same IP - string alts = name + " is lately known as:"; - bool found = false; - if (!ip.StartsWith("127.0.0.")) { - foreach (KeyValuePair prev in left) { - if (prev.Value == ip) { - found = true; - alts += " " + prev.Key; - } - } - - if (found) { - if (group.Permission < adminChatRank || !Server.adminsjoinsilent) { - Chat.MessageOps(alts); - //IRCBot.Say(temp, true); //Tells people in op channel on IRC - } - Server.s.Log(alts); + //Test code to show when people come back with different accounts on the same IP + string alts = name + " is lately known as:"; + bool found = false; + if (!ip.StartsWith("127.0.0.")) { + foreach (KeyValuePair prev in left) { + if (prev.Value == ip) { + found = true; + alts += " " + prev.Key; } } - CheckOutdatedClient(); - } catch (Exception e) { - Server.ErrorLog(e); - Chat.MessageAll("An error occurred: {0}", e.Message); + + if (found) { + if (group.Permission < adminChatRank || !Server.adminsjoinsilent) { + Chat.MessageOps(alts); + //IRCBot.Say(temp, true); //Tells people in op channel on IRC + } + Server.s.Log(alts); + } } + CheckOutdatedClient(); //OpenClassic Client Check SendBlockchange(0, 0, 0, 0); @@ -310,16 +300,14 @@ namespace MCGalaxy { Server.s.Log(name + " [" + ip + "] has joined the server."); Game.InfectMessages = PlayerDB.GetInfectMessages(this); Server.zombie.PlayerJoinedServer(this); - try { - ushort x = (ushort)((0.5 + level.spawnx) * 32); - ushort y = (ushort)((1 + level.spawny) * 32); - ushort z = (ushort)((0.5 + level.spawnz) * 32); - pos = new ushort[3] { x, y, z }; rot = new byte[2] { level.rotx, level.roty }; - Entities.SpawnEntities(this, x, y, z, rot[0], rot[1]); - } catch (Exception e) { - Server.ErrorLog(e); - Server.s.Log("Error spawning player \"" + name + "\""); - } + + ushort x = (ushort)((0.5 + level.spawnx) * 32); + ushort y = (ushort)((1 + level.spawny) * 32); + ushort z = (ushort)((0.5 + level.spawnz) * 32); + pos = new ushort[3] { x, y, z }; + rot = new byte[2] { level.rotx, level.roty }; + + Entities.SpawnEntities(this, x, y, z, rot[0], rot[1]); CmdGoto.CheckGamesJoin(this, null); Loading = false; } @@ -420,7 +408,7 @@ namespace MCGalaxy { if (!short.TryParse(reach, out reachDist)) return; ReachDistance = reachDist / 32f; if (HasCpeExt(CpeExt.ClickDistance)) - Send(Packet.MakeClickDistance(reachDist)); + Send(Packet.MakeClickDistance(reachDist)); } } }