/Player/Player.cs
C# | 5648 lines | 4925 code | 407 blank | 316 comment | 1441 complexity | e0ca8114698deb71d5b5de7aa8017194 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- /*
- Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge)
- Dual-licensed under the Educational Community License, Version 2.0 and
- the GNU General Public License, Version 3 (the "Licenses"); you may
- not use this file except in compliance with the Licenses. You may
- obtain a copy of the Licenses at
- http://www.opensource.org/licenses/ecl2.php
- http://www.gnu.org/licenses/gpl-3.0.html
- Unless required by applicable law or agreed to in writing,
- software distributed under the Licenses are distributed on an "AS IS"
- BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- or implied. See the Licenses for the specific language governing
- permissions and limitations under the Licenses.
- */
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using Newtonsoft.Json.Linq;
- using MCForge.SQL;
- namespace MCForge
- {
- public sealed partial class Player : IDisposable
- {
- public void ClearChat() { OnChat = null; }
- /// <summary>
- /// List of all server players.
- /// </summary>
- public static List<Player> players = new List<Player>();
- /// <summary>
- /// Key - Name
- /// Value - IP
- /// All players who have left this restart.
- /// </summary>
- public static Dictionary<string, string> left = new Dictionary<string, string>();
- /// <summary>
- ///
- /// </summary>
- public static List<Player> connections = new List<Player>(Server.players);
- System.Timers.Timer muteTimer = new System.Timers.Timer(1000);
- public static List<string> emoteList = new List<string>();
- public List<string> listignored = new List<string>();
- public List<string> mapgroups = new List<string>();
- public static List<string> globalignores = new List<string>();
- public static int totalMySQLFailed = 0;
- public static byte number { get { return (byte)players.Count; } }
- static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
- static MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
- public static string lastMSG = "";
- public static bool storeHelp = false;
- public static string storedHelp = "";
- private string truename;
- internal bool dontmindme = false;
- public Socket socket;
- System.Timers.Timer timespent = new System.Timers.Timer(1000);
- System.Timers.Timer loginTimer = new System.Timers.Timer(1000);
- public System.Timers.Timer pingTimer = new System.Timers.Timer(2000);
- System.Timers.Timer extraTimer = new System.Timers.Timer(22000);
- public System.Timers.Timer afkTimer = new System.Timers.Timer(2000);
- public int afkCount = 0;
- public DateTime afkStart;
- public string WoMVersion = "";
- public bool megaBoid = false;
- public bool cmdTimer = false;
- public bool UsingWom = false;
- byte[] buffer = new byte[0];
- byte[] tempbuffer = new byte[0xFF];
- public bool disconnected = false;
- public string time;
- public string name;
- public bool identified = false;
- public bool UsingID = false;
- public int ID = 0;
- public int warn = 0;
- public byte id;
- public int userID = -1;
- public string ip;
- public string exIP; // external IP
- public string color;
- public Group group;
- public bool hidden = false;
- public bool painting = false;
- public bool muted = false;
- public bool jailed = false;
- public bool agreed = false;
- public bool invincible = false;
- public string prefix = "";
- public string title = "";
- public string titlecolor;
- public int TotalMessagesSent = 0;
- public int passtries = 0;
- public int ponycount = 0;
- public int rdcount = 0;
- public bool hasreadrules = false;
- public bool canusereview = true;
- //Gc checks
- public string lastmsg = "";
- public int spamcount = 0, capscount = 0, floodcount = 0, multi = 0;
- public DateTime lastmsgtime = DateTime.MinValue;
- /// <summary>
- /// Console only please
- /// </summary>
- public bool canusegc = true;
- //Pyramid Code
- public int pyramidx1;
- public int pyramidx2;
- public int pyramidy1;
- public int pyramidy2;
- public int pyramidz1;
- public int pyramidz2;
- public string pyramidblock;
- public int pyramidtotal;
- public int pyramidtotal2;
- public bool pyramidsilent = false;
- public bool deleteMode = false;
- public bool ignorePermission = false;
- public bool ignoreGrief = false;
- public bool parseSmiley = true;
- public bool smileySaved = true;
- public bool opchat = false;
- public bool adminchat = false;
- public bool onWhitelist = false;
- public bool whisper = false;
- public string whisperTo = "";
- public bool ignoreglobal = false;
- public string storedMessage = "";
- public bool trainGrab = false;
- public bool onTrain = false;
- public bool allowTnt = true;
- public bool frozen = false;
- public string following = "";
- public string possess = "";
- // Only used for possession.
- //Using for anything else can cause unintended effects!
- public bool canBuild = true;
- public int money = 0;
- public long overallBlocks = 0;
- public int loginBlocks = 0;
- public DateTime timeLogged;
- public DateTime firstLogin;
- public int totalLogins = 0;
- public int totalKicked = 0;
- public int overallDeath = 0;
- public string savedcolor = "";
- public bool staticCommands = false;
- public DateTime ZoneSpam;
- public bool ZoneCheck = false;
- public bool zoneDel = false;
- public Thread commThread;
- public bool commUse = false;
- public bool aiming;
- public bool isFlying = false;
- public bool joker = false;
- public bool adminpen = false;
- public bool voice = false;
- public string voicestring = "";
- public int grieferStoneWarn = 0;
- // CTF
- public CTFTeam team;
- public bool carryingFlag;
- public bool justDroppedFlag = false;
- public CatchPos placedTNT;
- public CatchPos placedMine;
- public int captureStreak;
- public int captureCount;
- public int kills;
- public int deaths;
- public int drownCount;
- public int totalCaptures;
- public int totalKills;
- public int totalDeaths;
- public int totalReturns;
- bool isActivating;
- public struct CatchPos
- {
- public ushort x, y, z;
- public bool isActive;
- }
- public List<string> playersKilled = new List<string>();
- public int getKillCount(string name)
- {
- int count = 0;
- playersKilled.ForEach(delegate(string kill)
- {
- if (name.ToLower() == kill.ToLower())
- {
- count++;
- }
- });
- return count;
- }
- public void Reward(int reward)
- {
- money += reward;
- }
- public void killPlayer(Player killed)
- {
- playersKilled.Add(killed.name);
- killed.deaths++;
- kills++;
- Reward(CTF.killPlayerReward);
- if (getKillCount(killed.name) % 5 == 0)
- {
- Player.GlobalMessage("&f- " + color + name + "&b is dominating " + killed.color + killed.name + "&b!");
- }
- if (killed.carryingFlag)
- {
- Command.all.Find("drop").Use(killed, "");
- }
- killed.team.SpawnPlayer(killed);
- }
- //Countdown
- public bool playerofcountdown = false;
- public bool incountdown = false;
- public ushort countdowntempx;
- public ushort countdowntempz;
- public bool countdownsettemps = false;
- //Zombie
- public string Original = "";
- public bool referee = false;
- public int blockCount = 50;
- public bool voted = false;
- public int blocksStacked = 0;
- public int infectThisRound = 0;
- public int lastYblock = 0;
- public int lastXblock = 0;
- public int lastZblock = 0;
- public bool infected = false;
- public bool aka = false;
- public bool flipHead = true;
- public int playersInfected = 0;
- public int NoClipcount = 0;
- //SMP Mode
- public bool InSMP = false;
- public uint rock = (uint)0;
- public uint grass = (uint)0;
- public uint dirt = (uint)0;
- public uint stone = (uint)0;
- public uint wood = (uint)0;
- public uint shrub = (uint)0;
- public uint blackrock = (uint)0;// adminium
- public uint water = (uint)0;
- public uint waterstill = (uint)0;
- public uint lava = (uint)0;
- public uint lavastill = (uint)0;
- public uint sand = (uint)0;
- public uint gravel = (uint)0;
- public uint goldrock = (uint)0;
- public uint ironrock = (uint)0;
- public uint coal = (uint)0;
- public uint trunk = (uint)0;
- public uint leaf = (uint)0;
- public uint sponge = (uint)0;
- public uint glass = (uint)0;
- public uint red = (uint)0;
- public uint orange = (uint)0;
- public uint yellow = (uint)0;
- public uint lightgreen = (uint)0;
- public uint green = (uint)0;
- public uint aquagreen = (uint)0;
- public uint cyan = (uint)0;
- public uint lightblue = (uint)0;
- public uint blue = (uint)0;
- public uint purple = (uint)0;
- public uint lightpurple = (uint)0;
- public uint pink = (uint)0;
- public uint darkpink = (uint)0;
- public uint darkgrey = (uint)0;
- public uint lightgrey = (uint)0;
- public uint white = (uint)0;
- public uint yellowflower = (uint)0;
- public uint redflower = (uint)0;
- public uint mushroom = (uint)0;
- public uint redmushroom = (uint)0;
- public uint goldsolid = (uint)0;
- public uint iron = (uint)0;
- public uint staircasefull = (uint)0;
- public uint staircasestep = (uint)0;
- public uint brick = (uint)0;
- public uint tnt = (uint)0;
- public uint bookcase = (uint)0;
- public uint stonevine = (uint)0;
- public uint obsidian = (uint)0;
- public uint cobblestoneslab = (uint)0;
- public uint rope = (uint)0;
- public uint sandstone = (uint)0;
- public uint snowreal = (uint)0;
- public uint firereal = (uint)0;
- public uint lightpinkwool = (uint)0;
- public uint forestgreenwool = (uint)0;
- public uint brownwool = (uint)0;
- public uint deepblue = (uint)0;
- public uint turquoise = (uint)0;
- public uint ice = (uint)0;
- public uint ceramictile = (uint)0;
- public uint magmablock = (uint)0;
- public uint pillar = (uint)0;
- public uint crate = (uint)0;
- public uint stonebrick = (uint)0;
- //Tnt Wars
- public bool PlayingTntWars = false;
- public int CurrentAmountOfTnt = 0;
- public int CurrentTntGameNumber; //For keeping track of which game is which
- public int TntWarsHealth = 2;
- public int TntWarsKillStreak = 0;
- public float TntWarsScoreMultiplier = 1f;
- public int TNTWarsLastKillStreakAnnounced = 0;
- public bool inTNTwarsMap = false;
- public Player HarmedBy = null; //For Assists
- //Copy
- public List<CopyPos> CopyBuffer = new List<CopyPos>();
- public struct CopyPos { public ushort x, y, z; public ushort type; }
- public bool copyAir = false;
- public int[] copyoffset = new int[3] { 0, 0, 0 };
- public ushort[] copystart = new ushort[3] { 0, 0, 0 };
- public bool Mojangaccount
- {
- get
- {
- return truename.Contains('@');
- }
- }
- //Undo
- public struct UndoPos { public ushort x, y, z; public ushort type, newtype; public string mapName; public DateTime timePlaced; }
- public List<UndoPos> UndoBuffer = new List<UndoPos>();
- public List<UndoPos> RedoBuffer = new List<UndoPos>();
- public bool showPortals = false;
- public bool showMBs = false;
- public string prevMsg = "";
- //Block Change variable holding
- public int[] BcVar;
- //Movement
- public ushort oldBlock = 0;
- public ushort deathCount = 0;
- public ushort deathblock;
- //Games
- public DateTime lastDeath = DateTime.Now;
- public byte blockAction; //0-Nothing 1-solid 2-lava 3-water 4-active_lava 5 Active_water 6 OpGlass 7 BluePort 8 OrangePort
- public ushort modeType;
- public ushort[] bindings = new ushort[(ushort)128];
- public string[] cmdBind = new string[10];
- public string[] messageBind = new string[10];
- public string lastCMD = "";
- public sbyte c4circuitNumber = -1;
- public Level level = Server.mainLevel;
- public bool Loading = true; //True if player is loading a map.
- public ushort[] lastClick = new ushort[] { 0, 0, 0 };
- public ushort[] pos = new ushort[] { 0, 0, 0 };
- ushort[] oldpos = new ushort[] { 0, 0, 0 };
- // ushort[] basepos = new ushort[] { 0, 0, 0 };
- public byte[] rot = new byte[] { 0, 0 };
- byte[] oldrot = new byte[] { 0, 0 };
- //ushort[] clippos = new ushort[3] { 0, 0, 0 };
- //byte[] cliprot = new byte[2] { 0, 0 };
- // grief/spam detection
- public static int spamBlockCount = 200;
- public bool isUsingOpenClassic = false;
- public static int spamBlockTimer = 5;
- Queue<DateTime> spamBlockLog = new Queue<DateTime>(spamBlockCount);
- public int consecutivemessages;
- private System.Timers.Timer resetSpamCount = new System.Timers.Timer(Server.spamcountreset * 1000);
- //public static int spamChatCount = 3;
- //public static int spamChatTimer = 4;
- //Queue<DateTime> spamChatLog = new Queue<DateTime>(spamChatCount);
- // CmdVoteKick
- public VoteKickChoice voteKickChoice = VoteKickChoice.HasntVoted;
- // Extra storage for custom commands
- public ExtrasCollection Extras = new ExtrasCollection();
- //Chatrooms
- public string Chatroom;
- public List<string> spyChatRooms = new List<string>();
- public DateTime lastchatroomglobal;
- //Waypoints
- public List<Waypoint.WP> Waypoints = new List<Waypoint.WP>();
- //Random...
- public Random random = new Random();
- //Global Chat
- public bool muteGlobal;
- public bool loggedIn;
- public bool InGlobalChat { get; set; }
- public Dictionary<string, string> sounds = new Dictionary<string, string>();
- public bool isDev, isMod, isGCMod; //is this player a dev/mod/gcmod?
- public bool isStaff;
- public bool isProtected;
- public bool verifiedName;
- //CPE
- const string SelectionBoxExtName = "SelectionBoxExt";
- const int SelectionBoxExtVersion = 1;
- const string CustomBlocksExtName = "CustomBlocks";
- const int CustomBlocksExtVersion = 1;
- const byte CustomBlocksLevel = 1;
- const string ClickDistanceExtName = "ClickDistance";
- const int ClickDistanceExtVersion = 1;
- const string EnvColorsExtName = "EnvColors";
- const int EnvColorsExtVersion = 1;
- const string ChangeModelExtName = "ChangeModel";
- const int ChangeModelExtVersion = 1;
- const string EnvMapAppearanceExtName = "EnvMapAppearance";
- const int EnvMapAppearanceExtVersion = 1;
- const string HeldBlockExtName = "HeldBlock";
- const int HeldBlockExtVersion = 1;
- const string ExtPlayerListExtName = "ExtPlayerList";
- const int ExtPlayerListExtVersion = 1;
- const string SelectionCuboidExtName = "SelectionCuboid";
- const int SelectionCuboidExtVersion = 1;
- const string MessageTypesExtName = "MessageTypes";
- const int MessageTypesExtVersion = 1;
- const string EnvWeatherTypeExtName = "EnvWeatherType";
- const int EnvWeatherTypeExtVersion = 1;
- const string HackControlExtName = "HackControl";
- const int HackControlExtVersion = 1;
- // Note: if more levels are added, change UsesCustomBlocks from bool to int
- public bool SelectionBoxExt { get; set; }
- public bool UsesCustomBlocks { get; set; }
- public bool SupportsClickDistance = false;
- public bool SupportsEnvColors = false;
- public bool SupportsChangeModel = false;
- public bool SupportsEnvMapAppearance = false;
- public bool SupportsEnvWeatherType = false;
- public bool SupportsHeldBlock = false;
- public bool SupportsExtPlayerList = false;
- public bool SupportsSelectionCuboid = false;
- public bool SupportsMessageTypes = false;
- public bool SupportsHackControl = false;
- public static bool emotefix = false;
- public string appName;
- public int extensionCount;
- public List<string> extensions = new List<string>();
- public int customBlockSupportLevel;
- public bool extension;
- public struct OfflinePlayer
- {
- public string name, color, title, titleColor;
- public int money;
- //need moar? add moar! just make sure you adjust Player.FindOffline() method
- /// <summary>
- /// Creates a new OfflinePlayer object.
- /// </summary>
- /// <param name="nm">Name of the player.</param>
- /// <param name="clr">Color of player name.</param>
- /// <param name="tl">Title of player.</param>
- /// <param name="tlclr">Title color of player</param>
- /// <param name="mon">Player's money.</param>
- public OfflinePlayer(string nm, string clr, string tl, string tlclr, int mon) { name = nm; color = clr; title = tl; titleColor = tlclr; money = mon; }
- }
- public static string CheckPlayerStatus(Player p)
- {
- if (p.hidden)
- return "hidden";
- if (Server.afkset.Contains(p.name))
- return "afk";
- return "active";
- }
- public bool Readgcrules = false;
- public DateTime Timereadgcrules = DateTime.MinValue;
- public bool CheckIfInsideBlock()
- {
- return CheckIfInsideBlock(this);
- }
- public static bool CheckIfInsideBlock(Player p)
- {
- ushort x, y, z;
- x = (ushort)(p.pos[0] / 32);
- y = (ushort)(p.pos[1] / 32);
- y = (ushort)Math.Round((decimal)(((y * 32) + 4) / 32));
- z = (ushort)(p.pos[2] / 32);
- ushort b = p.level.GetTile(x, y, z);
- ushort b1 = p.level.GetTile(x, (ushort)(y - 1), z);
- if (Block.Walkthrough(Block.Convert(b)) && Block.Walkthrough(Block.Convert(b1)))
- {
- return false;
- }
- return Block.Convert(b) != Block.Zero && Block.Convert(b) != Block.op_air;
- }
- //This is so that plugin devs can declare a player without needing a socket..
- //They would still have to do p.Dispose()..
- public Player(string playername) { name = playername; }
- public Queue<Packet> Packets;
- public NetworkStream Stream;
- public BinaryReader Reader;
- public Player(Socket s)
- {
- try
- {
- socket = s;
- ip = socket.RemoteEndPoint.ToString().Split(':')[0];
- if (IPInPrivateRange(ip))
- exIP = ResolveExternalIP(ip);
- else
- exIP = ip;
- Server.s.Log(ip + " connected to the server.");
- for (byte i = 0; i < 128; ++i) bindings[i] = i;
- socket.BeginReceive(tempbuffer, 0, tempbuffer.Length, SocketFlags.None, new AsyncCallback(Receive), this);
- timespent.Elapsed += delegate
- {
- if (!Loading)
- {
- try
- {
- int Days = Convert.ToInt32(time.Split(' ')[0]);
- int Hours = Convert.ToInt32(time.Split(' ')[1]);
- int Minutes = Convert.ToInt32(time.Split(' ')[2]);
- int Seconds = Convert.ToInt32(time.Split(' ')[3]);
- Seconds++;
- if (Seconds >= 60)
- {
- Minutes++;
- Seconds = 0;
- }
- if (Minutes >= 60)
- {
- Hours++;
- Minutes = 0;
- }
- if (Hours >= 24)
- {
- Days++;
- Hours = 0;
- }
- time = "" + Days + " " + Hours + " " + Minutes + " " + Seconds;
- }
- catch { time = "0 0 0 1"; }
- }
- };
- timespent.Start();
- loginTimer.Elapsed += delegate
- {
- if (!Loading)
- {
- loginTimer.Stop();
- if (File.Exists("text/welcome.txt"))
- {
- try
- {
- using (StreamReader wm = File.OpenText("text/welcome.txt"))
- {
- List<string> welcome = new List<string>();
- while (!wm.EndOfStream)
- welcome.Add(wm.ReadLine());
- foreach (string w in welcome)
- SendMessage(w);
- }
- }
- catch { }
- }
- else
- {
- Server.s.Log("Could not find welcome.txt. Using default.");
- File.WriteAllText("text/welcome.txt", "Welcome to my server!");
- SendMessage("Welcome to my server!");
- }
- extraTimer.Start();
- loginTimer.Dispose();
- }
- }; loginTimer.Start();
- pingTimer.Elapsed += delegate { SendPing(); };
- pingTimer.Start();
- extraTimer.Elapsed += delegate
- {
- extraTimer.Stop();
- try
- {
- if (!Group.Find("Nobody").commands.Contains("inbox") && !Group.Find("Nobody").commands.Contains("send"))
- {
- //safe against SQL injections because no user input is given here
- DataTable Inbox = Database.fillData("SELECT * FROM `Inbox" + name + "`", true);
- SendMessage("&cYou have &f" + Inbox.Rows.Count + Server.DefaultColor + " &cmessages in /inbox");
- Inbox.Dispose();
- }
- }
- catch { }
- if (Server.updateTimer.Interval > 1000) SendMessage("Lowlag mode is currently &aON.");
- try
- {
- if (!Group.Find("Nobody").commands.Contains("pay") && !Group.Find("Nobody").commands.Contains("give") && !Group.Find("Nobody").commands.Contains("take")) SendMessage("You currently have &a" + money + Server.DefaultColor + " " + Server.moneys);
- }
- catch { }
- SendMessage("You have modified &a" + overallBlocks + Server.DefaultColor + " blocks!");
- if (players.Count == 1)
- SendMessage("There is currently &a" + players.Count + " player online.");
- else
- SendMessage("There are currently &a" + players.Count + " players online.");
- try
- {
- if (!Group.Find("Nobody").commands.Contains("award") && !Group.Find("Nobody").commands.Contains("awards") && !Group.Find("Nobody").commands.Contains("awardmod")) SendMessage("You have " + Awards.awardAmount(name) + " awards.");
- }
- catch { }
- try
- {
- ZombieGame.alive.Remove(this);
- ZombieGame.infectd.Remove(this);
- }
- catch { }
- if (Server.lava.active) SendMessage("There is a &aLava Survival " + Server.DefaultColor + "game active! Join it by typing /ls go");
- extraTimer.Dispose();
- };
- afkTimer.Elapsed += delegate
- {
- if (name == "") return;
- if (Server.afkset.Contains(name))
- {
- afkCount = 0;
- if (Server.afkkick > 0 && group.Permission < Server.afkkickperm)
- if (afkStart.AddMinutes(Server.afkkick) < DateTime.Now)
- Kick("Auto-kick, AFK for " + Server.afkkick + " minutes");
- if ((oldpos[0] != pos[0] || oldpos[1] != pos[1] || oldpos[2] != pos[2]) && (oldrot[0] != rot[0] || oldrot[1] != rot[1]))
- Command.all.Find("afk").Use(this, "");
- }
- else
- {
- if (oldpos[0] == pos[0] && oldpos[1] == pos[1] && oldpos[2] == pos[2] && oldrot[0] == rot[0] && oldrot[1] == rot[1])
- afkCount++;
- else
- afkCount = 0;
- if (afkCount > Server.afkminutes * 30)
- {
- if (name != null && !String.IsNullOrEmpty(name.Trim()))
- {
- Command.all.Find("afk").Use(this, "auto: Not moved for " + Server.afkminutes + " minutes");
- if (AFK != null)
- AFK(this);
- if (ONAFK != null)
- ONAFK(this);
- OnPlayerAFKEvent.Call(this);
- afkCount = 0;
- }
- }
- }
- };
- resetSpamCount.Elapsed += delegate
- {
- if (consecutivemessages > 0)
- consecutivemessages = 0;
- };
- resetSpamCount.Start();
- if (Server.afkminutes > 0) afkTimer.Start();
- connections.Add(this);
- }
- catch (Exception e) { Kick("Login failed!"); Server.ErrorLog(e); }
- }
- public bool HasExtension (string extName)
- {
- return ExtEntry.FindAll (cpe => cpe.name == extName) != null;
- }
- public void save()
- {
- //safe against SQL injects because no user input is provided
- string commandString =
- "UPDATE Players SET IP='" + ip + "'" +
- ", LastLogin='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
- ", totalLogin=" + totalLogins +
- ", totalDeaths=" + overallDeath +
- ", Money=" + money +
- ", totalBlocks=" + overallBlocks + " + " + loginBlocks +
- ", totalKicked=" + totalKicked +
- ", TimeSpent='" + time +
- "' WHERE Name='" + name + "'";
- if (MySQLSave != null)
- MySQLSave(this, commandString);
- OnMySQLSaveEvent.Call(this, commandString);
- if (cancelmysql)
- {
- cancelmysql = false;
- return;
- }
- if (!Server.useMySQL)
- SQLite.executeQuery(commandString);
- else
- MySQL.executeQuery(commandString);
- try
- {
- if (!smileySaved)
- {
- if (parseSmiley)
- emoteList.RemoveAll(s => s == name);
- else
- emoteList.Add(name);
- File.WriteAllLines("text/emotelist.txt", emoteList.ToArray());
- smileySaved = true;
- }
- }
- catch (Exception e)
- {
- Server.ErrorLog(e);
- }
- try
- {
- SaveUndo();
- }
- catch (Exception e)
- {
- Server.s.Log("Error saving undo data.");
- Server.ErrorLog(e);
- }
- }
- #region == INCOMING ==
- static void Receive(IAsyncResult result)
- {
- //Server.s.Log(result.AsyncState.ToString());
- Player p = (Player)result.AsyncState;
- if (p.disconnected || p.socket == null)
- return;
- try
- {
- int length = p.socket.EndReceive(result);
- if (length == 0) { p.Disconnect(); return; }
- byte[] b = new byte[p.buffer.Length + length];
- Buffer.BlockCopy(p.buffer, 0, b, 0, p.buffer.Length);
- Buffer.BlockCopy(p.tempbuffer, 0, b, p.buffer.Length, length);
- p.buffer = p.HandleMessage(b);
- if (p.dontmindme && p.buffer.Length == 0)
- {
- Server.s.Log("Disconnected");
- p.socket.Close();
- p.disconnected = true;
- return;
- }
- if (!p.disconnected)
- p.socket.BeginReceive(p.tempbuffer, 0, p.tempbuffer.Length, SocketFlags.None,
- new AsyncCallback(Receive), p);
- }
- catch (SocketException)
- {
- p.Disconnect();
- }
- catch (ObjectDisposedException)
- {
- // Player is no longer connected, socket was closed
- // Mark this as disconnected and remove them from active connection list
- Player.SaveUndo(p);
- if (connections.Contains(p))
- connections.Remove(p);
- p.disconnected = true;
- }
- catch (Exception e)
- {
- Server.ErrorLog(e);
- p.Kick("Error!");
- }
- }
- byte[] HandleMessage(byte[] buffer)
- {
- try
- {
- int length = 0; byte msg = buffer[0];
- // Get the length of the message by checking the first byte
- switch (msg)
- {
- //For wom
- case (byte)'G':
- level.textures.ServeCfg(this, buffer);
- return new byte[1];
- case 0:
- length = 130;
- break; // login
- case 5:
- if (!loggedIn)
- goto default;
- length = 8;
- break; // blockchange
- case 8:
- if (!loggedIn)
- goto default;
- length = 9;
- break; // input
- case 13:
- if (!loggedIn)
- goto default;
- length = 65;
- break; // chat
- case 16:
- length = 66;
- break;
- case 17:
- length = 68;
- break;
- case 19:
- length = 1;
- break;
- default:
- if (!dontmindme)
- Kick("Unhandled message id \"" + msg + "\"!");
- else
- Server.s.Log(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
- return new byte[0];
- }
- if (buffer.Length > length)
- {
- byte[] message = new byte[length];
- Buffer.BlockCopy(buffer, 1, message, 0, length);
- byte[] tempbuffer = new byte[buffer.Length - length - 1];
- Buffer.BlockCopy(buffer, length + 1, tempbuffer, 0, buffer.Length - length - 1);
- buffer = tempbuffer;
- // Thread thread = null;
- switch (msg)
- {
- case 0:
- HandleLogin(message);
- break;
- case 5:
- if (!loggedIn)
- break;
- HandleBlockchange(message);
- break;
- case 8:
- if (!loggedIn)
- break;
- HandleInput(message);
- break;
- case 13:
- if (!loggedIn)
- break;
- HandleChat(message);
- break;
- case 16:
- HandleExtInfo(message);
- break;
- case 17:
- HandleExtEntry(message);
- break;
- case 19:
- HandleCustomBlockSupportLevel(message);
- break;
- }
- //thread.Start((object)message);
- if (buffer.Length > 0)
- buffer = HandleMessage(buffer);
- else
- return new byte[0];
- }
- }
- catch (Exception e)
- {
- Server.ErrorLog(e);
- }
- return buffer;
- }
- public void HandleExtInfo(byte[] message)
- {
- appName = enc.GetString(message, 0, 64).Trim();
- extensionCount = message[65];
- }
- public struct CPE { public string name; public int version; }
- public List<CPE> ExtEntry = new List<CPE>();
- void HandleExtEntry(byte[] msg)
- {
- CPE tmp; tmp.name = enc.GetString(msg, 0, 64);
- tmp.version = BitConverter.ToInt32(msg, 64);
- ExtEntry.Add(tmp);
- }
- public void HandleCustomBlockSupportLevel(byte[] message)
- {
- customBlockSupportLevel = message[0];
- }
- void HandleLogin(byte[] message)
- {
- try
- {
- //byte[] message = (byte[])m;
- if (loggedIn)
- return;
- byte version = message[0];
- name = enc.GetString(message, 1, 64).Trim();
- truename = name;
- if (Server.omniban.CheckPlayer(this)) { Kick(Server.omniban.kickMsg); return; } //deprecated
- if (name.Split('@').Length > 1)
- {
- name = name.Split('@')[0];
- if (!MojangAccount.HasID(truename))
- MojangAccount.AddUser(truename);
- name += "_" + MojangAccount.GetID(truename);
- }
- string verify = enc.GetString(message, 65, 32).Trim();
- ushort type = message[129];
- //Forge Protection Check
- verifiedName = Server.verify ? true : false;
- if (Server.verify)
- {
- if (verify == BitConverter.ToString(md5.ComputeHash(enc.GetBytes(Server.salt + truename))).Replace("-", "").ToLower().TrimStart('0'))
- {
- identified = true;
- }
- if (verify == BitConverter.ToString(md5.ComputeHash(enc.GetBytes(Server.salt2 + truename))).Replace("-", "").ToLower())
- {
- JObject json;
- try
- {
- using (var client = new WebClient())
- {
- json = JObject.Parse(client.DownloadString("http://www.classicube.net/api/player/" + name.ToLower()));
- }
- ID = (int)json.SelectToken("id");
- UsingID = true;
- }
- catch (Exception e)
- {
- Server.ErrorLog(e);
- Server.s.Log("Could not get Player's ID, going with name bans!");
- UsingID = false;
- }
- identified = true;
- name += "+";
- }
- if (IPInPrivateRange(ip))
- {
- identified = true;
- }
- if (identified == false)
- {
- Kick("Login failed! Try again."); return;
- }
- isDev = Server.Devs.Contains(name.ToLower());
- isMod = Server.Mods.Contains(name.ToLower());
- isGCMod = Server.GCmods.Contains(name.ToLower());
- isStaff = isDev || isMod || isGCMod;
- isProtected = Server.forgeProtection == ForgeProtection.Mod && (isMod || isDev) ? true : Server.forgeProtection == ForgeProtection.Dev && isDev ? true : false;
- }
- try
- {
- Server.TempBan tBan = Server.tempBans.Find(tB => tB.name.ToLower() == name.ToLower());
- if (tBan.allowedJoin < DateTime.Now)
- {
- Server.tempBans.Remove(tBan);
- }
- else if (!isDev && !isMod)
- {
- Kick("You're still banned (temporary ban)!");
- }
- }
- catch { }
- // Whitelist check.
- if (Server.useWhitelist)
- {
- if (Server.verify)
- {
- if (Server.whiteList.Contains(name))
- {
- onWhitelist = true;
- }
- }
- else
- {
- // Verify Names is off. Gotta check the hard way.
- Database.AddParams("@IP", ip);
- DataTable ipQuery = Database.fillData("SELECT Name FROM Players WHERE IP = @IP");
- if (ipQuery.Rows.Count > 0)
- {
- if (ipQuery.Rows.Contains(name) && Server.whiteList.Contains(name))
- {
- onWhitelist = true;
- }
- }
- ipQuery.Dispose();
- }
- onWhitelist = isDev || isMod;
- if (!onWhitelist) { Kick("This is a private server!"); return; } //i think someone forgot this?
- }
- //premium check
- if (Server.PremiumPlayersOnly && !isDev && !isMod)
- {
- using (WebClient Client = new WebClient())
- {
- int tries = 0;
- while (tries++ < 3)
- {
- try
- {
- bool haspaid = Convert.ToBoolean(Client.DownloadString("http://www.minecraft.net/haspaid.jsp?user=" + name));
- if (!haspaid)
- Kick("Sorry, this is a premium server only!");
- break;
- }
- catch { }
- }
- }
- }
- if (File.Exists("ranks/ignore/" + this.name + ".txt"))
- {
- try
- {
- string[] checklines = File.ReadAllLines("ranks/ignore/" + this.name + ".txt");
- foreach (string checkline in checklines)
- {
- this.listignored.Add(checkline);
- }
- File.Delete("ranks/ignore/" + this.name + ".txt");
- }
- catch
- {
- Server.s.Log("Failed to load ignore list for: " + this.name);
- }
- }
- if (File.Exists("ranks/ignore/GlobalIgnore.xml"))
- {
- try
- {
- string[] searchxmls = File.ReadAllLines("ranks/ignore/GlobalIgnore.xml");
- foreach (string searchxml in searchxmls)
- {
- globalignores.Add(searchxml);
- }
- foreach (string ignorer in globalignores)
- {
- Player foundignore = Player.Find(ignorer);
- foundignore.ignoreglobal = true;
- }
- File.Delete("ranks/ignore/GlobalIgnore.xml");
- }
- catch
- {
- Server.s.Log("Failed to load global ignore list!");
- }
- }
- // ban check
- if (!isDev && !isMod)
- {
- if (Server.bannedIP.Contains(ip))
- {
- if (Server.useWhitelist)
- {
- if (!onWhitelist)
- {
- Kick(Server.customBanMessage);
- return;
- }
- }
- else
- {
- Kick(Server.customBanMessage);
- return;
- }
- }
- if (Group.findPlayerGroup(name) == Group.findPerm(LevelPermission.Banned))
- {
- if (Server.useWhitelist)
- {
- if (!onWhitelist)
- {
- Kick(Server.customBanMessage);
- return;
- }
- }
- else
- {
- if (UsingID && Ban.IsbannedID(ID.ToString()) || !UsingID && Ban.Isbanned(name))
- {
- string[] data = Ban.Getbandata(name);
- Kick("You were banned for \"" + data[1] + "\" by " + data[0]);
- }
- else
- Kick(Server.customBanMessage);
- return;
- }
- }
- }
- //server maxplayer check
- if (!isDev && !isMod && !VIP.Find(this))
- {
- // Check to see how many guests we have
- if (Player.players.Count >= Server.players && !IPInPrivateRange(ip)) { Kick("Server full!"); return; }
- // Code for limiting no. of guests
- if (Group.findPlayerGroup(name) == Group.findPerm(LevelPermission.Guest))
- {
- // Check to see how many guests we have
- int currentNumOfGuests = Player.players.Count(pl => pl.group.Permission <= LevelPermission.Guest);
- if (currentNumOfGuests >= Server.maxGuests)
- {
- if (Server.guestLimitNotify) GlobalMessageOps("Guest " + this.name + " couldn't log in - too many guests.");
- Server.s.Log("Guest " + this.name + " couldn't log in - too many guests.");
- Kick("Server has reached max number of guests");
- return;
- }
- }
- }
- if (version != Server.version) { Kick("Wrong version!"); return; }
- foreach (Player p in players)
- {
- if (p.name == name)
- {
- if (Server.verify)
- {
- p.Kick("Someone logged in as you!"); break;
- }
- else { Kick("Already logged in!"); return; }
- }
- }
- if (type == 0x42)
- {
- extension = true;
- SendExtInfo(14);
- SendExtEntry("ClickDistance", 1);
- SendExtEntry("CustomBlocks", 1);
- SendExtEntry("HeldBlock", 1);
- SendExtEntry("TextHotKey", 1);
- SendExtEntry("ExtPlayerList", 1);
- SendExtEntry("EnvColors", 1);
- SendExtEntry("SelectionCuboid", 1);
- SendExtEntry("BlockPermissions", 1);
- SendExtEntry("ChangeModel", 1);
- SendExtEntry("EnvMapAppearance", 1);
- SendExtEntry("EnvWeatherType", 1);
- SendExtEntry("HackControl", 1);
- SendExtEntry("EmoteFix", 1);
- SendExtEntry("MessageTypes", 1);
- SendCustomBlockSupportLevel(1);
- }
- try { left.Remove(name.ToLower()); }
- catch { }
- group = Group.findPlayerGroup(name);
- SendMotd();
- SendMap();
- Loading = true;
- if (disconnected) return;
- loggedIn = true;
- this.id = FreeId();
- lock (players)
- players.Add(this);
- connections.Remove(this);
- Server.s.PlayerListUpdate();
- //Test code to show when people come back with different accounts on the same IP
- string temp = name + " is lately known as:";
- bool found = false;
- if (!ip.StartsWith("127.0.0."))
- {
- foreach (KeyValuePair<string, string> prev in left)
- {
- if (prev.Value == ip)
- {
- found = true;
- temp += " " + prev.Key;
- }
- }
- if (found)
- {
- if (this.group.Permission < Server.adminchatperm || Server.adminsjoinsilent == false)
- {
- GlobalMessageOps(temp);
- //IRCBot.Say(temp, true); //Tells people in op channel on IRC
- }
- Server.s.Log(temp);
- }
- }
- }
- catch (Exception e)
- {
- Server.ErrorLog(e);
- Player.GlobalMessage("An error occurred: " + e.Message);
- }
- //OpenClassic Client Check
- SendBlockchange(0, 0, 0, 0);
- Database.AddParams("@Name", name);
- DataTable playerDb = Database.fillData("SELECT * FROM Players WHERE Name=@Name");
- if (playerDb.Rows.Count == 0)
- {
- this.prefix = "";
- this.time = "0 0 0 1";
- this.title = "";
- this.titlecolor = "";
- this.color = group.color;
- this.money = 0;
- this.firstLogin = DateTime.Now;
- this.totalLogins = 1;
- this.totalKicked = 0;
- this.overallDeath = 0;
- this.overallBlocks = 0;
- this.timeLogged = DateTime.Now;
- SendMessage("Welcome " + name + "! This is your first visiā¦
Large files files are truncated, but you can click here to view the full file