Exemplo n.º 1
0
        public void Start()
        {
            shuttingDown = false;
            Log("Starting Server");

            if (!Directory.Exists("properties"))
            {
                Directory.CreateDirectory("properties");
            }
            if (!Directory.Exists("bots"))
            {
                Directory.CreateDirectory("bots");
            }
            if (!Directory.Exists("text"))
            {
                Directory.CreateDirectory("text");
            }
            if (!Directory.Exists("db"))
            {
                Directory.CreateDirectory("db");
            }

            if (!Directory.Exists("extra"))
            {
                Directory.CreateDirectory("extra");
            }
            if (!Directory.Exists("extra/undo"))
            {
                Directory.CreateDirectory("extra/undo");
            }
            if (!Directory.Exists("extra/undoPrevious"))
            {
                Directory.CreateDirectory("extra/undoPrevious");
            }
            if (!Directory.Exists("extra/copy/"))
            {
                Directory.CreateDirectory("extra/copy/");
            }
            if (!Directory.Exists("extra/copyBackup/"))
            {
                Directory.CreateDirectory("extra/copyBackup/");
            }

            //if (!Directory.Exists("db/players/")) Directory.CreateDirectory("db/players/");

            try
            {
                if (File.Exists("server.properties"))
                {
                    File.Move("server.properties", "properties/server.properties");
                }
                if (File.Exists("rules.txt"))
                {
                    File.Move("rules.txt", "text/rules.txt");
                }
                if (File.Exists("welcome.txt"))
                {
                    File.Move("welcome.txt", "text/welcome.txt");
                }
                if (File.Exists("messages.txt"))
                {
                    File.Move("messages.txt", "text/messages.txt");
                }
                if (File.Exists("externalurl.txt"))
                {
                    File.Move("externalurl.txt", "text/externalurl.txt");
                }
                if (File.Exists("autoload.txt"))
                {
                    File.Move("autoload.txt", "text/autoload.txt");
                }
                if (File.Exists("IRC_Controllers.txt"))
                {
                    File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
                }
                if (useWhitelist)
                {
                    if (File.Exists("whitelist.txt"))
                    {
                        File.Move("whitelist.txt", "ranks/whitelist.txt");
                    }
                }
            } catch { }

            Properties.Load("properties/server.properties");
            Updater.Load("properties/update.properties");
            database = new Database(MySQLDatabaseName);
            Group.InitAll();
            Command.InitAll();
            GrpCommands.fillRanks();
            Block.SetBlocks();
            Awards.Load();

            if (File.Exists("text/emotelist.txt"))
            {
                foreach (string s in File.ReadAllLines("text/emotelist.txt"))
                {
                    Player.emoteList.Add(s);
                }
            }
            else
            {
                File.Create("text/emotelist.txt");
            }

            timeOnline = DateTime.Now;

            /*
             *          try
             *          {
             *              if (Server.useMySQL)
             *                  MySQL.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true);
             *          }
             *          catch (Exception e)
             *          {
             *              Server.s.Log("MySQL settings have not been set! Please reference the MySQL_Setup.txt file on setting up MySQL!");
             *              try
             *              {
             *                  WebClient web = new WebClient();
             *                  web.DownloadFile("http://updates.mcsong.x10.mx/MySQL_Setup.txt", "MySQL_Setup.txt");
             *                  web.Dispose();
             *                  Server.s.Log("MySQL_Setup.txt has been downloaded automatically.");
             *              }
             *              catch { Server.s.Log("MySQL_Setup.txt can be downloaded manually from http://updates.mcsong.x10.mx."); }
             *              Server.ErrorLog(e);
             *              //process.Kill();
             *              return;
             *          }*/

            /*MySQL.executeQuery("CREATE TABLE if not exists Players (ID MEDIUMINT not null auto_increment, Name VARCHAR(20), IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalKicked MEDIUMINT, color VARCHAR(6), title_color VARCHAR(6), PRIMARY KEY (ID));");
             *
             * // Check if the color column exists.
             * DataTable colorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='color'");
             *
             * if (colorExists.Rows.Count == 0)
             * {
             *  MySQL.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
             * }
             * colorExists.Dispose();
             *
             * // Check if the title color column exists.
             * DataTable tcolorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='title_color'");
             *
             * if (tcolorExists.Rows.Count == 0)
             * {
             *  MySQL.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
             * }
             * tcolorExists.Dispose();*/

            try { database.CreateTable("Players", new List <string> {
                    "ID", "Name", "IP", "FirstLogin", "LastLogin", "TotalLogins", "Title", "TotalDeaths", "Money", "TotalBlocks", "TotalKicks", "Color", "TColor"
                }); }
            catch { }

            if (levels != null)
            {
                foreach (Level l in levels)
                {
                    l.Unload();
                }
            }
            ml.Queue(delegate
            {
                try
                {
                    levels = new List <Level>(Server.maps);
                    MapGen = new MapGenerator();

                    Random random = new Random();

                    if (File.Exists("levels/" + Server.level + ".lvl"))
                    {
                        mainLevel        = Level.Load(Server.level);
                        mainLevel.unload = false;
                        if (mainLevel == null)
                        {
                            if (File.Exists("levels/" + Server.level + ".lvl.backup"))
                            {
                                Log("Attempting to load backup.");
                                File.Copy("levels/" + Server.level + ".lvl.backup", "levels/" + Server.level + ".lvl", true);
                                mainLevel = Level.Load(Server.level);
                                if (mainLevel == null)
                                {
                                    Log("BACKUP FAILED!");
                                    Console.ReadLine(); return;
                                }
                            }
                            else
                            {
                                Log("mainlevel not found");
                                Level temp = new Level(Server.level, 128, 64, 128, "flat");

                                temp.permissionvisit = LevelPermission.Guest;
                                temp.permissionbuild = LevelPermission.Guest;
                                temp.Save(true, true);
                                mainLevel = Level.Load(temp.name);
                            }
                        }
                    }
                    else
                    {
                        Log("mainlevel not found");
                        Level temp = new Level(Server.level, 128, 64, 128, "flat");

                        temp.permissionvisit = LevelPermission.Guest;
                        temp.permissionbuild = LevelPermission.Guest;
                        temp.Save(true, true);
                        mainLevel = Level.Load(temp.name);
                    }
                    addLevel(mainLevel);
                    mainLevel.physThread.Start();
                } catch (Exception e) { Server.ErrorLog(e); }
            });

            ml.Queue(delegate
            {
                bannedIP       = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);
                gcAgreed       = PlayerList.Load("GCAgreed.txt", null);

                foreach (Group grp in Group.GroupList)
                {
                    grp.playerList = PlayerList.Load(grp.fileName, grp);
                }
                if (Server.useWhitelist)
                {
                    whiteList = PlayerList.Load("whitelist.txt", null);
                }
            });

            ml.Queue(delegate
            {
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string line in lines)
                        {
                            //int temp = 0;
                            string _line = line.Trim();
                            try
                            {
                                if (_line == "")
                                {
                                    continue;
                                }
                                if (_line[0] == '#')
                                {
                                    continue;
                                }
                                int index = _line.IndexOf("=");

                                string key = _line.Split('=')[0].Trim();
                                string value;
                                try
                                {
                                    value = _line.Split('=')[1].Trim();
                                }
                                catch
                                {
                                    value = "0";
                                }

                                if (!key.Equals(mainLevel.name))
                                {
                                    Command.all.Find("load").Use(null, key + " " + value);
                                    Level l = Level.FindExact(key);
                                }
                                else
                                {
                                    try
                                    {
                                        int temp = int.Parse(value);
                                        if (temp >= 0 && temp <= 3)
                                        {
                                            mainLevel.setPhysics(temp);
                                        }
                                    }
                                    catch
                                    {
                                        Server.s.Log("Physics variable invalid");
                                    }
                                }
                            }
                            catch
                            {
                                Server.s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        Server.s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                Log("Creating listening socket on port " + Server.port + "... ");
                if (Setup())
                {
                    if (upnp)
                    {
                        if (UpnpSetup())
                        {
                            s.Log("Ports have been forwarded with upnp."); upnpRunning = true;
                        }
                        else
                        {
                            s.Log("Could not auto forward ports. Make sure upnp is enabled on your router."); upnpRunning = false;
                        }
                    }
                    if (!upnp || upnp && upnpRunning)
                    {
                        s.Log("Done.");
                    }
                }
                else
                {
                    s.Log("Could not create socket connection.  Shutting down.");
                    return;
                }
            });

            ml.Queue(delegate
            {
                updateTimer.Elapsed += delegate
                {
                    Player.GlobalUpdate();
                    PlayerBot.GlobalUpdatePosition();
                };

                updateTimer.Start();
            });


            // Heartbeat code here:

            ml.Queue(delegate
            {
                try
                {
                    SongBeat.Init();
                }
                catch (Exception e)
                {
                    Server.ErrorLog(e);
                }
            });

            // END Heartbeat code


            Thread processThread = new Thread(new ThreadStart(delegate
            {
                try
                {
                    Server.s.Log("Starting performance counters...");
                    PCCounter      = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    ProcessCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
                    PCCounter.BeginInit();
                    ProcessCounter.BeginInit();
                    PCCounter.NextValue();
                    ProcessCounter.NextValue();
                }
                catch { }
            }));

            processThread.Start();


            ml.Queue(delegate
            {
                messageTimer.Elapsed += delegate
                {
                    RandomMessage();
                };
                messageTimer.Start();

                process = System.Diagnostics.Process.GetCurrentProcess();

                if (File.Exists("text/messages.txt"))
                {
                    StreamReader r = File.OpenText("text/messages.txt");
                    while (!r.EndOfStream)
                    {
                        messages.Add(r.ReadLine());
                    }
                    r.Dispose();
                }
                else
                {
                    File.Create("text/messages.txt").Close();
                }

                if (Server.irc)
                {
                    new IRCBot();
                }
                if (Server.gc)
                {
                    new GlobalBot();
                }


                //      string CheckName = "FROSTEDBUTTS";

                //       if (Server.name.IndexOf(CheckName.ToLower())!= -1){ Server.s.Log("FROSTEDBUTTS DETECTED");}
                new AutoSaver(Server.backupInterval);     //2 and a half mins

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        foreach (Level l in levels)
                        {
                            l.saveChanges();
                        }
                    }
                }));
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (int i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                Player p = Player.players[i];

                                if (p.frozen)
                                {
                                    unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
                                }
                                else if (p.following != "")
                                {
                                    Player who = Player.Find(p.following);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.following = "";
                                        if (!p.canBuild)
                                        {
                                            p.canBuild = true;
                                        }
                                        if (who != null && who.possess == p.name)
                                        {
                                            who.possess = "";
                                        }
                                        continue;
                                    }
                                    if (p.canBuild)
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                    else
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                }
                                else if (p.possess != "")
                                {
                                    Player who = Player.Find(p.possess);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.possess = "";
                                    }
                                }

                                ushort x = (ushort)(p.pos[0] / 32);
                                ushort y = (ushort)(p.pos[1] / 32);
                                ushort z = (ushort)(p.pos[2] / 32);

                                if (p.level.Death)
                                {
                                    p.RealDeath(x, y, z);
                                }
                                p.CheckBlock(x, y, z);

                                p.oldBlock = (ushort)(x + y + z);
                            } catch (Exception e) { Server.ErrorLog(e); }
                        }
                    }
                }));

                locationChecker.Start();

                Log("Finished setting up server");
            });

            try
            {
                using (WebClient web = new WebClient())
                {
                    if (new List <string>(web.DownloadString("http://updates.mcsong.x10.mx/hostbans.txt").Split(',')).Contains(web.DownloadString("http://ipinfo.io/ip").Trim()))
                    {
                        s.Log("! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !");
                        s.Log("YOUR IP HAS BEEN HOST BANNED. APPEAL AT http://mcsong.x10.mx/forums.");
                        s.Log("! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !");
                        Exit();
                    }
                }
            }
            catch
            {
                // Hard-coded list
            }

            //PluginManager.AutoLoad();
        }