Example #1
0
DEF_UDP_RECEIVE_COMMAND(Client, PACKET_UDP_SERVER_RESPONSE)
{
	NetworkGameList *item;

	/* Just a fail-safe.. should never happen */
	if (_network_udp_server) return;

	DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString());

	/* Find next item */
	item = NetworkGameListAddItem(*client_addr);

	this->Recv_NetworkGameInfo(p, &item->info);

	item->info.compatible = true;
	{
		/* Checks whether there needs to be a request for names of GRFs and makes
		 * the request if necessary. GRFs that need to be requested are the GRFs
		 * that do not exist on the clients system and we do not have the name
		 * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
		 * The in_request array and in_request_count are used so there is no need
		 * to do a second loop over the GRF list, which can be relatively expensive
		 * due to the string comparisons. */
		const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
		const GRFConfig *c;
		uint in_request_count = 0;

		for (c = item->info.grfconfig; c != NULL; c = c->next) {
			if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
			if (c->status != GCS_NOT_FOUND || strcmp(c->name, UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
			in_request[in_request_count] = c;
			in_request_count++;
		}

		if (in_request_count > 0) {
			/* There are 'unknown' GRFs, now send a request for them */
			uint i;
			Packet packet(PACKET_UDP_CLIENT_GET_NEWGRFS);

			packet.Send_uint8(in_request_count);
			for (i = 0; i < in_request_count; i++) {
				this->Send_GRFIdentifier(&packet, in_request[i]);
			}

			this->SendPacket(&packet, &item->address);
		}
	}

	if (item->info.hostname[0] == '\0') {
		snprintf(item->info.hostname, sizeof(item->info.hostname), "%s", client_addr->GetHostname());
	}

	if (client_addr->GetAddress()->ss_family == AF_INET6) {
		strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
	}

	/* Check if we are allowed on this server based on the revision-match */
	item->info.version_compatible = IsNetworkCompatibleVersion(item->info.server_revision);
	item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs

	item->online = true;

	UpdateNetworkGameWindow(false);
}
void packetcreator::banme()
{
    packet p = packet(BANME);
    server->dispatch(p);
}
void packetcreator::playerlogin(int cid)
{
    packet p = packet(PLAYER_LOGIN);
    p.writeint(cid);
    server->dispatch(p);
}
Example #4
0
void world_session::_SendReportSpellStart( uint8 spell )
{
    world_packet packet(MSG_REPORT_SPELL_START, 0x00, m_endpoint, 1);
	packet << (uint8)spell;
	send_packet(packet);
}
void packetcreator::pong()
{
    packet p = packet(PONG);
    server->dispatch(p);
}
Example #6
0
			check_nt::packet parse() {
				check_nt::packet packet(buffer_);
				buffer_.clear();
				return packet;
			}
Example #7
0
void world_session::_SendPartialTimestampOpcode()
{
	world_packet packet(MSG_PARTIAL_TIMESTAMP, 0x0, m_endpoint, 2);
	packet << (uint16)m_timestamp;
	send_packet(packet, false);
}
Example #8
0
        void SetData(uint32 type, uint32 data)
        {
            switch (type)
            {
                case DATA_RAGE_WINTERCHILL_EVENT:
					Encounter[0] = data;
					break;
                case DATA_ANETHERON_EVENT:
                    Encounter[1] = data;
                    break;
                case DATA_KAZROGAL_EVENT:
					Encounter[2] = data;
					break;
                case DATA_AZGALOR_EVENT:
                    {
                        Encounter[3] = data;
                        if (data == DONE)
                        {
                            if (ArchiYell)
								break;
                            ArchiYell = true;

                            Creature* creature = instance->GetCreature(Azgalor);
                            if (creature)
                            {
                                Creature* unit = creature->SummonCreature(21987, creature->GetPositionX(), creature->GetPositionY(), creature->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 10000);

                                Map* map = creature->GetMap();
                                if (map->IsDungeon() && unit)
                                {
                                    unit->SetVisible(false);
                                    Map::PlayerList const &PlayerList = map->GetPlayers();
                                    if (PlayerList.isEmpty())
                                         return;

                                    for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
                                    {
                                         if (i->getSource())
                                         {
                                            WorldPacket packet(SMSG_MESSAGECHAT, 200);
                                            unit->BuildMonsterChat(&packet, CHAT_MSG_MONSTER_YELL, YELL_EFFORTS, 0, YELL_EFFORTS_NAME, i->getSource()->GetGUID());
                                            i->getSource()->GetSession()->SendPacket(&packet);

                                            WorldPacket data2(SMSG_PLAY_SOUND, 4);
                                            data2 << 10986;
                                            i->getSource()->GetSession()->SendPacket(&data2);
                                         }
                                    }
                                }
                            }
                        }
                    }
                    break;
                case DATA_ARCHIMONDE_EVENT:
					Encounter[4] = data;
					break;
                case DATA_RESET_TRASH_COUNT:
					Trash = 0;
					break;
                case DATA_TRASH:
                    if (data) Trash = data;
                    else     Trash--;
                    DoUpdateWorldState(WORLD_STATE_ENEMY_COUNT, Trash);
                    break;
                case TYPE_RETREAT:
                    if (data == SPECIAL)
                    {
                        if (!AncientGemGUID.empty())
                        {
                            for (std::list<uint64>::const_iterator itr = AncientGemGUID.begin(); itr != AncientGemGUID.end(); ++itr)
                            {
                                //don't know how long it expected
                                DoRespawnGameObject(*itr, DAY);
                            }
                        }
                    }
                    break;
                case DATA_ALLIANCE_RETREAT:
                    allianceRetreat = data;
                    HandleGameObject(HordeGate, true);
                    SaveToDB();
                    break;
                case DATA_HORDE_RETREAT:
                    hordeRetreat = data;
                    HandleGameObject(ElfGate, true);
                    SaveToDB();
                    break;
                case DATA_RAIDDAMAGE:
                    RaidDamage += data;
                    if (RaidDamage >= MINRAIDDAMAGE)
                        RaidDamage = MINRAIDDAMAGE;
                    break;
                case DATA_RESET_RAIDDAMAGE:
                    RaidDamage = 0;
                    break;
            }

             sLog->outDebug(LOG_FILTER_QCSCR, "QUANTUMCORE SCRIPTS: Instance Hyjal: Instance data updated for event %u (Data=%u)", type, data);

            if (data == DONE)
            {
                OUT_SAVE_INST_DATA;

                std::ostringstream saveStream;
                saveStream << Encounter[0] << ' ' << Encounter[1] << ' ' << Encounter[2] << ' '
					<< Encounter[3] << ' ' << Encounter[4]
                    << ' ' << allianceRetreat << ' ' << hordeRetreat
                    << ' ' << RaidDamage;

                str_data = saveStream.str();

                SaveToDB();
                OUT_SAVE_INST_DATA_COMPLETE;
            }
        }
Example #9
0
ScreenIODevice::ScreenIODevice(QPlainTextEdit *outWidget, QObject *parent) :
    QIODevice(parent)
{
    widget = outWidget;
    connect(this, SIGNAL(packet(QString)), this, SLOT(processPacket(QString)));
}
Example #10
0
   virtual const std::string Execute( const xml::XmlPacketArgs& args ) {


      // reset any existing configuration
      producer_.reset();
      consumer_.reset();
      bufferManager_.reset();
      hdf5_.reset();
      array_.clear();

      std::string response;
      std::string xml_data = command::ParseArg( "file", args );

      // incoming "file" is self-contained xml data.
      bool data_is_xml = true;

      xml_data = xml::XmlPacket::DecodeXml( xml_data );

      // parse configuration file
      ConfigFile configFile( xml_data, data_is_xml );

      // create constants
      const int BUFFER_SIZE        = configFile.BytesPerSecond();
      const double SAMPLE_RATE     = configFile.SampleRate();
      const int NUM_CHANNELS       = configFile.NumChannels();
      const int IPPS_PER_BUFFER    = static_cast<int>( ceil(1.0/configFile.IPP()));
      const int SAMPLES_PER_BUFFER = static_cast<int> ( configFile.SamplesPerIpp() * configFile.NumChannels() );

      // setup shared buffer header to assist in real-time processing 
      header_ = SharedBufferHeaderPtr( new ::xml::SharedBufferHeader(
               constants::NUM_BUFFERS,
               BUFFER_SIZE,
               SAMPLE_RATE,
               NUM_CHANNELS,
               IPPS_PER_BUFFER,
               SAMPLES_PER_BUFFER
               ));

      // create a response packet and return to requester
      std::string destination = command::ParseArg( "source", args );
      xml::XmlPacketArgs responsePacket;
      responsePacket["destination"] = destination;
      responsePacket["type"] = "response";
      gnuradar::xml::XmlPacket packet("gnuradar_server");

      try{

         // make sure we don't have an existing data set
         CheckForExistingFileSet ( configFile.DataFileBaseName() ) ;

         // setup HDF5 attributes and file set.
         hdf5_ = SetupHDF5( configFile );

         // read and parse configuration file.
         GnuRadarSettingsPtr settings = GetSettings( configFile );

         // create a device to communicate with hardware
         GnuRadarDevicePtr gnuRadarDevice( new GnuRadarDevice( settings ) );

         // setup shared memory buffers
         CreateSharedBuffers( BUFFER_SIZE );

         // setup the buffer manager
         bufferManager_ = SynchronizedBufferManagerPtr( 
               new SynchronizedBufferManager( 
                  array_, constants::NUM_BUFFERS, BUFFER_SIZE) );

         // setup table dimensions column = samples per ipp , row = IPP number
         vector<hsize_t> dims;
         dims.push_back( IPPS_PER_BUFFER );
         dims.push_back ( 
               static_cast<int> ( 
                  configFile.SamplesPerIpp() * configFile.NumChannels() ) 
               );

         // setup producer thread
         producer_ = gnuradar::ProducerThreadPtr (
               new ProducerThread ( bufferManager_, gnuRadarDevice ) );

         // flush header information
         header_->Close();

         // setup consumer thread
         consumer_ = gnuradar::ConsumerThreadPtr(
               new ConsumerThread ( bufferManager_ , header_, hdf5_, dims ) );

         // new model
         pcModel_->Initialize( bufferManager_, producer_, consumer_);

         // start producer thread
         pcModel_->Start();

         responsePacket["value"] = "OK";
         responsePacket["message"] = "Data collection successfully started.";
         response = packet.Format( responsePacket );

         // Start status thread to broadcast status packets to any subscribers.
         statusThread_->Stop();
         statusThread_->Start();

      }
      catch( std::runtime_error& e ){

         responsePacket["value"] = "ERROR";
         responsePacket["message"] = e.what();
         response = packet.Format( responsePacket );

      }
      catch( H5::Exception& e ){

         responsePacket["value"] = "ERROR";
         responsePacket["message"] = e.getDetailMsg();
         response = packet.Format( responsePacket );
      }

      return response;
   }
Example #11
0
	void GameListScreen::load() {
		network::Packet packet(network::Network::getSocket(), network::PacketType::SESSION_ASKGAME);
		packet.send();
		game::GameList::clear();

		m_buttonContainer = new Container();
		m_buttonContainer->setBackground("ressources/gui/background_characterFrame.png", full);
		this->add(m_buttonContainer);

		m_buttonUpContainer = new Container();
		m_buttonUpContainer->setLayout(new VerticalFixedLayout(VerticalFixedLayout::fixed, VerticalFixedLayout::fixed));
		m_buttonContainer->add(m_buttonUpContainer);

		m_buttonDownContainer = new Container();
		m_buttonDownContainer->setLayout(new VerticalFixedLayout(VerticalFixedLayout::full, VerticalFixedLayout::fixed));
		m_buttonContainer->add(m_buttonDownContainer);

		m_buttonContainer->setLayout(new SplitFixedLayout(SplitFixedLayout::horizontal, SplitFixedLayout::second, 60));

		m_mainContainer = new Container();
		m_mainContainer->setBackgroundColor(sf::Color(30, 30, 30));
		this->add(m_mainContainer);

		this->setLayout(new SplitFixedLayout(SplitFixedLayout::vertical, SplitFixedLayout::first, 250));

		m_matchmakingButton = new Button("Matchmaking", GUIStyle::button());
		m_matchmakingButton->setSize(200, 50);
		m_matchmakingButton->addListener(new GameListScreen_MainButton(this));
		m_buttonUpContainer->add(m_matchmakingButton);

		m_joinButton = new Button("Join Game", GUIStyle::button());
		m_joinButton->setSize(200, 50);
		m_joinButton->addListener(new GameListScreen_MainButton(this));
		m_joinButton->setEnable(false);
		m_buttonUpContainer->add(m_joinButton);

		m_createButton = new Button("Create Game", GUIStyle::button());
		m_createButton->setSize(200, 50);
		m_createButton->addListener(new GameListScreen_MainButton(this));
		m_buttonUpContainer->add(m_createButton);

		m_returnButton = new Button("Return", GUIStyle::button());
		m_returnButton->setSize(200, 50);
		m_returnButton->addListener(new GameListScreen_MainButton(this));
		m_buttonDownContainer->add(m_returnButton);

		std::vector<std::string> columns;
		columns.push_back("Name");
		columns.push_back("Creator");
		columns.push_back("Players");
		m_table = new Table(columns, GUIStyle::table());
		m_mainContainer->add(m_table);
		m_table->addListener(new GameListScreen_Table(this));
		m_table->setColumnsWidth(2, 100);

		m_tableStyle = new BasicStyle();
		m_tableStyle->setFontColor(sf::Color::White);

		refreshGame();

	}
Example #12
0
void djvFFmpegSave::write(const djvImage & in, const djvImageIoFrameInfo & frame)
    throw (djvError)
{
    //DJV_DEBUG("djvFFmpegSave::write");
    //DJV_DEBUG_PRINT("in = " << in);
    //DJV_DEBUG_PRINT("frame = " << frame);

    // Convert the image if necessary.

    const djvPixelData * p = &in;

    if (in.info() != _info)
    {
        //DJV_DEBUG_PRINT("convert = " << _image);

        _image.zero();

        djvOpenGlImage::copy(in, _image);

        p = &_image;
    }
    
    // Encode the image.

    avpicture_fill(
        (AVPicture *)_avFrameRgb,
        p->data(),
        _avFrameRgbPixel,
        p->w(),
        p->h());
    
    quint64 pixelByteCount = p->pixelByteCount();
    quint64 scanlineByteCount = p->scanlineByteCount();
    quint64 dataByteCount = p->dataByteCount();
    
    const uint8_t * const data [] =
    {
        p->data() + dataByteCount - scanlineByteCount,
        p->data() + dataByteCount - scanlineByteCount,
        p->data() + dataByteCount - scanlineByteCount,
        p->data() + dataByteCount - scanlineByteCount
    };
    
    const int lineSize [] =
    {
        -scanlineByteCount,
        -scanlineByteCount,
        -scanlineByteCount,
        -scanlineByteCount
    };
    
    sws_scale(
        _swsContext,
        //(uint8_t const * const *)_avFrameRgb->data,
        //_avFrameRgb->linesize,
        data,
        lineSize,
        0,
        p->h(),
        _avFrame->data,
        _avFrame->linesize);
    
    AVCodecContext * avCodecContext = _avStream->codec;

    djvFFmpeg::Packet packet;
    packet().data = 0;
    packet().size = 0;
    
    _avFrame->pts     = _frame++;
    _avFrame->quality = avCodecContext->global_quality;
    
    int finished = 0;
    
    int r = avcodec_encode_video2(
        avCodecContext,
        &packet(),
        _avFrame,
        &finished);
    
    if (r < 0)
    {
        throw djvError(
            djvFFmpeg::staticName,
            djvFFmpeg::toString(r));
    }

    //DJV_DEBUG_PRINT("finished = " << finished);
    //DJV_DEBUG_PRINT("size = " << packet().size);
    //DJV_DEBUG_PRINT("pts = " << static_cast<qint64>(packet().pts));
    //DJV_DEBUG_PRINT("dts = " << static_cast<qint64>(packet().dts));
    //DJV_DEBUG_PRINT("duration = " << static_cast<qint64>(packet().duration));

    // Write the image.
    
    packet().pts = av_rescale_q(
        packet().pts,
        avCodecContext->time_base,
        _avStream->time_base);
    packet().dts = av_rescale_q(
        packet().dts,
        avCodecContext->time_base,
        _avStream->time_base);
    packet().duration = av_rescale_q(
        packet().duration,
        avCodecContext->time_base,
        _avStream->time_base);
    packet().stream_index = _avStream->index;

    r = av_interleaved_write_frame(_avFormatContext, &packet());
    
    if (r < 0)
    {
        throw djvError(
            djvFFmpeg::staticName,
            djvFFmpeg::toString(r));
    }
}
Example #13
0
void WorldSession::HandleGuildFinderBrowse(WorldPacket& recvPacket)
{
    TC_LOG_DEBUG("network", "WORLD: Received CMSG_LF_GUILD_BROWSE");
    uint32 classRoles = 0;
    uint32 availability = 0;
    uint32 guildInterests = 0;
    uint32 playerLevel = 0; // Raw player level (1-85), do they use MAX_FINDER_LEVEL when on level 85 ?

    recvPacket >> classRoles >> availability >> guildInterests >> playerLevel;

    if (!(classRoles & GUILDFINDER_ALL_ROLES) || classRoles > GUILDFINDER_ALL_ROLES)
        return;
    if (!(availability & AVAILABILITY_ALWAYS) || availability > AVAILABILITY_ALWAYS)
        return;
    if (!(guildInterests & ALL_INTERESTS) || guildInterests > ALL_INTERESTS)
        return;
    if (playerLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) || playerLevel < 1)
        return;

    Player* player = GetPlayer();

    LFGuildPlayer settings(player->GetGUIDLow(), classRoles, availability, guildInterests, ANY_FINDER_LEVEL);
    LFGuildStore guildList = sGuildFinderMgr->GetGuildsMatchingSetting(settings, player->GetTeamId());
    uint32 guildCount = guildList.size();

    if (guildCount == 0)
    {
        WorldPacket packet(SMSG_LF_GUILD_BROWSE_UPDATED, 0);
        player->SendDirectMessage(&packet);
        return;
    }

    ByteBuffer bufferData(65 * guildCount);
    WorldPacket data(SMSG_LF_GUILD_BROWSE_UPDATED, 3 + guildCount * 65); // Estimated size
    data.WriteBits(guildCount, 19);

    for (LFGuildStore::const_iterator itr = guildList.begin(); itr != guildList.end(); ++itr)
    {
        LFGuildSettings guildSettings = itr->second;
        Guild* guild = sGuildMgr->GetGuildById(itr->first);

        ObjectGuid guildGUID = ObjectGuid(guild->GetGUID());

        data.WriteBit(guildGUID[7]);
        data.WriteBit(guildGUID[5]);
        data.WriteBits(guild->GetName().size(), 8);
        data.WriteBit(guildGUID[0]);
        data.WriteBits(guildSettings.GetComment().size(), 11);
        data.WriteBit(guildGUID[4]);
        data.WriteBit(guildGUID[1]);
        data.WriteBit(guildGUID[2]);
        data.WriteBit(guildGUID[6]);
        data.WriteBit(guildGUID[3]);

        bufferData << uint32(guild->GetEmblemInfo().GetColor());
        bufferData << uint32(guild->GetEmblemInfo().GetBorderStyle()); // Guessed
        bufferData << uint32(guild->GetEmblemInfo().GetStyle());

        bufferData.WriteString(guildSettings.GetComment());

        bufferData << uint8(0); // Unk

        bufferData.WriteByteSeq(guildGUID[5]);

        bufferData << uint32(guildSettings.GetInterests());

        bufferData.WriteByteSeq(guildGUID[6]);
        bufferData.WriteByteSeq(guildGUID[4]);

        bufferData << uint32(guild->GetLevel());

        bufferData.WriteString(guild->GetName());

        bufferData << uint32(guild->GetAchievementMgr().GetAchievementPoints());

        bufferData.WriteByteSeq(guildGUID[7]);

        bufferData << uint8(sGuildFinderMgr->HasRequest(player->GetGUIDLow(), guild->GetGUID())); // Request pending

        bufferData.WriteByteSeq(guildGUID[2]);
        bufferData.WriteByteSeq(guildGUID[0]);

        bufferData << uint32(guildSettings.GetAvailability());

        bufferData.WriteByteSeq(guildGUID[1]);

        bufferData << uint32(guild->GetEmblemInfo().GetBackgroundColor());
        bufferData << uint32(0); // Unk Int 2 (+ 128) // Always 0 or 1
        bufferData << uint32(guild->GetEmblemInfo().GetBorderColor());
        bufferData << uint32(guildSettings.GetClassRoles());

        bufferData.WriteByteSeq(guildGUID[3]);
        bufferData << uint32(guild->GetMembersCount());
    }

    data.FlushBits();
    data.append(bufferData);

    player->SendDirectMessage(&data);
}
void ScriptEngineServer::readClient(std::shared_ptr<ClientData> clientData)
{
	try
	{
		int32_t bufferMax = 1024;
		char buffer[bufferMax + 1];
		std::shared_ptr<std::vector<char>> packet(new std::vector<char>());
		int32_t bytesRead;
		_out.printDebug("Debug: Listening for incoming commands from client number " + std::to_string(clientData->fileDescriptor->id) + ".");
		while(!_stopServer)
		{
			//Timeout needs to be set every time, so don't put it outside of the while loop
			timeval timeout;
			timeout.tv_sec = 2;
			timeout.tv_usec = 0;
			fd_set readFileDescriptor;
			FD_ZERO(&readFileDescriptor);
			GD::bl->fileDescriptorManager.lock();
			int32_t nfds = clientData->fileDescriptor->descriptor + 1;
			if(nfds <= 0)
			{
				GD::bl->fileDescriptorManager.unlock();
				_out.printDebug("Connection to client number " + std::to_string(clientData->fileDescriptor->id) + " closed.");
				closeClientConnection(clientData);
				return;
			}
			FD_SET(clientData->fileDescriptor->descriptor, &readFileDescriptor);
			GD::bl->fileDescriptorManager.unlock();
			bytesRead = select(nfds, &readFileDescriptor, NULL, NULL, &timeout);
			if(bytesRead == 0) continue;
			if(bytesRead != 1)
			{
				_out.printDebug("Connection to client number " + std::to_string(clientData->fileDescriptor->id) + " closed.");
				closeClientConnection(clientData);
				return;
			}

			bytesRead = read(clientData->fileDescriptor->descriptor, buffer, bufferMax);
			if(bytesRead <= 0)
			{
				_out.printDebug("Connection to client number " + std::to_string(clientData->fileDescriptor->id) + " closed.");
				closeClientConnection(clientData);
				//If we close the socket, the socket file gets deleted. We don't want that
				//GD::bl->fileDescriptorManager.close(_serverFileDescriptor);
				return;
			}

			std::string command;
			command.insert(command.end(), buffer, buffer + bytesRead);
			//handleCommand(command, clientData);
		}
		closeClientConnection(clientData);
	}
    catch(const std::exception& ex)
    {
    	_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(BaseLib::Exception& ex)
    {
    	_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
    }
    catch(...)
    {
    	_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
    }
}
Example #15
0
//--------------------------------------------------------------------------------------//
//		Load Characters
//--------------------------------------------------------------------------------------//
void CClientSession::SendCharLoadReq(CNtlPacket * pPacket, CCharServer * app)
{
	sUC_CHARACTER_LOAD_REQ * req = (sUC_CHARACTER_LOAD_REQ*)pPacket->GetPacketData();
	printf("--- LOAD CHARACTERS  ACC ID: %i Farm ID: %i --- \n", req->accountId, req->serverFarmId);

	app->db->prepare("SELECT * FROM characters WHERE AccountID = ?");
	app->db->setInt(1, req->accountId);
	app->db->execute();
	cout << " TOTAL CHARACTERS: " << app->db->rowsCount() << endl;
// character info
	CNtlPacket packet(sizeof(sCU_CHARACTER_INFO));
	sCU_CHARACTER_INFO * res = (sCU_CHARACTER_INFO *)packet.GetPacketData();
	res->wOpCode = CU_CHARACTER_INFO;
	res->byCount = (int)app->db->rowsCount();
	for ( int i = 0; i < (int)app->db->rowsCount(); i++ )
	{
		app->db->fetch();
		wcscpy_s(res->sPcData[i].awchName, NTL_MAX_SIZE_CHAR_NAME_UNICODE, s2ws(app->db->getString("CharName")).c_str() );res->sPcData[i].charId = app->db->getInt("CharID");
		res->sPcData[i].byRace = app->db->getInt("Race");
		res->sPcData[i].byClass = app->db->getInt("Class");
		res->sPcData[i].bIsAdult = app->db->getBoolean("Adult");
		res->sPcData[i].byGender = app->db->getInt("Gender");
		res->sPcData[i].byFace = app->db->getInt("Face");
		res->sPcData[i].byHair = app->db->getInt("Hair");
		res->sPcData[i].byHairColor = app->db->getInt("HairColor");
		res->sPcData[i].bySkinColor = app->db->getInt("SkinColor");
		res->sPcData[i].byLevel = app->db->getInt("Level");
		res->sPcData[i].bTutorialFlag = app->db->getInt("TutorialFlag");
		res->sPcData[i].bNeedNameChange = app->db->getBoolean("NameChange");
		res->sPcData[i].dwMoney = app->db->getInt("Money");
		res->sPcData[i].dwMoneyBank = app->db->getInt("MoneyBank");
		res->sPcData[i].worldId = app->db->getInt("WorldID");
		res->sPcData[i].worldTblidx = app->db->getInt("WorldTable");
		res->sPcData[i].dwMapInfoIndex = app->db->getInt("MapInfoIndex");

		for(int j = 0; j < NTL_MAX_EQUIP_ITEM_SLOT; j++)
		{
			//Get items which the characters is wearing
			app->db2->prepare("select * from items WHERE place=7 AND pos=? AND owner_id=?");
			app->db2->setInt(1, j);
			app->db2->setInt(2, app->db->getInt("CharID"));
			app->db2->execute();
			app->db2->fetch();
			if(app->db2->rowsCount() == 0)
			{
				res->sPcData[i].sItem[j].tblidx =  INVALID_TBLIDX;
			}
			else
			{
				res->sPcData[i].sItem[j].tblidx = app->db2->getInt("tblidx");
			}

		}
	}
	packet.SetPacketLen( sizeof(sCU_CHARACTER_INFO) );
	int rc = g_pApp->Send( this->GetHandle(), &packet );
// load characters
	CNtlPacket packet2(sizeof(sCU_CHARACTER_LOAD_RES));
	sCU_CHARACTER_LOAD_RES * res2 = (sCU_CHARACTER_LOAD_RES *)packet2.GetPacketData();
	res2->wOpCode = CU_CHARACTER_LOAD_RES;
	res2->wResultCode = CHARACTER_SUCCESS;
	packet2.SetPacketLen( sizeof(sCU_CHARACTER_LOAD_RES) );
	rc = g_pApp->Send( this->GetHandle(), &packet2 );
}
Example #16
0
 ALWAYS_INLINE void serialize(char* buff, size_t* buff_n)
 {
     pack_message_id(Derived::message_id, buff, buff_n);
     packet(buff, buff_n, true);
     monitor.sent(this->message_id, this->size);
 }
Example #17
0
//--------------------------------------------------------------------------------------//
//		Create Character
//--------------------------------------------------------------------------------------//
void CClientSession::SendCharCreateReq(CNtlPacket * pPacket, CCharServer * app)
{
	sUC_CHARACTER_ADD_REQ * req = (sUC_CHARACTER_ADD_REQ*)pPacket->GetPacketData();
	printf("--- CHARACTER ADD REQUEST --- \n");

	app->db->prepare("CALL CharCreate (?,?,?,?,?,?,?,?,?, @charId, @wResultCode)");

	app->db->setString(1, Ntl_WC2MB(req->awchCharName));
	app->db->setInt(2, req->byRace);
	app->db->setInt(3, req->byClass);
	app->db->setInt(4, req->byGender);
	app->db->setInt(5, req->byFace);
	app->db->setInt(6, req->byHair);
	app->db->setInt(7, req->byHairColor);
	app->db->setInt(8, req->bySkinColor);
	app->db->setInt(9, this->accountID);

	app->db->execute();
	app->db->execute("SELECT @charId, @wResultCode");
	app->db->fetch(); 

	cout << "CHAR ID: " << app->db->print("@charId")
	<< " RESULT CODE: " << app->db->print("@wResultCode")
	<< endl;

	CNtlPacket packet(sizeof(sCU_CHARACTER_ADD_RES));
	sCU_CHARACTER_ADD_RES * res = (sCU_CHARACTER_ADD_RES *)packet.GetPacketData();

	res->wOpCode = CU_CHARACTER_ADD_RES;
	res->wResultCode = app->db->getInt("@wResultCode");

	if (res->wResultCode != 200) {

		packet.SetPacketLen( sizeof(sCU_CHARACTER_ADD_RES) );
		int rc = g_pApp->Send( this->GetHandle(), &packet );
		cout << " RESULT CODE: " << res->wResultCode << endl;

	}else{

	res->sPcDataSummary.charId = app->db->getInt("@charId");
	memcpy(res->sPcDataSummary.awchName, req->awchCharName, sizeof(wchar_t)* NTL_MAX_SIZE_CHAR_NAME_UNICODE);
	res->sPcDataSummary.byRace = req->byRace;
	res->sPcDataSummary.byClass = req->byClass;
	res->sPcDataSummary.bIsAdult = false;
	res->sPcDataSummary.byGender = req->byGender;
	res->sPcDataSummary.byFace = req->byFace;
	res->sPcDataSummary.byHair = req->byHair;
	res->sPcDataSummary.byHairColor = req->byHairColor;
	res->sPcDataSummary.bySkinColor = req->bySkinColor;
	res->sPcDataSummary.byLevel = 1;
	res->sPcDataSummary.worldId = 1;
	for (int j = 0; j < NTL_MAX_EQUIP_ITEM_SLOT; j++)
	{
		//Get items which the characters is wearing
		app->db2->prepare("select * from items WHERE place=7 AND pos=? AND owner_id=?");
		app->db2->setInt(1, j);
		app->db2->setInt(2, app->db->getInt("@charId"));
		app->db2->execute();
		app->db2->fetch();
		if (app->db2->rowsCount() == 0)
		{
			res->sPcDataSummary.sItem[j].tblidx = INVALID_TBLIDX;
		}
		else
		{
			res->sPcDataSummary.sItem[j].tblidx = app->db2->getInt("tblidx");
		}

	}

	packet.SetPacketLen( sizeof(sCU_CHARACTER_ADD_RES) );
	int rc = g_pApp->Send( this->GetHandle(), &packet );

	}
}
Example #18
0
		static packet unknown_response(std::string message) {
			return packet(nrpe::data::responsePacket, nrpe::data::version2, 3, message, 0);
		}
Example #19
0
void world_session::_SendFullTimestampOpcode()
{
	world_packet packet(MSG_FULL_TIMESTAMP, 0x80, m_endpoint, 4);
	packet << m_timestamp;
	send_packet(packet, false);
}
Example #20
0
		static packet make_request(std::string payload, unsigned int buffer_length) {
			return packet(nrpe::data::queryPacket, nrpe::data::version2, -1, payload, buffer_length);
		}
Example #21
0
void world_session::_SendImportantAckOpcode(uint32 timestamp)
{
	world_packet packet(MSG_IMPORTANT_ACK, 0x0, m_endpoint, 4);
	packet << (uint32)timestamp;
	send_packet(packet, false);
}
Example #22
0
		static nrpe::packet create_response(int ret, std::string string, int buffer_length) {
			return packet(nrpe::data::responsePacket, nrpe::data::version2, ret, string, buffer_length);
		}
Example #23
0
void RTMFPFlow::receive(UInt64 _stage,UInt64 deltaNAck,PacketReader& fragment,UInt8 flags) {
	if(_completed)
		return;

	if(!_pStream) { // if this==FlowNull
		fail("RTMFPMessage received for a RTMFPFlow unknown");
		(UInt64&)this->_stage = _stage;
		return;
	}

//	TRACE("RTMFPFlow ",id," _stage ",_stage);

	UInt64 nextStage = this->_stage+1;

	if(_stage < nextStage) {
		DEBUG("Stage ",_stage," on flow ",id," has already been received");
		return;
	}

	if(deltaNAck>_stage) {
		WARN("DeltaNAck ",deltaNAck," superior to _stage ",_stage," on flow ",id);
		deltaNAck=_stage;
	}
	
	if(this->_stage < (_stage-deltaNAck)) {
		auto it=_fragments.begin();
		while(it!=_fragments.end()) {
			if( it->first > _stage) 
				break;
			// leave all stages <= _stage
			PacketReader packet(it->second->data(),it->second->size());
			onFragment(it->first,packet,it->second.flags);
			if(it->second.flags&MESSAGE_END) {
				complete();
				return; // to prevent a crash bug!! (double fragments deletion)
			}
			_fragments.erase(it++);
		}

		nextStage = _stage;
	}
	
	if(_stage>nextStage) {
		// not following _stage, bufferizes the _stage
		auto it = _fragments.lower_bound(_stage);
		if(it==_fragments.end() || it->first!=_stage) {
			_fragments.emplace_hint(it,piecewise_construct,forward_as_tuple(_stage),forward_as_tuple(_poolBuffers,fragment,flags));
			if(_fragments.size()>100)
				DEBUG("_fragments.size()=",_fragments.size());
		} else
			DEBUG("Stage ",_stage," on flow ",id," has already been received");
	} else {
		onFragment(nextStage++,fragment,flags);
		if(flags&MESSAGE_END)
			complete();
		auto it=_fragments.begin();
		while(it!=_fragments.end()) {
			if( it->first > nextStage)
				break;
			PacketReader packet(it->second->data(), it->second->size());
			onFragment(nextStage++,packet,it->second.flags);
			if(it->second.flags&MESSAGE_END) {
				complete();
				return; // to prevent a crash bug!! (double fragments deletion)
			}
			_fragments.erase(it++);
		}

	}
}
Example #24
0
/// Read the client transmitted data
void WorldSocket::OnRead()
{
    TcpSocket::OnRead();

    while(1)
    {
        ///- Read the packet header and decipher it (if needed)
        if (!_remaining)
        {
            if (ibuf.GetLength() < 6)
                break;

            ClientPktHeader hdr;

            ibuf.Read((char *)&hdr, 6);
            _crypt.DecryptRecv((uint8 *)&hdr, 6);

            _remaining = ntohs(hdr.size) - 4;
            _cmd = hdr.cmd;
        }

        if (ibuf.GetLength() < _remaining)
            break;

        ///- Read the remaining of the packet
        WorldPacket packet((uint16)_cmd, _remaining);

        packet.resize(_remaining);
        if(_remaining) ibuf.Read((char*)packet.contents(), _remaining);
        _remaining = 0;

        ///- If log of world packets is enable, log the incoming packet
        if( sWorldLog.LogWorld() )
        {
            sWorldLog.Log("CLIENT:\nSOCKET: %u\nLENGTH: %u\nOPCODE: %s (0x%.4X)\nDATA:\n",
                (uint32)GetSocket(),
                packet.size(),
                LookupName(packet.GetOpcode(), g_worldOpcodeNames),
                packet.GetOpcode());

            uint32 p = 0;
            while (p < packet.size())
            {
                for (uint32 j = 0; j < 16 && p < packet.size(); j++)
                    sWorldLog.Log("%.2X ", packet[p++]);
                sWorldLog.Log("\n");
            }
            sWorldLog.Log("\n\n");
        }

        ///- If thepacket is PING or AUTH_SESSION, handle immediately
        switch (_cmd)
        {
            case CMSG_PING:
            {
                _HandlePing(packet);
                break;
            }
            case CMSG_AUTH_SESSION:
            {
                _HandleAuthSession(packet);
                break;
            }
            default:
            {
                ///- Else, put it in the world session queue for this user (need to be already authenticated)
                if (_session)
                    _session->QueuePacket(packet);
                else
                    sLog.outDetail("Received out of place packet with cmdid 0x%.4X", _cmd);
                break;
            }
        }
    }
}
void packetcreator::serverlrequest()
{
    packet p = packet(SERVER_REQUEST);
    server->dispatch(p);
}
Example #26
0
int WorldSocket::HandlePing(WorldPacket& recvPacket)
{
    uint32 ping;
    uint32 latency;

    // Get the ping packet content
    recvPacket >> ping;
    recvPacket >> latency;

    if (m_LastPingTime == ACE_Time_Value::zero)
        m_LastPingTime = ACE_OS::gettimeofday();            // for 1st ping
    else
    {
        ACE_Time_Value cur_time = ACE_OS::gettimeofday();
        ACE_Time_Value diff_time(cur_time);
        diff_time -= m_LastPingTime;
        m_LastPingTime = cur_time;

        if (diff_time < ACE_Time_Value(27))
        {
            ++m_OverSpeedPings;

            uint32 max_count = sWorld.getConfig(CONFIG_UINT32_MAX_OVERSPEED_PINGS);

            if (max_count && m_OverSpeedPings > max_count)
            {
                ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1);

                if (m_Session && m_Session->GetSecurity() == SEC_PLAYER)
                {
                    sLog.outError("WorldSocket::HandlePing: Player kicked for "
                                  "overspeeded pings address = %s",
                                  GetRemoteAddress().c_str());

                    return -1;
                }
            }
        }
        else
            m_OverSpeedPings = 0;
    }

    // critical section
    {
        ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1);

        if (m_Session)
            m_Session->SetLatency(latency);
        else
        {
            sLog.outError("WorldSocket::HandlePing: peer sent CMSG_PING, "
                          "but is not authenticated or got recently kicked,"
                          " address = %s",
                          GetRemoteAddress().c_str());
            return -1;
        }
    }

    WorldPacket packet(SMSG_PONG, 4);
    packet << ping;
    return SendPacket(packet);
}
void packetcreator::selectchar(int cid)
{
    packet p = packet(SELECT_CHAR);
    p.writeint(cid);
    server->dispatch(p);
}
Example #28
0
////////////////////////////////////////////////////
// This function decides the fate of the Everquest packet
// and dispatches it to the correct packet stream for handling function
void EQPacket::dispatchPacket(int size, unsigned char *buffer)
{
#ifdef DEBUG_PACKET
    debug ("dispatchPacket()");
#endif /* DEBUG_PACKET */
    /* Setup variables */

    // Create an object to parse the packet
    EQUDPIPPacketFormat packet(buffer, size, false);

    // signal a new packet
    emit newPacket(packet);

    /* Chat and Login Server Packets, Discard for now */
    if ((packet.getDestPort() == ChatServerPort) ||
            (packet.getSourcePort() == ChatServerPort))
        return;

    if (((packet.getDestPort() >= LoginServerMinPort) &&
            (packet.getDestPort() <= LoginServerMaxPort)) ||
            (packet.getSourcePort() >= LoginServerMinPort) &&
            (packet.getSourcePort() <= LoginServerMaxPort))
        return;

    /* discard pure ack/req packets and non valid flags*/
    if (packet.flagsHi() < 0x02 || packet.flagsHi() > 0x46 || size < 10)
    {
#if defined(PACKET_PROCESS_DIAG)
        seqDebug("discarding packet %s:%d ==>%s:%d flagsHi=%d size=%d",
                 (const char*)packet.getIPv4SourceA(), packet.getSourcePort(),
                 (const char*)packet.getIPv4DestA(), packet.getDestPort(),
                 packet.flagsHi(), size);
        seqDebug("%s", (const char*)packet.headerFlags(false));
#endif
        return;
    }

#if defined(PACKET_PROCESS_DIAG) && (PACKET_PROCESS_DIAG > 1)
    seqDebug("%s", (const char*)packet.headerFlags((PACKET_PROCESS_DIAG < 3)));
    uint32_t crc = packet.calcCRC32();
    if (crc != packet.crc32())
        seqWarn("CRC: Warning Packet seq = %d CRC (%08x) != calculated CRC (%08x)!",
                packet.seq(), packet.crc32(), crc);
#endif

    if (!packet.isValid())
    {
        seqWarn("INVALID PACKET: Bad CRC32 [%s:%d -> %s:%d] seq %04x len %d crc32 (%08x != %08x)",
                (const char*)packet.getIPv4SourceA(), packet.getSourcePort(),
                (const char*)packet.getIPv4DestA(), packet.getDestPort(),
                packet.seq(),
                packet.payloadLength(),
                packet.crc32(), packet.calcCRC32());
        return;
    }

    /* Client Detection */
    if (m_detectingClient && packet.getSourcePort() == WorldServerGeneralPort)
    {
        m_ip = packet.getIPv4DestA();
        m_client_addr = packet.getIPv4DestN();
        m_detectingClient = false;
        emit clientChanged(m_client_addr);
        seqInfo("Client Detected: %s", (const char*)m_ip);
    }
    else if (m_detectingClient && packet.getDestPort() == WorldServerGeneralPort)
    {
        m_ip = packet.getIPv4SourceA();
        m_client_addr = packet.getIPv4SourceN();
        m_detectingClient = false;
        emit clientChanged(m_client_addr);
        seqInfo("Client Detected: %s", (const char*)m_ip);
    }
    /* end client detection */



    if (packet.getSourcePort() == WorldServerChatPort)
    {
        dispatchWorldChatData(packet.payloadLength(), packet.payload(), DIR_Server);

        return;
    }
    else if (packet.getDestPort() == WorldServerChatPort)
    {
        dispatchWorldChatData(packet.payloadLength(), packet.payload(), DIR_Client);

        return;
    }

    /* stream identification */
    if (packet.getIPv4SourceN() == m_client_addr)
    {
        if (packet.getDestPort() == WorldServerGeneralPort)
            m_client2WorldStream->handlePacket(packet);
        else
            m_client2ZoneStream->handlePacket(packet);
    }
    else if (packet.getIPv4DestN() == m_client_addr)
    {
        if (packet.getSourcePort() == WorldServerGeneralPort)
            m_world2ClientStream->handlePacket(packet);
        else
            m_zone2ClientStream->handlePacket(packet);
    }

    return;
} /* end dispatchPacket() */
Example #29
0
bool FH2LocalClient::ScenarioInfoDialog(void)
{
    Settings & conf = Settings::Get();
    Cursor & cursor = Cursor::Get();
    Display & display = Display::Get();
    LocalEvent & le = LocalEvent::Get();

    if(!GetCurrentMapInfo() ||
	!GetPlayersInfo()) return false;

    const Sprite & panel = AGG::GetICN(ICN::NGHSBKG, 0);
    const Rect  rectPanel(204, 32, panel.w(), panel.h());
    const Point pointOpponentInfo(rectPanel.x + 24, rectPanel.y + 202);
    const Point pointClassInfo(rectPanel.x + 24, rectPanel.y + 282);
    const Rect  box(pointOpponentInfo, 360, 180);

    Rects::const_iterator itr;

    Interface::PlayersInfo playersInfo(true, false, false);

    playersInfo.UpdateInfo(conf.GetPlayers(), pointOpponentInfo, pointClassInfo);

    RedrawScenarioStaticInfo(rectPanel);
    playersInfo.RedrawInfo();

    Button buttonSelectMaps(rectPanel.x + 309, rectPanel.y + 45, ICN::NGEXTRA, 64, 65);
    Button buttonOk(rectPanel.x + 31, rectPanel.y + 380, ICN::NGEXTRA, 66, 67);
    Button buttonCancel(rectPanel.x + 287, rectPanel.y + 380, ICN::NGEXTRA, 68, 69);

    SpriteCursor sp;
    sp.SetSprite(AGG::GetICN(ICN::NGEXTRA, 80));

    if(! Modes(ST_ADMIN))
    {
	buttonOk.SetDisable(true);
	buttonSelectMaps.SetDisable(true);
    }

    buttonSelectMaps.Draw();
    buttonOk.Draw();
    buttonCancel.Draw();
    cursor.Show();
    display.Flip();

    bool exit = false;
    bool update_info = false;
    u8 change_color = Color::NONE;
    DEBUG(DBG_NETWORK, DBG_INFO, "start queue");

    while(!exit && le.HandleEvents())
    {
        if(Ready())
	{
	    QueueMessage packet;

	    if(!Recv(packet)) return false;
	    DEBUG(DBG_NETWORK, DBG_INFO, "recv: " << Network::GetMsgString(packet.GetID()));

	    switch(packet.GetID())
    	    {
		case MSG_READY:
		    break;

		case MSG_CHANGE_RACE:
		    Network::UnpackRaceColors(packet);
		    update_info = true;
		    break;

		case MSG_UPDATE_PLAYERS:
		{
		    MsgUpdatePlayers(packet);
		    if(Modes(ST_ADMIN))
		    {
			buttonOk.Release();
			buttonOk.SetDisable(false);
			buttonSelectMaps.Release();
			buttonSelectMaps.SetDisable(false);
		    }
		    else
		    {
			buttonOk.Press();
			buttonOk.SetDisable(true);
			buttonSelectMaps.Press();
			buttonSelectMaps.SetDisable(true);
		    }
		    update_info = true;
		    break;
		}

		case MSG_SET_CURRENT_MAP:
		    Network::PacketPopMapsFileInfo(packet, conf.CurrentFileInfo());
		    playersInfo.UpdateInfo(conf.GetPlayers(), pointOpponentInfo, pointClassInfo);
		    update_info = true;
		    break;

		case MSG_MESSAGE:
		    break;

		case MSG_SHUTDOWN:
		    exit = true;
		    break;


		default: break;
	    }
	}

	if(update_info)
	{
	    cursor.Hide();
	    RedrawScenarioStaticInfo(rectPanel);
	    playersInfo.RedrawInfo();
	    buttonSelectMaps.Draw();
	    buttonOk.Draw();
	    buttonCancel.Draw();
	    cursor.Show();
	    display.Flip();
	    update_info = false;
	}

	// press button
        if(buttonSelectMaps.isEnable()) le.MousePressLeft(buttonSelectMaps) ? buttonSelectMaps.PressDraw() : buttonSelectMaps.ReleaseDraw();
        if(buttonOk.isEnable()) le.MousePressLeft(buttonOk) ? buttonOk.PressDraw() : buttonOk.ReleaseDraw();
        le.MousePressLeft(buttonCancel) ? buttonCancel.PressDraw() : buttonCancel.ReleaseDraw();

	// click select
	if(Game::HotKeyPress(Game::EVENT_BUTTON_SELECT) ||
	    (buttonSelectMaps.isEnable() && le.MouseClickLeft(buttonSelectMaps)))
	{
	    cursor.Hide();
	    sp.Hide();
	    cursor.Show();

	    // recv maps_info_list
	    QueueMessage packet(MSG_GET_MAPS_LIST);
	    if(SendWait(packet, MSG_GET_MAPS_LIST, "ScenarioInfoDialog: "))
	    {
		MapsFileInfoList lists;
		Network::PacketPopMapsFileInfoList(packet, lists);
		if(const Maps::FileInfo *fi = Dialog::SelectScenario(lists))
        	{
		    // send set_maps_info
	    	    packet.Reset();
		    packet.SetID(MSG_SET_CURRENT_MAP);
	    	    packet.Push(fi->file);
		    DEBUG(DBG_NETWORK, DBG_INFO, "send: " << Network::GetMsgString(packet.GetID()));
	    	    if(!Send(packet)) return false;
		}
		update_info = true;
	    }
	}
	else
	// click cancel
        if(le.MouseClickLeft(buttonCancel) || Game::HotKeyPress(Game::EVENT_DEFAULT_EXIT))
    	    return false;
        else
        // click ok
        if(Game::HotKeyPress(Game::EVENT_DEFAULT_READY) || (buttonOk.isEnable() && le.MouseClickLeft(buttonOk)))
    	{
/*
	    packet.Reset();
	    packet.SetID(MSG_START_GAME);
	    DEBUG(DBG_NETWORK, DBG_INFO, "send: " << Network::GetMsgString(packet.GetID()));
	    if(!Send(packet)) return false;
	    cursor.Hide();
	    return true;
*/
	}
	else
	if(Modes(ST_ADMIN) && le.MouseClickLeft(box))
	{
	    // click colors
	    if(Player* player = playersInfo.GetFromOpponentClick(le.GetMouseCursor()))
	    {
		u8 humans = conf.GetPlayers().GetColors(CONTROL_HUMAN);

		if((humans & player->color) && Color::NONE == change_color)
		{
		    cursor.Hide();
		    sp.Move((*itr).x - 3, (*itr).y - 3);
		    cursor.Show();
		    display.Flip();
		    change_color = player->color;
		}
		else
		if(conf.CurrentFileInfo().AllowHumanColors() & player->color)
		{
		    cursor.Hide();
		    sp.Hide();
		    cursor.Show();
		    display.Flip();
		    if(Color::NONE != change_color)
		    {
			QueueMessage packet(MSG_CHANGE_COLORS);
			packet.Push(change_color);
			packet.Push(player->color);
		        DEBUG(DBG_NETWORK, DBG_INFO, "send: " << Network::GetMsgString(packet.GetID()));
			if(!Send(packet)) return false;
			change_color = Color::NONE;
		    }
		}
	    }
	    else
	    // click races
	    if(Player* player = playersInfo.GetFromClassClick(le.GetMouseCursor()))
	    {
		if(conf.AllowChangeRace(player->color))
		{
                    switch(player->race)
                    {
                        case Race::KNGT: player->race = Race::BARB; break;
                        case Race::BARB: player->race = Race::SORC; break;
                        case Race::SORC: player->race = Race::WRLK; break;
                        case Race::WRLK: player->race = Race::WZRD; break;
                        case Race::WZRD: player->race = Race::NECR; break;
                        case Race::NECR: player->race = Race::RAND; break;
                        case Race::RAND: player->race = Race::KNGT; break;
                        default: break;
                    }
		    if(change_color)
		    {
			cursor.Hide();
			sp.Hide();
			cursor.Show();
			display.Flip();
			change_color = Color::NONE;
		    }
		    if((player->race & Race::ALL) || player->race == Race::RAND)
		    {
			QueueMessage packet(MSG_CHANGE_RACE);
			packet.Push(player->color);
			packet.Push(player->race);
		        DEBUG(DBG_NETWORK, DBG_INFO, "send: " << Network::GetMsgString(packet.GetID()));
			if(!Send(packet)) return false;
		    }
		}
	    }
	}

        DELAY(10);
    }

    return false;
}
void BufferSender::handleIO( bool readyRead, bool readyWrite ) 
{
   mc2dbg2 << "[BufferSender]: handleIO(" 
           << readyRead << ", " << readyWrite << ")" 
           << " state: " << ::getStateString( getState() )
           << " selectable: " << getSelectable() << endl;
   //
   // if we got read signal, which indicates error
   //
   if ( readyRead ) {
      m_impl->state = ERROR;
   } else if ( readyWrite ) {
      if ( getState() == CONNECTING ) {
         if ( m_impl->m_bufferSendTime.getTime() >= 1000 ) {
            mc2dbg << warn << "[BufferSender] Took " 
                   << m_impl->m_bufferSendTime << " to connect to "
                   << " destination " << getDestination() << endl;
         }
         m_impl->state = READY;
         mc2dbg2 << "[BufferSender]: connected to: " << getDestination() 
                 << endl;
      }

      // start send clock if we start writting
      if ( m_impl->bytesLeft == m_impl->buff.size() ) {
         m_impl->m_bufferSendTime = DebugClock();
      }
      //
      // send the buffer and reset timeout 
      //
      setWorking();
      send();


      if ( m_impl->state == DONE ) {
         // if send time is larger than 1 second print info
         if ( m_impl->m_bufferSendTime.getTime() >= 1000 ) {

            // note: should probably use timer stuff in MultiPacketSender or
            // something else, since this class is not specific to Packets 
            // (thus the extra size check here)
            if ( m_impl->buff.size() > 4 ) {
               Packet packet( m_impl->buff.data() + 4, m_impl->buff.size() - 4,
                              true );
               mc2dbg << warn << "[BufferSender] It took " 
                      << m_impl->m_bufferSendTime << " to send buffer."
                      <<  " Packet type: " 
                      << packet.getSubTypeAsString() << endl;
            }
         }
         // start idle timer now when we got nothing to do
         setIdle();
      }

   } else {
      // woohaa, would be very bad....and strange.
      MC2_ASSERT( readyRead && readyWrite );
   }

   // if state is error
   // set timers to 0 and let the "creator" 
   // of this selectable take care of it.
   if ( m_impl->state == ERROR ) {
      mc2dbg2 << "[BufferSender] socket error. socket:" << getSelectable() << endl;
      setTimeout( 0 );
   }

}