Example #1
0
        void handleCharacterSelectMessage(AccountClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.APMSG_CHAR_SELECT_RESPONSE);

            ISL.Server.Account.Account acc=client.getAccount();

            if(acc==null)
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_NO_LOGIN);
                client.send(reply);
                return; // not logged in
            }

            int slot=msg.readInt8();
            Dictionary<uint, Character> chars=acc.getCharacters();

            if(chars.ContainsKey((uint)slot)==false)
            {
                // Invalid char selection
                reply.writeInt8((int)ErrorMessage.ERRMSG_INVALID_ARGUMENT);
                client.send(reply);
                return;
            }

            Character selectedChar=chars[(uint)slot];

            string address;
            int port;

            int charMapId=selectedChar.getMapId();
            bool gameServerHasMap=GameServerHandler.getGameServerFromMap(charMapId, out address, out port);

            if(!gameServerHasMap)
            {
                Logger.Write(LogLevel.Error, "Character Selection: No game server for map #{0}", selectedChar.getMapId());
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
                client.send(reply);
                return;
            }

            reply.writeInt8((int)ErrorMessage.ERRMSG_OK);

            Logger.Write(LogLevel.Debug, "{0} is trying to enter the servers.", selectedChar.getName());

            string magic_token=Various.GetUniqueID();
            reply.writeString(magic_token);
            reply.writeString(address);
            reply.writeInt16(port);

            // Give address and port for the chat server
            reply.writeString(Configuration.getValue("net_chatHost", "localhost"));

            // When the chatListenToClientPort is set, we use it.
            // Otherwise, we use the accountListenToClientPort + 2 if the option is set.
            // If neither, the DEFAULT_SERVER_PORT + 2 is used.
            int alternativePort=Configuration.getValue("net_accountListenToClientPort", Configuration.DEFAULT_SERVER_PORT)+2;
            reply.writeInt16(Configuration.getValue("net_chatListenToClientPort", alternativePort));

            GameServerHandler.registerClient(magic_token, selectedChar); //TODO Überprüfen ob diese beiden Funktionen funktionieren
            ChatHandler.registerChatClient(magic_token, selectedChar.getName(), acc.getLevel());

            client.send(reply);

            // log transaction
            Transaction trans=new Transaction();
            trans.mCharacterId=(uint)selectedChar.getDatabaseID();
            trans.mAction=(uint)TransactionMembers.TRANS_CHAR_SELECTED;

            Program.storage.addTransaction(trans);
        }
Example #2
0
        void handleQuitChannelMessage(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_QUIT_CHANNEL_RESPONSE);

            short channelId = msg.readInt16();
            ChatChannel channel = Program.chatChannelManager.getChannel(channelId);

            if (channelId == 0 || channel!=null)
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_INVALID_ARGUMENT);
            }
            else if (!channel.removeUser(client))
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
            }
            else
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                reply.writeInt16(channelId);

                // Send an CPMSG_UPDATE_CHANNEL to warn other clients a user left
                // the channel.
                warnUsersAboutPlayerEventInChat(channel, client.characterName, (int)ChatValues.CHAT_EVENT_LEAVING_PLAYER);

                // log transaction
                Transaction trans=new Transaction();
                trans.mCharacterId = client.characterId;
                trans.mAction =(uint)TransactionMembers.TRANS_CHANNEL_QUIT;
                trans.mMessage = "User left " + channel.getName();
                Program.storage.addTransaction(trans);

                if (channel.getUserList()!=null)
                {
                    Program.chatChannelManager.removeChannel(channel.getId());
                }
            }

            client.send(reply);
        }
Example #3
0
        void sendCharacterData(AccountClient client, Character ch)
        {
            MessageOut charInfo=new MessageOut(Protocol.APMSG_CHAR_INFO);

            charInfo.writeInt8((int)ch.getCharacterSlot());
            charInfo.writeString(ch.getName());
            charInfo.writeInt8(ch.getGender());
            charInfo.writeInt8(ch.getHairStyle());
            charInfo.writeInt8(ch.getHairColor());
            charInfo.writeInt16(ch.getLevel());
            charInfo.writeInt16(ch.getCharacterPoints());
            charInfo.writeInt16(ch.getCorrectionPoints());

            foreach(KeyValuePair<uint, AttributeValue> at in ch.mAttributes)
            {
                charInfo.writeInt32((int)at.Key);
                charInfo.writeInt32((int)(at.Value.@base*256));
                charInfo.writeInt32((int)(at.Value.modified*256));
            }

            client.send(charInfo);
        }
Example #4
0
        void sendGuildRejoin(ChatClient client)
        {
            // Get list of guilds and check what rights they have.
            List<Guild> guilds=Program.guildManager.getGuildsForPlayer((int)client.characterId);

            foreach(Guild guild in guilds)
            {
                int permissions = guild.getUserPermissions((int)client.characterId);
                string guildName = guild.getName();

                // Tell the client what guilds the character belongs to and their permissions
                MessageOut msg=new MessageOut(Protocol.CPMSG_GUILD_REJOIN);
                msg.writeString(guildName);
                msg.writeInt16(guild.getId());
                msg.writeInt16(permissions);

                // get channel id of guild channel
                ChatChannel channel = joinGuildChannel(guildName, client);

                // send the channel id for the autojoined channel
                msg.writeInt16(channel.getId());
                msg.writeString(channel.getAnnouncement());

                client.send(msg);

                sendGuildListUpdate(guildName, client.characterName, (int)ISL.Server.Enums.GuildValues.GUILD_EVENT_ONLINE_PLAYER);
            }
        }
