Ejemplo n.º 1
0
        public void handlePacketData(byte[] data)
        {
            int pos = 0;

            while (pos < data.Length)
            {
                try
                {
                    int MessageLength = Base64Encoding.DecodeInt32(new byte[] { data[pos++], data[pos++], data[pos++] });
                    int MessageId     = Base64Encoding.DecodeInt32(new byte[] { data[pos++], data[pos++] });

                    byte[] Content = new byte[MessageLength - 2];

                    for (int i = 0; i < Content.Length && pos < data.Length; i++)
                    {
                        Content[i] = data[pos++];
                    }
                    if (onNewPacket != null)
                    {
                        using (ClientMessage message = ClientMessageFactory.GetClientMessage(MessageId, Content))
                        {
                            onNewPacket.Invoke(message);
                        }
                    }
                }
                catch (Exception e)
                {
                    Logging.HandleException(e, "packet handling");
                    con.Dispose();
                }
            }
        }
Ejemplo n.º 2
0
        public void handlePacketData(byte[] data)
        {
            int position = 0;

            while (position < data.Length)
            {
                try
                {
                    var MessageLength = HabboEncoding.DecodeInt32(new byte[] { data[position++], data[position++], data[position++], data[position++] });
                    if (MessageLength < 2 || MessageLength > 4096)
                    {
                        continue;
                    }

                    var MessageId = HabboEncoding.DecodeInt16(new byte[] { data[position++], data[position++] });
                    var Content   = new byte[MessageLength - 2];

                    Buffer.BlockCopy(data, position, Content, 0, MessageLength - 2);
                    position += MessageLength - 2;

                    if (onNewPacket != null)
                    {
                        using (ClientMessage message = ClientMessageFactory.GetClientMessage(MessageId, Content))
                        {
                            onNewPacket.Invoke(message);
                        }
                    }
                }
                catch { }
            }
        }
