PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Server/Server.cs

https://github.com/Goodlyay/MCForge-Vanilla-Redux
C# | 1369 lines | 1145 code | 143 blank | 81 comment | 176 complexity | 1ffac308778e649719a8ba6055929a77 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.Diagnostics;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Threading;
  24. using System.Windows.Forms;
  25. using MCForge.SQL;
  26. using MonoTorrent.Client;
  27. using Newtonsoft.Json.Linq;
  28. namespace MCForge
  29. {
  30. public enum ForgeProtection { Off = 0, Mod = 1, Dev = 2 }
  31. public class Server
  32. {
  33. public static bool cancelcommand = false;
  34. public static bool canceladmin = false;
  35. public static bool cancellog = false;
  36. public static bool canceloplog = false;
  37. public static bool DownloadBeta = false;
  38. public static string apppath = Application.StartupPath;
  39. public delegate void OnConsoleCommand(string cmd, string message);
  40. public static event OnConsoleCommand ConsoleCommand;
  41. public delegate void OnServerError(Exception error);
  42. public static event OnServerError ServerError = null;
  43. public delegate void OnServerLog(string message);
  44. public static event OnServerLog ServerLog;
  45. public static event OnServerLog ServerAdminLog;
  46. public static event OnServerLog ServerOpLog;
  47. public delegate void HeartBeatHandler();
  48. public delegate void MessageEventHandler(string message);
  49. public delegate void PlayerListHandler(List<Player> playerList);
  50. public delegate void VoidHandler();
  51. public delegate void LogHandler(string message);
  52. public event LogHandler OnLog;
  53. public event LogHandler OnSystem;
  54. public event LogHandler OnCommand;
  55. public event LogHandler OnError;
  56. public event LogHandler OnOp;
  57. public event LogHandler OnAdmin;
  58. public event HeartBeatHandler HeartBeatFail;
  59. public event MessageEventHandler OnURLChange;
  60. public event PlayerListHandler OnPlayerListChange;
  61. public event VoidHandler OnSettingsUpdate;
  62. public static ForgeBot IRC;
  63. public static GlobalChatBot GlobalChat;
  64. public static Thread locationChecker;
  65. public static bool UseTextures = false;
  66. public static Thread blockThread;
  67. public static bool IgnoreOmnibans = false;
  68. //public static List<MySql.Data.MySqlClient.MySqlCommand> mySQLCommands = new List<MySql.Data.MySqlClient.MySqlCommand>();
  69. public static int speedPhysics = 250;
  70. public static Version Version { get { return System.Reflection.Assembly.GetAssembly(typeof(Server)).GetName().Version; } }
  71. public static string VersionString
  72. {
  73. get
  74. {
  75. return Version.Major + "." + Version.Minor + "." + Version.Build;
  76. }
  77. }
  78. // URL hash for connecting to the server
  79. public static string Hash = String.Empty;
  80. public static string CCURL = String.Empty;
  81. public static string URL = String.Empty;
  82. public static Socket listen;
  83. public static System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
  84. public static System.Timers.Timer updateTimer = new System.Timers.Timer(100);
  85. //static System.Timers.Timer heartbeatTimer = new System.Timers.Timer(60000); //Every 45 seconds
  86. static System.Timers.Timer messageTimer = new System.Timers.Timer(60000 * 5); //Every 5 mins
  87. public static System.Timers.Timer cloneTimer = new System.Timers.Timer(5000);
  88. //public static Thread physThread;
  89. //public static bool physPause;
  90. //public static DateTime physResume = DateTime.Now;
  91. //public static System.Timers.Timer physTimer = new System.Timers.Timer(1000);
  92. // static Thread botsThread;
  93. //Chatrooms
  94. public static List<string> Chatrooms = new List<string>();
  95. //Other
  96. public static bool higherranktp = true;
  97. public static bool agreetorulesonentry = false;
  98. public static bool UseCTF = true;
  99. public static bool ServerSetupFinished = false;
  100. public static PlayerList bannedIP;
  101. public static PlayerList whiteList;
  102. public static PlayerList ircControllers;
  103. public static PlayerList muted;
  104. public static PlayerList ignored;
  105. // The MCForge Developer List
  106. internal static readonly List<string> devs = new List<string>();
  107. public static List<string> Devs { get { return new List<string>(devs); } }
  108. //The MCForge Moderation List
  109. internal static readonly List<string> mods = new List<string>();
  110. public static List<string> Mods { get { return new List<string>(mods); } }
  111. //GCMods List
  112. internal static readonly List<string> gcmods = new List<string>(new string[] { "rwayy", "David", "JoeBukkit", "notrwaeh" } );
  113. public static List<string> GCmods { get { return new List<string>(gcmods); } }
  114. internal static readonly List<string> protectover = new List<string>(new string[] { "moderate", "mute", "freeze", "lockdown", "ban", "banip", "kickban", "kick", "global", "xban", "xundo", "undo", "uban", "unban", "unbanip", "demote", "promote", "restart", "shutdown", "setrank", "warn", "tempban", "impersonate", "sendcmd", "possess", "joker", "jail", "ignore", "voice" });
  115. public static List<string> ProtectOver { get { return new List<string>(protectover); } }
  116. public static ForgeProtection forgeProtection = ForgeProtection.Off;
  117. internal static readonly List<string> opstats = new List<string>(new string[] { "ban", "tempban", "kick", "warn", "mute", "freeze", "undo", "griefer", "demote", "promote" });
  118. public static List<string> Opstats { get { return new List<string>(opstats); } }
  119. public static List<TempBan> tempBans = new List<TempBan>();
  120. public struct TempBan { public string name; public DateTime allowedJoin; }
  121. public static MapGenerator MapGen;
  122. public static Thread checkPosThread;
  123. public static PerformanceCounter PCCounter = null;
  124. public static PerformanceCounter ProcessCounter = null;
  125. public static Level mainLevel;
  126. public static List<Level> levels;
  127. //reviewlist intitialize
  128. public static List<string> reviewlist = new List<string>();
  129. //Translate settings initialize
  130. public static bool transenabled = false;
  131. public static string translang = "en";
  132. public static List<string> transignore = new List<string>();
  133. //Global Chat Rules Accepted list
  134. public static List<string> gcaccepted = new List<string>();
  135. //public static List<levelID> allLevels = new List<levelID>();
  136. public struct levelID { public int ID; public string name; }
  137. public static List<string> afkset = new List<string>();
  138. public static List<string> ircafkset = new List<string>();
  139. public static List<string> afkmessages = new List<string>();
  140. public static List<string> messages = new List<string>();
  141. public static Dictionary<string, string> gcnamebans = new Dictionary<string, string>();
  142. public static Dictionary<string, string> gcipbans = new Dictionary<string, string>();
  143. public static DateTime timeOnline;
  144. public static string IP;
  145. //auto updater stuff
  146. public static bool autoupdate;
  147. public static bool autonotify;
  148. public static bool notifyPlayers;
  149. public static string restartcountdown = "";
  150. public static string selectedrevision = "";
  151. public static bool autorestart;
  152. public static DateTime restarttime;
  153. public static bool chatmod = false;
  154. //Global VoteKick In Progress Flag
  155. public static bool voteKickInProgress = false;
  156. public static int voteKickVotesNeeded = 0;
  157. //WoM Direct
  158. public static string Server_ALT = "";
  159. public static string Server_Disc = "";
  160. public static string Server_Flag = "";
  161. public static Dictionary<string, string> customdollars = new Dictionary<string, string>();
  162. // Extra storage for custom commands
  163. public ExtrasCollection Extras = new ExtrasCollection();
  164. //Color list as a char array
  165. public static Char[] ColourCodesNoPercent = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  166. //Zombie
  167. public static ZombieGame zombie;
  168. public static bool limitedblocks = false;
  169. public static bool ZombieModeOn = false;
  170. public static bool startZombieModeOnStartup = false;
  171. public static bool noRespawn = true;
  172. public static bool noLevelSaving = true;
  173. public static bool noPillaring = true;
  174. public static string ZombieName = "";
  175. public static int gameStatus = 0; //0 = not started, 1 = always on, 2 = one time, 3 = certain amount of rounds, 4 = stop game next round
  176. public static bool queLevel = false;
  177. public static bool queZombie = false;
  178. public static string nextZombie = "";
  179. public static string nextLevel = "";
  180. public static bool zombieRound = false;
  181. public static string lastPlayerToInfect = "";
  182. public static int infectCombo = 0;
  183. public static int YesVotes = 0;
  184. public static int NoVotes = 0;
  185. public static bool voting = false;
  186. public static bool votingforlevel = false;
  187. public static int Level1Vote = 0;
  188. public static int Level2Vote = 0;
  189. public static int Level3Vote = 0;
  190. public static bool ChangeLevels = true;
  191. public static bool UseLevelList = false;
  192. public static bool ZombieOnlyServer = true;
  193. public static List<String> LevelList = new List<String>();
  194. public static string lastLevelVote1 = "";
  195. public static string lastLevelVote2 = "";
  196. public static bool bufferblocks = true;
  197. // Lava Survival
  198. public static LavaSurvival lava;
  199. //CTF
  200. public bool CTF = false;
  201. // OmniBan
  202. public static OmniBan omniban;
  203. public static System.Timers.Timer omnibanCheckTimer = new System.Timers.Timer(60000 * 120);
  204. //Settings
  205. #region Server Settings
  206. public const byte version = 7;
  207. public static string salt = "";
  208. public static string salt2 = "";
  209. public static string name = "[MCForge] Default";
  210. public static string motd = "Welcome!";
  211. public static byte players = 12;
  212. //for the limiting no. of guests:
  213. public static byte maxGuests = 10;
  214. public static byte maps = 5;
  215. public static int port = 25565;
  216. public static bool pub = true;
  217. public static bool verify = true;
  218. public static bool worldChat = true;
  219. // public static bool guestGoto = false;
  220. //Spam Prevention
  221. public static bool checkspam = false;
  222. public static int spamcounter = 8;
  223. public static int mutespamtime = 60;
  224. public static int spamcountreset = 5;
  225. public static string ZallState = "Alive";
  226. //public static string[] userMOTD;
  227. public static string level = "main";
  228. public static string errlog = "error.log";
  229. // public static bool console = false; // never used
  230. public static bool reportBack = true;
  231. public static bool irc = false;
  232. public static bool ircColorsEnable = false;
  233. // public static bool safemode = false; //Never used
  234. public static int ircPort = 6667;
  235. public static string ircNick = "ForgeBot";
  236. public static string ircServer = "irc.mcforge.org";
  237. public static string ircChannel = "#changethis";
  238. public static string ircOpChannel = "#changethistoo";
  239. public static bool ircIdentify = false;
  240. public static string ircPassword = "";
  241. public static bool verifyadmins = true;
  242. public static LevelPermission verifyadminsrank = LevelPermission.Operator;
  243. public static bool restartOnError = true;
  244. public static bool antiTunnel = true;
  245. public static byte maxDepth = 4;
  246. public static int Overload = 1500;
  247. public static int rpLimit = 500;
  248. public static int rpNormLimit = 10000;
  249. public static int backupInterval = 300;
  250. public static int blockInterval = 60;
  251. public static string backupLocation = Application.StartupPath + "/levels/backups";
  252. public static bool physicsRestart = true;
  253. public static bool deathcount = true;
  254. public static bool AutoLoad = false;
  255. public static int physUndo = 20000;
  256. public static int totalUndo = 200;
  257. public static bool rankSuper = true;
  258. public static bool oldHelp = false;
  259. public static bool parseSmiley = true;
  260. public static bool useWhitelist = false;
  261. public static bool PremiumPlayersOnly = false;
  262. public static bool forceCuboid = false;
  263. public static bool profanityFilter = false;
  264. public static bool notifyOnJoinLeave = false;
  265. public static bool repeatMessage = false;
  266. public static bool globalignoreops = false;
  267. public static bool checkUpdates = true;
  268. public static bool useMySQL = false;
  269. public static string MySQLHost = "127.0.0.1";
  270. public static string MySQLPort = "3306";
  271. public static string MySQLUsername = "root";
  272. public static string MySQLPassword = "password";
  273. public static string MySQLDatabaseName = "MCZallDB";
  274. public static bool DatabasePooling = true;
  275. public static string DefaultColor = "&e";
  276. public static string IRCColour = "&5";
  277. public static bool UseGlobalChat = true;
  278. public static string GlobalChatNick = "MCF" + new Random().Next();
  279. public static string GlobalChatColor = "&6";
  280. public static int afkminutes = 10;
  281. public static int afkkick = 45;
  282. public static LevelPermission afkkickperm = LevelPermission.AdvBuilder;
  283. //public static int RemotePort = 1337; // Never used
  284. public static string defaultRank = "guest";
  285. public static bool dollardollardollar = true;
  286. public static bool unsafe_plugin = true;
  287. public static bool cheapMessage = true;
  288. public static string cheapMessageGiven = " is now being cheap and being immortal";
  289. public static bool customBan = false;
  290. public static string customBanMessage = "You're banned!";
  291. public static bool customShutdown = false;
  292. public static string customShutdownMessage = "Server shutdown. Rejoin in 10 seconds.";
  293. public static bool customGrieferStone = false;
  294. public static string customGrieferStoneMessage = "Oh noes! You were caught griefing!";
  295. public static string customPromoteMessage = "&6Congratulations for working hard and getting &2PROMOTED!";
  296. public static string customDemoteMessage = "&4DEMOTED! &6We're sorry for your loss. Good luck on your future endeavors! &1:'(";
  297. public static string moneys = "moneys";
  298. public static LevelPermission opchatperm = LevelPermission.Operator;
  299. public static LevelPermission adminchatperm = LevelPermission.Admin;
  300. public static bool logbeat = false;
  301. public static bool adminsjoinsilent = false;
  302. public static bool mono { get { return (Type.GetType("Mono.Runtime") != null); } }
  303. public static string server_owner = "Notch";
  304. public static bool WomDirect = false;
  305. public static bool UseSeasons = false;
  306. public static bool guestLimitNotify = false;
  307. public static bool guestJoinNotify = true;
  308. public static bool guestLeaveNotify = true;
  309. public static bool flipHead = false;
  310. public static bool shuttingDown = false;
  311. public static bool restarting = false;
  312. //hackrank stuff
  313. public static bool hackrank_kick = true;
  314. public static int hackrank_kick_time = 5; //seconds, it converts it to milliseconds in the command.
  315. // lol useless junk here lolololasdf poop
  316. public static bool showEmptyRanks = false;
  317. public static ushort grieferStoneType = 1;
  318. public static bool grieferStoneBan = true;
  319. public static LevelPermission grieferStoneRank = LevelPermission.Guest;
  320. //reviewoptions intitialize
  321. public static int reviewcooldown = 600;
  322. public static LevelPermission reviewenter = LevelPermission.Guest;
  323. public static LevelPermission reviewleave = LevelPermission.Guest;
  324. public static LevelPermission reviewview = LevelPermission.Operator;
  325. public static LevelPermission reviewnext = LevelPermission.Operator;
  326. public static LevelPermission reviewclear = LevelPermission.Operator;
  327. #endregion
  328. public static MainLoop ml;
  329. public static Server s;
  330. public Server()
  331. {
  332. ml = new MainLoop("server");
  333. Server.s = this;
  334. }
  335. //True = cancel event
  336. //Fale = dont cacnel event
  337. public static bool Check(string cmd, string message)
  338. {
  339. if (ConsoleCommand != null)
  340. ConsoleCommand(cmd, message);
  341. return cancelcommand;
  342. }
  343. public void Start()
  344. {
  345. shuttingDown = false;
  346. Log("Starting Server");
  347. {
  348. try
  349. {
  350. if (File.Exists("Restarter.exe"))
  351. {
  352. File.Delete("Restarter.exe");
  353. }
  354. }
  355. catch { }
  356. try
  357. {
  358. if (File.Exists("Restarter.pdb"))
  359. {
  360. File.Delete("Restarter.pdb");
  361. }
  362. }
  363. catch { }
  364. if (!File.Exists("MySql.Data.dll"))
  365. {
  366. Log("MySql.Data.dll doesn't exist, Downloading");
  367. try
  368. {
  369. using (WebClient WEB = new WebClient())
  370. {
  371. WEB.DownloadFile("http://mcforge.org/Update/MySql.Data.dll", "MySql.Data.dll");
  372. }
  373. if (File.Exists("MySql.Data.dll"))
  374. {
  375. Log("MySql.Data.dll download succesful!");
  376. }
  377. }
  378. catch
  379. {
  380. Log("Downloading MySql.Data.dll failed, please try again later");
  381. }
  382. }
  383. if (!File.Exists("System.Data.SQLite.dll"))
  384. {
  385. Log("System.Data.SQLite.dll doesn't exist, Downloading");
  386. try
  387. {
  388. using (WebClient WEB = new WebClient())
  389. {
  390. WEB.DownloadFile("http://mcforge.org/Update/System.Data.SQLite.dll", "System.Data.SQLite.dll");
  391. }
  392. if (File.Exists("System.Data.SQLite.dll"))
  393. {
  394. Log("System.Data.SQLite.dll download succesful!");
  395. }
  396. }
  397. catch
  398. {
  399. Log("Downloading System.Data.SQLite.dll failed, please try again later");
  400. }
  401. }
  402. if (!File.Exists("sqlite3.dll"))
  403. {
  404. Log("sqlite3.dll doesn't exist, Downloading");
  405. try
  406. {
  407. using (WebClient WEB = new WebClient())
  408. {
  409. WEB.DownloadFile("http://www.mcforge.org/sqlite3.dll", "sqlite3.dll");
  410. }
  411. if (File.Exists("sqlite3.dll"))
  412. {
  413. Log("sqlite3.dll download succesful!");
  414. }
  415. }
  416. catch
  417. {
  418. Log("Downloading sqlite3.dll failed, please try again later");
  419. }
  420. }
  421. if (!File.Exists("Newtonsoft.Json.dll"))
  422. {
  423. Log("Newtonsoft.Json.dll doesn't exist, Downloading");
  424. try
  425. {
  426. using (WebClient WEB = new WebClient())
  427. {
  428. WEB.DownloadFile("http://mcforge.org/Update/oldf/Newtonsoft.Json.dll", "Newtonsoft.Json.dll");
  429. }
  430. if (File.Exists("Newtonsoft.Json.dll"))
  431. {
  432. Log("Newtonsoft.Json.dll download successful!");
  433. }
  434. }
  435. catch
  436. {
  437. Log("Download Newtonsoft.Json.dll failed, please try again later");
  438. }
  439. }
  440. }
  441. UpdateGlobalSettings();
  442. if (!Directory.Exists("properties")) Directory.CreateDirectory("properties");
  443. if (!Directory.Exists("levels")) Directory.CreateDirectory("levels");
  444. if (!Directory.Exists("bots")) Directory.CreateDirectory("bots");
  445. if (!Directory.Exists("text")) Directory.CreateDirectory("text");
  446. if (!File.Exists("text/tempranks.txt")) File.CreateText("text/tempranks.txt").Dispose();
  447. if (!File.Exists("text/rankinfo.txt")) File.CreateText("text/rankinfo.txt").Dispose();
  448. if (!File.Exists("text/transexceptions.txt")) File.CreateText("text/transexceptions.txt").Dispose();
  449. if (!File.Exists("text/gcaccepted.txt")) File.CreateText("text/gcaccepted.txt").Dispose();
  450. if (!File.Exists("text/bans.txt")) File.CreateText("text/bans.txt").Dispose();
  451. // DO NOT STICK ANYTHING IN BETWEEN HERE!!!!!!!!!!!!!!!
  452. else
  453. {
  454. string bantext = File.ReadAllText("text/bans.txt");
  455. if (!bantext.Contains("%20") && bantext != "")
  456. {
  457. bantext = bantext.Replace("~", "%20");
  458. bantext = bantext.Replace("-", "%20");
  459. File.WriteAllText("text/bans.txt", bantext);
  460. }
  461. }
  462. if (!Directory.Exists("extra")) Directory.CreateDirectory("extra");
  463. if (!Directory.Exists("extra/undo")) Directory.CreateDirectory("extra/undo");
  464. if (!Directory.Exists("extra/undoPrevious")) Directory.CreateDirectory("extra/undoPrevious");
  465. if (!Directory.Exists("extra/copy/")) { Directory.CreateDirectory("extra/copy/"); }
  466. if (!Directory.Exists("extra/copyBackup/")) { Directory.CreateDirectory("extra/copyBackup/"); }
  467. if (!Directory.Exists("extra/Waypoints")) { Directory.CreateDirectory("extra/Waypoints"); }
  468. try
  469. {
  470. if (File.Exists("server.properties")) File.Move("server.properties", "properties/server.properties");
  471. if (File.Exists("rules.txt")) File.Move("rules.txt", "text/rules.txt");
  472. if (File.Exists("welcome.txt")) File.Move("welcome.txt", "text/welcome.txt");
  473. if (File.Exists("messages.txt")) File.Move("messages.txt", "text/messages.txt");
  474. if (File.Exists("externalurl.txt")) File.Move("externalurl.txt", "text/externalurl.txt");
  475. if (File.Exists("autoload.txt")) File.Move("autoload.txt", "text/autoload.txt");
  476. if (File.Exists("IRC_Controllers.txt")) File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
  477. if (useWhitelist) if (File.Exists("whitelist.txt")) File.Move("whitelist.txt", "ranks/whitelist.txt");
  478. }
  479. catch { }
  480. if (File.Exists("text/custom$s.txt"))
  481. {
  482. using (StreamReader r = new StreamReader("text/custom$s.txt"))
  483. {
  484. string line;
  485. while ((line = r.ReadLine()) != null)
  486. {
  487. if (line.StartsWith("//")) continue;
  488. var split = line.Split(new[] { ':' }, 2);
  489. if (split.Length == 2 && !String.IsNullOrEmpty(split[0]))
  490. {
  491. customdollars.Add(split[0], split[1]);
  492. }
  493. }
  494. }
  495. }
  496. else
  497. {
  498. s.Log("custom$s.txt does not exist, creating");
  499. using (StreamWriter SW = File.CreateText("text/custom$s.txt"))
  500. {
  501. SW.WriteLine("// This is used to create custom $s");
  502. SW.WriteLine("// If you start the line with a // it wont be used");
  503. SW.WriteLine("// It should be formatted like this:");
  504. SW.WriteLine("// $website:mcforge.org");
  505. SW.WriteLine("// That would replace '$website' in any message to 'mcforge.org'");
  506. SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)");
  507. SW.Close();
  508. }
  509. }
  510. if (File.Exists("text/emotelist.txt"))
  511. {
  512. foreach (string s in File.ReadAllLines("text/emotelist.txt"))
  513. {
  514. Player.emoteList.Add(s);
  515. }
  516. }
  517. else
  518. {
  519. File.Create("text/emotelist.txt").Dispose();
  520. }
  521. // LavaSurvival constructed here...
  522. lava = new LavaSurvival();
  523. zombie = new ZombieGame();
  524. LoadAllSettings();
  525. // OmniBan
  526. omniban = new OmniBan();
  527. timeOnline = DateTime.Now;
  528. {//MYSQL stuff
  529. try
  530. {
  531. Database.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true); // works in both now, SQLite simply ignores this.
  532. }
  533. //catch (MySql.Data.MySqlClient.MySqlException e)
  534. //{
  535. // Server.s.Log("MySQL settings have not been set! Many features will not be available if MySQL is not enabled");
  536. // // Server.ErrorLog(e);
  537. //}
  538. catch (Exception e)
  539. {
  540. ErrorLog(e);
  541. s.Log("MySQL settings have not been set! Please Setup using the properties window.");
  542. //process.Kill();
  543. return;
  544. }
  545. Database.executeQuery(string.Format("CREATE TABLE if not exists Players (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Name TEXT, IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalCuboided BIGINT, totalKicked MEDIUMINT, TimeSpent VARCHAR(20), color VARCHAR(6), title_color VARCHAR(6){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));
  546. Database.executeQuery(string.Format("CREATE TABLE if not exists Opstats (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Time DATETIME, Name TEXT, Cmd VARCHAR(40), Cmdmsg VARCHAR(40){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));
  547. if (!File.Exists("extra/alter.txt") && Server.useMySQL) {
  548. Database.executeQuery("ALTER TABLE Players MODIFY Name TEXT");
  549. Database.executeQuery("ALTER TABLE Opstats MODIFY Name TEXT");
  550. File.Create("extra/alter.txt");
  551. }
  552. //since 5.5.11 we are cleaning up the table Playercmds
  553. string query = Server.useMySQL ? "SHOW TABLES LIKE 'Playercmds'" : "SELECT name FROM sqlite_master WHERE type='table' AND name='Playercmds';";
  554. DataTable playercmds = Database.fillData(query); DataTable opstats = Database.fillData("SELECT * FROM Opstats");
  555. //if Playercmds exists copy-filter to Ostats and remove Playercmds
  556. if (playercmds.Rows.Count != 0) {
  557. foreach (string cmd in Server.Opstats)
  558. Database.executeQuery(string.Format("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = '{0}';", cmd));
  559. Database.executeQuery("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = 'review' AND cmdmsg = 'next';");
  560. Database.fillData("DROP TABLE Playercmds");
  561. }
  562. playercmds.Dispose(); opstats.Dispose();
  563. // Here, since SQLite is a NEW thing from 5.3.0.0, we do not have to check for existing tables in SQLite.
  564. if (useMySQL)
  565. {
  566. // Check if the color column exists.
  567. DataTable colorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='color'");
  568. if (colorExists.Rows.Count == 0)
  569. {
  570. MySQL.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
  571. //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
  572. }
  573. colorExists.Dispose();
  574. // Check if the title color column exists.
  575. DataTable tcolorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='title_color'");
  576. if (tcolorExists.Rows.Count == 0)
  577. {
  578. MySQL.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
  579. // else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
  580. }
  581. tcolorExists.Dispose();
  582. DataTable timespent = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='TimeSpent'");
  583. if (timespent.Rows.Count == 0)
  584. MySQL.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked");
  585. timespent.Dispose();
  586. DataTable totalCuboided = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='totalCuboided'");
  587. if (totalCuboided.Rows.Count == 0)
  588. MySQL.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks");
  589. totalCuboided.Dispose();
  590. }
  591. }
  592. Economy.LoadDatabase();
  593. UpdateStaffList();
  594. Log("MCForge Staff Protection Level: " + forgeProtection);
  595. if (levels != null)
  596. foreach (Level l in levels) { l.Unload(); }
  597. ml.Queue(delegate
  598. {
  599. try
  600. {
  601. levels = new List<Level>(maps);
  602. MapGen = new MapGenerator();
  603. if (File.Exists("levels/" + level + ".mcf"))
  604. {
  605. mainLevel = Level.Load(level);
  606. mainLevel.unload = false;
  607. if (mainLevel == null)
  608. {
  609. if (File.Exists("levels/" + level + ".mcf.backup"))
  610. {
  611. Log("Attempting to load backup of " + level + ".");
  612. File.Copy("levels/" + level + ".mcf.backup", "levels/" + level + ".mcf", true);
  613. mainLevel = Level.Load(level);
  614. if (mainLevel == null)
  615. {
  616. Log("BACKUP FAILED!");
  617. Console.ReadLine(); return;
  618. }
  619. }
  620. else
  621. {
  622. Log("mainlevel not found");
  623. mainLevel = new Level(level, 128, 64, 128, "flat") { permissionvisit = LevelPermission.Guest, permissionbuild = LevelPermission.Guest };
  624. mainLevel.Save();
  625. Level.CreateLeveldb(level);
  626. }
  627. }
  628. //Wom Textures
  629. if (UseTextures)
  630. {
  631. mainLevel.textures.sendwomid = true;
  632. mainLevel.textures.enabled = true;
  633. mainLevel.textures.MOTD = motd;
  634. mainLevel.textures.CreateCFG();
  635. }
  636. }
  637. else
  638. {
  639. Log("mainlevel not found");
  640. mainLevel = new Level(level, 128, 64, 128, "flat") { permissionvisit = LevelPermission.Guest, permissionbuild = LevelPermission.Guest };
  641. mainLevel.Save();
  642. Level.CreateLeveldb(level);
  643. }
  644. addLevel(mainLevel);
  645. // fenderrock - Make sure the level does have a physics thread
  646. if (mainLevel.physThread == null)
  647. mainLevel.StartPhysics();
  648. }
  649. catch (Exception e) { ErrorLog(e); }
  650. });
  651. Plugin.Load();
  652. ml.Queue(delegate
  653. {
  654. bannedIP = PlayerList.Load("banned-ip.txt", null);
  655. ircControllers = PlayerList.Load("IRC_Controllers.txt", null);
  656. muted = PlayerList.Load("muted.txt", null);
  657. foreach (Group grp in Group.GroupList)
  658. grp.playerList = PlayerList.Load(grp.fileName, grp);
  659. if (useWhitelist)
  660. whiteList = PlayerList.Load("whitelist.txt", null);
  661. if (!File.Exists("ranks/jailed.txt")) { File.Create("ranks/jailed.txt").Close(); Server.s.Log("CREATED NEW: ranks/jailed.txt"); }
  662. Extensions.UncapitalizeAll("ranks/banned.txt");
  663. Extensions.UncapitalizeAll("ranks/muted.txt");
  664. if (forgeProtection == ForgeProtection.Mod || forgeProtection == ForgeProtection.Dev) {
  665. foreach (string dev in Devs) {
  666. Extensions.DeleteExactLineWord("ranks/banned.txt", dev);
  667. Extensions.DeleteExactLineWord("ranks/muted.txt", dev);
  668. }
  669. }
  670. if (forgeProtection == ForgeProtection.Mod) {
  671. foreach (string mod in Mods) {
  672. Extensions.DeleteExactLineWord("ranks/banned.txt", mod);
  673. Extensions.DeleteExactLineWord("ranks/muted.txt", mod);
  674. }
  675. foreach (string gcmod in GCmods) {
  676. Extensions.DeleteExactLineWord("ranks/muted.txt", gcmod);
  677. }
  678. }
  679. if (this.CTF)
  680. {
  681. MCForge.CTF.redTeam = new CTFTeam("&c", Block.red);
  682. MCForge.CTF.blueTeam = new CTFTeam("&9", Block.deepblue);
  683. MCForge.CTF.Setup(Server.mainLevel, true);
  684. }
  685. });
  686. ml.Queue(delegate
  687. {
  688. transignore.AddRange(File.ReadAllLines("text/transexceptions.txt"));
  689. if (File.Exists("text/autoload.txt"))
  690. {
  691. try
  692. {
  693. string[] lines = File.ReadAllLines("text/autoload.txt");
  694. foreach (string _line in lines.Select(line => line.Trim()))
  695. {
  696. try
  697. {
  698. if (_line == "") { continue; }
  699. if (_line[0] == '#') { continue; }
  700. string key = _line.Split('=')[0].Trim();
  701. string value;
  702. try
  703. {
  704. value = _line.Split('=')[1].Trim();
  705. }
  706. catch
  707. {
  708. value = "0";
  709. }
  710. if (!key.Equals(mainLevel.name))
  711. {
  712. Command.all.Find("load").Use(null, key + " " + value);
  713. }
  714. // Level l = Level.FindExact(key);
  715. else
  716. {
  717. try
  718. {
  719. int temp = int.Parse(value);
  720. if (temp >= 0 && temp <= 3)
  721. {
  722. mainLevel.setPhysics(temp);
  723. }
  724. }
  725. catch
  726. {
  727. s.Log("Physics variable invalid");
  728. }
  729. }
  730. }
  731. catch
  732. {
  733. s.Log(_line + " failed.");
  734. }
  735. }
  736. }
  737. catch
  738. {
  739. s.Log("autoload.txt error");
  740. }
  741. GC.Collect();
  742. GC.WaitForPendingFinalizers();
  743. }
  744. else
  745. {
  746. Log("autoload.txt does not exist");
  747. }
  748. });
  749. ml.Queue(delegate
  750. {
  751. Translate.Init();
  752. foreach (string line in File.ReadAllLines("text/transexceptions.txt"))
  753. {
  754. transignore.Add(line); //loading all playernames of people who turned off translation
  755. }
  756. foreach (string line in File.ReadAllLines("text/gcaccepted.txt"))
  757. {
  758. gcaccepted.Add(line); //loading all playernames of people who turned off translation
  759. }
  760. MojangAccount.Load();
  761. Log("Creating listening socket on port " + port + "... ");
  762. Setup();
  763. //s.Log(Setup() ? "Done." : "Could not create socket connection. Shutting down.");
  764. });
  765. ml.Queue(delegate
  766. {
  767. updateTimer.Elapsed += delegate
  768. {
  769. Player.GlobalUpdate();
  770. PlayerBot.GlobalUpdatePosition();
  771. };
  772. updateTimer.Start();
  773. });
  774. // Heartbeat code here:
  775. ml.Queue(delegate
  776. {
  777. try
  778. {
  779. Heart.Init();
  780. }
  781. catch (Exception e)
  782. {
  783. Server.ErrorLog(e);
  784. }
  785. });
  786. ml.Queue(delegate
  787. {
  788. messageTimer.Elapsed += delegate
  789. {
  790. RandomMessage();
  791. };
  792. messageTimer.Start();
  793. process = System.Diagnostics.Process.GetCurrentProcess();
  794. if (File.Exists("text/messages.txt"))
  795. {
  796. using (StreamReader r = File.OpenText("text/messages.txt"))
  797. {
  798. while (!r.EndOfStream)
  799. messages.Add(r.ReadLine());
  800. }
  801. }
  802. else File.Create("text/messages.txt").Close();
  803. // We always construct this to prevent errors...
  804. IRC = new ForgeBot(Server.ircChannel, Server.ircOpChannel, Server.ircNick, Server.ircServer);
  805. GlobalChat = new GlobalChatBot(GlobalChatNick);
  806. if (Server.irc) IRC.Connect();
  807. if (Server.UseGlobalChat) GlobalChat.Connect();
  808. // OmniBan stuff!
  809. new Thread(new ThreadStart(() => omniban.Load(true))).Start();
  810. omnibanCheckTimer.Elapsed += delegate
  811. {
  812. omniban.Load(true);
  813. omniban.KickAll();
  814. };
  815. omnibanCheckTimer.Start();
  816. new AutoSaver(Server.backupInterval);
  817. blockThread = new Thread(new ThreadStart(delegate
  818. {
  819. while (true)
  820. {
  821. Thread.Sleep(blockInterval * 1000);
  822. levels.ForEach(delegate(Level l)
  823. {
  824. try
  825. {
  826. l.saveChanges();
  827. }
  828. catch (Exception e)
  829. {
  830. Server.ErrorLog(e);
  831. }
  832. });
  833. }
  834. }));
  835. blockThread.Start();
  836. ml.Queue(delegate
  837. {
  838. checkPosThread = new Thread(new ThreadStart(delegate
  839. {
  840. while (true)
  841. {
  842. Player.players.ForEach(delegate(Player p)
  843. {
  844. p.CheckPosition();
  845. });
  846. Thread.Sleep(250);
  847. }
  848. }));
  849. checkPosThread.Start();
  850. });
  851. locationChecker = new Thread(new ThreadStart(delegate
  852. {
  853. Player p, who;
  854. ushort x, y, z;
  855. int i;
  856. while (true)
  857. {
  858. Thread.Sleep(3);
  859. for (i = 0; i < Player.players.Count; i++)
  860. {
  861. try
  862. {
  863. p = Player.players[i];
  864. if (p.frozen)
  865. {
  866. unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
  867. }
  868. else if (p.following != "")
  869. {
  870. who = Player.Find(p.following);
  871. if (who == null || who.level != p.level)
  872. {
  873. p.following = "";
  874. if (!p.canBuild)
  875. {
  876. p.canBuild = true;
  877. }
  878. if (who != null && who.possess == p.name)
  879. {
  880. who.possess = "";
  881. }
  882. continue;
  883. }
  884. if (p.canBuild)
  885. {
  886. unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
  887. }
  888. else
  889. {
  890. unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
  891. }
  892. }
  893. else if (p.possess != "")
  894. {
  895. who = Player.Find(p.possess);
  896. if (who == null || who.level != p.level)
  897. p.possess = "";
  898. }
  899. x = (ushort)(p.pos[0] / 32);
  900. y = (ushort)(p.pos[1] / 32);
  901. z = (ushort)(p.pos[2] / 32);
  902. if (p.level.Death)
  903. p.RealDeath(x, y, z);
  904. p.CheckBlock(x, y, z);
  905. p.oldBlock = (ushort)(x + y + z);
  906. }
  907. catch (Exception e) { Server.ErrorLog(e); }
  908. }
  909. }
  910. }));
  911. locationChecker.Start();
  912. try
  913. {
  914. using (WebClient web = new WebClient())
  915. IP = web.DownloadString("http://server.mcforge.org/ip.php");
  916. }
  917. catch { }
  918. #if DEBUG
  919. UseTextures = true;
  920. #endif
  921. Log("Finished setting up server");
  922. ServerSetupFinished = true;
  923. Checktimer.StartTimer();
  924. Commands.CommandKeywords.SetKeyWords();
  925. try
  926. {
  927. if (Server.lava.startOnStartup)
  928. Server.lava.Start();
  929. if (Server.startZombieModeOnStartup)
  930. Server.zombie.StartGame(1, 0);
  931. }
  932. catch (Exception e) { Server.ErrorLog(e); }
  933. BlockQueue.Start();
  934. });
  935. }
  936. public static void LoadAllSettings()
  937. {
  938. SrvProperties.Load("properties/server.properties");
  939. Updater.Load("properties/update.properties");
  940. Group.InitAll();
  941. Command.InitAll();
  942. GrpCommands.fillRanks();
  943. Block.SetBlocks();
  944. Awards.Load();
  945. Economy.Load();
  946. Warp.LOAD();
  947. CommandOtherPerms.Load();
  948. ProfanityFilter.Init();
  949. }
  950. public static void Setup()
  951. {
  952. try
  953. {
  954. IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port);
  955. listen = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  956. listen.Bind(endpoint);
  957. listen.Listen((int)SocketOptionName.MaxConnections);
  958. listen.BeginAccept(Accept, Block.air);
  959. }
  960. catch (SocketException e) { ErrorLog(e); s.Log("Error Creating listener, socket shutting down"); }
  961. catch (Exception e) { ErrorLog(e); s.Log("Error Creating listener, socket shutting down"); }
  962. }
  963. static void Accept(IAsyncResult result)
  964. {
  965. if (shuttingDown) return;
  966. Player p = null;
  967. bool begin = false;
  968. try
  969. {
  970. p = new Player(listen.EndAccept(result));
  971. //new Thread(p.Start).Start();
  972. listen.BeginAccept(Accept, Block.air);
  973. begin = true;
  974. }
  975. catch (SocketException)
  976. {
  977. if (p != null)
  978. p.Disconnect();
  979. if (!begin)
  980. listen.BeginAccept(Accept, Block.air);
  981. }
  982. catch (Exception e)
  983. {
  984. ErrorLog(e);
  985. if (p != null)
  986. p.Disconnect();
  987. if (!begin)
  988. listen.BeginAccept(Accept, Block.air);
  989. }
  990. }
  991. public static void Exit(bool AutoRestart)
  992. {
  993. List<string> players = new List<string>();
  994. foreach (Player p in Player.players) { p.save(); players.Add(p.name); }
  995. foreach (string p in players)
  996. {
  997. if (!AutoRestart)
  998. Player.Find(p).Kick(Server.customShutdown ? Server.customShutdownMessage : "Server shutdown. Rejoin in 10 seconds.");
  999. else
  1000. Player.Find(p).Kick("Server restarted! Rejoin!");
  1001. }
  1002. //Player.players.ForEach(delegate(Player p) { p.Kick("Server shutdown. Rejoin in 10 seconds."); });
  1003. Player.connections.ForEach(
  1004. delegate(Player p)
  1005. {
  1006. if (!AutoRestart)
  1007. p.Kick(Server.customShutdown ? Server.customShutdownMe

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