/*
 * Get next record (throw EStreamOverflow)
 */
bool CMessageRecorder::loadNext( TMessageRecord& record )
{
	// WARNING!!! This features doesn't work anymore becaues bufferAsVector() is not available with new CMemStream
	nlstop;
	return false;

	nlassert( _File.is_open() );

	// Dump from file
	CMemStream stream ( true, true );
	uint32 len;
	char c;
	_File >> c; // skip "* ";
	_File >> (int&)len;
	_File.ignore(); // skip delimiter
	if ( ! _File.fail() )
	{
		_File.get( (char*)stream.bufferToFill( len+1 ), len+1, '\0' );
		//stream.bufferAsVector().resize( len ); // cut end of cstring
		nldebug( "MR:%s: Reading [%s]", _Filename.c_str(), stream.buffer() );

		// Serial from stream
		record.serial( stream ); // may throw EStreamOverflow if _File.fail()
	}

	return ! _File.fail(); // retest
}
Exemplo n.º 2
0
//-----------------------------------------------------------------------------
void CGmTpPendingCommand::saveMap()
{
	CMemStream stream;
	string fileName = toString("gm_pending_tp.bin");
	
	stream.serialCont( _CharacterTpPending );

	CBackupMsgSaveFile msg( fileName, CBackupMsgSaveFile::SaveFile, Bsi );
	msg.DataMsg.serialBuffer((uint8*)stream.buffer(), stream.size());
	Bsi.sendFile( msg );
}
Exemplo n.º 3
0
int main (int argc, char **argv)
{
	if (argc != 3)
	{
		nlinfo ("%s send udp datagram to a specific port to test a connection between client and server", argv[0]);
		nlinfo ("usage: <ip_address> <port>");
		exit (EXIT_FAILURE);
	}

	CUdpSimSock	*UdpSock = NULL;
	UdpSock = new CUdpSimSock( false );
	try
	{
		UdpSock->connect (CInetAddress (argv[1], atoi(argv[2])));
	}
	catch (Exception &e)
	{
		nlwarning ("Cannot connect to remote UDP host: %s", e.what());
		exit (EXIT_FAILURE);
	}

	uint8 *packet = new uint8[1000];
	uint32 psize;
	
	while(true)
	{
		CMemStream msgout;
		uint32 foo = 10;
		msgout.serial (foo);
		uint32 size = msgout.length();
		UdpSock->send (msgout.buffer(), size);
		nldebug ("Sent UDP datagram size %d to %s", size, UdpSock->localAddr().asString().c_str());

		while (UdpSock->dataAvailable())
		{
			psize = 1000;
			try
			{
				UdpSock->receive (packet, psize);
				nldebug ("Received UDP datagram size %d bytes from %s", psize, UdpSock->localAddr().asString().c_str());
			}
			catch ( Exception& e )
			{
				nlwarning ("Received failed: %s", e.what());
			}
		}
		nlSleep (1000);
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 4
0
void	cbQuery(CMemStream &msgin, TSockId host)
{
	uint32		queryId = CLogAnalyserService::getInstance()->getNextQueryId();
	std::string	queryStr;
	msgin.serial(queryStr);

	CLogAnalyserService::getInstance()->executeQuery(queryId, queryStr);

	CMemStream	msgout;
	uint32		fake	= 0;
	msgout.serial(fake);

	std::string	result = NLMISC::toString("1:%d:Query '%s' stacked:ver=2", queryId, queryStr.c_str());
	msgout.serial (result);
	WebServer->send (msgout, host);
}
	// From CInterfaceElementVisitor
	void visit(CInterfaceElement *elem)
	{
 		if (!elem) return;
		nlassert(!Stream.isReading());
		if (!elem->wantSerialConfig()) return; // has something to save ?
		// if yes, save the name for further retrieval
		std::string id = elem->getId();
		Stream.serial(id);
		// measure size of object
		// NB : here we write in a separate stream to accomplish this because
		// the object may do some 'serialPtr', this would cause the second serial to have a different size
		// because the object would already have been recorded in the ptr table of the stream
		CMemStream measureStream;
		nlassert(!measureStream.isReading());
		elem->serialConfig(measureStream);
		uint32 chunkSize = measureStream.getPos();
		Stream.serial(chunkSize);
		elem->serialConfig(Stream);
	}
Exemplo n.º 6
0
void	cbCancelQuery(CMemStream &msgin, TSockId host)
{
	CMemStream	msgout;
	uint32		fake	= 0;
	msgout.serial(fake);

	std::string	idStr;
	msgin.serial(idStr);

	uint32	queryId;
	NLMISC::fromString(idStr, queryId);

	CLogAnalyserService::getInstance()->cancelQuery(queryId);

	std::string	result = "1:Query cancelled";

	msgout.serial (result);
	WebServer->send (msgout, host);
}
Exemplo n.º 7
0
void CPsfBase::ReadProgram(CStream& stream)
{
	assert(m_program == NULL);

	CMemStream outputStream;
	uint8* compressedProgram = new uint8[m_programSize];
	stream.Read(compressedProgram, m_programSize);

	{
		z_stream zStream;
		const int bufferSize = 0x4000;
		uint8 buffer[bufferSize];
		memset(&zStream, 0, sizeof(zStream));
		inflateInit(&zStream);
		zStream.avail_in	= m_programSize;
		zStream.next_in		= reinterpret_cast<Bytef*>(compressedProgram);
		while(1)
		{
			zStream.avail_out	= bufferSize;
			zStream.next_out	= reinterpret_cast<Bytef*>(buffer);
			int result = inflate(&zStream, 0);
			if(result < 0)
			{
				throw std::runtime_error("Error occured while trying to decompress.");
			}
			outputStream.Write(buffer, bufferSize - zStream.avail_out);
			if(result == Z_STREAM_END)
			{
				break;
			}
		}
		inflateEnd(&zStream);
	}

	delete [] compressedProgram;

	m_uncompProgramSize = outputStream.GetSize();

	{
		m_program = new uint8[m_uncompProgramSize];
		memcpy(m_program, outputStream.GetBuffer(), m_uncompProgramSize);
	}
}
Exemplo n.º 8
0
void	cbQueryList(CMemStream &msgin, TSockId host)
{
	CMemStream	msgout;
	uint32		fake	= 0;
	msgout.serial(fake);

	std::vector<CLogAnalyserService::CQuery*>	queries;
	CLogAnalyserService::getInstance()->getQueryList(queries);

	std::string	result = "1:"+toString(queries.size())+"\n";

	uint	i;
	for (i=0; i<queries.size(); ++i)
	{
		result += toString("%d:%d:%d:%s\n", queries[i]->Id, (queries[i]->State == CLogAnalyserService::QueryAwaiting ? 0 : (queries[i]->State == CLogAnalyserService::QueryBeingTreated ? 1 : 2)), (int)(queries[i]->Progress), queries[i]->Query.c_str());
	}

	msgout.serial (result);
	WebServer->send (msgout, host);
}
/*
 * Add a record
 */
void CMessageRecorder::recordNext( sint64 updatecounter, TNetworkEvent event, TSockId sockid, CMessage& message )
{
	nlassert( _File.is_open() );

	if ( (_RecordAll) || (event != Sending) )
	{
		// Serial to stream
		TMessageRecord rec ( event, sockid, message, updatecounter /*CTime::getLocalTime()*/ );
		CMemStream stream ( false, true );
		rec.serial( stream );
		char c = '\0';      // end of cstring
		stream.serial( c ); // added to the stream for _File << (char*)stream.buffer()

		// Dump to file
		nldebug( "MR:%s: Recording [%s]", _Filename.c_str(), stream.buffer() );
		int len = (int)(stream.length()-2); // not the null character (and its separator) at the end of the buffer
		_File << "* ";
		_File <<  len; // if we put the expression directly, it makes an access violation ! Weird.
		_File << " ";
		_File << (char*)stream.buffer() << endl;
	}
}
Exemplo n.º 10
0
void sendPing ()
{
	CMemStream msgout;
	for (TClientMap::iterator it = ClientMap.begin (); it != ClientMap.end(); it++)
	{
		msgout.clear();

		sint64 t = CTime::getLocalTime ();
		msgout.serial (t);

		uint32 p = GETCLIENTA(it)->NextPingNumber;
		msgout.serial (p);

		uint32 b = GETCLIENTA(it)->BlockNumber;
		msgout.serial (b);

		uint8 dummy=0;
		while (msgout.length() < 200)
			msgout.serial (dummy);

		uint32 size =  msgout.length();
		nlassert (size == 200);

		try
		{
			// send the new ping to the client
			ReceiveTask->DataSock->sendTo (msgout.buffer(), size, GETCLIENTA(it)->Address);
		}
		catch (const Exception &e)
		{
			nlwarning ("Can't send UDP packet to '%s' (%s)", GETCLIENTA(it)->Address.asString().c_str(), e.what());
		}

		GETCLIENTA(it)->NextPingNumber++;
		GETCLIENTA(it)->NbPing++;
	}
}
Exemplo n.º 11
0
void CMirrorService::receiveMessageToForwardFromClient( CMessage& msgin, TServiceId senderId )
{
	H_AUTO(receiveMessageToForwardFromClient);

	uint8 counter;
	msgin.serial( counter ); // there are no multiple messages, but there can be multiple destinations
	if ( counter == MSG_BROADCAST )
	{
		CMemStream ms = msgin.extractStreamFromPos( msgin.getHeaderSize() + sizeof(counter) );
#ifdef NL_DEBUG
		string name = msgin.readTypeAtCurrentPos(); // warning: the pos is updated in msgin
		nldebug( "MSG: Broadcasting message from %s (msg %s, %u b)", servStr(senderId).c_str(), name.c_str(), ms.length() );
#endif
		pushMessageToLocalQueue( _MessagesToBroadcastLocally, senderId, ms );
		_RemoteMSList.pushMessageToRemoteQueue( DEST_MSG_BROADCAST, senderId, ms );
	}
	else
	{
		for ( uint i=0; i!=(uint)counter; ++i )
		{
			TServiceId destId;
			msgin.serial( destId );
			TClientServices::iterator ics = _ClientServices.find( destId );
			if ( ics != _ClientServices.end() )
			{
				// Destination service is local => buffer the message (which is found in the stream after the list of destinations)
				CMemStream m = msgin.extractStreamFromPos( msgin.getHeaderSize() + sizeof(counter) + counter*sizeof(destId) );
				pushMessageToLocalQueue( GET_CLIENT_SERVICE_INFO(ics).Messages, senderId, m );
			}
			else
			{
				// Destination service is remote => find the corresponding remote MS and buffer the message
				CMemStream m = msgin.extractStreamFromPos( msgin.getHeaderSize() + sizeof(counter) + counter*sizeof(destId) );
				_RemoteMSList.pushMessageToRemoteQueue( (TServiceId)destId, (TServiceId)senderId, m );
			}
		}
	}
}
Exemplo n.º 12
0
template <class T> bool check (T value)
{
	T result;
	CMemStream msgout;
	msgout.serial (value);
	CMemStream msgin (true);
	msgin.fill (msgout.buffer(), msgout.size());
	msgin.serial (result);
	
	if (value != result)
	{
		nlwarning ("CHECK FAILED: %s != %s", toString (value).c_str(), toString (result).c_str());
	}

	if (toString(value) != toString(result))
	{
		nlwarning ("toString() CHECK FAILED: %s != %s", toString (value).c_str(), toString (result).c_str());
	}
		
	return value == result;
}
Exemplo n.º 13
0
//
// Main
//
int main( int argc, char **argv )
{
	createDebug ();
	DebugLog->addNegativeFilter(" ");
	
	InfoLog->displayRawNL ("\nNevrax UDP benchmark client\n\nPress <CTRL-C> to exit");

	CPath::addSearchPath(UDP_DIR);

	loadConfigFile ();

	CCallbackClient *cc = new CCallbackClient;
	
	cc->addCallbackArray (CallbackArray, sizeof(CallbackArray)/sizeof(CallbackArray[0]));
	cc->setDisconnectionCallback (cbDisconnect, NULL);

	try
	{
		InfoLog->displayRawNL ("Try to connect to %s:%d", ServerAddr.c_str(), TCPPort);
		cc->connect(CInetAddress (ServerAddr, TCPPort));

		CMessage msgout ("INIT");
		msgout.serial (ConnectionName);
		msgout.serial (Version);
		cc->send (msgout);

		InfoLog->displayRawNL ("Waiting the server answer...");
	}
	catch(Exception &e)
	{
		InfoLog->displayRawNL ("Can't connect to %s:%d (%s)\n", ServerAddr.c_str(), TCPPort, e.what());
		exit ("");
	}

	uint8 *packet = new uint8[MaxUDPPacketSize];
	uint32 psize;

#ifdef USE_3D

	UDriver *Driver = UDriver::createDriver();
	Driver->setDisplay(UDriver::CMode(800, 600, 32, true));
	UScene *Scene= Driver->createScene(false);
	UCamera Camera= Scene->getCam();
	Camera.setTransformMode(UTransform::DirectMatrix);
	UTextContext *TextContext= Driver->createTextContext(CPath::lookup("n019003l.pfb"));
	TextContext->setFontSize(18);

	Camera.setPerspective(80*Pi/180, 1.33, 0.15, 1000);

	CEvent3dMouseListener MouseListener;
	MouseListener.addToServer(Driver->EventServer);
	MouseListener.setFrustrum(Camera.getFrustum());
	MouseListener.setHotSpot(CVector(0,0,0));
	CMatrix		initMat;
	initMat.setPos(CVector(0,-5,0));
	MouseListener.setMatrix(initMat);

#endif



	while (cc->connected ())
	{
#ifdef USE_3D

		// Manip.
		Camera.setMatrix(MouseListener.getViewMatrix());

		Driver->EventServer.pump();
		if(Driver->AsyncListener.isKeyPushed(KeyESCAPE))
			return EXIT_SUCCESS;

		Driver->clearBuffers(CRGBA(255,255,255,0));

		Scene->render();

		CGraph::render (*Driver, *TextContext);

		Driver->swapBuffers();

		FpsGraph.addValue (1);

#endif


		CConfigFile::checkConfigFiles ();

		// update TCP connection
		cc->update ();

		// update UDP connection
		if (UdpSock != NULL)
		{
			if (Mode == 0)
			{
				// init the UDP connection
				CMemStream msgout;
				msgout.serial (Mode);
				msgout.serial (Session);
				uint32 size = msgout.length();
#ifdef USE_3D
				UploadGraph.addValue ((float)size);
#endif
				UdpSock->send (msgout.buffer(), size);
				nldebug ("Sent init udp connection");
				nlSleep (100);
			}

			while (UdpSock->dataAvailable())
			{
				psize = MaxUDPPacketSize;
				UdpSock->receive (packet, psize);
#ifdef USE_3D
				DownloadGraph.addValue ((float)psize);
#endif
				CMemStream msgin( true );
				memcpy (msgin.bufferToFill (psize), packet, psize);

				sint64 t;
				msgin.serial (t);

				uint32 p;
				msgin.serial (p);

				uint32 b;
				msgin.serial (b);
	
				// I received a ping, send a pong

				CMemStream msgout;
				msgout.serial (Mode);
				msgout.serial (t);
				msgout.serial (p);
				msgout.serial (b);
				uint8 dummy=0;
				while (msgout.length() < 200)
					msgout.serial (dummy);

				uint32 size =  msgout.length();
				nlassert (size == 200);

#ifdef USE_3D
				UploadGraph.addValue ((float)size);
#endif
				UdpSock->send (msgout.buffer(), size);
			}
		}

		nlSleep (1);
	}
	
	exit ("");
	return EXIT_SUCCESS;
}
Exemplo n.º 14
0
void	CLogAnalyserService::updateWebConnection()
{

	nlassert(WebServer != NULL);

	try
	{
		WebServer->update ();

		while (WebServer->dataAvailable ())
		{
			// create a string mem stream to easily communicate with web server
			NLMISC::CMemStream msgin (true);
			TSockId		host;
			bool		success = false;
			std::string	reason;

			try
			{
				WebServer->receive (msgin, &host);

				uint32	fake = 0;
				msgin.serial(fake);

				uint8	messageType = 0xff;
				msgin.serial (messageType);

				if(messageType<sizeof(WebCallbackArray)/sizeof(WebCallbackArray[0]))
				{
					WebCallbackArray[messageType](msgin, host);
					success = true;
				}
				else
				{
					reason = "unknown command "+toString(messageType);
				}
			}
			catch (Exception &e)
			{
				nlwarning ("Error during receiving: '%s'", e.what ());
				reason = e.what();
			}

			if(!success)
			{
				nlwarning ("Failed to decode Web command");

				CMemStream	msgout;
				uint32		fake = 0;
				msgout.serial(fake);

				std::string	result = "0:Failed to decode command";
				if (!reason.empty())
					result += " ("+reason+")";
				msgout.serial (result);
				WebServer->send (msgout, host);
			}
		}
	}
	catch (Exception &e)
	{
		nlwarning ("Error during update: '%s'", e.what ());
	}
}
Exemplo n.º 15
0
void	cbResult(CMemStream &msgin, TSockId host)
{
	CMemStream	msgout;
	uint32		fake	= 0;
	msgout.serial(fake);

	std::string	idStr;
	msgin.serial(idStr);

	std::string	result;
	bool		success = false;
	uint		numPage = 0;
	sint		page = 0;
	std::string	filter;
	bool		filter_exclusive = false;
	uint32		queryId = 0xffffffff;

	//nlinfo("received query '%s'", idStr.c_str());

	string::size_type		pos = idStr.find("%!");
	if (pos != std::string::npos)
	{
		// parse input
		const char*	p = idStr.c_str()+pos+2;
		while (*p != '\0')
		{
			std::string	param;
			std::string	value;
			while (*p != '\0' && *p != '=')
				param += *(p++);
			if (*p != '=')
				break;
			++p;
			while (*p != '\0' && *p != ' ')
			{
				if (*p == '\\')
					++p;
				if (*p == '\0')
					break;
				value += *(p++);
			}

			while (*p == ' ')
				++p;

			//nlinfo("param=%s value=%s", param.c_str(), value.c_str());

			if (param == "id")				NLMISC::fromString(value, queryId);
			else if (param == "page")		NLMISC::fromString(value, page);
			else if (param == "filter")		filter = value;
			else if (param == "fmode")		filter_exclusive = (value == "exclusive");
		}
	}
	else
	{
		// old compatibility mode
		vector<string>	res;
		explode(idStr, string(":"), res);

		if (res.size() >= 1)
		{
			if (res.size() >= 2)
				NLMISC::fromString(res[1], page);
			else
				page = 0;

			NLMISC::fromString(res[0], queryId);
		}
	}

	//nlinfo("display result for: id=%d page=%d filter=%s", queryId, page, filter.c_str());

	if (queryId != 0xffffffff)
		success = CLogAnalyserService::getInstance()->getQueryResult(queryId, result, page, numPage, filter, filter_exclusive, LinePerPage);
	else
		result = "queryId not specified ('"+idStr+"' query provided)";

	if (success)
		result = "1:"+toString(numPage)+":"+toString(page)+":"+result;
	else
		result = "0:"+result;

	msgout.serial (result);
	WebServer->send (msgout, host);
}