Ejemplo n.º 3
0
 public IncomingMessageProcessor(
     ClientMessageFactory clientMessageFactory,
     ILoggingService loggingService)
 {
     this.clientMessageFactory = clientMessageFactory;
     this.loggingService       = loggingService;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Handles the message.
 /// </summary>
 /// <param name="messageId">The message identifier.</param>
 /// <param name="packetContent">Content of the packet.</param>
 /// <param name="position">The position.</param>
 /// <param name="packetLength">Length of the packet.</param>
 private void HandleMessage(int messageId, byte[] packetContent, int position, int packetLength)
 {
     using (ClientMessage clientMessage = ClientMessageFactory.GetClientMessage(messageId, packetContent, position, packetLength))
         if (_currentClient?.GetMessageHandler() != null)
         {
             _currentClient.GetMessageHandler().HandleRequest(clientMessage);
         }
 }
Ejemplo n.º 5
0
        public void handlePacketData(byte[] data)
        {
            int pos = 0;

            while (pos < data.Length)
            {
                try
                {
                    int MessageLength = HabboEncoding.DecodeInt32(new byte[] { data[pos++], data[pos++], data[pos++], data[pos++] });
                    if (MessageLength < 2 || MessageLength > 1024)
                    {
                        //Logging.WriteLine("bad size packet!");
                        continue;
                    }
                    int MessageId = HabboEncoding.DecodeInt16(new byte[] { data[pos++], data[pos++] });



                    byte[] Content = new byte[MessageLength - 2];

                    for (int i = 0; i < Content.Length && pos < data.Length; i++)
                    {
                        Content[i] = data[pos++];
                    }

                    //Logging.WriteLine("[REQUEST] [" + MessageId + " / len: " + MessageLength + "] => " + Encoding.Default.GetString(Content).Replace(Convert.ToChar(0).ToString(), "{char0}"));

                    if (onNewPacket != null)
                    {
                        using (ClientMessage message = ClientMessageFactory.GetClientMessage(MessageId, Content))
                        {
                            onNewPacket.Invoke(message);
                        }
                    }
                }
                catch (Exception e)
                {
                    int MessageLength = HabboEncoding.DecodeInt32(new byte[] { data[pos++], data[pos++], data[pos++], data[pos++] });
                    int MessageId     = HabboEncoding.DecodeInt16(new byte[] { data[pos++], data[pos++] });
                    Logging.HandleException(e, "packet handling ----> " + MessageId);
                    con.Dispose();
                }
            }
        }
Ejemplo n.º 6
0
        internal static void FlushCache()
        {
            try
            {
                int usersCacheCount = UsersCache.ClearCache();
                ClientMessageFactory.flushCache();
                int totalRoomDataCount = OtanixEnvironment.GetGame().GetRoomManager().ClearRoomDataCache();
                int groups             = OtanixEnvironment.GetGame().GetGroup().ClearGroupsCache();

                OtanixEnvironment.GetGame().GetLandingTopUsersManager().Load();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("[" + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString() + "] finalizado " + usersCacheCount + " usuários, " + totalRoomDataCount + " quartos e " + groups + " grupos <" + integerClear + ">.");
                Console.ResetColor();
            }
            finally
            {
                integerClear = 0;
            }
        }
Ejemplo n.º 7
0
 public void Dispose()
 {
     ClientMessageFactory.ObjectCallback(this);
     GC.SuppressFinalize(this);
 }
Ejemplo n.º 8
0
        internal static void Initialize()
        {
            ServerStarted = DateTime.Now;
            //Console.ForegroundColor = ConsoleColor.DarkBlue;
            //Console.WriteLine("\n                                                                 ");
            //Console.WriteLine(@"        $$$$$$\    $$\                         $$\                ");
            //Console.WriteLine(@"       $$  __$$\   $$ |                        \__|               ");
            //Console.WriteLine(@"       $$ /  $$ |$$$$$$\    $$$$$$\  $$$$$$$\  $$\ $$\   $$\      ");
            //Console.WriteLine(@"       $$ |  $$ |\_$$  _|   \____$$\ $$  __$$\ $$ |\$$\ $$  |     ");
            //Console.WriteLine(@"       $$ |  $$ |  $$ |     $$$$$$$ |$$ |  $$ |$$ | \$$$$  /      ");
            //Console.WriteLine(@"       $$ |  $$ |  $$ |$$\ $$  __$$ |$$ |  $$ |$$ | $$  $$<       ");
            //Console.WriteLine(@"        $$$$$$  |  \$$$$  |\$$$$$$$ |$$ |  $$ |$$ |$$  /\$$\      ");
            //Console.WriteLine(@"        \______/    \____/  \_______|\__|  \__|\__|\__/  \__|     ");
            //Console.WriteLine("\n                                                                 ");
            //Console.ForegroundColor = ConsoleColor.DarkGreen;
            //Console.WriteLine(@"   © 2016 - 2017 - Todos os direitos reservados ao Thiago Araujo.");
            //Console.WriteLine(@"                                                                 ");
            Console.ForegroundColor = ConsoleColor.Gray;

            try
            {
                #region Starting
                Configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"Settings/configuration.ini"));

                UsersCache.Initialize();
                LowPriorityWorker.Init();
                APIexterna.InitStatus();
                LanguageLocale.Init();
                ChatCommandRegister.Init();
                PetLocale.Init();
                #endregion
                #region MySQL Configuration
                var starts = DateTime.Now;
                Logging.WriteLine("[Otanix] @ Conectando na database...");

                manager = new DatabaseManager(uint.Parse(GetConfig().data["db.pool.maxsize"]),
                                              int.Parse(GetConfig().data["db.pool.minsize"]));
                manager.setServerDetails(
                    GetConfig().data["db.hostname"],
                    uint.Parse(GetConfig().data["db.port"]),
                    GetConfig().data["db.username"],
                    GetConfig().data["db.password"],
                    GetConfig().data["db.name"]);
                manager.init();

                var timeUsed2 = DateTime.Now - starts;
                Logging.WriteLine("[Otanix] @ Conectado com sucesso na database! (" + timeUsed2.Seconds + " s, " + timeUsed2.Milliseconds + " ms)");
                #endregion
                #region Cycles Configuration
                starts = DateTime.Now;

                StaticClientMessageHandler.Initialize();
                ClientMessageFactory.Init();

                var timeUsed3 = DateTime.Now - starts;
                Logging.WriteLine("[Otanix] @ Iniciando os ciclos! (" + timeUsed3.Seconds + " s, " + timeUsed3.Milliseconds +
                                  " ms)");

                Game = new Game();
                Game.ContinueLoading();
                #endregion
                #region Connections Configuration
                ConnectionManager = new ConnectionHandeling(int.Parse(GetConfig().data["game.tcp.port"]),
                                                            int.Parse(GetConfig().data["game.tcp.conlimit"]),
                                                            int.Parse(GetConfig().data["game.tcp.conperip"]),
                                                            GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
                ConnectionManager.init();
                ConnectionManager.Start();

                Handler.Initialize(RsaKeyHolder.N, RsaKeyHolder.D, RsaKeyHolder.E);
                Logging.WriteLine("[Otanix] @ RSA Crypto iniciada!");

                if (GetConfig().data["mus.enable"].ToLower() == "true")
                {
                    MusSystem = new MusSocket(int.Parse(GetConfig().data["mus.tcp.port"]));
                }
                #endregion
                #region Last Process
                var TimeUsed = DateTime.Now - ServerStarted;
                Logging.WriteLine("[Otanix] @ ENVIRONMENT -> PRONTO! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
                Console.Title = "Otanix Emulador ~ Versão privada por Thiago Araujo para " + EmuSettings.HOTEL_LINK;

                if (Debugger.IsAttached)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Logging.WriteLine("[Otanix] @ Alerta: Servidor está em DEBUG, console ativado!");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Logging.WriteLine("[Otanix] @ Alerta: Servidor não está em DEBUG, console desativado!");
                    Logging.DisablePrimaryWriting(false);
                }

                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("[Otanix] @ Alerta: Pressione alguma tecla para ativar o console de comandos.");
                Console.ForegroundColor = ConsoleColor.White;
                #endregion
            }
            catch (KeyNotFoundException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Logging.WriteLine("Avviso: controlla il file di configurazione, alcuni valori sembrano mancare.");
                Logging.WriteLine("Avviso: premere un tasto qualsiasi per terminare il programma...");
                Logging.WriteLine(e.ToString());
                Console.ReadKey(true);
                Destroy();
            }
            catch (InvalidOperationException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Logging.WriteLine("Avviso: impossibile avviare il programma, " + e.Message);
                Logging.WriteLine("Avviso: premere un tasto qualsiasi per terminare il programma...");

                Console.ReadKey(true);
                Destroy();
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Avviso: errore di avvio irreversibile, " + e);
                Console.WriteLine("Avviso: premere un tasto qualsiasi per terminare il programma...");

                Console.ReadKey();
                Environment.Exit(1);
            }
            Console.ForegroundColor = ConsoleColor.White;
        }