Example #5
0
        void handleListChannelsMessage(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_LIST_CHANNELS_RESPONSE);

            List<ChatChannel> channels=Program.chatChannelManager.getPublicChannels();

            foreach(ChatChannel channel in channels)
            {
                reply.writeString(channel.getName());
                reply.writeInt16(channel.getUserList().Count);
            }

            client.send(reply);

            // log transaction
            Transaction trans=new Transaction();
            trans.mCharacterId = client.characterId;
            trans.mAction =(uint)TransactionMembers.TRANS_CHANNEL_LIST;
            Program.storage.addTransaction(trans);
        }
Example #6
0
        public bool start(int gameServerPort)
        {
            string accountServerAddress=Configuration.getValue("net_accountHost", "localhost");

            // When the accountListenToGamePort is set, we use it.
            // Otherwise, we use the accountListenToClientPort + 1 if the option is set.
            // If neither, the DEFAULT_SERVER_PORT + 1 is used.
            int alternativePort=Configuration.getValue("net_accountListenToClientPort", 0)+1;
            if(alternativePort==1)
                alternativePort=Configuration.DEFAULT_SERVER_PORT+1;

            int accountServerPort=Configuration.getValue("net_accountListenToGamePort", alternativePort);

            if(!start(accountServerAddress, accountServerPort))
            {
                Logger.Write(LogLevel.Information, "Unable to create a connection to an account server.");
                return false;
            }

            Logger.Write(LogLevel.Information, "Connection established to the account server.");

            string gameServerAddress=Configuration.getValue("net_gameHost", "localhost");
            string password=Configuration.getValue("net_password", "changeMe");

            // Register with the account server and send the list of maps we handle
            MessageOut msg=new MessageOut(Protocol.GAMSG_REGISTER);
            msg.writeString(gameServerAddress);
            msg.writeInt16(gameServerPort);
            msg.writeString(password);
            msg.writeInt32((int)Program.itemManager.getDatabaseVersion());

            Dictionary<int, MapComposite> m=MapManager.getMaps();

            foreach(int map in m.Keys)
            {
                msg.writeInt16(map);
            }

            send(msg);

            // initialize sync buffer
            if(mSyncBuffer==null)
                mSyncBuffer=new MessageOut(Protocol.GAMSG_PLAYER_SYNC);

            return true;
        }
Example #7
0
 void removeFloorItems(int mapId, int itemId, int amount, int posX, int posY)
 {
     MessageOut msg=new MessageOut(Protocol.GAMSG_REMOVE_ITEM_ON_MAP);
     msg.writeInt32(mapId);
     msg.writeInt32(itemId);
     msg.writeInt16(amount);
     msg.writeInt16(posX);
     msg.writeInt16(posY);
     send(msg);
 }
Example #8
0
        void handleGuildAcceptInvite(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_GUILD_ACCEPT_RESPONSE);
            string guildName = msg.readString();
            bool error = true; // set true by default, and set false only if success

            // check guild exists and that member was invited
            // then add them as guild member
            // and remove from invite list
            Guild guild = Program.guildManager.findByName(guildName);

            if (guild!=null)
            {
                if (guild.checkInvited((int)client.characterId))
                {
                    // add user to guild
                    Program.guildManager.addGuildMember(guild, (int)client.characterId);
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                    reply.writeString(guild.getName());
                    reply.writeInt16(guild.getId());
                    reply.writeInt16(guild.getUserPermissions((int)client.characterId));

                    // have character join guild channel
                    ChatChannel channel = joinGuildChannel(guild.getName(), client);
                    reply.writeInt16(channel.getId());
                    sendGuildListUpdate(guildName, client.characterName, (int)GuildValues.GUILD_EVENT_NEW_PLAYER);

                    // success! set error to false
                    error = false;
                }
            }

            if (error)
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
            }

            client.send(reply);
        }
Example #9
0
        void handleGuildCreate(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_GUILD_CREATE_RESPONSE);

            // Check if guild already exists and if so, return error
            string guildName = msg.readString();

            if (!Program.guildManager.doesExist(guildName))
            {
                // check the player hasnt already created a guild
                if(Program.guildManager.alreadyOwner((int)client.characterId))
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_LIMIT_REACHED);
                }
                else
                {
                    // Guild doesnt already exist so create it
                    Guild guild=Program.guildManager.createGuild(guildName, (int)client.characterId);
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                    reply.writeString(guildName);
                    reply.writeInt16(guild.getId());
                    reply.writeInt16(guild.getUserPermissions((int)client.characterId));

                    // Send autocreated channel id
                    ChatChannel channel = joinGuildChannel(guildName, client);
                    reply.writeInt16(channel.getId());
                }
            }
            else
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_ALREADY_TAKEN);
            }

            client.send(reply);
        }
