示例#1
0
        public bool SaveAccount(ushort conn)
        {
            int Idx = GetIndex(conn);

            try
            {
                string CorrectPatch = Functions.getCorrectPath(AccountList[Idx].Account.Info.AccountName);
                string indented     = "";
                using (StreamWriter file = File.CreateText(CorrectPatch + ".json"))
                {
                    indented = JsonConvert.SerializeObject(AccountList[Idx].Account, Formatting.Indented);
                    file.Write(indented);
                }

                W2Log.Write(String.Format("save account sucess: {0}/{1}", Idx, AccountList[Idx].Account.Info.AccountName), ELogType.GAME_EVENT);


                indented.Replace(AccountList[Idx].Account.Info.AccountPass, "null");
                int update = MySQL.nQuery(string.Format("INSERT INTO `accounts_json` (`login`, `conteudo`) VALUES ('{0}', '{1}') ON DUPLICATE KEY UPDATE `login` = '{2}' ", AccountList[Idx].Account.Info.AccountName.ToLower(), indented, AccountList[Idx].Account.Info.AccountName.ToLower()));
                if (update != 0)
                {
                    W2Log.Write(string.Format("Sucess DBSaveAccount update json: {0} - {1}", Idx, AccountList[Idx].Account.Info.AccountName));
                }


                return(true);
            }
            catch (Exception e)
            {
                W2Log.Write(String.Format("save account fail: {0}/{1}", AccountList[Idx].Account.Info.AccountName, e.Message), ELogType.GAME_EVENT);
                return(false);
            }
        }
示例#2
0
 public void ReadBaseMob(DBController gs)
 {
     try
     {
         string[] MobName = { "TransKnight", "Foema", "BeastMaster", "Huntress" };
         for (int i = 0; i < MobName.Length; i++)
         {
             string BaseDir = "./DataBase/BaseMob/" + MobName[i];
             if (!File.Exists(BaseDir + ".json"))
             {
                 gs.BaseMob[i] = Functions.ReadAccount <STRUCT_MOB>(BaseDir);
                 using (StreamWriter file = File.CreateText(BaseDir + ".json"))
                 {
                     string indented = JsonConvert.SerializeObject(gs.BaseMob[i], Formatting.Indented);
                     file.Write(indented);
                 }
             }
             using (StreamReader r = new StreamReader(BaseDir + ".json"))
             {
                 string json = r.ReadToEnd();
                 gs.BaseMob[i] = JsonConvert.DeserializeObject <STRUCT_MOB>(json);
             }
         }
     }
     catch (Exception e)
     {
         W2Log.Write("can't read BaseMobs" + e.Message);
     }
 }
示例#3
0
        //Process GuildIndo (Envia as Guildas Para TMSRV)
        public static DBResult Exec_MSG_GuildInfo(DBController gs, pServer GameServer)
        {
            MSG_GuildInfo sm = W2Marshal.GetStructure <MSG_GuildInfo>(GameServer.RecvPacket.RawBuffer);

            int myguild = sm.Guild;

            if (myguild <= 0 || myguild >= 5000)
            {
                W2Log.Write($"guild index out or range { sm.Guild}");
                return(DBResult.NO_ERROR);
            }

            gs.g_pGuildInfo[myguild] = sm.GuildInfo;

            if (myguild != gs.g_pGuildInfo[myguild].GuildID)
            {
                W2Log.Write($"guild index fixed {gs.g_pGuildInfo[myguild].GuildID } to {myguild}");
                gs.g_pGuildInfo[myguild].GuildID = myguild;
            }


            gs.SendGuildInfo(myguild);

            W2Log.Write($"guild update {gs.g_pGuildInfo[myguild].GuildID } - {gs.g_pGuildInfo[myguild].GuildName}");

            if (!Functions.WriteGuildInfo(gs.g_pGuildInfo))
            {
                W2Log.Write("fail to write guild info");
            }



            return(DBResult.NO_ERROR);
        }
示例#4
0
        //Process UpdateSaphire (Atualiza as Saphriras requerida pelos Reis)
        public static DBResult Exec_MSG_DBUpdateSapphire(DBController gs, pServer GameServer)
        {
            _MSG_SIGNALPARM sm = W2Marshal.GetStructure <_MSG_SIGNALPARM>(GameServer.RecvPacket.RawBuffer);

            ConfigServer.ReadConfigFile(gs.Config);

            int Old = gs.Config.Sapphire;

            if (sm.parm == 1)
            {
                gs.Config.Sapphire *= 2;
            }
            else
            {
                gs.Config.Sapphire /= 2;
            }

            if (gs.Config.Sapphire < 1)
            {
                gs.Config.Sapphire = 1;
            }
            else if (gs.Config.Sapphire > 64)
            {
                gs.Config.Sapphire = 64;
            }


            gs.Server.SendSignalParm(0, BaseDef._MSG_DBSetIndex, -1, gs.Config.Sapphire, sm.Header.ClientId);

            ConfigServer.saveConfig(gs.Config);
            W2Log.Write($"sucess db set saphire: {Old} -> {gs.Config.Sapphire}");
            return(DBResult.NO_ERROR);
        }
        private void CGameStateController_OnProcessSecTimer(CGameStateController gs)
        {
            if (DateTime.Now - m_LastGlobalAccSave >= m_GlobalAccSaveDueTime)
            {
                for (int i = 0; i < gs.Players.Length; i++)
                {
                    if (gs.Players[i]?.State == EPlayerState.AT_WORLD)
                    {
                        var account = gs.Players[i].AccountData.Value;

                        if (AccountCRUD.TrySaveAccount(ref account) != AccountCRUD.EResult.NO_ERROR)
                        {
                            // TODO: the account could not be saved for some reason.
                            // Do something...
                            throw new Exception($"The account {gs.Players[i].AccountData.Value.Info.LoginInfo.AccName} couldn't be saved.");
                        }
                        else
                        {
                            W2Log.Write($"The account {gs.Players[i].AccountData.Value.Info.LoginInfo.AccName} was saved successfuly.", ELogType.GAME_EVENT);
                        }
                    }
                }

                m_LastGlobalAccSave = gs.SinceInit;
            }
        }
