PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Server.cs

https://github.com/Goodlyay/MCForge-Vanilla-Redux
C# | 1348 lines | 1126 code | 138 blank | 84 comment | 176 complexity | dde5a08235da35faafbc88e5e3b0d862 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 = false;
  99. public static bool ServerSetupFinished = false;
  100. public static Auto_CTF ctf = null;
  101. public static PlayerList bannedIP;
  102. public static PlayerList whiteList;
  103. public static PlayerList ircControllers;
  104. public static PlayerList muted;
  105. public static PlayerList ignored;
  106. // The MCForge Developer List
  107. internal static readonly List<string> devs = new List<string>(new string[] { "Hetal+", "EricKilla+", "Rayne+" });
  108. public static List<string> Devs { get { return new List<string>(devs); } }
  109. //The MCForge Moderation List
  110. internal static readonly List<string> mods = new List<string>();
  111. public static List<string> Mods { get { return new List<string>(mods); } }
  112. //GCMods List
  113. internal static readonly List<string> gcmods = new List<string>(new string[] { "rwayy", "David", "JoeBukkit", "notrwaeh" } );
  114. public static List<string> GCmods { get { return new List<string>(gcmods); } }
  115. 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" });
  116. public static List<string> ProtectOver { get { return new List<string>(protectover); } }
  117. public static ForgeProtection forgeProtection = ForgeProtection.Off;
  118. internal static readonly List<string> opstats = new List<string>(new string[] { "ban", "tempban", "kick", "warn", "mute", "freeze", "undo", "griefer", "demote", "promote" });
  119. public static List<string> Opstats { get { return new List<string>(opstats); } }
  120. public static List<TempBan> tempBans = new List<TempBan>();
  121. public struct TempBan { public string name; public DateTime allowedJoin; }
  122. public static MapGenerator MapGen;
  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 ZombieModeOn = false;
  169. public static bool startZombieModeOnStartup = false;
  170. public static bool noRespawn = true;
  171. public static bool noLevelSaving = true;
  172. public static bool noPillaring = true;
  173. public static string ZombieName = "";
  174. public static int gameStatus = 0; //0 = not started, 1 = always on, 2 = one time, 3 = certain amount of rounds, 4 = stop game next round
  175. public static bool queLevel = false;
  176. public static bool queZombie = false;
  177. public static string nextZombie = "";
  178. public static string nextLevel = "";
  179. public static bool zombieRound = false;
  180. public static string lastPlayerToInfect = "";
  181. public static int infectCombo = 0;
  182. public static int YesVotes = 0;
  183. public static int NoVotes = 0;
  184. public static bool voting = false;
  185. public static bool votingforlevel = false;
  186. public static int Level1Vote = 0;
  187. public static int Level2Vote = 0;
  188. public static int Level3Vote = 0;
  189. public static bool ChangeLevels = true;
  190. public static bool UseLevelList = false;
  191. public static bool ZombieOnlyServer = true;
  192. public static List<String> LevelList = new List<String>();
  193. public static string lastLevelVote1 = "";
  194. public static string lastLevelVote2 = "";
  195. public static bool bufferblocks = true;
  196. // Lava Survival
  197. public static LavaSurvival lava;
  198. // OmniBan
  199. public static OmniBan omniban;
  200. public static System.Timers.Timer omnibanCheckTimer = new System.Timers.Timer(60000 * 120);
  201. //Settings
  202. #region Server Settings
  203. public const byte version = 7;
  204. public static string salt = "";
  205. public static string salt2 = "";
  206. public static string name = "[MCForge] Default";
  207. public static string motd = "Welcome!";
  208. public static byte players = 12;
  209. //for the limiting no. of guests:
  210. public static byte maxGuests = 10;
  211. public static byte maps = 5;
  212. public static int port = 25565;
  213. public static bool pub = true;
  214. public static bool verify = true;
  215. public static bool worldChat = true;
  216. // public static bool guestGoto = false;
  217. //Spam Prevention
  218. public static bool checkspam = false;
  219. public static int spamcounter = 8;
  220. public static int mutespamtime = 60;
  221. public static int spamcountreset = 5;
  222. public static string ZallState = "Alive";
  223. //public static string[] userMOTD;
  224. public static string level = "main";
  225. public static string errlog = "error.log";
  226. // public static bool console = false; // never used
  227. public static bool reportBack = true;
  228. public static bool irc = false;
  229. public static bool ircColorsEnable = false;
  230. // public static bool safemode = false; //Never used
  231. public static int ircPort = 6667;
  232. public static string ircNick = "ForgeBot";
  233. public static string ircServer = "irc.mcforge.org";
  234. public static string ircChannel = "#changethis";
  235. public static string ircOpChannel = "#changethistoo";
  236. public static bool ircIdentify = false;
  237. public static string ircPassword = "";
  238. public static bool verifyadmins = true;
  239. public static LevelPermission verifyadminsrank = LevelPermission.Operator;
  240. public static bool restartOnError = true;
  241. public static bool antiTunnel = true;
  242. public static byte maxDepth = 4;
  243. public static int Overload = 1500;
  244. public static int rpLimit = 500;
  245. public static int rpNormLimit = 10000;
  246. public static int backupInterval = 300;
  247. public static int blockInterval = 60;
  248. public static string backupLocation = Application.StartupPath + "/levels/backups";
  249. public static bool physicsRestart = true;
  250. public static bool deathcount = true;
  251. public static bool AutoLoad = false;
  252. public static int physUndo = 20000;
  253. public static int totalUndo = 200;
  254. public static bool rankSuper = true;
  255. public static bool oldHelp = false;
  256. public static bool parseSmiley = true;
  257. public static bool useWhitelist = false;
  258. public static bool PremiumPlayersOnly = false;
  259. public static bool forceCuboid = false;
  260. public static bool profanityFilter = false;
  261. public static bool notifyOnJoinLeave = false;
  262. public static bool repeatMessage = false;
  263. public static bool globalignoreops = false;
  264. public static bool checkUpdates = true;
  265. public static bool useMySQL = false;
  266. public static string MySQLHost = "127.0.0.1";
  267. public static string MySQLPort = "3306";
  268. public static string MySQLUsername = "root";
  269. public static string MySQLPassword = "password";
  270. public static string MySQLDatabaseName = "MCZallDB";
  271. public static bool DatabasePooling = true;
  272. public static string DefaultColor = "&e";
  273. public static string IRCColour = "&5";
  274. public static bool UseGlobalChat = true;
  275. public static string GlobalChatNick = "MCF" + new Random().Next();
  276. public static string GlobalChatColor = "&6";
  277. public static int afkminutes = 10;
  278. public static int afkkick = 45;
  279. public static LevelPermission afkkickperm = LevelPermission.AdvBuilder;
  280. //public static int RemotePort = 1337; // Never used
  281. public static string defaultRank = "guest";
  282. public static bool dollardollardollar = true;
  283. public static bool unsafe_plugin = true;
  284. public static bool cheapMessage = true;
  285. public static string cheapMessageGiven = " is now being cheap and being immortal";
  286. public static bool customBan = false;
  287. public static string customBanMessage = "You're banned!";
  288. public static bool customShutdown = false;
  289. public static string customShutdownMessage = "Server shutdown. Rejoin in 10 seconds.";
  290. public static bool customGrieferStone = false;
  291. public static string customGrieferStoneMessage = "Oh noes! You were caught griefing!";
  292. public static string customPromoteMessage = "&6Congratulations for working hard and getting &2PROMOTED!";
  293. public static string customDemoteMessage = "&4DEMOTED! &6We're sorry for your loss. Good luck on your future endeavors! &1:'(";
  294. public static string moneys = "moneys";
  295. public static LevelPermission opchatperm = LevelPermission.Operator;
  296. public static LevelPermission adminchatperm = LevelPermission.Admin;
  297. public static bool logbeat = false;
  298. public static bool adminsjoinsilent = false;
  299. public static bool mono { get { return (Type.GetType("Mono.Runtime") != null); } }
  300. public static string server_owner = "Notch";
  301. public static bool WomDirect = false;
  302. public static bool UseSeasons = false;
  303. public static bool guestLimitNotify = false;
  304. public static bool guestJoinNotify = true;
  305. public static bool guestLeaveNotify = true;
  306. public static bool flipHead = false;
  307. public static bool shuttingDown = false;
  308. public static bool restarting = false;
  309. //hackrank stuff
  310. public static bool hackrank_kick = true;
  311. public static int hackrank_kick_time = 5; //seconds, it converts it to milliseconds in the command.
  312. // lol useless junk here lolololasdf poop
  313. public static bool showEmptyRanks = false;
  314. public static ushort grieferStoneType = 1;
  315. public static bool grieferStoneBan = true;
  316. public static LevelPermission grieferStoneRank = LevelPermission.Guest;
  317. //reviewoptions intitialize
  318. public static int reviewcooldown = 600;
  319. public static LevelPermission reviewenter = LevelPermission.Guest;
  320. public static LevelPermission reviewleave = LevelPermission.Guest;
  321. public static LevelPermission reviewview = LevelPermission.Operator;
  322. public static LevelPermission reviewnext = LevelPermission.Operator;
  323. public static LevelPermission reviewclear = LevelPermission.Operator;
  324. #endregion
  325. public static MainLoop ml;
  326. public static Server s;
  327. public Server()
  328. {
  329. ml = new MainLoop("server");
  330. Server.s = this;
  331. }
  332. //True = cancel event
  333. //Fale = dont cacnel event
  334. public static bool Check(string cmd, string message)
  335. {
  336. if (ConsoleCommand != null)
  337. ConsoleCommand(cmd, message);
  338. return cancelcommand;
  339. }
  340. public void Start()
  341. {
  342. shuttingDown = false;
  343. Log("Starting Server");
  344. {
  345. try
  346. {
  347. if (File.Exists("Restarter.exe"))
  348. {
  349. File.Delete("Restarter.exe");
  350. }
  351. }
  352. catch { }
  353. try
  354. {
  355. if (File.Exists("Restarter.pdb"))
  356. {
  357. File.Delete("Restarter.pdb");
  358. }
  359. }
  360. catch { }
  361. if (!File.Exists("MySql.Data.dll"))
  362. {
  363. Log("MySql.Data.dll doesn't exist, Downloading");
  364. try
  365. {
  366. using (WebClient WEB = new WebClient())
  367. {
  368. WEB.DownloadFile("http://update.mcforge.org/MySql.Data.dll", "MySql.Data.dll");
  369. }
  370. if (File.Exists("MySql.Data.dll"))
  371. {
  372. Log("MySql.Data.dll download succesful!");
  373. }
  374. }
  375. catch
  376. {
  377. Log("Downloading MySql.Data.dll failed, please try again later");
  378. }
  379. }
  380. if (!File.Exists("System.Data.SQLite.dll"))
  381. {
  382. Log("System.Data.SQLite.dll doesn't exist, Downloading");
  383. try
  384. {
  385. using (WebClient WEB = new WebClient())
  386. {
  387. WEB.DownloadFile("http://update.mcforge.org/System.Data.SQLite.dll", "System.Data.SQLite.dll");
  388. }
  389. if (File.Exists("System.Data.SQLite.dll"))
  390. {
  391. Log("System.Data.SQLite.dll download succesful!");
  392. }
  393. }
  394. catch
  395. {
  396. Log("Downloading System.Data.SQLite.dll failed, please try again later");
  397. }
  398. }
  399. if (!File.Exists("sqlite3.dll"))
  400. {
  401. Log("sqlite3.dll doesn't exist, Downloading");
  402. try
  403. {
  404. using (WebClient WEB = new WebClient())
  405. {
  406. WEB.DownloadFile("http://www.mcforge.org/sqlite3.dll", "sqlite3.dll");
  407. }
  408. if (File.Exists("sqlite3.dll"))
  409. {
  410. Log("sqlite3.dll download succesful!");
  411. }
  412. }
  413. catch
  414. {
  415. Log("Downloading sqlite3.dll failed, please try again later");
  416. }
  417. }
  418. if (!File.Exists("Newtonsoft.Json.dll"))
  419. {
  420. Log("Newtonsoft.Json.dll doesn't exist, Downloading");
  421. try
  422. {
  423. using (WebClient WEB = new WebClient())
  424. {
  425. WEB.DownloadFile("http://update.mcforge.org/oldf/Newtonsoft.Json.dll", "Newtonsoft.Json.dll");
  426. }
  427. if (File.Exists("Newtonsoft.Json.dll"))
  428. {
  429. Log("Newtonsoft.Json.dll download successful!");
  430. }
  431. }
  432. catch
  433. {
  434. Log("Download Newtonsoft.Json.dll failed, please try again later");
  435. }
  436. }
  437. }
  438. UpdateGlobalSettings();
  439. if (!Directory.Exists("properties")) Directory.CreateDirectory("properties");
  440. if (!Directory.Exists("levels")) Directory.CreateDirectory("levels");
  441. if (!Directory.Exists("bots")) Directory.CreateDirectory("bots");
  442. if (!Directory.Exists("text")) Directory.CreateDirectory("text");
  443. if (!File.Exists("text/tempranks.txt")) File.CreateText("text/tempranks.txt").Dispose();
  444. if (!File.Exists("text/rankinfo.txt")) File.CreateText("text/rankinfo.txt").Dispose();
  445. if (!File.Exists("text/transexceptions.txt")) File.CreateText("text/transexceptions.txt").Dispose();
  446. if (!File.Exists("text/gcaccepted.txt")) File.CreateText("text/gcaccepted.txt").Dispose();
  447. if (!File.Exists("text/bans.txt")) File.CreateText("text/bans.txt").Dispose();
  448. // DO NOT STICK ANYTHING IN BETWEEN HERE!!!!!!!!!!!!!!!
  449. else
  450. {
  451. string bantext = File.ReadAllText("text/bans.txt");
  452. if (!bantext.Contains("%20") && bantext != "")
  453. {
  454. bantext = bantext.Replace("~", "%20");
  455. bantext = bantext.Replace("-", "%20");
  456. File.WriteAllText("text/bans.txt", bantext);
  457. }
  458. }
  459. if (!Directory.Exists("extra")) Directory.CreateDirectory("extra");
  460. if (!Directory.Exists("extra/undo")) Directory.CreateDirectory("extra/undo");
  461. if (!Directory.Exists("extra/undoPrevious")) Directory.CreateDirectory("extra/undoPrevious");
  462. if (!Directory.Exists("extra/copy/")) { Directory.CreateDirectory("extra/copy/"); }
  463. if (!Directory.Exists("extra/copyBackup/")) { Directory.CreateDirectory("extra/copyBackup/"); }
  464. if (!Directory.Exists("extra/Waypoints")) { Directory.CreateDirectory("extra/Waypoints"); }
  465. try
  466. {
  467. if (File.Exists("server.properties")) File.Move("server.properties", "properties/server.properties");
  468. if (File.Exists("rules.txt")) File.Move("rules.txt", "text/rules.txt");
  469. if (File.Exists("welcome.txt")) File.Move("welcome.txt", "text/welcome.txt");
  470. if (File.Exists("messages.txt")) File.Move("messages.txt", "text/messages.txt");
  471. if (File.Exists("externalurl.txt")) File.Move("externalurl.txt", "text/externalurl.txt");
  472. if (File.Exists("autoload.txt")) File.Move("autoload.txt", "text/autoload.txt");
  473. if (File.Exists("IRC_Controllers.txt")) File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
  474. if (useWhitelist) if (File.Exists("whitelist.txt")) File.Move("whitelist.txt", "ranks/whitelist.txt");
  475. }
  476. catch { }
  477. if (File.Exists("text/custom$s.txt"))
  478. {
  479. using (StreamReader r = new StreamReader("text/custom$s.txt"))
  480. {
  481. string line;
  482. while ((line = r.ReadLine()) != null)
  483. {
  484. if (line.StartsWith("//")) continue;
  485. var split = line.Split(new[] { ':' }, 2);
  486. if (split.Length == 2 && !String.IsNullOrEmpty(split[0]))
  487. {
  488. customdollars.Add(split[0], split[1]);
  489. }
  490. }
  491. }
  492. }
  493. else
  494. {
  495. s.Log("custom$s.txt does not exist, creating");
  496. using (StreamWriter SW = File.CreateText("text/custom$s.txt"))
  497. {
  498. SW.WriteLine("// This is used to create custom $s");
  499. SW.WriteLine("// If you start the line with a // it wont be used");
  500. SW.WriteLine("// It should be formatted like this:");
  501. SW.WriteLine("// $website:mcforge.org");
  502. SW.WriteLine("// That would replace '$website' in any message to 'mcforge.org'");
  503. SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)");
  504. SW.Close();
  505. }
  506. }
  507. if (File.Exists("text/emotelist.txt"))
  508. {
  509. foreach (string s in File.ReadAllLines("text/emotelist.txt"))
  510. {
  511. Player.emoteList.Add(s);
  512. }
  513. }
  514. else
  515. {
  516. File.Create("text/emotelist.txt").Dispose();
  517. }
  518. // LavaSurvival constructed here...
  519. lava = new LavaSurvival();
  520. zombie = new ZombieGame();
  521. LoadAllSettings();
  522. //derp
  523. if (!Server.LevelList.Contains("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)"))
  524. Server.LevelList.Add("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)");
  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 + ".lvl"))
  604. {
  605. mainLevel = Level.Load(level);
  606. mainLevel.unload = false;
  607. if (mainLevel == null)
  608. {
  609. if (File.Exists("levels/" + level + ".lvl.backup"))
  610. {
  611. Log("Attempting to load backup of " + level + ".");
  612. File.Copy("levels/" + level + ".lvl.backup", "levels/" + level + ".lvl", 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. });
  680. ml.Queue(delegate
  681. {
  682. transignore.AddRange(File.ReadAllLines("text/transexceptions.txt"));
  683. if (File.Exists("text/autoload.txt"))
  684. {
  685. try
  686. {
  687. string[] lines = File.ReadAllLines("text/autoload.txt");
  688. foreach (string _line in lines.Select(line => line.Trim()))
  689. {
  690. try
  691. {
  692. if (_line == "") { continue; }
  693. if (_line[0] == '#') { continue; }
  694. string key = _line.Split('=')[0].Trim();
  695. string value;
  696. try
  697. {
  698. value = _line.Split('=')[1].Trim();
  699. }
  700. catch
  701. {
  702. value = "0";
  703. }
  704. if (!key.Equals(mainLevel.name))
  705. {
  706. Command.all.Find("load").Use(null, key + " " + value);
  707. // Level l = Level.FindExact(key);
  708. }
  709. else
  710. {
  711. try
  712. {
  713. int temp = int.Parse(value);
  714. if (temp >= 0 && temp <= 3)
  715. {
  716. mainLevel.setPhysics(temp);
  717. }
  718. }
  719. catch
  720. {
  721. s.Log("Physics variable invalid");
  722. }
  723. }
  724. }
  725. catch
  726. {
  727. s.Log(_line + " failed.");
  728. }
  729. }
  730. }
  731. catch
  732. {
  733. s.Log("autoload.txt error");
  734. }
  735. GC.Collect();
  736. GC.WaitForPendingFinalizers();
  737. }
  738. else
  739. {
  740. Log("autoload.txt does not exist");
  741. }
  742. });
  743. ml.Queue(delegate
  744. {
  745. Translate.Init();
  746. foreach (string line in File.ReadAllLines("text/transexceptions.txt"))
  747. {
  748. transignore.Add(line); //loading all playernames of people who turned off translation
  749. }
  750. foreach (string line in File.ReadAllLines("text/gcaccepted.txt"))
  751. {
  752. gcaccepted.Add(line); //loading all playernames of people who turned off translation
  753. }
  754. MojangAccount.Load();
  755. Log("Creating listening socket on port " + port + "... ");
  756. Setup();
  757. //s.Log(Setup() ? "Done." : "Could not create socket connection. Shutting down.");
  758. });
  759. ml.Queue(delegate
  760. {
  761. updateTimer.Elapsed += delegate
  762. {
  763. Player.GlobalUpdate();
  764. PlayerBot.GlobalUpdatePosition();
  765. };
  766. updateTimer.Start();
  767. });
  768. // Heartbeat code here:
  769. ml.Queue(delegate
  770. {
  771. try
  772. {
  773. Heart.Init();
  774. }
  775. catch (Exception e)
  776. {
  777. Server.ErrorLog(e);
  778. }
  779. });
  780. ml.Queue(delegate
  781. {
  782. messageTimer.Elapsed += delegate
  783. {
  784. RandomMessage();
  785. };
  786. messageTimer.Start();
  787. process = System.Diagnostics.Process.GetCurrentProcess();
  788. if (File.Exists("text/messages.txt"))
  789. {
  790. using (StreamReader r = File.OpenText("text/messages.txt"))
  791. {
  792. while (!r.EndOfStream)
  793. messages.Add(r.ReadLine());
  794. }
  795. }
  796. else File.Create("text/messages.txt").Close();
  797. // We always construct this to prevent errors...
  798. IRC = new ForgeBot(Server.ircChannel, Server.ircOpChannel, Server.ircNick, Server.ircServer);
  799. GlobalChat = new GlobalChatBot(GlobalChatNick);
  800. if (Server.irc) IRC.Connect();
  801. if (Server.UseGlobalChat) GlobalChat.Connect();
  802. // OmniBan stuff!
  803. new Thread(new ThreadStart(() => omniban.Load(true))).Start();
  804. omnibanCheckTimer.Elapsed += delegate
  805. {
  806. omniban.Load(true);
  807. omniban.KickAll();
  808. };
  809. omnibanCheckTimer.Start();
  810. new AutoSaver(Server.backupInterval);
  811. blockThread = new Thread(new ThreadStart(delegate
  812. {
  813. while (true)
  814. {
  815. Thread.Sleep(blockInterval * 1000);
  816. levels.ForEach(delegate(Level l)
  817. {
  818. try
  819. {
  820. l.saveChanges();
  821. }
  822. catch (Exception e)
  823. {
  824. Server.ErrorLog(e);
  825. }
  826. });
  827. }
  828. }));
  829. blockThread.Start();
  830. locationChecker = new Thread(new ThreadStart(delegate
  831. {
  832. Player p, who;
  833. ushort x, y, z;
  834. int i;
  835. while (true)
  836. {
  837. Thread.Sleep(3);
  838. for (i = 0; i < Player.players.Count; i++)
  839. {
  840. try
  841. {
  842. p = Player.players[i];
  843. if (p.frozen)
  844. {
  845. unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
  846. }
  847. else if (p.following != "")
  848. {
  849. who = Player.Find(p.following);
  850. if (who == null || who.level != p.level)
  851. {
  852. p.following = "";
  853. if (!p.canBuild)
  854. {
  855. p.canBuild = true;
  856. }
  857. if (who != null && who.possess == p.name)
  858. {
  859. who.possess = "";
  860. }
  861. continue;
  862. }
  863. if (p.canBuild)
  864. {
  865. unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
  866. }
  867. else
  868. {
  869. unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
  870. }
  871. }
  872. else if (p.possess != "")
  873. {
  874. who = Player.Find(p.possess);
  875. if (who == null || who.level != p.level)
  876. p.possess = "";
  877. }
  878. x = (ushort)(p.pos[0] / 32);
  879. y = (ushort)(p.pos[1] / 32);
  880. z = (ushort)(p.pos[2] / 32);
  881. if (p.level.Death)
  882. p.RealDeath(x, y, z);
  883. p.CheckBlock(x, y, z);
  884. p.oldBlock = (ushort)(x + y + z);
  885. }
  886. catch (Exception e) { Server.ErrorLog(e); }
  887. }
  888. }
  889. }));
  890. locationChecker.Start();
  891. try
  892. {
  893. using (WebClient web = new WebClient())
  894. IP = web.DownloadString("http://server.mcforge.org/ip.php");
  895. }
  896. catch { }
  897. #if DEBUG
  898. UseTextures = true;
  899. #endif
  900. Log("Finished setting up server");
  901. ServerSetupFinished = true;
  902. Checktimer.StartTimer();
  903. Commands.CommandKeywords.SetKeyWords();
  904. try
  905. {
  906. if (Server.lava.startOnStartup)
  907. Server.lava.Start();
  908. if (Server.startZombieModeOnStartup)
  909. Server.zombie.StartGame(1, 0);
  910. //This doesnt use the main map
  911. if (Server.UseCTF)
  912. ctf = new Auto_CTF();
  913. }
  914. catch (Exception e) { Server.ErrorLog(e); }
  915. BlockQueue.Start();
  916. });
  917. }
  918. public static void LoadAllSettings()
  919. {
  920. SrvProperties.Load("properties/server.properties");
  921. Updater.Load("properties/update.properties");
  922. Group.InitAll();
  923. Command.InitAll();
  924. GrpCommands.fillRanks();
  925. Block.SetBlocks();
  926. Awards.Load();
  927. Economy.Load();
  928. Warp.LOAD();
  929. CommandOtherPerms.Load();
  930. ProfanityFilter.Init();
  931. }
  932. public static void Setup()
  933. {
  934. try
  935. {
  936. IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port);
  937. listen = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  938. listen.Bind(endpoint);
  939. listen.Listen((int)SocketOptionName.MaxConnections);
  940. listen.BeginAccept(Accept, null);
  941. }
  942. catch (SocketException e) { ErrorLog(e); s.Log("Error Creating listener, socket shutting down"); }
  943. catch (Exception e) { ErrorLog(e); s.Log("Error Creating listener, socket shutting down"); }
  944. }
  945. static void Accept(IAsyncResult result)
  946. {
  947. if (shuttingDown) return;
  948. Player p = null;
  949. bool begin = false;
  950. try
  951. {
  952. p = new Player(listen.EndAccept(result));
  953. //new Thread(p.Start).Start();
  954. listen.BeginAccept(Accept, null);
  955. begin = true;
  956. }
  957. catch (SocketException)
  958. {
  959. if (p != null)
  960. p.Disconnect();
  961. if (!begin)
  962. listen.BeginAccept(Accept, null);
  963. }
  964. catch (Exception e)
  965. {
  966. ErrorLog(e);
  967. if (p != null)
  968. p.Disconnect();
  969. if (!begin)
  970. listen.BeginAccept(Accept, null);
  971. }
  972. }
  973. public static void Exit(bool AutoRestart)
  974. {
  975. List<string> players = new List<string>();
  976. foreach (Player p in Player.players) { p.save(); players.Add(p.name); }
  977. foreach (string p in players)
  978. {
  979. if (!AutoRestart)
  980. Player.Find(p).Kick(Server.customShutdown ? Server.customShutdownMessage : "Server shutdown. Rejoin in 10 seconds.");
  981. else
  982. Player.Find(p).Kick("Server restarted! Rejoin!");
  983. }
  984. //Player.players.ForEach(delegate(Player p) { p.Kick("Server shutdown. Rejoin in 10 seconds."); });
  985. Player.connections.ForEach(
  986. delegate(Player p)
  987. {
  988. if (!AutoRestart)
  989. p.Kick(Server.customShutdown ? Server.customShutdownMessage : "Server shutdown. Rejoin in 10 seconds.");
  990. else
  991. p.Kick("Server restarted! Rejoin!");
  992. }
  993. );
  994. Plugin.Unload();
  995. if (listen != null)
  996. {
  997. listen.Close();
  998. }
  999. try
  1000. {
  1001. GlobalChat.Disconnect(!AutoRestart ? "Server is shutting down." : "Server is restarting.");

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