Example #10
0
        void handleChatMessage(ChatClient client, MessageIn msg)
        {
            string text = msg.readString();

            // Pass it through the slang filter (false when it contains bad words)
            if (!Program.stringFilter.filterContent(text))
            {
                warnPlayerAboutBadWords(client);
                return;
            }

            short channelId = msg.readInt16();
            ChatChannel channel = Program.chatChannelManager.getChannel(channelId);

            if (channel!=null)
            {
            Logger.Write(LogLevel.Debug, "{0} says in channel {1}: {2}", client.characterName, channelId, text);

                MessageOut result=new MessageOut(Protocol.CPMSG_PUBMSG);
                result.writeInt16(channelId);
                result.writeString(client.characterName);
                result.writeString(text);
                sendInChannel(channel, result);
            }

            // log transaction
            Transaction trans=new Transaction();
            trans.mCharacterId = client.characterId;
            trans.mAction=(uint)TransactionMembers.TRANS_MSG_PUBLIC;
            trans.mMessage = "User said " + text;
            Program.storage.addTransaction(trans);
        }
Example #11
0
        void handleEnterChannelMessage(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_ENTER_CHANNEL_RESPONSE);

            string channelName=msg.readString();
            string givenPassword=msg.readString();
            ChatChannel channel=null;

            if(Program.chatChannelManager.channelExists(channelName)||
                Program.chatChannelManager.tryNewPublicChannel(channelName))
            {
                channel=Program.chatChannelManager.getChannel(channelName);
            }

            if(channel!=null)
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_INVALID_ARGUMENT);
            }
            else if(channel.getPassword()!=null&&channel.getPassword()!=givenPassword)
            {
                // Incorrect password (should probably have its own return value)
                reply.writeInt8((int)ErrorMessage.ERRMSG_INSUFFICIENT_RIGHTS);
            }
            else if(!channel.canJoin())
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_INVALID_ARGUMENT);
            }
            else
            {
                if(channel.addUser(client))
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                    // The user entered the channel, now give him the channel
                    // id, the announcement string and the user list.
                    reply.writeInt16(channel.getId());
                    reply.writeString(channelName);
                    reply.writeString(channel.getAnnouncement());
                    List<ChatClient> users=channel.getUserList();

                    foreach(ChatClient user in users)
                    {
                        reply.writeString(user.characterName);
                        reply.writeString(channel.getUserMode(user));
                    }

                    // Send an CPMSG_UPDATE_CHANNEL to warn other clients a user went
                    // in the channel.
                    warnUsersAboutPlayerEventInChat(channel, client.characterName, (int)ChatValues.CHAT_EVENT_NEW_PLAYER);

                    // log transaction
                    Transaction trans=new Transaction();
                    trans.mCharacterId=client.characterId;
                    trans.mAction=(uint)TransactionMembers.TRANS_CHANNEL_JOIN;
                    trans.mMessage="User joined "+channelName;
                    Program.storage.addTransaction(trans);
                }
                else
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
                }
            }

            client.send(reply);
        }