示例#6
0
        static public void Start( )
        {
            bool Importend = false;

            foreach (string file in Directory.EnumerateFiles("./DataBase/ImportInfo/", "*.user"))
            {
                using (StreamReader sr = new StreamReader(file))
                {
                    string line;
                    int    countLine = 0;
                    string Login = string.Empty, Senha = string.Empty, Nome = string.Empty, Email = string.Empty, IP = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        line.Trim().Trim(' ');

                        if (countLine == 0)
                        {
                            Login = line;
                        }
                        if (countLine == 1)
                        {
                            Senha = line;
                        }
                        if (countLine == 2)
                        {
                            Nome = line;
                        }
                        if (countLine == 3)
                        {
                            Email = line;
                        }
                        if (countLine == 4)
                        {
                            IP = line;
                        }
                        countLine++;
                    }
                    if (!string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Senha) && !string.IsNullOrEmpty(Nome) && !string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(IP))
                    {
                        if (!File.Exists(Functions.getCorrectPath(Login) + ".json"))
                        {
                            Importend = Functions.CreateEmptyAccount(Login, Senha, IP, Email, Nome);
                        }
                    }
                    if (Importend)
                    {
                        sr.Close();
                        File.Delete(file);
                        Importend = false;
                        W2Log.Write(String.Format($"sucess import user: {Login} - {Email}"), ELogType.CRITICAL_ERROR);
                        return;
                    }
                    else
                    {
                        W2Log.Write(String.Format($"can't import user: {Login}"), ELogType.CRITICAL_ERROR);
                    }
                }
            }
        }
示例#7
0
        /// <summary>
        /// Disconnect the player.
        /// Exceptions:
        ///     Throws any exceptions except the "GameStateException.Code == INVALID_PLAYER_INDEX".
        /// </summary>
        /// <param name="player"></param>
        public void DisconnectPlayer(CPlayer player)
        {
            if (player.State != EPlayerState.CLOSED)
            {
                // TODO: send the dced spawn in the visible area around the player.
                // TODO: proceed removind the player of all the game state: mob grid, spawned mobs, etc.

                player.State = EPlayerState.CLOSED;

                W2Log.Write($"The player {player.Index} was disconnected from the server.", ELogType.GAME_EVENT);
            }
        }
示例#8
0
        //Process ImportItem
        public static DBResult Exec_MSG_DBSendItem(DBController gs, pServer GameServer)
        {
            MSG_DBSendItem sm = W2Marshal.GetStructure <MSG_DBSendItem>(GameServer.RecvPacket.RawBuffer);

            int Idx = gs.GetIndex(sm.Header.ClientId);


            if (String.IsNullOrEmpty(gs.AccountList[Idx].Account.Info.AccountName))
            {
                W2Log.Write("MSG_DBSendItem error user is empty");
            }

            CultureInfo Culture   = new CultureInfo("pt-BR");
            DateTime    localDate = DateTime.Now;
            string      atual     = localDate.ToString(Culture).Replace('/', '-').ToString();


            if (sm.Result == 0)//Sucesso
            {
                int updated = gs.MySQL.nQuery(string.Format("UPDATE `lista_compras` SET `data_envio` = '{0}' WHERE `id` = '{1}' and `login_conta` = '{2}' ", atual, sm.id_pedido, gs.AccountList[Idx].Account.Info.AccountName));

                if (updated != 0)
                {
                    W2Log.Write(string.Format("Sucess DBSendItem: {0} - {1}", atual, sm.id_pedido));
                }
                else
                {
                    W2Log.Write(string.Format("Fail DBSendItem: {0} - {1}", atual, sm.id_pedido));
                }

                return(DBResult.NO_ERROR);
            }

            if (sm.Result == 3)//Falta espaço no Cargo recriar o arquivo
            {
                W2Log.Write(string.Format("Fail DBSendItem: {0} - {1} no empty cargo slot", atual, sm.id_pedido));
                bool recreatedItem = Functions.CreateImportItem(gs.AccountList[Idx].Account.Info.AccountName, sm.Items, sm.id_pedido, false);
                if (recreatedItem)
                {
                    W2Log.Write(string.Format("Recreated DBSendItem: {0} - {1}/{2}", atual, sm.id_pedido, gs.AccountList[Idx].Account.Info.AccountName));
                }
            }

            if (sm.id_pedido == 344359 && sm.Result == 5)//Selo da alma enviado com sucesso
            {
                W2Log.Write(string.Format("Sucess send seal of soul: {0} - {1}", atual, sm.id_pedido));
            }



            return(DBResult.NO_ERROR);
        }
        /// <summary>
        /// Send a given game packet to the player.
        /// </summary>
        public void SendPacket <T>(T packet) where T : struct, IGamePacket
        {
            if (m_Stream.CanWrite)
            {
                byte[] rawPacket = W2Marshal.GetBytes(packet);

                PacketSecurity.Encrypt(rawPacket, 0);

                m_Stream.Write(rawPacket, 0, rawPacket.Length);

                W2Log.Write(String.Format("Packet 0x{0:X} were sent to the player (Index: {1}).", packet.Header.Opcode, Index), ELogType.NETWORK);
            }
        }