Ejemplo n.º 9
0
Archivo: Yupi.cs Proyecto: dm5wg/Yupi
        /// <summary>
        ///     Main Void, Initializes the Emulator.
        /// </summary>
        internal static void Initialize()
        {
            Console.Title = "Yupi Emulator | Starting [...]";

            ServerStarted      = DateTime.Now;
            _defaultEncoding   = Encoding.Default;
            MutedUsersByFilter = new Dictionary <uint, uint>();

            ChatEmotions.Initialize();

            CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");

            YupiRootDirectory = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;

            YupiVariablesDirectory = Path.Combine(YupiRootDirectory, "Variables");

            try
            {
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/main.ini"));
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/Welcome/settings.ini"),
                                                 true);

                MySqlConnectionStringBuilder mySqlConnectionStringBuilder = new MySqlConnectionStringBuilder
                {
                    Server                = ServerConfigurationSettings.Data["db.hostname"],
                    Port                  = uint.Parse(ServerConfigurationSettings.Data["db.port"]),
                    UserID                = ServerConfigurationSettings.Data["db.username"],
                    Password              = ServerConfigurationSettings.Data["db.password"],
                    Database              = ServerConfigurationSettings.Data["db.name"],
                    MinimumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.minsize"]),
                    MaximumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.maxsize"]),
                    Pooling               = true,
                    AllowZeroDateTime     = true,
                    ConvertZeroDateTime   = true,
                    DefaultCommandTimeout = 300u,
                    ConnectionTimeout     = 10u
                };

                Manager = new DatabaseManager(mySqlConnectionStringBuilder.ToString());

                using (IQueryAdapter commitableQueryReactor = GetDatabaseManager().GetQueryReactor())
                {
                    ConfigData = new ServerDatabaseSettings(commitableQueryReactor);
                    PetCommandHandler.Init(commitableQueryReactor);
                    PetLocale.Init(commitableQueryReactor);
                    OfflineMessages = new Dictionary <uint, List <OfflineMessage> >();
                    OfflineMessage.InitOfflineMessages(commitableQueryReactor);
                }

                ConsoleTimer       = int.Parse(ServerConfigurationSettings.Data["console.clear.time"]);
                ConsoleTimerOn     = bool.Parse(ServerConfigurationSettings.Data["console.clear.enabled"]);
                FriendRequestLimit = (uint)int.Parse(ServerConfigurationSettings.Data["client.maxrequests"]);

                LibraryParser.Incoming = new Dictionary <int, LibraryParser.StaticRequestHandler>();
                LibraryParser.Library  = new Dictionary <string, string>();
                LibraryParser.Outgoing = new Dictionary <string, int>();
                LibraryParser.Config   = new Dictionary <string, string>();

                if (ServerConfigurationSettings.Data.ContainsKey("client.build"))
                {
                    LibraryParser.ReleaseName = ServerConfigurationSettings.Data["client.build"];
                }
                else
                {
                    throw new Exception("Unable to Continue if No Release is configured to the Emulator Handle.");
                }

                LibraryParser.RegisterLibrary();
                LibraryParser.RegisterOutgoing();
                LibraryParser.RegisterIncoming();
                LibraryParser.RegisterConfig();

                Plugins = new Dictionary <string, IPlugin>();

                ICollection <IPlugin> plugins = LoadPlugins();

                if (plugins != null)
                {
                    foreach (IPlugin item in plugins.Where(item => item != null))
                    {
                        Plugins.Add(item.PluginName, item);

                        Writer.WriteLine("Loaded Plugin: " + item.PluginName + " Version: " + item.PluginVersion,
                                         "Yupi.Plugins", ConsoleColor.DarkBlue);
                    }
                }

                ServerExtraSettings.RunExtraSettings();
                FurnitureDataManager.SetCache();
                CrossDomainSettings.Set();

                _game = new Game.Game(int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]));

                _game.GetNavigator().LoadNewPublicRooms();
                _game.ContinueLoading();

                FurnitureDataManager.Clear();

                if (ServerConfigurationSettings.Data.ContainsKey("server.lang"))
                {
                    ServerLanguage = Convert.ToString(ServerConfigurationSettings.Data["server.lang"]);
                }

                _languages = new ServerLanguageSettings(ServerLanguage);

                Writer.WriteLine("Loaded " + _languages.Count() + " Languages Vars", "Yupi.Interpreters");

                if (plugins != null)
                {
                    foreach (IPlugin itemTwo in plugins)
                    {
                        itemTwo?.message_void();
                    }
                }

                if (ConsoleTimerOn)
                {
                    Writer.WriteLine("Console Clear Timer is Enabled, with " + ConsoleTimer + " Seconds.", "Yupi.Boot");
                }

                ClientMessageFactory.Init();

                Writer.WriteLine(
                    "Game server started at port " + int.Parse(ServerConfigurationSettings.Data["game.tcp.port"]),
                    "Server.Game");

                _connectionManager = new ConnectionHandler(int.Parse(ServerConfigurationSettings.Data["game.tcp.port"]),
                                                           int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]),
                                                           int.Parse(ServerConfigurationSettings.Data["game.tcp.conperip"]),
                                                           ServerConfigurationSettings.Data["game.tcp.antiddos"].ToLower() == "true",
                                                           ServerConfigurationSettings.Data["game.tcp.enablenagles"].ToLower() == "true");

                if (LibraryParser.Config["Crypto.Enabled"] == "true")
                {
                    Handler.Initialize(LibraryParser.Config["Crypto.RSA.N"], LibraryParser.Config["Crypto.RSA.D"],
                                       LibraryParser.Config["Crypto.RSA.E"]);

                    Writer.WriteLine("Started RSA crypto service", "Yupi.Crypto");
                }
                else
                {
                    Writer.WriteLine("The encryption system is disabled.", "Yupi.Crypto", ConsoleColor.DarkYellow);
                }

                LibraryParser.Initialize();

                if (ConsoleTimerOn)
                {
                    Timer = new Timer {
                        Interval = ConsoleTimer
                    };
                    Timer.Elapsed += TimerElapsed;
                    Timer.Start();
                }

                if (ServerConfigurationSettings.Data.ContainsKey("StaffAlert.MinLevel"))
                {
                    StaffAlertMinRank = uint.Parse(ServerConfigurationSettings.Data["StaffAlert.MinLevel"]);
                }

                if (ServerConfigurationSettings.Data.ContainsKey("game.multithread.enabled"))
                {
                    SeparatedTasksInMainLoops = ServerConfigurationSettings.Data["game.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("client.multithread.enabled"))
                {
                    SeparatedTasksInGameClientManager =
                        ServerConfigurationSettings.Data["client.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("debug.packet"))
                {
                    if (ServerConfigurationSettings.Data["debug.packet"] == "true")
                    {
                        PacketDebugMode = true;
                    }
                }

                Writer.WriteLine("Yupi Emulator ready. Status: idle", "Yupi.Boot");

                IsLive = true;
            }
            catch (Exception e)
            {
                Writer.WriteLine("Error When Starting Yupi Environment!" + Environment.NewLine + e.Message, "Yupi.Boot",
                                 ConsoleColor.Red);
                Writer.WriteLine("Please press Y to get more details or press other Key to Exit", "Yupi.Boot",
                                 ConsoleColor.Red);
                ConsoleKeyInfo key = Console.ReadKey();

                if (key.Key == ConsoleKey.Y)
                {
                    Console.WriteLine();
                    Writer.WriteLine(
                        Environment.NewLine + "[Message] Error Details: " + Environment.NewLine + e.StackTrace +
                        Environment.NewLine + e.InnerException + Environment.NewLine + e.TargetSite +
                        Environment.NewLine + "[Message] Press Any Key To Exit", "Yupi.Boot", ConsoleColor.Red);
                    Console.ReadKey();
                    Environment.Exit(1);
                }
                else
                {
                    Environment.Exit(1);
                }
            }
        }
Ejemplo n.º 10
0
        internal static void Initialize()
        {
            PrettyVersion = string.Format("Firewind {0}", Assembly.GetExecutingAssembly().GetName().Version);
            Console.Clear();
            DateTime Start = DateTime.Now;

            SystemMute = false;

            ServerStarted = DateTime.Now;

            Console.Title = "Firewind: Loading environment.";

            Logging.WriteWithColor("      _______ __                       __           __ ", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |    ___|__|.----.-----.--.--.--.|__|.-----.--|  |", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |    ___|  ||   _|  -__|  |  |  ||  ||     |  _  |", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |___|   |__||__| |_____|________||__||__|__|_____|", ConsoleColor.Cyan);
            Logging.WriteLine("");
            Logging.WriteLine("==============================================================");

            DefaultEncoding = Encoding.Default;
            Logging.WriteLine("     " + PrettyVersion);
            Logging.WriteLine(string.Format("     Licenced to {0}", LicenseHolder));
            Logging.WriteLine(string.Format("     Maximum players: {0}", MaxUsers == 0 ? "Unlimited!" : MaxUsers.ToString()));

            Logging.WriteLine("");

            Logging.WriteLine("     Go to the GitHub repo for bug reporting/contributions!");
            cultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
            IsDebugging = IsDebugging ? System.Diagnostics.Debugger.IsAttached : false;

            try
            {
                LanguageLocale.Init();
                ChatCommandRegister.Init();
                PetCommandHandeler.Init();
                PetLocale.Init();

                if (IsDebugging)
                {
                    Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings_test/configuration.ini"));
                }
                else
                {
                    Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings/configuration.ini"));
                }

                DateTime Starts = DateTime.Now;
                Logging.WriteLine("Connecting to database...");

                manager = new DatabaseManager(uint.Parse(FirewindEnvironment.GetConfig().data["db.pool.maxsize"]), int.Parse(FirewindEnvironment.GetConfig().data["db.pool.minsize"]));
                manager.setServerDetails(
                    FirewindEnvironment.GetConfig().data["db.hostname"],
                    uint.Parse(FirewindEnvironment.GetConfig().data["db.port"]),
                    FirewindEnvironment.GetConfig().data["db.username"],
                    FirewindEnvironment.GetConfig().data["db.password"],
                    FirewindEnvironment.GetConfig().data["db.name"]);
                manager.init();

                TimeSpan TimeUsed2 = DateTime.Now - Starts;
                Logging.WriteLine("Connected to database! (" + TimeUsed2.Seconds + " s, " + TimeUsed2.Milliseconds + " ms)");

                LanguageLocale.InitSwearWord();

                friendRequestLimit = (uint)(int.Parse(FirewindEnvironment.GetConfig().data["client.maxrequests"]));

                Game = new Game(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conlimit"]));
                Game.ContinueLoading();

                ConnectionManager = new ConnectionHandling(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.port"]),
                                                           MaxUsers,
                                                           int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conperip"]),
                                                           FirewindEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
                ConnectionManager.init();
                ConnectionManager.Start();

                StaticClientMessageHandler.Initialize();
                ClientMessageFactory.Init();

                string[] arrayshit = FirewindEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(';');

                MusSystem = new RConListener(FirewindEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(FirewindEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0);

                useSSO = true;
                if (Configuration.data.ContainsKey("auth.ssodisabled"))
                {
                    if (Configuration.data["auth.ssodisabled"] == "false")
                    {
                        useSSO = false;
                    }
                }

                if (Configuration.data.ContainsKey("spambans.enabled"))
                {
                    if (Configuration.data["spambans.enabled"] == "true")
                    {
                        spamBans       = true;
                        spamBans_limit = Convert.ToInt32(Configuration.data["spambans.limit"]);
                        Logging.WriteLine("Spam Bans enabled");
                    }
                }
                if (Configuration.data.ContainsKey("SeparatedTasksInMainLoops.enabled"))
                {
                    if (Configuration.data["SeparatedTasksInMainLoops.enabled"] == "true")
                    {
                        SeparatedTasksInMainLoops = true;
                        Logging.WriteLine("MultiTasking in MainLoop");
                    }
                }

                if (Configuration.data.ContainsKey("SeparatedTasksInGameClientManager.enabled"))
                {
                    if (Configuration.data["SeparatedTasksInGameClientManager.enabled"] == "true")
                    {
                        SeparatedTasksInGameClientManager = true;
                        Logging.WriteLine("MultiTasking in ClientManager");
                    }
                }

                TimeSpan TimeUsed = DateTime.Now - Start;

                Logging.WriteWithColor("Firewind -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)", ConsoleColor.Cyan);

                isLive = true;
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Logging.WriteLine("Server is debugging: Console writing enabled", true);
                }
                else
                {
                    Logging.WriteLine("Server is not debugging: Console writing disabled", false);
                    Logging.DisablePrimaryWriting(false);
                }
            }
            catch (KeyNotFoundException e)
            {
                Logging.WriteLine("Please check your configuration file - some values appear to be missing.");
                Logging.WriteLine("Press any key to shut down ...");
                Logging.WriteLine(e.ToString());
                Console.ReadKey(true);
                FirewindEnvironment.Destroy();

                return;
            }
            catch (InvalidOperationException e)
            {
                Logging.WriteLine("Failed to initialize Firewind Emulator: " + e.Message);
                Logging.WriteLine("Press any key to shut down ...");

                Console.ReadKey(true);
                FirewindEnvironment.Destroy();

                return;
            }

            catch (Exception e)
            {
                Logging.WriteLine("Fatal error during startup: " + e.ToString());
                Logging.WriteLine("Press a key to exit");

                Console.ReadKey();
                Environment.Exit(1);
            }

            // Check if this is habin or not
            try
            {
                using (IQueryAdapter dbClient = manager.getQueryreactor())
                {
                    dbClient.setQuery("SELECT column_name FROM information_schema.columns WHERE table_schema = '" + FirewindEnvironment.GetConfig().data["db.name"] + "' AND table_name = 'users' AND column_name = 'hpo'");
                    IsHabin = dbClient.findsResult();
                }
            }
            catch { }
        }
Ejemplo n.º 11
0
        internal static void Initialize()
        {
            Console.Clear();
            DateTime Start = DateTime.Now;

            SystemMute = false;

            IrcEnabled           = false;
            ServerStarted        = DateTime.Now;
            Console.Title        = PiciEnvironment.Title + " " + PiciEnvironment.Version;
            Console.WindowHeight = 30;
            DefaultEncoding      = Encoding.Default;

            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("");
            Console.WriteLine("          ______ _       _    _______             ");
            Console.WriteLine("         (_____ (_)     (_)  (_______)            ");
            Console.WriteLine("          _____) )  ____ _    _____   ____  _   _ ");
            Console.WriteLine(@"         |  ____/ |/ ___) |  |  ___) |    \| | | |");
            Console.WriteLine(@"         | |    | ( (___| |  | |_____| | | | |_| |");
            Console.WriteLine(@"         |_|    |_|\____)_|  |_______)_|_|_|____/ ");


            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("                              " + PiciEnvironment.Title + " " + PiciEnvironment.Version + " (Build " + PiciEnvironment.Build + ")");


            Console.WriteLine();

            Console.ResetColor();
            Console.ForegroundColor = ConsoleColor.White;

            Console.WriteLine();

            cultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
            LanguageLocale.Init();

            try
            {
                ChatCommandRegister.Init();
                PetCommandHandeler.Init();
                PetLocale.Init();
                Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"config.conf"));

                DateTime Starts = DateTime.Now;

                dbType = DatabaseType.MySQL;

                manager = new DatabaseManager(uint.Parse(PiciEnvironment.GetConfig().data["db.pool.maxsize"]), uint.Parse(PiciEnvironment.GetConfig().data["db.pool.minsize"]), int.Parse(PiciEnvironment.GetConfig().data["db.pool.minsize"]), dbType);
                manager.setServerDetails(
                    PiciEnvironment.GetConfig().data["db.hostname"],
                    uint.Parse(PiciEnvironment.GetConfig().data["db.port"]),
                    PiciEnvironment.GetConfig().data["db.username"],
                    PiciEnvironment.GetConfig().data["db.password"],
                    PiciEnvironment.GetConfig().data["db.name"]);
                manager.init();

                TimeSpan TimeUsed2 = DateTime.Now - Starts;

                LanguageLocale.InitSwearWord();

                Game = new Game(int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conlimit"]));
                Game.ContinueLoading();

                ConnectionManager = new ConnectionHandeling(int.Parse(PiciEnvironment.GetConfig().data["game.tcp.port"]),
                                                            int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conlimit"]),
                                                            int.Parse(PiciEnvironment.GetConfig().data["game.tcp.conperip"]),
                                                            PiciEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
                ConnectionManager.init();

                ConnectionManager.Start();

                StaticClientMessageHandler.Initialize();
                ClientMessageFactory.Init();

                string[] arrayshit = PiciEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(","));

                MusSystem = new MusSocket(PiciEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(PiciEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0);

                //InitIRC();

                groupsEnabled = true;

                useSSO = true;

                TimeSpan TimeUsed = DateTime.Now - Start;

                Logging.WriteLine("Server -> Started! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
                isLive = true;

                Console.Beep();


                if (bool_0_12)
                {
                    Console.WriteLine("Coffee team, I appreciate you testing. ;-*");
                    System.Threading.Thread.Sleep(2500);
                    PreformShutDown(true);
                    return;
                }
            }
            catch (KeyNotFoundException e)
            {
                Logging.WriteLine("Please check your configuration file - some values appear to be missing.");
                Logging.WriteLine("Press any key to shut down ...");
                Logging.WriteLine(e.ToString());
                Console.ReadKey(true);
                PiciEnvironment.Destroy();

                return;
            }
            catch (InvalidOperationException e)
            {
                Logging.WriteLine("Failed to initialize PiciEmulator: " + e.Message);
                Logging.WriteLine("Press any key to shut down ...");

                Console.ReadKey(true);
                PiciEnvironment.Destroy();

                return;
            }

            catch (Exception e)
            {
                Console.WriteLine("Fatal error during startup: " + e.ToString());
                Console.WriteLine("Press a key to exit");

                Console.ReadKey();
                Environment.Exit(1);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Main Void, Initializes the Emulator.
        /// </summary>
        internal static void Initialize()
        {
            Console.Title = "Yupi Emulator | Starting [...]";

            YupiServerStartDateTime = DateTime.Now;
            YupiServerTextEncoding  = Encoding.Default;
            MutedUsersByFilter      = new Dictionary <uint, uint>();

            ChatEmotions.Initialize();

            CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");

            YupiRootDirectory = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;

            YupiVariablesDirectory = Path.Combine(YupiRootDirectory, "Variables");

            try
            {
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/main.ini"));
                ServerConfigurationSettings.Load(Path.Combine(YupiVariablesDirectory, "Settings/Welcome/settings.ini"), true);

                if (uint.Parse(ServerConfigurationSettings.Data["db.pool.maxsize"]) > MaxRecommendedMySqlConnections)
                {
                    YupiWriterManager.WriteLine("MySQL Max Conn is High!, Recommended Value: " + MaxRecommendedMySqlConnections, "Yupi.Data", ConsoleColor.DarkYellow);
                }

                MySqlConnectionStringBuilder mySqlConnectionStringBuilder = new MySqlConnectionStringBuilder
                {
                    Server                = ServerConfigurationSettings.Data["db.hostname"],
                    Port                  = uint.Parse(ServerConfigurationSettings.Data["db.port"]),
                    UserID                = ServerConfigurationSettings.Data["db.username"],
                    Password              = ServerConfigurationSettings.Data["db.password"],
                    Database              = ServerConfigurationSettings.Data["db.name"],
                    MinimumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.minsize"]),
                    MaximumPoolSize       = uint.Parse(ServerConfigurationSettings.Data["db.pool.maxsize"]),
                    Pooling               = true,
                    AllowZeroDateTime     = true,
                    ConvertZeroDateTime   = true,
                    DefaultCommandTimeout = 300,
                    ConnectionTimeout     = 10
                };

                YupiDatabaseManager = new BasicDatabaseManager(mySqlConnectionStringBuilder);

                using (IQueryAdapter queryReactor = GetDatabaseManager().GetQueryReactor())
                {
                    DatabaseSettings = new ServerDatabaseSettings(queryReactor);
                    PetCommandHandler.Init(queryReactor);
                    PetLocale.Init(queryReactor);
                    OfflineMessages = new Dictionary <uint, List <OfflineMessage> >();
                    OfflineMessage.InitOfflineMessages(queryReactor);
                }

                YupiLogManager.Init(MethodBase.GetCurrentMethod().DeclaringType);

                ConsoleCleanTimeInterval = int.Parse(ServerConfigurationSettings.Data["console.clear.time"]);
                ConsoleTimerOn           = bool.Parse(ServerConfigurationSettings.Data["console.clear.enabled"]);
                FriendRequestLimit       = (uint)int.Parse(ServerConfigurationSettings.Data["client.maxrequests"]);

                LibraryParser.Incoming = new Dictionary <int, LibraryParser.StaticRequestHandler>();
                LibraryParser.Library  = new Dictionary <string, string>();
                LibraryParser.Outgoing = new Dictionary <string, int>();
                LibraryParser.Config   = new Dictionary <string, string>();

                LibraryParser.ReleaseName = ServerConfigurationSettings.Data["client.build"];

                LibraryParser.RegisterLibrary();
                LibraryParser.RegisterOutgoing();
                LibraryParser.RegisterIncoming();
                LibraryParser.RegisterConfig();

                Plugins = new Dictionary <string, IPlugin>();

                ICollection <IPlugin> plugins = LoadPlugins();

                if (plugins != null)
                {
                    foreach (IPlugin item in plugins.Where(item => item != null))
                    {
                        Plugins.Add(item.PluginName, item);

                        YupiWriterManager.WriteLine("Loaded Plugin: " + item.PluginName + " ServerVersion: " + item.PluginVersion, "Yupi.Plugins", ConsoleColor.DarkBlue);
                    }
                }

                ServerExtraSettings.RunExtraSettings();
                FurnitureDataManager.SetCache();
                CrossDomainSettings.Set();

                GameServer = new HabboHotel(int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]));

                GameServer.ContinueLoading();

                FurnitureDataManager.Clear();

                if (ServerConfigurationSettings.Data.ContainsKey("server.lang"))
                {
                    ServerLanguage = ServerConfigurationSettings.Data["server.lang"];
                }

                ServerLanguageVariables = new ServerLanguageSettings(ServerLanguage);

                YupiWriterManager.WriteLine("Loaded " + ServerLanguageVariables.Count() + " Languages Vars", "Yupi.Boot");

                if (plugins != null)
                {
                    foreach (IPlugin plugin in plugins)
                    {
                        plugin?.message_void();
                    }
                }

                if (ConsoleTimerOn)
                {
                    YupiWriterManager.WriteLine("Console Clear ConsoleRefreshTimer is Enabled, with " + ConsoleCleanTimeInterval + " Seconds.", "Yupi.Boot");
                }

                ClientMessageFactory.Init();

                YupiUserConnectionManager = new ConnectionHandler(int.Parse(ServerConfigurationSettings.Data["game.tcp.port"]),
                                                                  int.Parse(ServerConfigurationSettings.Data["game.tcp.conlimit"]),
                                                                  int.Parse(ServerConfigurationSettings.Data["game.tcp.conperip"]),
                                                                  ServerConfigurationSettings.Data["game.tcp.antiddos"].ToLower() == "true",
                                                                  ServerConfigurationSettings.Data["game.tcp.enablenagles"].ToLower() == "true");

                YupiWriterManager.WriteLine("Server Started at Port "
                                            + ServerConfigurationSettings.Data["game.tcp.port"] + " and Address "
                                            + ServerConfigurationSettings.Data["game.tcp.bindip"], "Yupi.Boot");

                if (LibraryParser.Config["Crypto.Enabled"] == "true")
                {
                    Handler.Initialize(LibraryParser.Config["Crypto.RSA.N"], LibraryParser.Config["Crypto.RSA.D"], LibraryParser.Config["Crypto.RSA.E"]);

                    YupiWriterManager.WriteLine("Started RSA crypto service", "Yupi.Crypto");
                }
                else
                {
                    YupiWriterManager.WriteLine("The encryption system is disabled.", "Yupi.Crypto", ConsoleColor.DarkYellow);
                }

                LibraryParser.Initialize();

                if (ConsoleTimerOn)
                {
                    ConsoleRefreshTimer = new Timer {
                        Interval = ConsoleCleanTimeInterval
                    };
                    ConsoleRefreshTimer.Elapsed += ConsoleRefreshTimerElapsed;
                    ConsoleRefreshTimer.Start();
                }

                if (ServerConfigurationSettings.Data.ContainsKey("game.multithread.enabled"))
                {
                    SeparatedTasksInMainLoops = ServerConfigurationSettings.Data["game.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("client.multithread.enabled"))
                {
                    SeparatedTasksInGameClientManager = ServerConfigurationSettings.Data["client.multithread.enabled"] == "true";
                }

                if (ServerConfigurationSettings.Data.ContainsKey("debug.packet"))
                {
                    PacketDebugMode = ServerConfigurationSettings.Data["debug.packet"] == "true";
                }

                YupiWriterManager.WriteLine("Yupi Emulator ready.", "Yupi.Boot");

                IsLive = true;
            }
            catch (Exception e)
            {
                YupiWriterManager.WriteLine("Error When Starting Yupi Environment!" + Environment.NewLine + e.Message, "Yupi.Boot", ConsoleColor.Red);
                YupiWriterManager.WriteLine("Please press Y to get more details or press other Key to Exit", "Yupi.Boot", ConsoleColor.Red);

                ConsoleKeyInfo key = Console.ReadKey();

                if (key.Key == ConsoleKey.Y)
                {
                    Console.WriteLine();

                    YupiWriterManager.WriteLine(
                        Environment.NewLine + "[Message] Error Details: " + Environment.NewLine + e.StackTrace +
                        Environment.NewLine + e.InnerException + Environment.NewLine + e.TargetSite +
                        Environment.NewLine + "[Message] Press Any Key To Exit", "Yupi.Boot", ConsoleColor.Red);

                    Console.ReadKey();
                }

                Environment.Exit(1);
            }
        }
Ejemplo n.º 13
0
        public void handlePacketData(byte[] data)
        {
            int i = 0;

            if (currentClient != null && currentClient.ARC4 != null)
            {
                currentClient.ARC4.Decrypt(ref data);
            }
            checked
            {
                while (i < data.Length)
                {
                    try
                    {
                        int num = HabboEncoding.DecodeInt32(new byte[]
                        {
                            data[i++],
                            data[i++],
                            data[i++],
                            data[i++]
                        });
                        if (num >= 2 && num <= 1024)
                        {
                            int messageId = HabboEncoding.DecodeInt16(new byte[]
                            {
                                data[i++],
                                data[i++]
                            });
                            byte[] array = new byte[num - 2];
                            int    num2  = 0;
                            while (num2 < array.Length && i < data.Length)
                            {
                                array[num2] = data[i++];
                                num2++;
                            }
                            if (this.onNewPacket != null)
                            {
                                using (ClientMessage clientMessage = ClientMessageFactory.GetClientMessage(messageId, array))
                                {
                                    this.onNewPacket(clientMessage);
                                }
                            }
                        }
                    }
                    catch (Exception pException)
                    {
                        HabboEncoding.DecodeInt32(new byte[]
                        {
                            data[i++],
                            data[i++],
                            data[i++],
                            data[i++]
                        });
                        int num3 = HabboEncoding.DecodeInt16(new byte[]
                        {
                            data[i++],
                            data[i++]
                        });
                        Logging.HandleException(pException, "packet handling ----> " + num3);
                        this.con.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 14
0
        internal static void Initialize()
        {
            Console.Clear();
            DateTime Start = DateTime.Now;

            SystemMute = false;

            ServerStarted   = DateTime.Now;
            Console.Title   = "Loading Butterfly Emulator";
            DefaultEncoding = Encoding.Default;
            //Logging.rzFlag();
            Logging.WriteLine();
            Logging.WriteLine(PrettyVersion);



            cultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
            LanguageLocale.Init();

            try
            {
                ChatCommandRegister.Init();
                PetCommandHandeler.Init();
                PetLocale.Init();
                Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings/configuration.ini"));
                if (ButterflyEnvironment.GetConfig().data["db.password"] == "changeme")
                {
                    throw new ArgumentException("Your MySQL password may not be 'changeme'.\nChange your password to start the server.");
                }

                DateTime Starts = DateTime.Now;
                Logging.WriteLine("Connecting to database...");

                dbType = GetConfig().data.ContainsKey("db.mssql") && GetConfig().data["db.mssql"] == "true" ? DatabaseType.MSSQL : DatabaseType.MySQL;

                manager = new DatabaseManager(uint.Parse(ButterflyEnvironment.GetConfig().data["db.pool.maxsize"]), int.Parse(ButterflyEnvironment.GetConfig().data["db.pool.minsize"]), dbType);
                manager.setServerDetails(
                    ButterflyEnvironment.GetConfig().data["db.hostname"],
                    uint.Parse(ButterflyEnvironment.GetConfig().data["db.port"]),
                    ButterflyEnvironment.GetConfig().data["db.username"],
                    ButterflyEnvironment.GetConfig().data["db.password"],
                    ButterflyEnvironment.GetConfig().data["db.name"]);
                manager.init();

                TimeSpan TimeUsed2 = DateTime.Now - Starts;
                Logging.WriteLine("Connected to database! (" + TimeUsed2.Seconds + " s, " + TimeUsed2.Milliseconds + " ms)");

                LanguageLocale.InitSwearWord();

                Game = new Game(int.Parse(ButterflyEnvironment.GetConfig().data["game.tcp.conlimit"]));
                Game.ContinueLoading();

                ConnectionManager = new ConnectionHandeling(int.Parse(ButterflyEnvironment.GetConfig().data["game.tcp.port"]),
                                                            int.Parse(ButterflyEnvironment.GetConfig().data["game.tcp.conlimit"]),
                                                            int.Parse(ButterflyEnvironment.GetConfig().data["game.tcp.conperip"]),
                                                            ButterflyEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
                ConnectionManager.init();

                ConnectionManager.Start();

                StaticClientMessageHandler.Initialize();
                ClientMessageFactory.Init();

                string[] arrayshit = ButterflyEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(Convert.ToChar(","));

                MusSystem = new MusSocket(ButterflyEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(ButterflyEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0);

                groupsEnabled = false;
                if (Configuration.data.ContainsKey("groups.enabled"))
                {
                    if (Configuration.data["groups.enabled"] == "true")
                    {
                        groupsEnabled = true;
                    }
                }

                useSSO = true;
                if (Configuration.data.ContainsKey("auth.ssodisabled"))
                {
                    if (Configuration.data["auth.ssodisabled"] == "false")
                    {
                        useSSO = false;
                    }
                }

                TimeSpan TimeUsed = DateTime.Now - Start;

                Logging.WriteLine("ENVIRONMENT -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
                isLive = true;
                if (System.Diagnostics.Debugger.IsAttached || Configuration.data["debug.console"] == "1")
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Logging.WriteLine("Server is debugging: Console writing enabled");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Logging.WriteLine("Server is not debugging: Console writing disabled");
                    Logging.DisablePrimaryWriting(false);
                }
            }
            catch (KeyNotFoundException e)
            {
                Logging.WriteLine("Please check your configuration file - some values appear to be missing.");
                Logging.WriteLine("Press any key to shut down ...");
                Logging.WriteLine(e.ToString());
                Console.ReadKey(true);
                ButterflyEnvironment.Destroy();

                return;
            }
            catch (InvalidOperationException e)
            {
                Logging.WriteLine("Failed to initialize ButterflyEmulator: " + e.Message);
                Logging.WriteLine("Press any key to shut down ...");

                Console.ReadKey(true);
                ButterflyEnvironment.Destroy();

                return;
            }

            catch (Exception e)
            {
                Console.WriteLine("Fatal error during startup: " + e.ToString());
                Console.WriteLine("Press a key to exit");

                Console.ReadKey();
                Environment.Exit(1);
            }
        }