Example #12
0
        protected override void processMessage(NetComputer comp, MessageIn message)
        {
            ChatClient computer=(ChatClient)(comp);
            MessageOut result=new MessageOut();

            if(computer.characterName==null)
            {
                if(message.getId()!=Protocol.PCMSG_CONNECT) return;

                string magic_token=message.readString();
                mTokenCollector.addPendingClient(magic_token, computer);
                sendGuildRejoin(computer);
                return;
            }

            switch(message.getId())
            {
                case Protocol.PCMSG_CHAT:
                    handleChatMessage(computer, message);
                    break;

                case Protocol.PCMSG_ANNOUNCE:
                    handleAnnounceMessage(computer, message);
                    break;

                case Protocol.PCMSG_PRIVMSG:
                    handlePrivMsgMessage(computer, message);
                    break;

                case Protocol.PCMSG_WHO:
                    handleWhoMessage(computer);
                    break;

                case Protocol.PCMSG_ENTER_CHANNEL:
                    handleEnterChannelMessage(computer, message);
                    break;

                case Protocol.PCMSG_USER_MODE:
                    handleModeChangeMessage(computer, message);
                    break;

                case Protocol.PCMSG_KICK_USER:
                    handleKickUserMessage(computer, message);
                    break; //TODO hinzugef�gt, evt sollte es durchfallen

                case Protocol.PCMSG_QUIT_CHANNEL:
                    handleQuitChannelMessage(computer, message);
                    break;

                case Protocol.PCMSG_LIST_CHANNELS:
                    handleListChannelsMessage(computer, message);
                    break;

                case Protocol.PCMSG_LIST_CHANNELUSERS:
                    handleListChannelUsersMessage(computer, message);
                    break;

                case Protocol.PCMSG_TOPIC_CHANGE:
                    handleTopicChange(computer, message);
                    break;

                case Protocol.PCMSG_DISCONNECT:
                    handleDisconnectMessage(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_CREATE:
                    handleGuildCreate(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_INVITE:
                    handleGuildInvite(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_ACCEPT:
                    handleGuildAcceptInvite(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_GET_MEMBERS:
                    handleGuildGetMembers(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_PROMOTE_MEMBER:
                    handleGuildMemberLevelChange(computer, message);
                    break;

                case Protocol.PCMSG_GUILD_KICK_MEMBER:
                    handleGuildKickMember(computer, message);
                    break; //TODO hinzugef�gt, evt sollte es durchfallen

                case Protocol.PCMSG_GUILD_QUIT:
                    handleGuildQuit(computer, message);
                    break;

                case Protocol.PCMSG_PARTY_INVITE_ANSWER:
                    handlePartyInviteAnswer(computer, message);
                    break;

                case Protocol.PCMSG_PARTY_QUIT:
                    handlePartyQuit(computer);
                    break;

                default:
                    Logger.Write(LogLevel.Warning, "processMessage, Invalid message type {0}", message.getId());
                    result.writeInt16((int)Protocol.XXMSG_INVALID);
                    break;
            }

            if(result.getLength()>0)
                computer.send(result);
        }
Example #13
0
 public void warnUsersAboutPlayerEventInChat(ChatChannel channel, string info, byte eventId)
 {
     MessageOut msg=new MessageOut(Protocol.CPMSG_CHANNEL_EVENT);
     msg.writeInt16(channel.getId());
     msg.writeInt8(eventId);
     msg.writeString(info);
     sendInChannel(channel, msg);
 }
Example #14
0
        public void sendGuildListUpdate(string guildName, string characterName, byte eventId)
        {
            Guild guild=Program.guildManager.findByName(guildName);

            if(guild!=null)
            {
                MessageOut msg=new MessageOut(Protocol.CPMSG_GUILD_UPDATE_LIST);

                msg.writeInt16(guild.getId());
                msg.writeString(characterName);
                msg.writeInt8(eventId);

                foreach(GuildMember member in guild.getMembers())
                {
                    Character c=Program.storage.getCharacter(member.mId, null);

                    if(mPlayerMap.ContainsKey(c.getName()))
                    {
                        ChatClient chr=mPlayerMap[c.getName()];
                        chr.send(msg);
                    }
                }
            }
        }
Example #15
0
        public void serializeCharacterData(MessageOut msg)
        {
            // general character properties
            msg.writeInt8(getAccountLevel());
            msg.writeInt8((int)getGender());
            msg.writeInt8(getHairStyle());
            msg.writeInt8(getHairColor());
            msg.writeInt16(getLevel());
            msg.writeInt16(getCharacterPoints());
            msg.writeInt16(getCorrectionPoints());

            msg.writeInt16(mAttributes.Count);

            //            foreach(KeyValuePair<uint, AttributeValue> pair in mAttributes)
            //            {
            //                msg.writeInt16((Int16)pair.Key);
            //
            //                msg.writeDouble(pair.Value.@base);
            //                msg.writeDouble(pair.Value.modified);
            //            }

            foreach(KeyValuePair<uint, Attribute> pair in mAttributes)
            {
                msg.writeInt16((int)pair.Key);
                msg.writeDouble(pair.Value.getBase());
                msg.writeDouble(pair.Value.getModifiedAttribute());
            }

            // character skills
            msg.writeInt16(getSkillSize());

            foreach(KeyValuePair<int, int> pair in mExperience)
            {
                msg.writeInt16(pair.Key);
                msg.writeInt32(pair.Value);
            }

            // status effects currently affecting the character
            msg.writeInt16(getStatusEffectSize());

            foreach(KeyValuePair<int, int> pair in mStatusEffects)
            {
                msg.writeInt16(pair.Key);
                msg.writeInt16(pair.Value);
            }

            // location
            msg.writeInt16(getMapId());
            Point pos=getPosition();
            msg.writeInt16(pos.x);
            msg.writeInt16(pos.y);

            // kill count
            msg.writeInt16(getKillCountSize());

            foreach(KeyValuePair<int, int> pair in mKillCount)
            {
                msg.writeInt16(pair.Key);
                msg.writeInt32(pair.Value);
            }

            // character specials
            msg.writeInt16(mSpecials.Count);

            foreach(KeyValuePair<int, Special> pair in mSpecials)
            {
                msg.writeInt32(pair.Key);
            }

            // inventory - must be last because size isn't transmitted
            Possessions poss=getPossessions();
            Dictionary< uint, EquipmentItem > equipData=poss.getEquipment();
            msg.writeInt16(equipData.Count); // number of equipment

            foreach(KeyValuePair<uint, EquipmentItem> k in equipData)
            {
                msg.writeInt16((int)k.Key);                 // Equip slot id
                msg.writeInt16((int)k.Value.itemId);         // ItemId
                msg.writeInt16((int)k.Value.itemInstance);   // Item Instance id
            }

            Dictionary< uint, InventoryItem > inventoryData=poss.getInventory();

            foreach(KeyValuePair<uint, InventoryItem> j in inventoryData)
            {
                msg.writeInt16((int)j.Key);           // slot id
                msg.writeInt16((int)j.Value.itemId);   // item id
                msg.writeInt16((int)j.Value.amount);   // amount
            }
        }
Example #16
0
        void handleGuildGetMembers(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_GUILD_GET_MEMBERS_RESPONSE);
            short guildId = msg.readInt16();
            Guild guild = Program.guildManager.findById(guildId);

            // check for valid guild
            // write a list of member names that belong to the guild
            if (guild!=null)
            {
                // make sure the requestor is in the guild
                if (guild.checkInGuild((int)client.characterId))
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                    reply.writeInt16(guildId);

                    foreach(GuildMember member in guild.getMembers())
                    {
                        Character c = Program.storage.getCharacter(member.mId, null);
                        string memberName = c.getName();
                        reply.writeString(memberName);
                        reply.writeInt8((int)((mPlayerMap.ContainsKey(memberName)?1:0)));
                    }
                }
            }
            else
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
            }

            client.send(reply);
        }
Example #17
0
        //    internal GameServer getGameServerFromMap(int);
        //internal void GameServerHandler::dumpStatistics(std::ostream &);
        /// <summary>
        /// Processes server messages.
        /// </summary>
        /// <param name="computer"></param>
        /// <param name="message"></param>
        protected override void processMessage(NetComputer computer, MessageIn message)
        {
            MessageOut result=new MessageOut();
            GameServer server=(GameServer)(computer);

            switch(message.getId())
            {
                case Protocol.GAMSG_REGISTER:
                    {
                        Logger.Write(LogLevel.Debug, "GAMSG_REGISTER");

                        // TODO: check the credentials of the game server
                        server.address=message.readString();
                        server.port=message.readInt16();
                        string password=message.readString();

                        // checks the version of the remote item database with our local copy
                        uint dbversion=(uint)message.readInt32();
                        Logger.Write(LogLevel.Information, "Game server uses itemsdatabase with version {0}", dbversion);

                        Logger.Write(LogLevel.Debug, "AGMSG_REGISTER_RESPONSE");
                        MessageOut outmessage=new MessageOut(Protocol.AGMSG_REGISTER_RESPONSE);

                        if(dbversion==Program.storage.getItemDatabaseVersion())
                        {
                            Logger.Write(LogLevel.Debug, "Item databases between account server and gameserver are in sync");
                            outmessage.writeInt16((int)DataVersion.DATA_VERSION_OK);
                        }
                        else
                        {
                            Logger.Write(LogLevel.Debug, "Item database of game server has a wrong version");
                            outmessage.writeInt16((int)DataVersion.DATA_VERSION_OUTDATED);
                        }
                        if(password==Configuration.getValue("net_password", "changeMe"))
                        {
                            outmessage.writeInt16((int)Password.PASSWORD_OK);
                            computer.send(outmessage);

                            // transmit global world state variables
                            Dictionary<string, string> variables;
                            variables=Program.storage.getAllWorldStateVars(0);

                            foreach(KeyValuePair<string, string> pair in variables)
                            {
                                outmessage.writeString(pair.Key);
                                outmessage.writeString(pair.Value);
                            }
                        }
                        else
                        {
                            Logger.Write(LogLevel.Information, "The password given by {0}:{1} was bad.", server.address, server.port);
                            outmessage.writeInt16((int)Password.PASSWORD_BAD);
                            computer.disconnect(outmessage);
                            break;
                        }

                        Logger.Write(LogLevel.Information, "Game server {0}:{1} wants to register {2}  maps.", server.address, server.port, (message.getUnreadLength()/2));

                        while(message.getUnreadLength()!=0)
                        {
                            int id=message.readInt16();
                            Logger.Write(LogLevel.Information, "Registering map {0}.", id);

                            GameServer s=GameServerHandler.getGameServerFromMap(id);
                            if(s!=null)
                            {
                                Logger.Write(LogLevel.Error, "Server Handler: map is already registered by {0}:{1}.", s.address, s.port);
                            }
                            else
                            {
                                MessageOut tmpOutMsg=new MessageOut(Protocol.AGMSG_ACTIVE_MAP);

                                // Map variables
                                tmpOutMsg.writeInt16(id);
                                Dictionary<string, string> variables;
                                variables=Program.storage.getAllWorldStateVars(id);

                                // Map vars number
                                tmpOutMsg.writeInt16(variables.Count);

                                foreach(KeyValuePair<string, string> pair in variables)
                                {
                                    tmpOutMsg.writeString(pair.Key);
                                    tmpOutMsg.writeString(pair.Value);
                                }

                                // Persistent Floor Items
                                List<FloorItem> items=Program.storage.getFloorItemsFromMap(id);

                                tmpOutMsg.writeInt16(items.Count); //number of floor items

                                // Send each map item: item_id, amount, pos_x, pos_y
                                foreach(FloorItem i in items)
                                {
                                    tmpOutMsg.writeInt32(i.getItemId());
                                    tmpOutMsg.writeInt16(i.getItemAmount());
                                    tmpOutMsg.writeInt16(i.getPosX());
                                    tmpOutMsg.writeInt16(i.getPosY());
                                }

                                computer.send(tmpOutMsg);
                                //MapStatistics m=server.maps[(ushort)id]; //Auskommentiert da nicht klar ist wo dieser Wert gesetzt wird
                                //m.nbThings=0;
                                //m.nbMonsters=0;
                            }
                        }
                    } break;

                case Protocol.GAMSG_PLAYER_DATA:
                    {
                        Logger.Write(LogLevel.Debug, "GAMSG_PLAYER_DATA");
                        int id=message.readInt32();

                        try
                        {
                            Character ptr=Program.storage.getCharacter(id, null);

                            CharacterData.deserializeCharacterData(ptr, message);
                            if(!Program.storage.updateCharacter(ptr))
                            {
                                Logger.Write(LogLevel.Error, "Failed to update character {0}.", id);
                            }
                        }
                        catch
                        {
                            Logger.Write(LogLevel.Error, "Received data for non-existing character {0}.", id);
                        }
                    } break;

                case Protocol.GAMSG_PLAYER_SYNC:
                    {
                        Logger.Write(LogLevel.Debug, "GAMSG_PLAYER_SYNC");
                        GameServerHandler.syncDatabase(message);
                    } break;

                case Protocol.GAMSG_REDIRECT:
                    {
                        Logger.Write(LogLevel.Debug, "GAMSG_REDIRECT");
                        int id=message.readInt32();
                        //string magic_token(utils::getMagicToken());
                        string magic_token=Various.GetUniqueID();

                        try
                        {
                            Character ptr=Program.storage.getCharacter(id, null);

                            int mapId=ptr.getMapId();

                            try
                            {
                                GameServer s=GameServerHandler.getGameServerFromMap(mapId);

                                GameServerHandler.registerGameClient(s, magic_token, ptr);
                                result.writeInt16((int)Protocol.AGMSG_REDIRECT_RESPONSE);
                                result.writeInt32(id);
                                result.writeString(magic_token);
                                result.writeString(s.address);
                                result.writeInt16(s.port);
                            }
                            catch
                            {
                                Logger.Write(LogLevel.Error, "Server Change: No game server for map {0}.", mapId);
                            }
                        }
                        catch
                        {
                            Logger.Write(LogLevel.Error, "Received data for non-existing character {0}.", id);
                        }
                    } break;

                case Protocol.GAMSG_PLAYER_RECONNECT:
                    {
                        Logger.Write(LogLevel.Debug, "GAMSG_PLAYER_RECONNECT");
                        int id=message.readInt32();
                        string magic_token=message.readString();
                        //string magic_token=message.readString(ManaServ.MAGIC_TOKEN_LENGTH);

                        try
                        {
                            Character ptr=Program.storage.getCharacter(id, null);
                            int accountID=ptr.getAccountID();
                            AccountClientHandler.prepareReconnect(magic_token, accountID);
                        }
                        catch
                        {
                            Logger.Write(LogLevel.Error, "Received data for non-existing character {0}.", id);
                        }
                    } break;

                case Protocol.GAMSG_GET_VAR_CHR:
                    {
                        int id=message.readInt32();
                        string name=message.readString();
                        string value=Program.storage.getQuestVar(id, name);
                        result.writeInt16((Int16)Protocol.AGMSG_GET_VAR_CHR_RESPONSE);
                        result.writeInt32(id);
                        result.writeString(name);
                        result.writeString(value);
                    } break;

                case Protocol.GAMSG_SET_VAR_CHR:
                    {
                        int id=message.readInt32();
                        string name=message.readString();
                        string value=message.readString();
                        Program.storage.setQuestVar(id, name, value);
                    } break;

                case Protocol.GAMSG_SET_VAR_WORLD:
                    {
                        string name=message.readString();
                        string value=message.readString();
                        // save the new value to the database
                        Program.storage.setWorldStateVar(name, value);

                        // relay the new value to all gameservers
                        foreach(NetComputer client in clients)
                        {
                            MessageOut varUpdateMessage=new MessageOut(Protocol.AGMSG_SET_VAR_WORLD);
                            varUpdateMessage.writeString(name);
                            varUpdateMessage.writeString(value);
                            client.send(varUpdateMessage);
                        }
                    } break;

                case Protocol.GAMSG_SET_VAR_MAP:
                    {
                        int mapid=message.readInt32();
                        string name=message.readString();
                        string value=message.readString();
                        Program.storage.setWorldStateVar(name, mapid, value);
                    } break;

                case Protocol.GAMSG_BAN_PLAYER:
                    {
                        int id=message.readInt32();
                        int duration=message.readInt32();
                        Program.storage.banCharacter(id, duration);
                    } break;

                case Protocol.GAMSG_CHANGE_PLAYER_LEVEL:
                    {
                        int id=message.readInt32();
                        int level=message.readInt16();
                        Program.storage.setPlayerLevel(id, level);
                    } break;

                case Protocol.GAMSG_CHANGE_ACCOUNT_LEVEL:
                    {
                        int id=message.readInt32();
                        int level=message.readInt16();

                        // get the character so we can get the account id
                        Character c=Program.storage.getCharacter(id, null);

                        if(c!=null)
                        {
                            Program.storage.setAccountLevel(c.getAccountID(), level);
                        }
                    } break;

                case Protocol.GAMSG_STATISTICS:
                    {
                        //while (message.getUnreadLength()!=0)
                        //{
                        //    int mapId = message.readInt16();
                        //    ServerStatistics::iterator i = server.maps.find(mapId);

                        //    if (i == server.maps.end())
                        //    {
                        //        Logger.Add(LogLevel.Error, "Server {0}:{1} should not be sending statistics for map {2}.", server.address, server.port, mapId);
                        //        // Skip remaining data.
                        //        break;
                        //    }

                        //    MapStatistics m = i.second;
                        //    m.nbThings =(ushort) message.readInt16();
                        //    m.nbMonsters=(ushort)message.readInt16();
                        //    int nb = message.readInt16();
                        //    m.players.resize(nb);
                        //    for (int j = 0; j < nb; ++j)
                        //    {
                        //        m.players[j] = message.readInt32();
                        //    }
                        //}
                    } break;

                case Protocol.GCMSG_REQUEST_POST:
                    {
                        // Retrieve the post for user
                        Logger.Write(LogLevel.Debug, "GCMSG_REQUEST_POST");
                        result.writeInt16((int)Protocol.CGMSG_POST_RESPONSE);

                        // get the character id
                        int characterId=message.readInt32();

                        // send the character id of sender
                        result.writeInt32(characterId);

                        // get the character based on the id
                        Character ptr=Program.storage.getCharacter(characterId, null);
                        if(ptr!=null)
                        {
                            // Invalid character
                            Logger.Write(LogLevel.Error, "Error finding character id for post");
                            break;
                        }

                        // get the post for that character
                        Post post=Program.postalManager.getPost(ptr);

                        // send the post if valid
                        if(post!=null)
                        {
                            for(int i=0; i<post.getNumberOfLetters(); ++i)
                            {
                                // get each letter, send the sender's name,
                                // the contents and any attachments
                                Letter letter=post.getLetter(i);
                                result.writeString(letter.getSender().getName());
                                result.writeString(letter.getContents());
                                List<InventoryItem> items=letter.getAttachments();

                                for(uint j=0; j<items.Count; ++j)
                                {
                                    result.writeInt16((int)items[(int)j].itemId);
                                    result.writeInt16((int)items[(int)j].amount);
                                }
                            }

                            // clean up
                            Program.postalManager.clearPost(ptr);
                        }

                    } break;

                case Protocol.GCMSG_STORE_POST:
                    {
                        //// Store the letter for the user
                        //Logger.Add(LogLevel.Debug, "GCMSG_STORE_POST");
                        //result.writeInt16((int)Protocol.CGMSG_STORE_POST_RESPONSE);

                        //// get the sender and receiver
                        //int senderId = message.readInt32();
                        //string receiverName = message.readString();

                        //// for sending it back
                        //result.writeInt32(senderId);

                        //// get their characters
                        //Character sender = Program.storage.getCharacter(senderId, null);
                        //Character receiver=Program.storage.getCharacter(receiverName);

                        //if (sender!=null || receiver!=null)
                        //{
                        //    // Invalid character
                        //    Logger.Add(LogLevel.Error, "Error finding character id for post");
                        //    result.writeInt8(ManaServ.ERRMSG_INVALID_ARGUMENT);
                        //    break;
                        //}

                        //// get the letter contents
                        //string contents = message.readString();

                        //List<Pair<int>> items;

                        //while (message.getUnreadLength()!=0)
                        //{
                        //    items.Add(new Pair<int>(message.readInt16(), message.readInt16()));
                        //}

                        //// save the letter
                        //Logger.Add(LogLevel.Debug, "Creating letter");
                        //Letter letter = new Letter(0, sender, receiver);
                        //letter.addText(contents);

                        //for (uint i = 0; i < items.Count; ++i)
                        //{
                        //    InventoryItem item;
                        //    item.itemId = items[i].first;
                        //    item.amount = items[i].second;
                        //    letter.addAttachment(item);
                        //}

                        //Program.postalManager.addLetter(letter);

                        //result.writeInt8(ManaServ.ERRMSG_OK);
                    } break;

                case Protocol.GAMSG_TRANSACTION:
                    {
                        Logger.Write(LogLevel.Debug, "TRANSACTION");
                        int id=message.readInt32();
                        int action=message.readInt32();
                        string messageS=message.readString();

                        Transaction trans=new Transaction();
                        trans.mCharacterId=(uint)id;
                        trans.mAction=(uint)action;
                        trans.mMessage=messageS;
                        Program.storage.addTransaction(trans);
                    } break;

                case Protocol.GCMSG_PARTY_INVITE:
                    Program.chatHandler.handlePartyInvite(message);
                    break;

                case Protocol.GAMSG_CREATE_ITEM_ON_MAP:
                    {
                        int mapId=message.readInt32();
                        int itemId=message.readInt32();
                        int amount=message.readInt16();
                        int posX=message.readInt16();
                        int posY=message.readInt16();

                        Logger.Write(LogLevel.Debug, "Gameserver create item {0} on map {1} ", itemId, mapId);

                        Program.storage.addFloorItem(mapId, itemId, amount, posX, posY);
                    } break;

                case Protocol.GAMSG_REMOVE_ITEM_ON_MAP:
                    {
                        int mapId=message.readInt32();
                        int itemId=message.readInt32();
                        int amount=message.readInt16();
                        int posX=message.readInt16();
                        int posY=message.readInt16();

                        Logger.Write(LogLevel.Debug, "Gameserver removed item {0} from map {1}", itemId, mapId);

                        Program.storage.removeFloorItem(mapId, itemId, amount, posX, posY);
                    } break;

                default:
                    {
                        Logger.Write(LogLevel.Warning, "ServerHandler::processMessage, Invalid message type: {0}", message.getId());
                        result.writeInt16((int)Protocol.XXMSG_INVALID);
                        break;
                    }
            }

            // return result
            if(result.getLength()>0)
            {
                computer.send(result);
            }
        }
Example #18
0
        void handleGuildInvite(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_GUILD_INVITE_RESPONSE);
            MessageOut invite=new MessageOut(Protocol.CPMSG_GUILD_INVITED);

            // send an invitation from sender to character to join guild
            int guildId=msg.readInt16();
            string character=msg.readString();

            // get the chat client and the guild
            ChatClient invitedClient=mPlayerMap[character];
            Guild guild=Program.guildManager.findById((short)guildId);

            if(invitedClient!=null&&guild!=null)
            {
                // check permissions of inviter, and that they arent inviting themself,
                // and arent someone already in the guild
                if(guild.canInvite((int)client.characterId)&&(client.characterName!=character)&&!guild.checkInGuild((int)invitedClient.characterId))
                {
                    // send the name of the inviter and the name of the guild
                    // that the character has been invited to join
                    string senderName=client.characterName;
                    string guildName=guild.getName();
                    invite.writeString(senderName);
                    invite.writeString(guildName);
                    invite.writeInt16(guildId);
                    invitedClient.send(invite);
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);

                    // add member to list of invited members to the guild
                    guild.addInvited((int)invitedClient.characterId);
                }
                else
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
                }
            }
            else
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
            }

            client.send(reply);
        }