示例#10
0
        /// <summary>
        /// Send a given game packet to the GameServer.
        /// </summary>
        public void SendPacket <T>(T packet) where T : struct, DBSRVPackets
        {
            if (m_Stream.CanWrite)
            {
                byte[] rawPacket = W2Marshal.GetBytes(packet);

                PacketSecurity.Encrypt(rawPacket, 0);

                m_Stream.Write(rawPacket, 0, rawPacket.Length);

                W2Log.Write(String.Format("O pacote 0x{0:X} foi enviado para o GameServer(Index:{1}).", packet.Header.PacketID, Index), ELogType.NETWORK);
            }
        }
示例#11
0
        //Process Record (Cria o Record de Users online em X time)
        public static DBResult Exec_MSG_MessageDBRecord(DBController gs, pServer GameServer)
        {
            MSG_MessageDBRecord sm = W2Marshal.GetStructure <MSG_MessageDBRecord>(GameServer.RecvPacket.RawBuffer);
            bool ret = Functions.ProcessRecord(gs.PlayerCount, sm.Record);

            W2Log.Write(sm.Record);

            if (ret == false)
            {
                W2Log.Write("DBRecord Fail");
            }

            return(DBResult.NO_ERROR);
        }
示例#12
0
        //Process SaveMob (SaveUser)
        public static DBResult Exec_MSG_DBSaveMob(DBController gs, pServer GameServer)
        {
            _MSG_DBSaveMob sm = W2Marshal.GetStructure <_MSG_DBSaveMob>(GameServer.RecvPacket.RawBuffer);

            int Idx = gs.GetIndex(sm.Header.ClientId);

            int Slot = gs.AccountList[Idx].Slot;

            if (Slot < 0 || Slot >= 4)
            {
                W2Log.Write(String.Format("err,savemob1 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                return(DBResult.NO_ERROR);
            }

            if (Slot != sm.Slot)
            {
                W2Log.Write(String.Format("err,savemob2 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                //[19:52:28] err,savemob2 2 0 -1 wedbr123 wedbr123

                return(DBResult.NO_ERROR);
            }

            if (gs.AccountList[Idx].State == EServerStatus.CLOSED)
            {
                W2Log.Write(String.Format("err,savemob3 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                return(DBResult.NO_ERROR);
            }

            //


            gs.AccountList[Idx].Account.Donate         = sm.Donate;
            gs.AccountList[Idx].Account.Mob[Slot]      = sm.Mob;
            gs.AccountList[Idx].Account.MobExtra[Slot] = sm.Extra;
            gs.AccountList[Idx].Account.other          = sm.Other;

            gs.AccountList[Idx].Account.Affects[Slot].Affects = sm.Affects;

            gs.AccountList[Idx].Account.Cargo = sm.Cargo;
            gs.AccountList[Idx].Account.Skillbar[Slot].ShortSkill = sm.ShortSkill;
            gs.AccountList[Idx].Account.Coin = sm.Coin;


            gs.SaveAccount(sm.Header.ClientId);



            return(DBResult.NO_ERROR);
        }
示例#13
0
        public bool AddAccountList(int Idx)
        {
            if (AccountList[Idx].State != EServerStatus.CLOSED)
            {
                W2Log.Write(String.Format("err,addAccountlist - already added {0}/{1}", AccountList[Idx].Account.Info.AccountName, AccountList[Idx].State), ELogType.GAME_EVENT);
                return(false);
            }

            int conn = Idx / BaseDef.MAX_MAXUSER;

            AccountList[Idx].State = EServerStatus.WAITING_TO_LOGIN;
            AccountList[Idx].Slot  = -1;
            PlayerCount++;
            return(true);
        }
示例#14
0
        //Process SaveMob (CloseUser)
        public static DBResult Exec_MSG_SavingQuit(DBController gs, pServer GameServer)
        {
            _MSG_DBSaveMob sm = W2Marshal.GetStructure <_MSG_DBSaveMob>(GameServer.RecvPacket.RawBuffer);

            int Idx = gs.GetIndex(sm.Header.ClientId);


            int Slot = gs.AccountList[Idx].Slot;

            if (Slot < 0 || Slot >= 4)
            {
                W2Log.Write(String.Format("err,savenquit1 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                return(DBResult.NO_ERROR);
            }

            if (Slot != sm.Slot)
            {
                W2Log.Write(String.Format("err,savenquit2 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                return(DBResult.NO_ERROR);
            }

            if (gs.AccountList[Idx].State == EServerStatus.CLOSED)
            {
                W2Log.Write(String.Format("err,savenquit3 {0} {1} {2} {3} {4}", sm.Header.ClientId, Slot, sm.Slot, gs.AccountList[Idx].Account.Info.AccountName, sm.Accountname.Value));
                return(DBResult.NO_ERROR);
            }


            gs.AccountList[Idx].Account.Donate                    = sm.Donate;
            gs.AccountList[Idx].Account.Mob[Slot]                 = sm.Mob;
            gs.AccountList[Idx].Account.MobExtra[Slot]            = sm.Extra;
            gs.AccountList[Idx].Account.other                     = sm.Other;
            gs.AccountList[Idx].Account.Affects[Slot].Affects     = sm.Affects;
            gs.AccountList[Idx].Account.Cargo                     = sm.Cargo;
            gs.AccountList[Idx].Account.Skillbar[Slot].ShortSkill = sm.ShortSkill;
            gs.AccountList[Idx].Account.Coin = sm.Coin;


            if (gs.SaveAccount(sm.Header.ClientId))
            {
                W2Log.Write(String.Format("account logout: {0}/{1}", Idx, sm.Accountname.Value), ELogType.CRITICAL_ERROR);
                gs.RemoveAccountList(Idx);
                gs.Server.SendSignal(sm.Header.ClientId, BaseDef._MSG_DBCNFAccountLogOut);
                return(DBResult.NO_ERROR);
            }

            return(DBResult.NO_ERROR);
        }
示例#15
0
 public void saveConfig()
 {
     try
     {
         using (StreamWriter file = File.CreateText("config.json"))
         {
             string indented = JsonConvert.SerializeObject(Config, Formatting.Indented);
             file.Write(indented);
         }
     }
     catch (Exception e)
     {
         W2Log.Write("Erro ao salvar config.json");
         return;
     }
 }
示例#16
0
        /// <summary>
        /// Process the GameServer requests.
        /// This method fires the <see cref="OnProcessPacket"/> event to be hooked up by plugins.
        /// </summary>
        public DBResult ProcessPlayerRequest(pServer GameServer)
        {
            DBResult result = DBResult.NO_ERROR;

            foreach (DProcessPacket target in OnProcessPacket.GetInvocationList())
            {
                result = target(this, GameServer);

                if (result != DBResult.NO_ERROR && result != DBResult.PACKET_NOT_HANDLED && result != DBResult.WAIT)
                {
                    W2Log.Write("CRITICAL ERROR", ELogType.CRITICAL_ERROR);
                    break;
                }
            }
            return(result);
        }
示例#17
0
        //Pacote de Login (SelChar -> TMSRV -> ToWord)
        public static DBResult Exec_MSG_DBCharacterLogin2(DBController gs, pServer GameServer)
        {
            _MSG_DBCharacterLogin2 sm = W2Marshal.GetStructure <_MSG_DBCharacterLogin2>(GameServer.RecvPacket.RawBuffer);


            if (sm.Slot < 0 || sm.Slot >= 4)
            {
                W2Log.Write("err,charlogin slot illegal");
                return(DBResult.NO_ERROR);
            }

            int idx = gs.GetIndex(sm.Header.ClientId);

            gs.AccountList[idx].Slot = (short)sm.Slot;

            _MSG_CNFCharacterLogin ret = W2Marshal.CreatePacket <_MSG_CNFCharacterLogin>(BaseDef._MSG_CNFCharacterLogin, sm.Header.ClientId);

            STRUCT_ACCOUNTFILE File = gs.AccountList[idx].Account;

            if (String.IsNullOrEmpty(File.Info.AccountName))
            {
                W2Log.Write(String.Format("err,charlogin mobname {0} empty", File.Info.AccountName));

                return(DBResult.NO_ERROR);
            }



            ret.Slot = (short)sm.Slot;

            ret.Mob = File.Mob[sm.Slot];
            ret.Mob.CurrentScore = ret.Mob.BaseScore;


            ret.ShortSkill = File.Skillbar[sm.Slot].ShortSkill;



            ret.Affects = File.Affects[sm.Slot].Affects;

            ret.mobExtra = File.MobExtra[sm.Slot];

            ret.mobExtra.ClassMaster  = File.MobExtra[sm.Slot].ClassMaster;
            gs.AccountList[idx].State = EServerStatus.INGAME;
            GameServer.SendPacket(ret);
            return(DBResult.NO_ERROR);
        }
示例#18
0
        //Process Capsule (Envia o Selo da Alma para a TMSRV)
        public static DBResult Exec_MSG_DBCapsuleInfo(DBController gs, pServer GameServer)
        {
            _MSG_SIGNALPARM sm = W2Marshal.GetStructure <_MSG_SIGNALPARM>(GameServer.RecvPacket.RawBuffer);

            ConfigServer.ReadConfigFile(gs.Config);

            int Index = sm.parm;


            STRUCT_CAPSULE file = new STRUCT_CAPSULE();

            if (!Functions.ReadCapsule(Index, out file))
            {
                W2Log.Write($"Exec_MSG_DBCapsuleInfo error read capsule index: {Index}");
                return(DBResult.NO_ERROR);
            }

            MSG_CNFDBCapsuleInfo p = W2Marshal.CreatePacket <MSG_CNFDBCapsuleInfo>(BaseDef._MSG_CNFDBCapsuleInfo, sm.Header.ClientId);


            p.Index = Index;

            p.Capsule.Read        = 1;
            p.Capsule.MortalClass = file.Mob.Class;
            p.Capsule.ClassCele   = file.Extra.SaveCelestial.Class;
            p.Capsule.SubClass    = file.Mob.Class;
            p.Capsule.LevelCele   = file.Extra.SaveCelestial.BaseScore.Level;
            p.Capsule.LevelSub    = file.Mob.BaseScore.Level;

            p.Capsule.For = file.Mob.BaseScore.Str;
            p.Capsule.Int = file.Mob.BaseScore.Int;
            p.Capsule.Dex = file.Mob.BaseScore.Dex;
            p.Capsule.Con = file.Mob.BaseScore.Con;

            p.Capsule.ScoreBonus = file.Mob.ScoreBonus;
            p.Capsule.SkillPoint = file.Mob.SkillBonus;

            p.Capsule.ArchQuest      = file.Extra.Arch.Cristal;
            p.Capsule.CelestialQuest = file.Extra.Celestial.Reset;
            p.Capsule.ArcanaQuest    = file.Extra.Circle;


            gs.Server.SendPacket(p);

            W2Log.Write($"error read capsule index: {Index}");
            return(DBResult.NO_ERROR);
        }
示例#19
0
        //Process ItemLog (Log de itens, id e sua quantidade)
        public static DBResult Exec_MSG_DBItemDayLog(DBController gs, pServer GameServer)
        {
            _MSG_SIGNALPARM sm = W2Marshal.GetStructure <_MSG_SIGNALPARM>(GameServer.RecvPacket.RawBuffer);

            int item = sm.parm;

            if (item <= 0 || item >= BaseDef.MAX_ITEMLIST)
            {
                W2Log.Write($"err, itemid {item} invalid", ELogType.CRITICAL_ERROR);
                return(DBResult.NO_ERROR);
            }

            gs.ItemDayLog[item].Count++;
            gs.Config.ItemCount++;
            W2Log.SendUpdate();
            return(DBResult.NO_ERROR);
        }
示例#20
0
        /// <summary>
        /// Process the player requests.
        /// This method fires the <see cref="OnProcessPacket"/> event to be hooked up by plugins.
        /// </summary>
        public EPlayerRequestResult ProcessPlayerRequest(CPlayer player)
        {
            EPlayerRequestResult result = EPlayerRequestResult.NO_ERROR;

            foreach (DProcessPacket target in OnProcessPacket.GetInvocationList())
            {
                result = target(this, player);

                if (result != EPlayerRequestResult.NO_ERROR && result != EPlayerRequestResult.PACKET_NOT_HANDLED)
                {
                    W2Log.Write("eita", ELogType.CRITICAL_ERROR);
                    break;
                }
            }

            return(result);
        }
示例#21
0
 public bool ReadAccount(string Accountname, out STRUCT_ACCOUNTFILE CurrentAccount)
 {
     CurrentAccount = new STRUCT_ACCOUNTFILE();
     try
     {
         string correctPatch = Functions.getCorrectPath(Accountname);
         using (StreamReader r = new StreamReader(correctPatch + ".json"))
         {
             string json = r.ReadToEnd();
             CurrentAccount = JsonConvert.DeserializeObject <STRUCT_ACCOUNTFILE>(json);
         }
         return(true);
     }
     catch (Exception e)
     {
         W2Log.Write(e.Message);
         return(false);
     }
 }
示例#22
0
        //Process GuildAlly (Requisição de Aliança)
        public static DBResult Exec_MSG_GuildAlly(DBController gs, pServer GameServer)
        {
            _MSG_SIGNALPARM2 sm = W2Marshal.GetStructure <_MSG_SIGNALPARM2>(GameServer.RecvPacket.RawBuffer);

            int myguild = sm.parm;

            if (myguild <= 0 || myguild >= 5000)
            {
                W2Log.Write($"Guild out or range {myguild}", ELogType.CRITICAL_ERROR);
                return(DBResult.NO_ERROR);
            }

            W2Log.Write($"guild ally request { sm.parm}, { sm.parm2} ");

            gs.g_pGuildAlly[myguild] = (short)sm.parm2;

            gs.Server.SendSignalParm(0, BaseDef._MSG_GuildAlly, sm.parm, sm.parm2);

            return(DBResult.NO_ERROR);
        }
示例#23
0
        public bool SaveAccount(STRUCT_ACCOUNTFILE accfile)
        {
            try
            {
                string CorrectPatch = Functions.getCorrectPath(accfile.Info.AccountName);
                using (StreamWriter file = File.CreateText(CorrectPatch + ".json"))
                {
                    string indented = JsonConvert.SerializeObject(accfile, Formatting.Indented);
                    file.Write(indented);
                }

                W2Log.Write(String.Format("save account sucess: {0}", accfile.Info.AccountName), ELogType.GAME_EVENT);
                return(true);
            }
            catch (Exception e)
            {
                W2Log.Write(String.Format("save account fail: {0}/{1}", accfile.Info.AccountName, e.Message), ELogType.GAME_EVENT);
                return(false);
            }
        }
示例#24
0
        static public bool UpdateUser(DBController gs, string Login, string Senha)
        {
            STRUCT_ACCOUNTFILE target = new STRUCT_ACCOUNTFILE();

            if (!gs.ReadAccount(Login, out target))
            {
                W2Log.Write(String.Format("fail to read account file {0}", Login), ELogType.GAME_EVENT);
                return(false);
            }

            if (0 != String.Compare(target.Info.AccountName, Login))
            {
                W2Log.Write(String.Format("fail to read account file {0}/{1}", Login, target.Info.AccountName), ELogType.GAME_EVENT);
                return(false);
            }
            // W2Log.Write(String.Format("pass teste file {0}/{1}", target.Info.AccountPass, Senha), ELogType.GAME_EVENT);
            target.Info.AccountPass = Senha;

            try
            {
                string CorrectPatch = Functions.getCorrectPath(target.Info.AccountName);
                using (StreamWriter file = File.CreateText(CorrectPatch + ".json"))
                {
                    string indented = JsonConvert.SerializeObject(target, Formatting.Indented);
                    file.Write(indented);
                }

                W2Log.Write(String.Format("save account sucess: {0}", target.Info.AccountName), ELogType.GAME_EVENT);
                return(true);
            }
            catch (Exception e)
            {
                W2Log.Write(String.Format("save account fail: {0}/{1}", target.Info.AccountName, e.Message), ELogType.GAME_EVENT);
                return(false);
            }
        }
示例#25
0
        static public void Start(DBController gs)
        {
            foreach (string file in Directory.EnumerateFiles("./npc/"))
            {
                using (StreamReader sr = new StreamReader(file))
                {
                    try
                    {
                        STRUCT_MOB CurrentMob = Functions.ReadAccount <STRUCT_MOB>(file);
                        string     indented   = JsonConvert.SerializeObject(CurrentMob, Formatting.Indented);

                        int update = gs.MySQL.nQuery(string.Format("INSERT INTO `mobs_json` (`nome`, `conteudo`) VALUES ('{0}', '{1}') ON DUPLICATE KEY UPDATE `nome` = '{2}' ", CurrentMob.Name, indented, CurrentMob.Name));
                        if (update != 0)
                        {
                            W2Log.Write(string.Format("Sucess update drops: {0}", file));
                        }
                    }
                    catch (Exception e)
                    {
                        return;
                    }
                }
            }
        }
示例#26
0
 public bool CreateChar(string CharName, string AccountName)
 {
     try
     {
         string path = Functions.getCorrectCharPath(CharName);
         if (File.Exists(path))
         {
             return(false);
         }
         else
         {
             using (StreamWriter sw = File.CreateText(path))
             {
                 sw.WriteLine(AccountName.ToLower());
             }
             return(true);
         }
     }
     catch (Exception e)
     {
         W2Log.Write(e.Message);
         return(false);
     }
 }
示例#27
0
        /// <summary>
        /// Start listenning the server connection.
        /// </summary>
        private async void StartServer_Channel1()
        {
            TcpListener listener = new TcpListener(IPAddress.Parse(Config.IPAddrs), Config.Port);

            listener.Start();

            W2Log.Write($"DBserver iniciado com IP: {listener.Server.LocalEndPoint}.", ELogType.NETWORK);

            try
            {
                while (true)
                {
                    TcpClient thisClient = await listener.AcceptTcpClientAsync();

                    W2Log.Write($"Nova gameserver conectada: {thisClient.Client.RemoteEndPoint}.", ELogType.NETWORK);

                    ProcessClient_Channel1(thisClient);
                }
            }
            finally
            {
                listener.Stop();
            }
        }
        /// <summary>
        /// Start listenning the server connection.
        /// </summary>
        private async void StartServer_Channel1()
        {
            TcpListener listener = new TcpListener(IPAddress.Parse("192.168.1.69"), 8281);

            listener.Start();

            W2Log.Write($"The Game Server is listenning at {listener.Server.LocalEndPoint}.", ELogType.NETWORK);

            try
            {
                while (true)
                {
                    TcpClient thisClient = await listener.AcceptTcpClientAsync();

                    W2Log.Write($"New client connected {thisClient.Client.RemoteEndPoint}.", ELogType.NETWORK);

                    ProcessClient_Channel1(thisClient);
                }
            }
            finally
            {
                listener.Stop();
            }
        }
示例#29
0
        /// <summary>
        /// Process the newly connected client.
        /// </summary>
        /// <param name="client">The newly connected client.</param>
        private async void ProcessClient_Channel1(TcpClient client)
        {
            using (client)
                using (NetworkStream stream = client.GetStream())
                {
                    pServer         GameServer = new pServer(stream);
                    CCompoundBuffer packet     = GameServer.RecvPacket;

                    try
                    {
                        // Iterate processing incoming GameServer packets until he disconnects.
                        while (GameServer.State != EServerStatus.CLOSED)
                        {
                            int readCount = 0;

                            try
                            {
                                readCount = await stream.ReadAsync(packet.RawBuffer, 0, BaseDef.MAXL_PACKET);
                            }
                            catch (Exception e)
                            {
                                break;
                            }

                            if (readCount != 4 && (readCount < 12 || readCount > BaseDef.MAXL_PACKET)) // Invalid game packet.
                            {
                                // gameController.DisconnectPlayer(GameServer);
                                break;
                            }
                            else // Possible valid game packet chunk.
                            {
                                unsafe
                                {
                                    packet.Offset = 0;
                                    fixed(byte *PinnedPacketChunk = &packet.RawBuffer[packet.Offset])
                                    {
                                        // Check for the init code.
                                        if (*(uint *)&PinnedPacketChunk[packet.Offset] == BaseDef.INIT_CODE)
                                        {
                                            packet.Offset = 4;

                                            // If a valid index can't be assigned to the GameServer, disconnect him
                                            if (!gameController.TryInsertPlayer(GameServer))
                                            {
                                                GameServer.SendPacket(MTextMessagePacket.Create("O servidor está lotado. Tente novamente mais tarde."));
                                                // gameController.DisconnectPlayer(GameServer);
                                                continue;
                                            }

                                            // If all the received chunk resumes to the INIT_CODE, read the next packet.
                                            if (readCount == 4)
                                            {
                                                continue;
                                            }
                                        }

                                        // Process all possible packets that were possibly sent together.
                                        while (packet.Offset < readCount && GameServer.State != EServerStatus.CLOSED)
                                        {
                                            // Check if the game packet size is bigger than the remaining received chunk.
                                            if (packet.ReadNextUShort(0) > readCount - packet.Offset || packet.ReadNextUShort(0) < 12)
                                            {
                                                throw new Exception("Pacote recebido inválido.O pacote de leitura é maior que o restante do pacote.");
                                                //continue;
                                            }

                                            // Tries to decrypt the packet.
                                            if (!PacketSecurity.Decrypt(packet))
                                            {
                                                throw new Exception($"Não é possível descriptografar um pacote recebido de {client.Client.RemoteEndPoint}.");
                                            }

                                            // W2Log.Write(String.Format("Em processamento recv packet {{0x{0:X}/{1}}} a partir de {2}.", packet.ReadNextUShort(4), packet.ReadNextUShort(0), client.Client.RemoteEndPoint), ELogType.NETWORK);

                                            // Process the incoming packet.
                                            DBResult requestResult = gameController.ProcessPlayerRequest(GameServer);

                                            // Treat the processing packet return.
                                            switch (requestResult)
                                            {
                                            //case DBResult.PACKET_NOT_HANDLED:
                                            //{
                                            //    W2Log.Write(String.Format("Recv packet {{0x{0:X}/{1}}} de {2} não foi processado.",
                                            //        packet.ReadNextUShort(4), packet.ReadNextUShort(0), client.Client.RemoteEndPoint), ELogType.NETWORK);

                                            //    byte[] rawPacket = new byte[packet.ReadNextUShort(0)];
                                            //    for (int i = 0; i < rawPacket.Length; i++)
                                            //        rawPacket[i] = PinnedPacketChunk[i + packet.Offset];

                                            //    File.WriteAllBytes($@"..\..\{packet.ReadNextUShort(4)}.bin",
                                            //        rawPacket);
                                            //    break;
                                            //}

                                            case DBResult.CHECKSUM_FAIL:
                                            {
                                                W2Log.Write($"Recibo de pacote de { client.Client.RemoteEndPoint} tem soma de verificação inválida.", ELogType.CRITICAL_ERROR);
                                                //gameController.DisconnectPlayer(GameServer);
                                                break;
                                            }

                                            case DBResult.PLAYER_INCONSISTENT_STATE:
                                            {
                                                W2Log.Write($"Um GameServer foi desconectado devido ao DBResult inconsistente.", ELogType.CRITICAL_ERROR);
                                                //gameController.DisconnectPlayer(GameServer);
                                                break;
                                            }

                                            case DBResult.WAIT:
                                            {
                                                break;
                                            }
                                            }

                                            // Correct the offset to process the next packet in the received chunk.
                                            PlayersCount.Text             = gameController.PlayerCount.ToString();
                                            GameServer.RecvPacket.Offset += packet.ReadNextUShort(0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        W2Log.Write($"Uma exceção não tratada aconteceu processando o GameServer {GameServer.Index}. MSG: {ex.Message}", ELogType.CRITICAL_ERROR);
                    }
                    finally
                    {
                        // gameController.DisconnectPlayer(GameServer);
                    }
                }
        }
        /// <summary>
        /// Process the newly connected client.
        /// </summary>
        /// <param name="client">The newly connected client.</param>
        private async void ProcessClient_Channel1(TcpClient client)
        {
            using (client)
                using (NetworkStream stream = client.GetStream())
                {
                    CPlayer         player = new CPlayer(stream);
                    CCompoundBuffer packet = player.RecvPacket;

                    try
                    {
                        // Iterate processing incoming player packets until he disconnects.
                        while (player.State != EPlayerState.CLOSED)
                        {
                            int readCount = await stream.ReadAsync(packet.RawBuffer, 0, NetworkBasics.MAXL_PACKET);

                            if (readCount != 4 && (readCount < 12 || readCount > NetworkBasics.MAXL_PACKET)) // Invalid game packet.
                            {
                                gameController.DisconnectPlayer(player);
                                break;
                            }
                            else // Possible valid game packet chunk.
                            {
                                unsafe
                                {
                                    packet.Offset = 0;
                                    fixed(byte *PinnedPacketChunk = &packet.RawBuffer[packet.Offset])
                                    {
                                        // Check for the init code.
                                        if (*(uint *)&PinnedPacketChunk[packet.Offset] == NetworkBasics.INIT_CODE)
                                        {
                                            packet.Offset = 4;

                                            // If a valid index can't be assigned to the player, disconnect him
                                            if (!gameController.TryInsertPlayer(player))
                                            {
                                                player.SendPacket(MTextMessagePacket.Create("O servidor está lotado. Tente novamente mais tarde."));
                                                gameController.DisconnectPlayer(player);
                                                continue;
                                            }

                                            // If all the received chunk resumes to the INIT_CODE, read the next packet.
                                            if (readCount == 4)
                                            {
                                                continue;
                                            }
                                        }

                                        // Process all possible packets that were possibly sent together.
                                        while (packet.Offset < readCount && player.State != EPlayerState.CLOSED)
                                        {
                                            // Check if the game packet size is bigger than the remaining received chunk.
                                            if (packet.ReadNextUShort(0) > readCount - packet.Offset || packet.ReadNextUShort(0) < 12)
                                            {
                                                throw new Exception("Invalid received packet. Reading packet is bigger than the remaining chunk.");
                                            }

                                            // Tries to decrypt the packet.
                                            if (!PacketSecurity.Decrypt(packet))
                                            {
                                                throw new Exception($"Can't decrypt a packet received from {client.Client.RemoteEndPoint}.");
                                            }

                                            W2Log.Write(String.Format("Processing recv packet {{0x{0:X}/{1}}} from {2}.",
                                                                      packet.ReadNextUShort(4), packet.ReadNextUShort(0), client.Client.RemoteEndPoint), ELogType.NETWORK);

                                            // Process the incoming packet.
                                            EPlayerRequestResult requestResult = gameController.ProcessPlayerRequest(player);

                                            // Treat the processing packet return.
                                            switch (requestResult)
                                            {
                                            case EPlayerRequestResult.PACKET_NOT_HANDLED:
                                            {
                                                W2Log.Write(String.Format("Recv packet {{0x{0:X}/{1}}} from {2} didn't was processed.",
                                                                          packet.ReadNextUShort(4), packet.ReadNextUShort(0), client.Client.RemoteEndPoint), ELogType.NETWORK);

                                                byte[] rawPacket = new byte[packet.ReadNextUShort(0)];
                                                for (int i = 0; i < rawPacket.Length; i++)
                                                {
                                                    rawPacket[i] = PinnedPacketChunk[i + packet.Offset];
                                                }

                                                File.WriteAllBytes($@"..\..\Dumped Packets\Inner Packets\{packet.ReadNextUShort(4)}.bin",
                                                                   rawPacket);
                                                break;
                                            }

                                            case EPlayerRequestResult.CHECKSUM_FAIL:
                                            {
                                                W2Log.Write($"Recv packet from {client.Client.RemoteEndPoint} have invalid checksum.", ELogType.CRITICAL_ERROR);
                                                gameController.DisconnectPlayer(player);
                                                break;
                                            }

                                            case EPlayerRequestResult.PLAYER_INCONSISTENT_STATE:
                                            {
                                                W2Log.Write($"A player was disconnected due to inconsistent PlayerState.", ELogType.CRITICAL_ERROR);
                                                gameController.DisconnectPlayer(player);
                                                break;
                                            }
                                            }

                                            // Correct the offset to process the next packet in the received chunk.
                                            player.RecvPacket.Offset += packet.ReadNextUShort(0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        W2Log.Write($"An unhandled exception happened processing the player {player.Index}. MSG: {ex.Message}", ELogType.CRITICAL_ERROR);
                    }
                    finally
                    {
                        gameController.DisconnectPlayer(player);
                    }
                }
        }