Esempio n. 1
0
 public virtual void AddPacketInfo(Packet packet)
 {
     packet.AddUInt32(Id);
     packet.AddByte((byte)ClassType);
     packet.AddUInt16(Type);
     packet.AddByte(Lvl);
     packet.AddFloat((float)Hp);
     packet.AddFloat((float)Stats.MaxHp);
     packet.AddUInt16(Count);
 }
Esempio n. 2
0
        private void GetCityHasApBonus(Session session, Packet packet)
        {
            ICity city;

            uint cityId;

            try
            {
                cityId = packet.GetUInt32();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            locker.Lock(cityId, out city).Do(() =>
            {
                if (city == null)
                {
                    ReplyError(session, packet, Error.ObjectNotFound);
                    return;
                }

                var reply = new Packet(packet);
                reply.AddByte((byte)(city.AlignmentPoint >= 75m ? 1 : 0));

                session.Write(reply);
            });
        }
Esempio n. 3
0
        public bool AccountCreate(string uName, string pass, string realName, string location, string email, string HDDSerial, out AccountReply result)
        {
            result = AccountReply.THIS_IS_WRONG;
            if (!m_client.ConnectedAndInitialized || !Initialized)
                return false;

            Packet builder = new Packet(PacketFamily.Account, PacketAction.Create);
            //eoserv doesn't care...
            builder.AddShort(1337);
            builder.AddByte(42);

            builder.AddBreakString(uName);
            builder.AddBreakString(pass);
            builder.AddBreakString(realName);
            builder.AddBreakString(location);
            builder.AddBreakString(email);
            builder.AddBreakString(System.Net.Dns.GetHostName());
            builder.AddBreakString(HDDSerial);

            if (!m_client.SendPacket(builder) || !m_account_responseEvent.WaitOne(Constants.ResponseTimeout))
                return false;

            result = m_account_reply;

            return true;
        }
Esempio n. 4
0
        private void ListAll(Session session, Packet packet)
        {
            locker.Lock(session.Player).Do(() =>
            {
                if (!session.Player.IsInTribe)
                {
                    ReplyError(session, packet, Error.TribesmanNotPartOfTribe);
                    return;
                }

                var reply       = new Packet(packet);
                var strongholds = strongholdManager.StrongholdsForTribe(session.Player.Tribesman.Tribe).ToList();
                reply.AddInt16((short)strongholds.Count);
                foreach (var stronghold in strongholds)
                {
                    reply.AddUInt32(stronghold.ObjectId);
                    reply.AddString(stronghold.Name);
                    reply.AddByte(stronghold.Lvl);
                    reply.AddUInt32(stronghold.PrimaryPosition.X);
                    reply.AddUInt32(stronghold.PrimaryPosition.Y);
                }

                session.Write(reply);
            });
        }
Esempio n. 5
0
        private static void Run()
        {
            socketAwaitablePool   = new SocketAwaitablePool(50);
            blockingBufferManager = new BlockingBufferManager(1000, 50);

            while (true)
            {
                try
                {
                    var policySession = Connect();

                    policySession.SendAsyncImmediatelly(Encoding.UTF8.GetBytes("<policy-file-request/>\n")).Wait();

                    var newSession = Connect();

                    var loginPacket = new Packet(Command.Login);
                    loginPacket.AddInt16(0); // version
                    loginPacket.AddInt16(0); // revision
                    loginPacket.AddByte(0);
                    loginPacket.AddString("1234");
                    loginPacket.AddString("");
                    newSession.SendAsyncImmediatelly(loginPacket.GetBytes()).Wait();

                    policySession.Socket.Shutdown(SocketShutdown.Both);
                    policySession.Socket.Close();

                    newSession.Socket.Shutdown(SocketShutdown.Both);
                    newSession.Socket.Close();
                }
                catch (Exception) { }
            }
        }
Esempio n. 6
0
        public void SendChat(string channelName,
                             ChatType type,
                             uint playerId,
                             string playerName,
                             IDictionary <AchievementTier, byte> achievements,
                             bool distinguish,
                             string message)
        {
            logger.Info("[{0} {1}] {3} {2}:{4}", SystemClock.Now, channel, playerName, playerId, message);

            byte goldAchievements;

            achievements.TryGetValue(AchievementTier.Gold, out goldAchievements);

            byte silverAchievements;

            achievements.TryGetValue(AchievementTier.Silver, out silverAchievements);

            byte bronzeAchievements;

            achievements.TryGetValue(AchievementTier.Bronze, out bronzeAchievements);

            var chatPacket = new Packet(Command.Chat);

            chatPacket.AddByte((byte)type);
            chatPacket.AddByte(goldAchievements);
            chatPacket.AddByte(silverAchievements);
            chatPacket.AddByte(bronzeAchievements);
            chatPacket.AddByte((byte)(distinguish ? 1 : 0));
            chatPacket.AddUInt32(playerId);
            chatPacket.AddString(playerName);
            chatPacket.AddString(message);

            if (logger.IsDebugEnabled)
            {
                logger.Debug("Sending chat to {0} players", channel.SubscriberCount(channelName));
            }

            channel.Post(channelName, chatPacket);
        }
Esempio n. 7
0
        public void SendSystemChat(string messageId, params string[] messageArgs)
        {
            Packet chatPacket = new Packet(Command.SystemChat);

            chatPacket.AddString(messageId);
            chatPacket.AddByte((byte)messageArgs.Length);
            foreach (var messageArg in messageArgs)
            {
                chatPacket.AddString(messageArg);
            }

            channel.Post("/GLOBAL", chatPacket);
        }
Esempio n. 8
0
        public void TribeUpdate()
        {
            if (!Global.Current.FireEvents)
            {
                return;
            }

            var packet = new Packet(Command.TribeChannelUpdate);

            packet.AddUInt32(Tribesman == null ? 0 : Tribesman.Tribe.Id);
            packet.AddUInt32(TribeRequest);
            packet.AddByte((byte)(Tribesman == null ? 0 : tribesman.Rank.Id));

            channel.Post(PlayerChannel, packet);
        }
Esempio n. 9
0
        private void HideNewUnitsUpdate(ICity city)
        {
            if (!ShouldUpdate(city))
            {
                return;
            }

            channel.Post(GetChannelName(city), () =>
            {
                var packet = new Packet(Command.CityHideNewUnitsUpdate);
                packet.AddUInt32(city.Id);
                packet.AddByte(city.HideNewUnits ? (byte)1 : (byte)0);
                return(packet);
            });
        }
Esempio n. 10
0
        private void TechnologiesTechnologyAdded(ICity city, TechnologyEventArgs args)
        {
            if (!ShouldUpdate(city))
            {
                return;
            }

            channel.Post(GetChannelName(city), () =>
            {
                var packet = new Packet(Command.TechAdded);
                packet.AddUInt32(city.Id);
                packet.AddUInt32(args.Technology.OwnerLocation == EffectLocation.City ? 0 : args.Technology.OwnerId);
                packet.AddUInt32(args.Technology.Type);
                packet.AddByte(args.Technology.Level);
                return(packet);
            });
        }
Esempio n. 11
0
        private void RadiusUpdateEvent(ICity city)
        {
            if (!ShouldUpdate(city))
            {
                return;
            }

            regionManager.UpdateObject(city.MainBuilding, city.MainBuilding.PrimaryPosition.X, city.MainBuilding.PrimaryPosition.Y);

            channel.Post(GetChannelName(city), () =>
            {
                var packet = new Packet(Command.CityRadiusUpdate);
                packet.AddUInt32(city.Id);
                packet.AddByte(city.Radius);
                return(packet);
            });
        }
Esempio n. 12
0
        public void SendSystemChat(IChannelListener session, string messageId, params string[] messageArgs)
        {
            if (session == null)
            {
                return;
            }

            Packet chatPacket = new Packet(Command.SystemChat);

            chatPacket.AddString(messageId);
            chatPacket.AddByte((byte)messageArgs.Length);
            foreach (var messageArg in messageArgs)
            {
                chatPacket.AddString(messageArg);
            }

            session.OnPost(chatPacket);
        }
Esempio n. 13
0
        private void GetMiniMapRegion(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            byte regionSubscribeCount;

            try
            {
                regionSubscribeCount = packet.GetByte();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(regionSubscribeCount);

            for (uint i = 0; i < regionSubscribeCount; ++i)
            {
                ushort regionId;
                try
                {
                    regionId = packet.GetUInt16();
                }
                catch (Exception)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                MiniMapRegion region;
                if (!world.Regions.MiniMapRegions.TryGetMiniMapRegion(regionId, out region))
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt16(regionId);
                reply.AddBytes(region.GetCityBytes());
            }

            session.Write(reply);
        }
Esempio n. 14
0
        private void UpdateClients()
        {
            try
            {
                while (!this.ResetEvent.Wait(200))
                {
                    try
                    {
                        var descriptors = this.ConnectedClients.ToArray();
                        if (descriptors.Length == 0)
                        {
                            continue;
                        }
                        Packet           p       = new Packet();
                        List <TcpClient> sockets = new List <TcpClient>();

                        p.AddUInt16((ushort)descriptors.Length);
                        foreach (ClientDescriptor descriptor in descriptors)
                        {
                            sockets.Add(descriptor.TcpClient);
                            p.AddString(descriptor.PlayerName);
                            p.AddUInt32(descriptor.PlayerID);
                            p.AddUInt16(descriptor.PlayerLevel);
                            p.AddUInt16((ushort)descriptor.Location.X);
                            p.AddUInt16((ushort)descriptor.Location.Y);
                            p.AddByte((byte)descriptor.Location.Z);
                        }
                        p.AddLength();
                        foreach (TcpClient tc in sockets)
                        {
                            if (!tc.Connected)
                            {
                                continue;
                            }
                            p.Send(tc);
                        }
                    }
                    catch { }
                }
            }
            catch { }
        }
Esempio n. 15
0
        private void GetName(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            byte count;

            uint[] strongholdIds;
            try
            {
                count         = packet.GetByte();
                strongholdIds = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    strongholdIds[i] = packet.GetUInt32();
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(count);

            for (int i = 0; i < count; i++)
            {
                uint        strongholdId = strongholdIds[i];
                IStronghold stronghold;
                if (!strongholdManager.TryGetStronghold(strongholdIds[i], out stronghold))
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt32(strongholdId);
                reply.AddString(stronghold.Name);
            }

            session.Write(reply);
        }
Esempio n. 16
0
        private void GetName(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            byte count;

            uint[] tribeIds;
            try
            {
                count    = packet.GetByte();
                tribeIds = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    tribeIds[i] = packet.GetUInt32();
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(count);
            for (int i = 0; i < count; i++)
            {
                uint   tribeId = tribeIds[i];
                ITribe tribe;

                if (!world.TryGetObjects(tribeId, out tribe))
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt32(tribeId);
                reply.AddString(tribe.Name);
            }

            session.Write(reply);
        }
Esempio n. 17
0
        private void GetCityUsername(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            byte count;

            uint[] cityIds;
            try
            {
                count   = packet.GetByte();
                cityIds = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    cityIds[i] = packet.GetUInt32();
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(count);
            for (int i = 0; i < count; i++)
            {
                uint  cityId = cityIds[i];
                ICity city;

                if (!world.TryGetObjects(cityId, out city))
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt32(cityId);
                reply.AddString(city.Name);
            }

            session.Write(reply);
        }
Esempio n. 18
0
        private void GetUsername(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            byte count;

            uint[] playerIds;
            try
            {
                count     = packet.GetByte();
                playerIds = new uint[count];
                for (int i = 0; i < count; i++)
                {
                    playerIds[i] = packet.GetUInt32();
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(count);
            foreach (var playerId in playerIds)
            {
                IPlayer player;
                if (!world.Players.TryGetValue(playerId, out player))
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt32(player.PlayerId);
                reply.AddString(player.Name);
            }

            session.Write(reply);
        }
Esempio n. 19
0
        private void Login(Session session, Packet packet)
        {
            IPlayer player;

            short            clientVersion;
            short            clientRevision;
            LoginHandlerMode loginMode;
            string           playerName;
            string           loginKey;

            try
            {
                clientVersion  = packet.GetInt16();
                clientRevision = packet.GetInt16();
                loginMode      = (LoginHandlerMode)packet.GetByte();
                playerName     = packet.GetString();
                loginKey       = packet.GetString();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                session.CloseSession();
                return;
            }

            if (clientVersion <= Config.client_min_version && clientRevision < Config.client_min_revision)
            {
                ReplyError(session, packet, Error.ClientOldVersion);
                session.CloseSession();
                return;
            }

            LoginResponseData loginResponseData;
            var loginResult = loginHandler.Login(loginMode, playerName, loginKey, out loginResponseData);

            if (loginResult != Error.Ok)
            {
                ReplyError(session, packet, loginResult);
                session.CloseSession();
                return;
            }

            // If we are under admin only mode then kick out non admin
            if (Config.server_admin_only && loginResponseData.Player.Rights == PlayerRights.Basic)
            {
                ReplyError(session, packet, Error.UnderMaintenance);
                session.CloseSession();
                return;
            }

            //Create the session id that will be used for the calls to the web server
            string sessionId;

            if (Config.server_admin_always && !Config.server_production)
            {
                sessionId = loginResponseData.Player.Id.ToString(CultureInfo.InvariantCulture);
                loginResponseData.Player.Rights = PlayerRights.Bureaucrat;
            }
            else
            {
                SHA1   sha  = new SHA1CryptoServiceProvider();
                byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(loginResponseData.Player.Id + Config.database_salt + DateTime.UtcNow.Ticks + Config.Random.Next()));
                sessionId = BitConverter.ToString(hash).Replace("-", String.Empty);
            }

            lock (loginLock)
            {
                bool newPlayer = !world.Players.TryGetValue(loginResponseData.Player.Id, out player);

                //If it's a new player then add him to our session
                if (newPlayer)
                {
                    logger.Info(string.Format("Creating new player {0}({1}) IP: {2}", playerName, loginResponseData.Player.Id, session.RemoteIP));

                    player = playerFactory.CreatePlayer(loginResponseData.Player.Id, SystemClock.Now, SystemClock.Now, playerName, string.Empty, loginResponseData.Player.Rights, sessionId);

                    if (!world.Players.TryAdd(player.PlayerId, player))
                    {
                        session.CloseSession();
                        return;
                    }
                }
                else
                {
                    player.Name = playerName;
                }

                logger.Info(string.Format("Player login in {0}({1}) IP: {2}", player.Name, player.PlayerId, session.RemoteIP));
            }

            locker.Lock(args =>
            {
                var lockedPlayer = (IPlayer)args[0];
                return(lockedPlayer.IsInTribe ? new ILockable[] { lockedPlayer.Tribesman.Tribe } : new ILockable[0]);
            }, new object[] { player }, player).Do(() =>
            {
                // If someone is already connected as this player, kick them off potentially
                if (player.Session != null)
                {
                    player.Session.CloseSession();
                    player.Session = null;

                    // Kick people off who are spamming logins
                    if (SystemClock.Now.Subtract(player.LastLogin).TotalMilliseconds < 1500)
                    {
                        session.CloseSession();
                        return;
                    }
                }

                // Setup session references
                session.Player = player;
                player.HasTwoFactorAuthenticated = null;
                player.TwoFactorSecretKey        = loginResponseData.Player.TwoFactorSecretKey;
                player.Session   = session;
                player.SessionId = sessionId;
                player.Rights    = loginResponseData.Player.Rights;
                player.LastLogin = SystemClock.Now;
                player.Banned    = loginResponseData.Player.Banned;
                player.Achievements.Clear();
                player.Achievements.AddRange(loginResponseData.Achievements);
                player.ThemePurchases.Clear();
                player.ThemePurchases.AddRange(loginResponseData.ThemePurchases);

                dbManager.Save(player);

                // If player was banned then kick his ass out
                if (loginResponseData.Player.Banned)
                {
                    ReplyError(session, packet, Error.Banned);
                    session.CloseSession();
                    return;
                }

                var reply     = new Packet(packet);
                reply.Option |= (ushort)Packet.Options.Compressed;

                reply.AddString(Config.welcome_motd);

                //Player Info
                reply.AddUInt32(player.PlayerId);
                reply.AddString(player.PlayerHash);
                reply.AddUInt32(player.TutorialStep);
                reply.AddBoolean(player.SoundMuted);
                reply.AddBoolean(player.Rights >= PlayerRights.Admin);
                reply.AddString(sessionId);
                reply.AddString(player.Name);
                reply.AddInt32(Config.newbie_protection);
                reply.AddInt32(loginResponseData.Player.Balance);
                reply.AddUInt32(UnixDateTime.DateTimeToUnix(player.Created.ToUniversalTime()));
                reply.AddInt32(player.Tribesman == null
                                       ? 0
                                       : tribeManager.GetIncomingList(player.Tribesman.Tribe).Count());
                reply.AddInt16((short)(player.Tribesman == null ? 0 : player.Tribesman.Tribe.AssignmentCount));

                //Server time
                reply.AddUInt32(UnixDateTime.DateTimeToUnix(DateTime.UtcNow.ToUniversalTime()));

                //Server rate
                reply.AddString(Config.seconds_per_unit.ToString(CultureInfo.InvariantCulture));

                // If it's a new player we send simply a 1 which means the client will need to send back a city name
                // Otherwise, we just send the whole login info
                if (player.GetCityCount() == 0)
                {
                    reply.AddByte(1);
                }
                else
                {
                    reply.AddByte(0);
                    PacketHelper.AddLoginToPacket(session, themeManager, reply);
                    SubscribeDefaultChannels(session, session.Player);
                }

                session.Write(reply);

                // Restart any city actions that may have been stopped due to inactivity
                foreach (var city in player.GetCityList()
                         .Where(city => city.Worker.PassiveActions.Values.All(x => x.Type != ActionType.CityPassive)))
                {
                    city.Worker.DoPassive(city, actionFactory.CreateCityPassiveAction(city.Id), false);
                }
            });
        }
Esempio n. 20
0
        public bool CharacterCreate(byte gender, byte hairStyle, byte hairColor, byte race, string name, out CharacterReply reply, out CharacterRenderData[] data)
        {
            data = null;
            reply = CharacterReply.THIS_IS_WRONG;
            if (!m_client.ConnectedAndInitialized || !Initialized)
                return false;

            Packet builder = new Packet(PacketFamily.Character, PacketAction.Create);
            builder.AddShort(255);
            builder.AddShort(gender);
            builder.AddShort(hairStyle);
            builder.AddShort(hairColor);
            builder.AddShort(race);
            builder.AddByte(255);
            builder.AddBreakString(name);

            if (!m_client.SendPacket(builder) || !m_character_responseEvent.WaitOne(Constants.ResponseTimeout))
                return false;

            reply = m_character_reply;

            if (reply == CharacterReply.THIS_IS_WRONG || m_character_data == null || m_character_data.Length == 0)
                return false;

            data = m_character_data;

            return true;
        }
Esempio n. 21
0
        public static void HandleRemove(Packet packet, IClient client, bool fromQueue)
        {
            /*short deleteId = */packet.GetShort();
            int id = packet.GetShort();

            if (id < 0 || id > client.Account.Characters.Count)
                throw new ArgumentOutOfRangeException("Login character ID out of range");

            Character deleteMe = client.Account.Characters[id];
            client.Account.Characters.Remove(deleteMe);
            deleteMe.Delete();
            client.Account.Store();
            client.Server.Database.Commit();

            Packet reply = new Packet(PacketFamily.Character, PacketAction.Reply);
            reply.AddShort((short)CharacterReply.Deleted);
            reply.AddChar((byte)client.Account.Characters.Count);
            reply.AddByte(1); // TODO: What is this?
            reply.AddBreak();

            // TODO: Some kind of character list packet builder
            int i = 0;
            foreach (Character character in client.Account.Characters)
            {
                reply.AddBreakString(character.Name);
                reply.AddInt(i++);
                reply.AddChar(character.Level);
                reply.AddChar((byte)character.Gender);
                reply.AddChar(character.HairStyle);
                reply.AddChar(character.HairColor);
                reply.AddChar((byte)character.Skin);
                reply.AddChar((byte)character.Admin);
                reply.AddShort((short)(character.Boots  != null ? character.Boots.Data.special1  : 0));
                reply.AddShort((short)(character.Armor  != null ? character.Armor.Data.special1  : 0));
                reply.AddShort((short)(character.Hat    != null ? character.Hat.Data.special1    : 0));
                reply.AddShort((short)(character.Shield != null ? character.Shield.Data.special1 : 0));
                reply.AddShort((short)(character.Weapon != null ? character.Weapon.Data.special1 : 0));
                reply.AddBreak();
            }

            client.Send(reply);
        }
Esempio n. 22
0
        public static void HandleCreate(Packet packet, IClient client, bool fromQueue)
        {
            short createId = packet.GetShort();
            Gender gender = (Gender)packet.GetShort();
            short hairStyle = packet.GetShort();
            short hairColor = packet.GetShort();
            Skin skin = (Skin)packet.GetShort();
            packet.GetByte();
            string name = packet.GetBreakString().ToLower();

            if (!Enum.IsDefined(typeof(Gender), gender))
                throw new ArgumentOutOfRangeException("Invalid gender on character creation (" + gender + ")");

            // TODO: Make these configurable
            if (hairStyle < 1 || hairStyle > 20
             || hairColor < 0 || hairColor > 9)
                throw new ArgumentOutOfRangeException("Hair parameters out of range on character creation (" + hairStyle + ", " + hairColor + ")");

            if (!Enum.IsDefined(typeof(Skin), skin))
                throw new ArgumentOutOfRangeException("Invalid skin on character creation (" + skin + ")");

            Packet reply = new Packet(PacketFamily.Character, PacketAction.Reply);

            // TODO: Make this configurable
            if (client.Account.Characters.Count >= 3)
            {
                reply.AddShort((short)CharacterReply.Full);
                client.Send(reply);
                return;
            }

            if (!Character.ValidName(name))
            {
                reply.AddShort((short)CharacterReply.NotApproved);
                client.Send(reply);
                return;
            }

            // TODO: Make a CharacterExists function
            var checkCharacter = from Character c in client.Server.Database.Container
                                 where c.name == name
                                 select 1;

            if (checkCharacter.Count() != 0)
            {
                reply.AddShort((short)CharacterReply.Exists);
                client.Send(reply);
                return;
            }

            Character newCharacter = new Character(client.Server, client, name, gender, (byte)hairStyle, (byte)hairColor, skin);
            client.Account.Characters.Add(newCharacter);
            newCharacter.Store();
            client.Account.Store();
            client.Server.Database.Commit();

            reply.AddShort((short)CharacterReply.OK);
            reply.AddChar((byte)client.Account.Characters.Count);
            reply.AddByte(1); // TODO: What is this?
            reply.AddBreak();

            // TODO: Some kind of character list packet builder
            int i = 0;
            foreach (Character character in client.Account.Characters)
            {
                reply.AddBreakString(character.Name);
                reply.AddInt(i++);
                reply.AddChar(character.Level);
                reply.AddChar((byte)character.Gender);
                reply.AddChar(character.HairStyle);
                reply.AddChar(character.HairColor);
                reply.AddChar((byte)character.Skin);
                reply.AddChar((byte)character.Admin);
                reply.AddShort((short)(character.Boots  != null ? character.Boots.Data.special1  : 0));
                reply.AddShort((short)(character.Armor  != null ? character.Armor.Data.special1  : 0));
                reply.AddShort((short)(character.Hat    != null ? character.Hat.Data.special1    : 0));
                reply.AddShort((short)(character.Shield != null ? character.Shield.Data.special1 : 0));
                reply.AddShort((short)(character.Weapon != null ? character.Weapon.Data.special1 : 0));
                reply.AddBreak();
            }

            client.Send(reply);
        }
Esempio n. 23
0
        private void StructureInfo(Session session, Packet packet)
        {
            ICity      city;
            IStructure structure;

            uint cityId;
            uint objectId;

            try
            {
                cityId   = packet.GetUInt32();
                objectId = packet.GetUInt32();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            locker.Lock(cityId, objectId, out city, out structure).Do(() =>
            {
                if (city == null || structure == null)
                {
                    ReplyError(session, packet, Error.ObjectNotFound);
                    return;
                }

                var reply = new Packet(packet);
                reply.AddUInt16(structure.Stats.Base.Type);
                reply.AddByte(structure.Stats.Base.Lvl);
                if (session.Player == structure.City.Owner)
                {
                    reply.AddUInt16(structure.Stats.Labor);
                    reply.AddUInt16((ushort)structure.Stats.Hp);

                    foreach (var prop in propertyFactory.GetProperties(structure.Type))
                    {
                        switch (prop.Type)
                        {
                        case DataType.Byte:
                            reply.AddByte((byte)prop.GetValue(structure));
                            break;

                        case DataType.UShort:
                            reply.AddUInt16((ushort)prop.GetValue(structure));
                            break;

                        case DataType.UInt:
                            reply.AddUInt32((uint)prop.GetValue(structure));
                            break;

                        case DataType.String:
                            reply.AddString((string)prop.GetValue(structure));
                            break;

                        case DataType.Int:
                            reply.AddInt32((int)prop.GetValue(structure));
                            break;

                        case DataType.Float:
                            reply.AddFloat((float)prop.GetValue(structure));
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var prop in propertyFactory.GetProperties(structure.Type, Visibility.Public))
                    {
                        switch (prop.Type)
                        {
                        case DataType.Byte:
                            reply.AddByte((byte)prop.GetValue(structure));
                            break;

                        case DataType.UShort:
                            reply.AddUInt16((ushort)prop.GetValue(structure));
                            break;

                        case DataType.UInt:
                            reply.AddUInt32((uint)prop.GetValue(structure));
                            break;

                        case DataType.String:
                            reply.AddString((string)prop.GetValue(structure));
                            break;

                        case DataType.Int:
                            reply.AddInt32((int)prop.GetValue(structure));
                            break;

                        case DataType.Float:
                            reply.AddFloat((float)prop.GetValue(structure));
                            break;
                        }
                    }
                }

                session.Write(reply);
            });
        }
Esempio n. 24
0
        //255 means use character's current location
        public bool DropItem(short id, int amount, byte x = 255, byte y = 255)
        {
            if (!m_client.ConnectedAndInitialized || !Initialized)
                return false;

            Packet pkt = new Packet(PacketFamily.Item, PacketAction.Drop);
            pkt.AddShort(id);
            pkt.AddInt(amount);
            if (x == 255 && y == 255)
            {
                pkt.AddByte(x);
                pkt.AddByte(y);
            }
            else
            {
                pkt.AddChar(x);
                pkt.AddChar(y);
            }

            return m_client.SendPacket(pkt);
        }
Esempio n. 25
0
        private void GetRegion(Session session, Packet packet)
        {
            var reply = new Packet(packet);

            reply.Option |= (ushort)Packet.Options.Compressed;

            ushort regionId;

            byte regionSubscribeCount;

            try
            {
                regionSubscribeCount = packet.GetByte();

                if (regionSubscribeCount > 15)
                {
                    throw new Exception("Too many regions requested");
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            reply.AddByte(regionSubscribeCount);

            for (uint i = 0; i < regionSubscribeCount; ++i)
            {
                try
                {
                    regionId = packet.GetUInt16();
                }
                catch (Exception)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                var region = world.Regions.GetRegion(regionId);
                if (region == null)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                reply.AddUInt16(regionId);
                reply.AddBytes(region.GetObjectBytes());
                world.Regions.SubscribeRegion(session, regionId);
            }

            byte regionUnsubscribeCount;

            try
            {
                regionUnsubscribeCount = packet.GetByte();

                if (regionUnsubscribeCount > 15)
                {
                    throw new Exception("Too many unsubscribe regions");
                }
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            for (uint i = 0; i < regionUnsubscribeCount; ++i)
            {
                try
                {
                    regionId = packet.GetUInt16();
                }
                catch (Exception)
                {
                    ReplyError(session, packet, Error.Unexpected);
                    return;
                }

                world.Regions.UnsubscribeRegion(session, regionId);
            }

            if (channel.SubscriptionCount(session) > 30)
            {
                session.CloseSession();
            }
            else
            {
                session.Write(reply);
            }
        }
Esempio n. 26
0
        private void Subscribe(Session session, Packet packet)
        {
            uint battleId;

            try
            {
                battleId = packet.GetUInt32();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            IBattleManager battleManager;

            if (!world.TryGetObjects(battleId, out battleManager))
            {
                ReplyError(session, packet, Error.BattleNotViewable);
                return;
            }

            CallbackLock.CallbackLockHandler lockHandler = delegate
            {
                var toBeLocked = new List <ILockable>();

                toBeLocked.AddRange(battleManager.LockList);

                return(toBeLocked.ToArray());
            };

            locker.Lock(lockHandler, null, session.Player).Do(() =>
            {
                IEnumerable <string> errorParams;
                var canWatchBattle = battleManager.CanWatchBattle(session.Player, out errorParams);
                if (!Config.battle_instant_watch && canWatchBattle != Error.Ok)
                {
                    packet = ReplyError(session, packet, canWatchBattle, false);
                    packet.AddByte((byte)errorParams.Count());
                    foreach (var errorParam in errorParams)
                    {
                        packet.AddString(errorParam);
                    }
                    session.Write(packet);
                    return;
                }

                var reply = new Packet(packet);
                reply.AddByte((byte)battleManager.Location.Type);
                reply.AddUInt32(battleManager.Location.Id);
                reply.AddString(battleManager.Location.GetName());
                reply.AddUInt32(battleManager.Round);

                // Battle properties
                PacketHelper.AddBattleProperties(battleManager.ListProperties(), reply);
                PacketHelper.AddToPacket(battleManager.Attackers, reply);
                PacketHelper.AddToPacket(battleManager.Defenders, reply);

                try
                {
                    Global.Current.Channel.Subscribe(session, "/BATTLE/" + battleManager.BattleId);
                }
                catch (DuplicateSubscriptionException)
                {
                }

                session.Write(reply);
            });
        }
Esempio n. 27
0
        private bool processByte(Packet p, byte b)
        {
            if (b != kDelimiter && p.State == PacketState.WaitForInitialDelimiter)
            {
                return false;
            }
            if (b == kDelimiter)
            {
                if(p.State == PacketState.WaitForInitialDelimiter)
                {
                    p.State = PacketState.WaitForFinalDelimiter;
                }
                else if(p.State == PacketState.WaitForFinalDelimiter && p.GetData().Length != 0)
                {
                    return true;
                }
                return false;
            }
            if (b == kEscape)
            {
                p.State = PacketState.EscapeNextByte;
                return false;
            }

            if (p.State == PacketState.EscapeNextByte)
            {
                p.AddByte((byte)(b ^ (1 << 5)));
                p.State = PacketState.WaitForFinalDelimiter;
            }
            else
            {
                p.AddByte(b);
            }
            return false;
        }
Esempio n. 28
0
        private void GetTroopInfo(Session session, Packet packet)
        {
            ICity        city;
            ITroopObject troop;

            uint cityId;
            uint objectId;

            try
            {
                cityId   = packet.GetUInt32();
                objectId = packet.GetUInt32();
            }
            catch (Exception)
            {
                ReplyError(session, packet, Error.Unexpected);
                return;
            }

            locker.Lock(cityId, objectId, out city, out troop).Do(() =>
            {
                if (city == null || troop == null || troop.Stub == null)
                {
                    ReplyError(session, packet, Error.ObjectNotFound);
                    return;
                }

                var reply = new Packet(packet);
                reply.AddUInt16(troop.Stub.TroopId);

                if (city.Owner == session.Player)
                {
                    reply.AddByte(troop.Stats.AttackRadius);
                    reply.AddFloat((float)troop.Stats.Speed);
                    reply.AddUInt32(troop.TargetX);
                    reply.AddUInt32(troop.TargetY);

                    var template = new Dictionary <ushort, IBaseUnitStats>();

                    reply.AddByte(troop.Stub.FormationCount);
                    foreach (var formation in troop.Stub)
                    {
                        reply.AddByte((byte)formation.Type);
                        reply.AddByte((byte)formation.Count);
                        foreach (var kvp in formation)
                        {
                            reply.AddUInt16(kvp.Key);
                            reply.AddUInt16(kvp.Value);
                            template[kvp.Key] = city.Template[kvp.Key];
                        }
                    }

                    reply.AddUInt16((ushort)template.Count);
                    IEnumerator <KeyValuePair <ushort, IBaseUnitStats> > templateIter = template.GetEnumerator();
                    while (templateIter.MoveNext())
                    {
                        KeyValuePair <ushort, IBaseUnitStats> kvp = templateIter.Current;
                        reply.AddUInt16(kvp.Key);
                        reply.AddByte(kvp.Value.Lvl);
                    }
                }

                session.Write(reply);
            });
        }
Esempio n. 29
0
        private void UpdateClients()
        {
            try
            {
                while (!this.ResetEvent.Wait(200))
                {
                    try
                    {
                        var descriptors = this.ConnectedClients.ToArray();
                        if (descriptors.Length == 0) continue;
                        Packet p = new Packet();
                        List<TcpClient> sockets = new List<TcpClient>();

                        p.AddUInt16((ushort)descriptors.Length);
                        foreach (ClientDescriptor descriptor in descriptors)
                        {
                            sockets.Add(descriptor.TcpClient);
                            p.AddString(descriptor.PlayerName);
                            p.AddUInt32(descriptor.PlayerID);
                            p.AddUInt16(descriptor.PlayerLevel);
                            p.AddUInt16((ushort)descriptor.Location.X);
                            p.AddUInt16((ushort)descriptor.Location.Y);
                            p.AddByte((byte)descriptor.Location.Z);
                        }
                        p.AddLength();
                        foreach (TcpClient tc in sockets)
                        {
                            if (!tc.Connected) continue;
                            p.Send(tc);
                        }
                    }
                    catch { }
                }
            }
            catch { }
        }