Example #19
0
 void changeAccountLevel(Character c, int level)
 {
     MessageOut msg=new MessageOut(Protocol.GAMSG_CHANGE_ACCOUNT_LEVEL);
     msg.writeInt32(c.getDatabaseID());
     msg.writeInt16(level);
     send(msg);
 }
Example #20
0
        void handleGuildQuit(ChatClient client, MessageIn msg)
        {
            MessageOut reply=new MessageOut(Protocol.CPMSG_GUILD_QUIT_RESPONSE);
            short guildId = msg.readInt16();
            Guild guild = Program.guildManager.findById(guildId);

            // check for valid guild
            // check the member is in the guild
            // remove the member from the guild
            if (guild!=null)
            {
                if (guild.checkInGuild((int)client.characterId))
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_OK);
                    reply.writeInt16(guildId);

                    // Check if there are no members left, remove the guild channel
                    if (guild.memberCount() == 0)
                    {
                        Program.chatChannelManager.removeChannel(Program.chatChannelManager.getChannelId(guild.getName()));
                    }

                    // guild manager checks if the member is the last in the guild
                    // and removes the guild if so
                    Program.guildManager.removeGuildMember(guild, (int)client.characterId);
                    sendGuildListUpdate(guild.getName(), client.characterName, (int)GuildValues.GUILD_EVENT_LEAVING_PLAYER);
                }
                else
                {
                    reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
                }
            }
            else
            {
                reply.writeInt8((int)ErrorMessage.ERRMSG_FAILURE);
            }

            //client.send(reply);
        }
