PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/Player/Player.cs

https://github.com/Goodlyay/MCForge-Vanilla-Redux
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

  1. /*
  2. Copyright 2010 MCSharp team (Modified for use with MCZall/MCLawl/MCForge)
  3. Dual-licensed under the Educational Community License, Version 2.0 and
  4. the GNU General Public License, Version 3 (the "Licenses"); you may
  5. not use this file except in compliance with the Licenses. You may
  6. obtain a copy of the Licenses at
  7. http://www.opensource.org/licenses/ecl2.php
  8. http://www.gnu.org/licenses/gpl-3.0.html
  9. Unless required by applicable law or agreed to in writing,
  10. software distributed under the Licenses are distributed on an "AS IS"
  11. BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  12. or implied. See the Licenses for the specific language governing
  13. permissions and limitations under the Licenses.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Data;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Security.Cryptography;
  24. using System.Text;
  25. using System.Text.RegularExpressions;
  26. using System.Threading;
  27. using Newtonsoft.Json.Linq;
  28. using MCForge.SQL;
  29. namespace MCForge
  30. {
  31. public sealed partial class Player : IDisposable
  32. {
  33. public void ClearChat() { OnChat = null; }
  34. /// <summary>
  35. /// List of all server players.
  36. /// </summary>
  37. public static List<Player> players = new List<Player>();
  38. /// <summary>
  39. /// Key - Name
  40. /// Value - IP
  41. /// All players who have left this restart.
  42. /// </summary>
  43. public static Dictionary<string, string> left = new Dictionary<string, string>();
  44. /// <summary>
  45. ///
  46. /// </summary>
  47. public static List<Player> connections = new List<Player>(Server.players);
  48. System.Timers.Timer muteTimer = new System.Timers.Timer(1000);
  49. public static List<string> emoteList = new List<string>();
  50. public List<string> listignored = new List<string>();
  51. public List<string> mapgroups = new List<string>();
  52. public static List<string> globalignores = new List<string>();
  53. public static int totalMySQLFailed = 0;
  54. public static byte number { get { return (byte)players.Count; } }
  55. static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  56. static MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
  57. public static string lastMSG = "";
  58. public static bool storeHelp = false;
  59. public static string storedHelp = "";
  60. private string truename;
  61. internal bool dontmindme = false;
  62. public Socket socket;
  63. System.Timers.Timer timespent = new System.Timers.Timer(1000);
  64. System.Timers.Timer loginTimer = new System.Timers.Timer(1000);
  65. public System.Timers.Timer pingTimer = new System.Timers.Timer(2000);
  66. System.Timers.Timer extraTimer = new System.Timers.Timer(22000);
  67. public System.Timers.Timer afkTimer = new System.Timers.Timer(2000);
  68. public int afkCount = 0;
  69. public DateTime afkStart;
  70. public string WoMVersion = "";
  71. public bool megaBoid = false;
  72. public bool cmdTimer = false;
  73. public bool UsingWom = false;
  74. byte[] buffer = new byte[0];
  75. byte[] tempbuffer = new byte[0xFF];
  76. public bool disconnected = false;
  77. public string time;
  78. public string name;
  79. public bool identified = false;
  80. public bool UsingID = false;
  81. public int ID = 0;
  82. public int warn = 0;
  83. public byte id;
  84. public int userID = -1;
  85. public string ip;
  86. public string exIP; // external IP
  87. public string color;
  88. public Group group;
  89. public bool hidden = false;
  90. public bool painting = false;
  91. public bool muted = false;
  92. public bool jailed = false;
  93. public bool agreed = false;
  94. public bool invincible = false;
  95. public string prefix = "";
  96. public string title = "";
  97. public string titlecolor;
  98. public int TotalMessagesSent = 0;
  99. public int passtries = 0;
  100. public int ponycount = 0;
  101. public int rdcount = 0;
  102. public bool hasreadrules = false;
  103. public bool canusereview = true;
  104. //Gc checks
  105. public string lastmsg = "";
  106. public int spamcount = 0, capscount = 0, floodcount = 0, multi = 0;
  107. public DateTime lastmsgtime = DateTime.MinValue;
  108. /// <summary>
  109. /// Console only please
  110. /// </summary>
  111. public bool canusegc = true;
  112. //Pyramid Code
  113. public int pyramidx1;
  114. public int pyramidx2;
  115. public int pyramidy1;
  116. public int pyramidy2;
  117. public int pyramidz1;
  118. public int pyramidz2;
  119. public string pyramidblock;
  120. public int pyramidtotal;
  121. public int pyramidtotal2;
  122. public bool pyramidsilent = false;
  123. public bool deleteMode = false;
  124. public bool ignorePermission = false;
  125. public bool ignoreGrief = false;
  126. public bool parseSmiley = true;
  127. public bool smileySaved = true;
  128. public bool opchat = false;
  129. public bool adminchat = false;
  130. public bool onWhitelist = false;
  131. public bool whisper = false;
  132. public string whisperTo = "";
  133. public bool ignoreglobal = false;
  134. public string storedMessage = "";
  135. public bool trainGrab = false;
  136. public bool onTrain = false;
  137. public bool allowTnt = true;
  138. public bool frozen = false;
  139. public string following = "";
  140. public string possess = "";
  141. // Only used for possession.
  142. //Using for anything else can cause unintended effects!
  143. public bool canBuild = true;
  144. public int money = 0;
  145. public long overallBlocks = 0;
  146. public int loginBlocks = 0;
  147. public DateTime timeLogged;
  148. public DateTime firstLogin;
  149. public int totalLogins = 0;
  150. public int totalKicked = 0;
  151. public int overallDeath = 0;
  152. public string savedcolor = "";
  153. public bool staticCommands = false;
  154. public DateTime ZoneSpam;
  155. public bool ZoneCheck = false;
  156. public bool zoneDel = false;
  157. public Thread commThread;
  158. public bool commUse = false;
  159. public bool aiming;
  160. public bool isFlying = false;
  161. public bool joker = false;
  162. public bool adminpen = false;
  163. public bool voice = false;
  164. public string voicestring = "";
  165. public int grieferStoneWarn = 0;
  166. // CTF
  167. public CTFTeam team;
  168. public bool carryingFlag;
  169. public bool justDroppedFlag = false;
  170. public CatchPos placedTNT;
  171. public CatchPos placedMine;
  172. public int captureStreak;
  173. public int captureCount;
  174. public int kills;
  175. public int deaths;
  176. public int drownCount;
  177. public int totalCaptures;
  178. public int totalKills;
  179. public int totalDeaths;
  180. public int totalReturns;
  181. bool isActivating;
  182. public struct CatchPos
  183. {
  184. public ushort x, y, z;
  185. public bool isActive;
  186. }
  187. public List<string> playersKilled = new List<string>();
  188. public int getKillCount(string name)
  189. {
  190. int count = 0;
  191. playersKilled.ForEach(delegate(string kill)
  192. {
  193. if (name.ToLower() == kill.ToLower())
  194. {
  195. count++;
  196. }
  197. });
  198. return count;
  199. }
  200. public void Reward(int reward)
  201. {
  202. money += reward;
  203. }
  204. public void killPlayer(Player killed)
  205. {
  206. playersKilled.Add(killed.name);
  207. killed.deaths++;
  208. kills++;
  209. Reward(CTF.killPlayerReward);
  210. if (getKillCount(killed.name) % 5 == 0)
  211. {
  212. Player.GlobalMessage("&f- " + color + name + "&b is dominating " + killed.color + killed.name + "&b!");
  213. }
  214. if (killed.carryingFlag)
  215. {
  216. Command.all.Find("drop").Use(killed, "");
  217. }
  218. killed.team.SpawnPlayer(killed);
  219. }
  220. //Countdown
  221. public bool playerofcountdown = false;
  222. public bool incountdown = false;
  223. public ushort countdowntempx;
  224. public ushort countdowntempz;
  225. public bool countdownsettemps = false;
  226. //Zombie
  227. public string Original = "";
  228. public bool referee = false;
  229. public int blockCount = 50;
  230. public bool voted = false;
  231. public int blocksStacked = 0;
  232. public int infectThisRound = 0;
  233. public int lastYblock = 0;
  234. public int lastXblock = 0;
  235. public int lastZblock = 0;
  236. public bool infected = false;
  237. public bool aka = false;
  238. public bool flipHead = true;
  239. public int playersInfected = 0;
  240. public int NoClipcount = 0;
  241. //SMP Mode
  242. public bool InSMP = false;
  243. public uint rock = (uint)0;
  244. public uint grass = (uint)0;
  245. public uint dirt = (uint)0;
  246. public uint stone = (uint)0;
  247. public uint wood = (uint)0;
  248. public uint shrub = (uint)0;
  249. public uint blackrock = (uint)0;// adminium
  250. public uint water = (uint)0;
  251. public uint waterstill = (uint)0;
  252. public uint lava = (uint)0;
  253. public uint lavastill = (uint)0;
  254. public uint sand = (uint)0;
  255. public uint gravel = (uint)0;
  256. public uint goldrock = (uint)0;
  257. public uint ironrock = (uint)0;
  258. public uint coal = (uint)0;
  259. public uint trunk = (uint)0;
  260. public uint leaf = (uint)0;
  261. public uint sponge = (uint)0;
  262. public uint glass = (uint)0;
  263. public uint red = (uint)0;
  264. public uint orange = (uint)0;
  265. public uint yellow = (uint)0;
  266. public uint lightgreen = (uint)0;
  267. public uint green = (uint)0;
  268. public uint aquagreen = (uint)0;
  269. public uint cyan = (uint)0;
  270. public uint lightblue = (uint)0;
  271. public uint blue = (uint)0;
  272. public uint purple = (uint)0;
  273. public uint lightpurple = (uint)0;
  274. public uint pink = (uint)0;
  275. public uint darkpink = (uint)0;
  276. public uint darkgrey = (uint)0;
  277. public uint lightgrey = (uint)0;
  278. public uint white = (uint)0;
  279. public uint yellowflower = (uint)0;
  280. public uint redflower = (uint)0;
  281. public uint mushroom = (uint)0;
  282. public uint redmushroom = (uint)0;
  283. public uint goldsolid = (uint)0;
  284. public uint iron = (uint)0;
  285. public uint staircasefull = (uint)0;
  286. public uint staircasestep = (uint)0;
  287. public uint brick = (uint)0;
  288. public uint tnt = (uint)0;
  289. public uint bookcase = (uint)0;
  290. public uint stonevine = (uint)0;
  291. public uint obsidian = (uint)0;
  292. public uint cobblestoneslab = (uint)0;
  293. public uint rope = (uint)0;
  294. public uint sandstone = (uint)0;
  295. public uint snowreal = (uint)0;
  296. public uint firereal = (uint)0;
  297. public uint lightpinkwool = (uint)0;
  298. public uint forestgreenwool = (uint)0;
  299. public uint brownwool = (uint)0;
  300. public uint deepblue = (uint)0;
  301. public uint turquoise = (uint)0;
  302. public uint ice = (uint)0;
  303. public uint ceramictile = (uint)0;
  304. public uint magmablock = (uint)0;
  305. public uint pillar = (uint)0;
  306. public uint crate = (uint)0;
  307. public uint stonebrick = (uint)0;
  308. //Tnt Wars
  309. public bool PlayingTntWars = false;
  310. public int CurrentAmountOfTnt = 0;
  311. public int CurrentTntGameNumber; //For keeping track of which game is which
  312. public int TntWarsHealth = 2;
  313. public int TntWarsKillStreak = 0;
  314. public float TntWarsScoreMultiplier = 1f;
  315. public int TNTWarsLastKillStreakAnnounced = 0;
  316. public bool inTNTwarsMap = false;
  317. public Player HarmedBy = null; //For Assists
  318. //Copy
  319. public List<CopyPos> CopyBuffer = new List<CopyPos>();
  320. public struct CopyPos { public ushort x, y, z; public ushort type; }
  321. public bool copyAir = false;
  322. public int[] copyoffset = new int[3] { 0, 0, 0 };
  323. public ushort[] copystart = new ushort[3] { 0, 0, 0 };
  324. public bool Mojangaccount
  325. {
  326. get
  327. {
  328. return truename.Contains('@');
  329. }
  330. }
  331. //Undo
  332. public struct UndoPos { public ushort x, y, z; public ushort type, newtype; public string mapName; public DateTime timePlaced; }
  333. public List<UndoPos> UndoBuffer = new List<UndoPos>();
  334. public List<UndoPos> RedoBuffer = new List<UndoPos>();
  335. public bool showPortals = false;
  336. public bool showMBs = false;
  337. public string prevMsg = "";
  338. //Block Change variable holding
  339. public int[] BcVar;
  340. //Movement
  341. public ushort oldBlock = 0;
  342. public ushort deathCount = 0;
  343. public ushort deathblock;
  344. //Games
  345. public DateTime lastDeath = DateTime.Now;
  346. public byte blockAction; //0-Nothing 1-solid 2-lava 3-water 4-active_lava 5 Active_water 6 OpGlass 7 BluePort 8 OrangePort
  347. public ushort modeType;
  348. public ushort[] bindings = new ushort[(ushort)128];
  349. public string[] cmdBind = new string[10];
  350. public string[] messageBind = new string[10];
  351. public string lastCMD = "";
  352. public sbyte c4circuitNumber = -1;
  353. public Level level = Server.mainLevel;
  354. public bool Loading = true; //True if player is loading a map.
  355. public ushort[] lastClick = new ushort[] { 0, 0, 0 };
  356. public ushort[] pos = new ushort[] { 0, 0, 0 };
  357. ushort[] oldpos = new ushort[] { 0, 0, 0 };
  358. // ushort[] basepos = new ushort[] { 0, 0, 0 };
  359. public byte[] rot = new byte[] { 0, 0 };
  360. byte[] oldrot = new byte[] { 0, 0 };
  361. //ushort[] clippos = new ushort[3] { 0, 0, 0 };
  362. //byte[] cliprot = new byte[2] { 0, 0 };
  363. // grief/spam detection
  364. public static int spamBlockCount = 200;
  365. public bool isUsingOpenClassic = false;
  366. public static int spamBlockTimer = 5;
  367. Queue<DateTime> spamBlockLog = new Queue<DateTime>(spamBlockCount);
  368. public int consecutivemessages;
  369. private System.Timers.Timer resetSpamCount = new System.Timers.Timer(Server.spamcountreset * 1000);
  370. //public static int spamChatCount = 3;
  371. //public static int spamChatTimer = 4;
  372. //Queue<DateTime> spamChatLog = new Queue<DateTime>(spamChatCount);
  373. // CmdVoteKick
  374. public VoteKickChoice voteKickChoice = VoteKickChoice.HasntVoted;
  375. // Extra storage for custom commands
  376. public ExtrasCollection Extras = new ExtrasCollection();
  377. //Chatrooms
  378. public string Chatroom;
  379. public List<string> spyChatRooms = new List<string>();
  380. public DateTime lastchatroomglobal;
  381. //Waypoints
  382. public List<Waypoint.WP> Waypoints = new List<Waypoint.WP>();
  383. //Random...
  384. public Random random = new Random();
  385. //Global Chat
  386. public bool muteGlobal;
  387. public bool loggedIn;
  388. public bool InGlobalChat { get; set; }
  389. public Dictionary<string, string> sounds = new Dictionary<string, string>();
  390. public bool isDev, isMod, isGCMod; //is this player a dev/mod/gcmod?
  391. public bool isStaff;
  392. public bool isProtected;
  393. public bool verifiedName;
  394. //CPE
  395. const string SelectionBoxExtName = "SelectionBoxExt";
  396. const int SelectionBoxExtVersion = 1;
  397. const string CustomBlocksExtName = "CustomBlocks";
  398. const int CustomBlocksExtVersion = 1;
  399. const byte CustomBlocksLevel = 1;
  400. const string ClickDistanceExtName = "ClickDistance";
  401. const int ClickDistanceExtVersion = 1;
  402. const string EnvColorsExtName = "EnvColors";
  403. const int EnvColorsExtVersion = 1;
  404. const string ChangeModelExtName = "ChangeModel";
  405. const int ChangeModelExtVersion = 1;
  406. const string EnvMapAppearanceExtName = "EnvMapAppearance";
  407. const int EnvMapAppearanceExtVersion = 1;
  408. const string HeldBlockExtName = "HeldBlock";
  409. const int HeldBlockExtVersion = 1;
  410. const string ExtPlayerListExtName = "ExtPlayerList";
  411. const int ExtPlayerListExtVersion = 1;
  412. const string SelectionCuboidExtName = "SelectionCuboid";
  413. const int SelectionCuboidExtVersion = 1;
  414. const string MessageTypesExtName = "MessageTypes";
  415. const int MessageTypesExtVersion = 1;
  416. const string EnvWeatherTypeExtName = "EnvWeatherType";
  417. const int EnvWeatherTypeExtVersion = 1;
  418. const string HackControlExtName = "HackControl";
  419. const int HackControlExtVersion = 1;
  420. // Note: if more levels are added, change UsesCustomBlocks from bool to int
  421. public bool SelectionBoxExt { get; set; }
  422. public bool UsesCustomBlocks { get; set; }
  423. public bool SupportsClickDistance = false;
  424. public bool SupportsEnvColors = false;
  425. public bool SupportsChangeModel = false;
  426. public bool SupportsEnvMapAppearance = false;
  427. public bool SupportsEnvWeatherType = false;
  428. public bool SupportsHeldBlock = false;
  429. public bool SupportsExtPlayerList = false;
  430. public bool SupportsSelectionCuboid = false;
  431. public bool SupportsMessageTypes = false;
  432. public bool SupportsHackControl = false;
  433. public static bool emotefix = false;
  434. public string appName;
  435. public int extensionCount;
  436. public List<string> extensions = new List<string>();
  437. public int customBlockSupportLevel;
  438. public bool extension;
  439. public struct OfflinePlayer
  440. {
  441. public string name, color, title, titleColor;
  442. public int money;
  443. //need moar? add moar! just make sure you adjust Player.FindOffline() method
  444. /// <summary>
  445. /// Creates a new OfflinePlayer object.
  446. /// </summary>
  447. /// <param name="nm">Name of the player.</param>
  448. /// <param name="clr">Color of player name.</param>
  449. /// <param name="tl">Title of player.</param>
  450. /// <param name="tlclr">Title color of player</param>
  451. /// <param name="mon">Player's money.</param>
  452. public OfflinePlayer(string nm, string clr, string tl, string tlclr, int mon) { name = nm; color = clr; title = tl; titleColor = tlclr; money = mon; }
  453. }
  454. public static string CheckPlayerStatus(Player p)
  455. {
  456. if (p.hidden)
  457. return "hidden";
  458. if (Server.afkset.Contains(p.name))
  459. return "afk";
  460. return "active";
  461. }
  462. public bool Readgcrules = false;
  463. public DateTime Timereadgcrules = DateTime.MinValue;
  464. public bool CheckIfInsideBlock()
  465. {
  466. return CheckIfInsideBlock(this);
  467. }
  468. public static bool CheckIfInsideBlock(Player p)
  469. {
  470. ushort x, y, z;
  471. x = (ushort)(p.pos[0] / 32);
  472. y = (ushort)(p.pos[1] / 32);
  473. y = (ushort)Math.Round((decimal)(((y * 32) + 4) / 32));
  474. z = (ushort)(p.pos[2] / 32);
  475. ushort b = p.level.GetTile(x, y, z);
  476. ushort b1 = p.level.GetTile(x, (ushort)(y - 1), z);
  477. if (Block.Walkthrough(Block.Convert(b)) && Block.Walkthrough(Block.Convert(b1)))
  478. {
  479. return false;
  480. }
  481. return Block.Convert(b) != Block.Zero && Block.Convert(b) != Block.op_air;
  482. }
  483. //This is so that plugin devs can declare a player without needing a socket..
  484. //They would still have to do p.Dispose()..
  485. public Player(string playername) { name = playername; }
  486. public Queue<Packet> Packets;
  487. public NetworkStream Stream;
  488. public BinaryReader Reader;
  489. public Player(Socket s)
  490. {
  491. try
  492. {
  493. socket = s;
  494. ip = socket.RemoteEndPoint.ToString().Split(':')[0];
  495. if (IPInPrivateRange(ip))
  496. exIP = ResolveExternalIP(ip);
  497. else
  498. exIP = ip;
  499. Server.s.Log(ip + " connected to the server.");
  500. for (byte i = 0; i < 128; ++i) bindings[i] = i;
  501. socket.BeginReceive(tempbuffer, 0, tempbuffer.Length, SocketFlags.None, new AsyncCallback(Receive), this);
  502. timespent.Elapsed += delegate
  503. {
  504. if (!Loading)
  505. {
  506. try
  507. {
  508. int Days = Convert.ToInt32(time.Split(' ')[0]);
  509. int Hours = Convert.ToInt32(time.Split(' ')[1]);
  510. int Minutes = Convert.ToInt32(time.Split(' ')[2]);
  511. int Seconds = Convert.ToInt32(time.Split(' ')[3]);
  512. Seconds++;
  513. if (Seconds >= 60)
  514. {
  515. Minutes++;
  516. Seconds = 0;
  517. }
  518. if (Minutes >= 60)
  519. {
  520. Hours++;
  521. Minutes = 0;
  522. }
  523. if (Hours >= 24)
  524. {
  525. Days++;
  526. Hours = 0;
  527. }
  528. time = "" + Days + " " + Hours + " " + Minutes + " " + Seconds;
  529. }
  530. catch { time = "0 0 0 1"; }
  531. }
  532. };
  533. timespent.Start();
  534. loginTimer.Elapsed += delegate
  535. {
  536. if (!Loading)
  537. {
  538. loginTimer.Stop();
  539. if (File.Exists("text/welcome.txt"))
  540. {
  541. try
  542. {
  543. using (StreamReader wm = File.OpenText("text/welcome.txt"))
  544. {
  545. List<string> welcome = new List<string>();
  546. while (!wm.EndOfStream)
  547. welcome.Add(wm.ReadLine());
  548. foreach (string w in welcome)
  549. SendMessage(w);
  550. }
  551. }
  552. catch { }
  553. }
  554. else
  555. {
  556. Server.s.Log("Could not find welcome.txt. Using default.");
  557. File.WriteAllText("text/welcome.txt", "Welcome to my server!");
  558. SendMessage("Welcome to my server!");
  559. }
  560. extraTimer.Start();
  561. loginTimer.Dispose();
  562. }
  563. }; loginTimer.Start();
  564. pingTimer.Elapsed += delegate { SendPing(); };
  565. pingTimer.Start();
  566. extraTimer.Elapsed += delegate
  567. {
  568. extraTimer.Stop();
  569. try
  570. {
  571. if (!Group.Find("Nobody").commands.Contains("inbox") && !Group.Find("Nobody").commands.Contains("send"))
  572. {
  573. //safe against SQL injections because no user input is given here
  574. DataTable Inbox = Database.fillData("SELECT * FROM `Inbox" + name + "`", true);
  575. SendMessage("&cYou have &f" + Inbox.Rows.Count + Server.DefaultColor + " &cmessages in /inbox");
  576. Inbox.Dispose();
  577. }
  578. }
  579. catch { }
  580. if (Server.updateTimer.Interval > 1000) SendMessage("Lowlag mode is currently &aON.");
  581. try
  582. {
  583. 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);
  584. }
  585. catch { }
  586. SendMessage("You have modified &a" + overallBlocks + Server.DefaultColor + " blocks!");
  587. if (players.Count == 1)
  588. SendMessage("There is currently &a" + players.Count + " player online.");
  589. else
  590. SendMessage("There are currently &a" + players.Count + " players online.");
  591. try
  592. {
  593. 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.");
  594. }
  595. catch { }
  596. try
  597. {
  598. ZombieGame.alive.Remove(this);
  599. ZombieGame.infectd.Remove(this);
  600. }
  601. catch { }
  602. if (Server.lava.active) SendMessage("There is a &aLava Survival " + Server.DefaultColor + "game active! Join it by typing /ls go");
  603. extraTimer.Dispose();
  604. };
  605. afkTimer.Elapsed += delegate
  606. {
  607. if (name == "") return;
  608. if (Server.afkset.Contains(name))
  609. {
  610. afkCount = 0;
  611. if (Server.afkkick > 0 && group.Permission < Server.afkkickperm)
  612. if (afkStart.AddMinutes(Server.afkkick) < DateTime.Now)
  613. Kick("Auto-kick, AFK for " + Server.afkkick + " minutes");
  614. if ((oldpos[0] != pos[0] || oldpos[1] != pos[1] || oldpos[2] != pos[2]) && (oldrot[0] != rot[0] || oldrot[1] != rot[1]))
  615. Command.all.Find("afk").Use(this, "");
  616. }
  617. else
  618. {
  619. if (oldpos[0] == pos[0] && oldpos[1] == pos[1] && oldpos[2] == pos[2] && oldrot[0] == rot[0] && oldrot[1] == rot[1])
  620. afkCount++;
  621. else
  622. afkCount = 0;
  623. if (afkCount > Server.afkminutes * 30)
  624. {
  625. if (name != null && !String.IsNullOrEmpty(name.Trim()))
  626. {
  627. Command.all.Find("afk").Use(this, "auto: Not moved for " + Server.afkminutes + " minutes");
  628. if (AFK != null)
  629. AFK(this);
  630. if (ONAFK != null)
  631. ONAFK(this);
  632. OnPlayerAFKEvent.Call(this);
  633. afkCount = 0;
  634. }
  635. }
  636. }
  637. };
  638. resetSpamCount.Elapsed += delegate
  639. {
  640. if (consecutivemessages > 0)
  641. consecutivemessages = 0;
  642. };
  643. resetSpamCount.Start();
  644. if (Server.afkminutes > 0) afkTimer.Start();
  645. connections.Add(this);
  646. }
  647. catch (Exception e) { Kick("Login failed!"); Server.ErrorLog(e); }
  648. }
  649. public bool HasExtension (string extName)
  650. {
  651. return ExtEntry.FindAll (cpe => cpe.name == extName) != null;
  652. }
  653. public void save()
  654. {
  655. //safe against SQL injects because no user input is provided
  656. string commandString =
  657. "UPDATE Players SET IP='" + ip + "'" +
  658. ", LastLogin='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
  659. ", totalLogin=" + totalLogins +
  660. ", totalDeaths=" + overallDeath +
  661. ", Money=" + money +
  662. ", totalBlocks=" + overallBlocks + " + " + loginBlocks +
  663. ", totalKicked=" + totalKicked +
  664. ", TimeSpent='" + time +
  665. "' WHERE Name='" + name + "'";
  666. if (MySQLSave != null)
  667. MySQLSave(this, commandString);
  668. OnMySQLSaveEvent.Call(this, commandString);
  669. if (cancelmysql)
  670. {
  671. cancelmysql = false;
  672. return;
  673. }
  674. if (!Server.useMySQL)
  675. SQLite.executeQuery(commandString);
  676. else
  677. MySQL.executeQuery(commandString);
  678. try
  679. {
  680. if (!smileySaved)
  681. {
  682. if (parseSmiley)
  683. emoteList.RemoveAll(s => s == name);
  684. else
  685. emoteList.Add(name);
  686. File.WriteAllLines("text/emotelist.txt", emoteList.ToArray());
  687. smileySaved = true;
  688. }
  689. }
  690. catch (Exception e)
  691. {
  692. Server.ErrorLog(e);
  693. }
  694. try
  695. {
  696. SaveUndo();
  697. }
  698. catch (Exception e)
  699. {
  700. Server.s.Log("Error saving undo data.");
  701. Server.ErrorLog(e);
  702. }
  703. }
  704. #region == INCOMING ==
  705. static void Receive(IAsyncResult result)
  706. {
  707. //Server.s.Log(result.AsyncState.ToString());
  708. Player p = (Player)result.AsyncState;
  709. if (p.disconnected || p.socket == null)
  710. return;
  711. try
  712. {
  713. int length = p.socket.EndReceive(result);
  714. if (length == 0) { p.Disconnect(); return; }
  715. byte[] b = new byte[p.buffer.Length + length];
  716. Buffer.BlockCopy(p.buffer, 0, b, 0, p.buffer.Length);
  717. Buffer.BlockCopy(p.tempbuffer, 0, b, p.buffer.Length, length);
  718. p.buffer = p.HandleMessage(b);
  719. if (p.dontmindme && p.buffer.Length == 0)
  720. {
  721. Server.s.Log("Disconnected");
  722. p.socket.Close();
  723. p.disconnected = true;
  724. return;
  725. }
  726. if (!p.disconnected)
  727. p.socket.BeginReceive(p.tempbuffer, 0, p.tempbuffer.Length, SocketFlags.None,
  728. new AsyncCallback(Receive), p);
  729. }
  730. catch (SocketException)
  731. {
  732. p.Disconnect();
  733. }
  734. catch (ObjectDisposedException)
  735. {
  736. // Player is no longer connected, socket was closed
  737. // Mark this as disconnected and remove them from active connection list
  738. Player.SaveUndo(p);
  739. if (connections.Contains(p))
  740. connections.Remove(p);
  741. p.disconnected = true;
  742. }
  743. catch (Exception e)
  744. {
  745. Server.ErrorLog(e);
  746. p.Kick("Error!");
  747. }
  748. }
  749. byte[] HandleMessage(byte[] buffer)
  750. {
  751. try
  752. {
  753. int length = 0; byte msg = buffer[0];
  754. // Get the length of the message by checking the first byte
  755. switch (msg)
  756. {
  757. //For wom
  758. case (byte)'G':
  759. level.textures.ServeCfg(this, buffer);
  760. return new byte[1];
  761. case 0:
  762. length = 130;
  763. break; // login
  764. case 5:
  765. if (!loggedIn)
  766. goto default;
  767. length = 8;
  768. break; // blockchange
  769. case 8:
  770. if (!loggedIn)
  771. goto default;
  772. length = 9;
  773. break; // input
  774. case 13:
  775. if (!loggedIn)
  776. goto default;
  777. length = 65;
  778. break; // chat
  779. case 16:
  780. length = 66;
  781. break;
  782. case 17:
  783. length = 68;
  784. break;
  785. case 19:
  786. length = 1;
  787. break;
  788. default:
  789. if (!dontmindme)
  790. Kick("Unhandled message id \"" + msg + "\"!");
  791. else
  792. Server.s.Log(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
  793. return new byte[0];
  794. }
  795. if (buffer.Length > length)
  796. {
  797. byte[] message = new byte[length];
  798. Buffer.BlockCopy(buffer, 1, message, 0, length);
  799. byte[] tempbuffer = new byte[buffer.Length - length - 1];
  800. Buffer.BlockCopy(buffer, length + 1, tempbuffer, 0, buffer.Length - length - 1);
  801. buffer = tempbuffer;
  802. // Thread thread = null;
  803. switch (msg)
  804. {
  805. case 0:
  806. HandleLogin(message);
  807. break;
  808. case 5:
  809. if (!loggedIn)
  810. break;
  811. HandleBlockchange(message);
  812. break;
  813. case 8:
  814. if (!loggedIn)
  815. break;
  816. HandleInput(message);
  817. break;
  818. case 13:
  819. if (!loggedIn)
  820. break;
  821. HandleChat(message);
  822. break;
  823. case 16:
  824. HandleExtInfo(message);
  825. break;
  826. case 17:
  827. HandleExtEntry(message);
  828. break;
  829. case 19:
  830. HandleCustomBlockSupportLevel(message);
  831. break;
  832. }
  833. //thread.Start((object)message);
  834. if (buffer.Length > 0)
  835. buffer = HandleMessage(buffer);
  836. else
  837. return new byte[0];
  838. }
  839. }
  840. catch (Exception e)
  841. {
  842. Server.ErrorLog(e);
  843. }
  844. return buffer;
  845. }
  846. public void HandleExtInfo(byte[] message)
  847. {
  848. appName = enc.GetString(message, 0, 64).Trim();
  849. extensionCount = message[65];
  850. }
  851. public struct CPE { public string name; public int version; }
  852. public List<CPE> ExtEntry = new List<CPE>();
  853. void HandleExtEntry(byte[] msg)
  854. {
  855. CPE tmp; tmp.name = enc.GetString(msg, 0, 64);
  856. tmp.version = BitConverter.ToInt32(msg, 64);
  857. ExtEntry.Add(tmp);
  858. }
  859. public void HandleCustomBlockSupportLevel(byte[] message)
  860. {
  861. customBlockSupportLevel = message[0];
  862. }
  863. void HandleLogin(byte[] message)
  864. {
  865. try
  866. {
  867. //byte[] message = (byte[])m;
  868. if (loggedIn)
  869. return;
  870. byte version = message[0];
  871. name = enc.GetString(message, 1, 64).Trim();
  872. truename = name;
  873. if (Server.omniban.CheckPlayer(this)) { Kick(Server.omniban.kickMsg); return; } //deprecated
  874. if (name.Split('@').Length > 1)
  875. {
  876. name = name.Split('@')[0];
  877. if (!MojangAccount.HasID(truename))
  878. MojangAccount.AddUser(truename);
  879. name += "_" + MojangAccount.GetID(truename);
  880. }
  881. string verify = enc.GetString(message, 65, 32).Trim();
  882. ushort type = message[129];
  883. //Forge Protection Check
  884. verifiedName = Server.verify ? true : false;
  885. if (Server.verify)
  886. {
  887. if (verify == BitConverter.ToString(md5.ComputeHash(enc.GetBytes(Server.salt + truename))).Replace("-", "").ToLower().TrimStart('0'))
  888. {
  889. identified = true;
  890. }
  891. if (verify == BitConverter.ToString(md5.ComputeHash(enc.GetBytes(Server.salt2 + truename))).Replace("-", "").ToLower())
  892. {
  893. JObject json;
  894. try
  895. {
  896. using (var client = new WebClient())
  897. {
  898. json = JObject.Parse(client.DownloadString("http://www.classicube.net/api/player/" + name.ToLower()));
  899. }
  900. ID = (int)json.SelectToken("id");
  901. UsingID = true;
  902. }
  903. catch (Exception e)
  904. {
  905. Server.ErrorLog(e);
  906. Server.s.Log("Could not get Player's ID, going with name bans!");
  907. UsingID = false;
  908. }
  909. identified = true;
  910. name += "+";
  911. }
  912. if (IPInPrivateRange(ip))
  913. {
  914. identified = true;
  915. }
  916. if (identified == false)
  917. {
  918. Kick("Login failed! Try again."); return;
  919. }
  920. isDev = Server.Devs.Contains(name.ToLower());
  921. isMod = Server.Mods.Contains(name.ToLower());
  922. isGCMod = Server.GCmods.Contains(name.ToLower());
  923. isStaff = isDev || isMod || isGCMod;
  924. isProtected = Server.forgeProtection == ForgeProtection.Mod && (isMod || isDev) ? true : Server.forgeProtection == ForgeProtection.Dev && isDev ? true : false;
  925. }
  926. try
  927. {
  928. Server.TempBan tBan = Server.tempBans.Find(tB => tB.name.ToLower() == name.ToLower());
  929. if (tBan.allowedJoin < DateTime.Now)
  930. {
  931. Server.tempBans.Remove(tBan);
  932. }
  933. else if (!isDev && !isMod)
  934. {
  935. Kick("You're still banned (temporary ban)!");
  936. }
  937. }
  938. catch { }
  939. // Whitelist check.
  940. if (Server.useWhitelist)
  941. {
  942. if (Server.verify)
  943. {
  944. if (Server.whiteList.Contains(name))
  945. {
  946. onWhitelist = true;
  947. }
  948. }
  949. else
  950. {
  951. // Verify Names is off. Gotta check the hard way.
  952. Database.AddParams("@IP", ip);
  953. DataTable ipQuery = Database.fillData("SELECT Name FROM Players WHERE IP = @IP");
  954. if (ipQuery.Rows.Count > 0)
  955. {
  956. if (ipQuery.Rows.Contains(name) && Server.whiteList.Contains(name))
  957. {
  958. onWhitelist = true;
  959. }
  960. }
  961. ipQuery.Dispose();
  962. }
  963. onWhitelist = isDev || isMod;
  964. if (!onWhitelist) { Kick("This is a private server!"); return; } //i think someone forgot this?
  965. }
  966. //premium check
  967. if (Server.PremiumPlayersOnly && !isDev && !isMod)
  968. {
  969. using (WebClient Client = new WebClient())
  970. {
  971. int tries = 0;
  972. while (tries++ < 3)
  973. {
  974. try
  975. {
  976. bool haspaid = Convert.ToBoolean(Client.DownloadString("http://www.minecraft.net/haspaid.jsp?user=" + name));
  977. if (!haspaid)
  978. Kick("Sorry, this is a premium server only!");
  979. break;
  980. }
  981. catch { }
  982. }
  983. }
  984. }
  985. if (File.Exists("ranks/ignore/" + this.name + ".txt"))
  986. {
  987. try
  988. {
  989. string[] checklines = File.ReadAllLines("ranks/ignore/" + this.name + ".txt");
  990. foreach (string checkline in checklines)
  991. {
  992. this.listignored.Add(checkline);
  993. }
  994. File.Delete("ranks/ignore/" + this.name + ".txt");
  995. }
  996. catch
  997. {
  998. Server.s.Log("Failed to load ignore list for: " + this.name);
  999. }
  1000. }
  1001. if (File.Exists("ranks/ignore/GlobalIgnore.xml"))
  1002. {
  1003. try
  1004. {
  1005. string[] searchxmls = File.ReadAllLines("ranks/ignore/GlobalIgnore.xml");
  1006. foreach (string searchxml in searchxmls)
  1007. {
  1008. globalignores.Add(searchxml);
  1009. }
  1010. foreach (string ignorer in globalignores)
  1011. {
  1012. Player foundignore = Player.Find(ignorer);
  1013. foundignore.ignoreglobal = true;
  1014. }
  1015. File.Delete("ranks/ignore/GlobalIgnore.xml");
  1016. }
  1017. catch
  1018. {
  1019. Server.s.Log("Failed to load global ignore list!");
  1020. }
  1021. }
  1022. // ban check
  1023. if (!isDev && !isMod)
  1024. {
  1025. if (Server.bannedIP.Contains(ip))
  1026. {
  1027. if (Server.useWhitelist)
  1028. {
  1029. if (!onWhitelist)
  1030. {
  1031. Kick(Server.customBanMessage);
  1032. return;
  1033. }
  1034. }
  1035. else
  1036. {
  1037. Kick(Server.customBanMessage);
  1038. return;
  1039. }
  1040. }
  1041. if (Group.findPlayerGroup(name) == Group.findPerm(LevelPermission.Banned))
  1042. {
  1043. if (Server.useWhitelist)
  1044. {
  1045. if (!onWhitelist)
  1046. {
  1047. Kick(Server.customBanMessage);
  1048. return;
  1049. }
  1050. }
  1051. else
  1052. {
  1053. if (UsingID && Ban.IsbannedID(ID.ToString()) || !UsingID && Ban.Isbanned(name))
  1054. {
  1055. string[] data = Ban.Getbandata(name);
  1056. Kick("You were banned for \"" + data[1] + "\" by " + data[0]);
  1057. }
  1058. else
  1059. Kick(Server.customBanMessage);
  1060. return;
  1061. }
  1062. }
  1063. }
  1064. //server maxplayer check
  1065. if (!isDev && !isMod && !VIP.Find(this))
  1066. {
  1067. // Check to see how many guests we have
  1068. if (Player.players.Count >= Server.players && !IPInPrivateRange(ip)) { Kick("Server full!"); return; }
  1069. // Code for limiting no. of guests
  1070. if (Group.findPlayerGroup(name) == Group.findPerm(LevelPermission.Guest))
  1071. {
  1072. // Check to see how many guests we have
  1073. int currentNumOfGuests = Player.players.Count(pl => pl.group.Permission <= LevelPermission.Guest);
  1074. if (currentNumOfGuests >= Server.maxGuests)
  1075. {
  1076. if (Server.guestLimitNotify) GlobalMessageOps("Guest " + this.name + " couldn't log in - too many guests.");
  1077. Server.s.Log("Guest " + this.name + " couldn't log in - too many guests.");
  1078. Kick("Server has reached max number of guests");
  1079. return;
  1080. }
  1081. }
  1082. }
  1083. if (version != Server.version) { Kick("Wrong version!"); return; }
  1084. foreach (Player p in players)
  1085. {
  1086. if (p.name == name)
  1087. {
  1088. if (Server.verify)
  1089. {
  1090. p.Kick("Someone logged in as you!"); break;
  1091. }
  1092. else { Kick("Already logged in!"); return; }
  1093. }
  1094. }
  1095. if (type == 0x42)
  1096. {
  1097. extension = true;
  1098. SendExtInfo(14);
  1099. SendExtEntry("ClickDistance", 1);
  1100. SendExtEntry("CustomBlocks", 1);
  1101. SendExtEntry("HeldBlock", 1);
  1102. SendExtEntry("TextHotKey", 1);
  1103. SendExtEntry("ExtPlayerList", 1);
  1104. SendExtEntry("EnvColors", 1);
  1105. SendExtEntry("SelectionCuboid", 1);
  1106. SendExtEntry("BlockPermissions", 1);
  1107. SendExtEntry("ChangeModel", 1);
  1108. SendExtEntry("EnvMapAppearance", 1);
  1109. SendExtEntry("EnvWeatherType", 1);
  1110. SendExtEntry("HackControl", 1);
  1111. SendExtEntry("EmoteFix", 1);
  1112. SendExtEntry("MessageTypes", 1);
  1113. SendCustomBlockSupportLevel(1);
  1114. }
  1115. try { left.Remove(name.ToLower()); }
  1116. catch { }
  1117. group = Group.findPlayerGroup(name);
  1118. SendMotd();
  1119. SendMap();
  1120. Loading = true;
  1121. if (disconnected) return;
  1122. loggedIn = true;
  1123. this.id = FreeId();
  1124. lock (players)
  1125. players.Add(this);
  1126. connections.Remove(this);
  1127. Server.s.PlayerListUpdate();
  1128. //Test code to show when people come back with different accounts on the same IP
  1129. string temp = name + " is lately known as:";
  1130. bool found = false;
  1131. if (!ip.StartsWith("127.0.0."))
  1132. {
  1133. foreach (KeyValuePair<string, string> prev in left)
  1134. {
  1135. if (prev.Value == ip)
  1136. {
  1137. found = true;
  1138. temp += " " + prev.Key;
  1139. }
  1140. }
  1141. if (found)
  1142. {
  1143. if (this.group.Permission < Server.adminchatperm || Server.adminsjoinsilent == false)
  1144. {
  1145. GlobalMessageOps(temp);
  1146. //IRCBot.Say(temp, true); //Tells people in op channel on IRC
  1147. }
  1148. Server.s.Log(temp);
  1149. }
  1150. }
  1151. }
  1152. catch (Exception e)
  1153. {
  1154. Server.ErrorLog(e);
  1155. Player.GlobalMessage("An error occurred: " + e.Message);
  1156. }
  1157. //OpenClassic Client Check
  1158. SendBlockchange(0, 0, 0, 0);
  1159. Database.AddParams("@Name", name);
  1160. DataTable playerDb = Database.fillData("SELECT * FROM Players WHERE Name=@Name");
  1161. if (playerDb.Rows.Count == 0)
  1162. {
  1163. this.prefix = "";
  1164. this.time = "0 0 0 1";
  1165. this.title = "";
  1166. this.titlecolor = "";
  1167. this.color = group.color;
  1168. this.money = 0;
  1169. this.firstLogin = DateTime.Now;
  1170. this.totalLogins = 1;
  1171. this.totalKicked = 0;
  1172. this.overallDeath = 0;
  1173. this.overallBlocks = 0;
  1174. this.timeLogged = DateTime.Now;
  1175. SendMessage("Welcome " + name + "! This is your first visiā€¦

Large files files are truncated, but you can click here to view the full file