Example #21
0
        public static bool insert(Thing ptr)
        {
            //assert(!dbgLockObjects);

            MapComposite map=ptr.getMap();
            //assert(map && map.isActive());

            /* Non-visible objects have neither position nor public ID, so their
               insertion cannot fail. Take care of them first. */
            if(!ptr.isVisible())
            {
                map.insert(ptr);
                ptr.inserted();
                return true;
            }

            // Check that coordinates are actually valid.
            Actor obj=(Actor)ptr;
            Map mp=map.getMap();

            Point pos=obj.getPosition();
            if((int)pos.x/mp.getTileWidth()>=mp.getWidth()||
                (int)pos.y/mp.getTileHeight()>=mp.getHeight())
            {
                Logger.Write(LogLevel.Error, "Tried to insert an actor at position {0}, {1} outside map {2}.", pos.x, pos.y, map.getID());

                // Set an arbitrary small position.
                pos=new Point(100, 100);
                obj.setPosition(pos);
            }

            if(!map.insert(obj))
            {
                // The map is overloaded, no room to add a new actor
                Logger.Write(LogLevel.Error, "Too many actors on map {0}.", map.getID());
                return false;
            }

            obj.inserted();

            // DEBUG INFO //TODO Implementieren
            //            switch(obj.getType())
            //            {
            //                case ThingType.OBJECT_ITEM:
            //                    Logger.Write(LogLevel.Debug, "Item inserted: "
            //                       (Item)(obj).getItemClass().getDatabaseID());
            //                    break;
            //
            //                case ThingType.OBJECT_NPC:
            //                    Logger.Write(LogLevel.Debug, "NPC inserted: "<<static_cast<NPC*>(obj).getNPC());
            //                    break;
            //
            //                case ThingType.OBJECT_CHARACTER:
            //                    Logger.Write(LogLevel.Debug, "Player inserted: "
            //                        <<static_cast<Being*>(obj).getName());
            //                    break;
            //
            //                case ThingType.OBJECT_EFFECT:
            //                    Logger.Write(LogLevel.Debug, "Effect inserted: "
            //                        <<static_cast<Effect*>(obj).getEffectId());
            //                    break;
            //
            //                case ThingType.OBJECT_MONSTER:
            //                    Logger.Write(LogLevel.Debug, "Monster inserted: "
            //                        <<static_cast<Monster*>(obj).getSpecy().getId());
            //                    break;
            //
            //                case ThingType.OBJECT_ACTOR:
            //                case ThingType.OBJECT_OTHER:
            //                default:
            //                    Logger.Write(LogLevel.Debug, "Thing inserted: "<<obj.getType());
            //            }

            obj.raiseUpdateFlags((byte)UpdateFlag.UPDATEFLAG_NEW_ON_MAP);
            if(obj.getType()!=ThingType.OBJECT_CHARACTER)
                return true;

            /* Since the player does not know yet where in the world its character is,
               we send a map-change message, even if it is the first time it
               connects to this server. */
            MessageOut mapChangeMessage=new MessageOut(Protocol.GPMSG_PLAYER_MAP_CHANGE);
            mapChangeMessage.writeString(map.getName());
            mapChangeMessage.writeInt16(pos.x);
            mapChangeMessage.writeInt16(pos.y);
            Program.gameHandler.sendTo((Character)(obj), mapChangeMessage);

            // update the online state of the character
            Program.accountHandler.updateOnlineStatus(((Character)obj).getDatabaseID(), true);

            return true;
        }
Example #22
0
 void sendNpcError(GameClient client, int id, string errorMsg)
 {
     MessageOut msg=new MessageOut(Protocol.GPMSG_NPC_ERROR);
     msg.writeInt16(id);
     msg.writeString(errorMsg);
     client.send(msg);
 }