WONStatus PeerAuthServer::GetComplete(WONStatus theStatus, ByteBufferPtr &theComplete)
{
	mState = STATE_NOT_STARTED; // reset state now
	
	WriteBuffer aComplete(mLengthFieldSize);
	aComplete.AppendLong(203);					// Auth peer to peer service
	aComplete.AppendLong(53);					// Complete

	if(theStatus!=WS_Success)
	{
		aComplete.AppendShort(WS_CommServ_InvalidParameters); // failure status
		aComplete.AppendShort(1); // num errors
		aComplete.AppendString(WONStatusToString(theStatus));
	}
	else
	{
		aComplete.AppendShort(WS_Success);
		WriteBuffer anEncryptBuf;
		anEncryptBuf.AppendShort(mSecretA.GetKeyLen());
		anEncryptBuf.AppendBytes(mSecretA.GetKey(),mSecretA.GetKeyLen());

			
		ByteBufferPtr anEncrypt = mClientCertificate->GetPubKey().Encrypt(anEncryptBuf.data(),anEncryptBuf.length());
		if(anEncrypt.get()==NULL)
			return WS_PeerAuthServer_FailedToEncryptWithClientPubKey;

		aComplete.AppendShort(anEncrypt->length());
		aComplete.AppendBytes(anEncrypt->data(),anEncrypt->length());
		mSession = new AuthSession(mAuthType, 0, mSecretB, mLengthFieldSize);
	}
	
	theComplete = aComplete.ToByteBuffer();
	return WS_Success;
}
bool PeerAuthServerOp::CallbackHook(AsyncOp *theOp, int theType)
{
	if(!theOp->Succeeded())
	{
		Finish(theOp->GetStatus());
		return true;
	}

	if(theType==PeerAuth_Track_Recv)
	{
		RecvMsgOp *aRecvOp = dynamic_cast<RecvMsgOp*>(theOp);
		if(aRecvOp==NULL)
			return true;

		ByteBufferPtr aSendMsg;
		ByteBufferPtr aRecvMsg = aRecvOp->GetMsg();
		WONStatus aStatus = mPeerAuthServer.HandleRecvMsg(aRecvMsg->data(),aRecvMsg->length(),aSendMsg);

		int aSendType = 0;
		if(aStatus==WS_Success && mPeerAuthServer.GetState()==PeerAuthServer::STATE_NOT_STARTED) // --> finished
			aSendType = PeerAuth_Track_LastSend;

		if(aSendMsg.get()!=NULL)
			mSocket->QueueOp((SocketOp*)Track(new SendMsgOp(aSendMsg),aSendType), SendTime()); // send reply

		if(aStatus!=WS_Success)
			Finish(aStatus);
		else if(aSendType!=PeerAuth_Track_LastSend) // need to recv a reply
			mSocket->QueueOp((SocketOp*)Track(new RecvMsgOp,PeerAuth_Track_Recv), RecvTime()); // get ready for challenge2
	}
	else if(theType==PeerAuth_Track_LastSend)
		Success();

	return true;
}
Esempio n. 3
0
WONStatus RecvMsgOp::StartMsgRecv()
{
	mState = RECEIVING_MESSAGE;

	ByteBufferPtr aBytes = GetBytes();
	ReadBuffer aBuf(aBytes->data(),aBytes->length());
	DWORD aNewNumBytes = 0;
	switch(aBuf.length())
	{
		case 1: aNewNumBytes = (unsigned char)aBuf.ReadByte(); break;
		case 2: aNewNumBytes = (unsigned short)aBuf.ReadShort(); break;
		case 4: aNewNumBytes = (unsigned long)aBuf.ReadLong(); break;
	}

	if(aNewNumBytes<=aBuf.length() || aNewNumBytes>=256000)
		return WS_RecvMsg_InvalidMessageLength;
	
	mState = RECEIVING_MESSAGE;
	mNumBytes = aNewNumBytes - aBuf.length();
	
	WONStatus aStatus = StartRecvBytes();
	if(aStatus==WS_Success)
		return ExtractMsg();
	else
		return aStatus;
}
Esempio n. 4
0
bool WONAPI::WriteAuthSettings(const string& theAuthAddress,
                               unsigned short theAuthPort,
                               const string& theLoginName,
                               const string& theCommunityName,
                               const string& thePassword)
{
    RegKey aKey(REGKEY_CURRENT_USER, KEY_TOOLS_AUTH, true);
    if(aKey.IsOpen())
    {
        aKey.SetValue(VALUE_AUTHSERVERIP, theAuthAddress);
        aKey.SetValue(VALUE_AUTHSERVERPORT, theAuthPort);
        aKey.SetValue(VALUE_USERNAME, theLoginName);
        aKey.SetValue(VALUE_COMMUNITY, theCommunityName);

        if(!thePassword.empty())
        {
            ByteBufferPtr aCryptReturnP = gPasswordKey.Encrypt((const char*)thePassword.c_str(), thePassword.size());
            if(aCryptReturnP.get() != NULL)
            {
                aKey.SetValue(VALUE_PASSWORD, aCryptReturnP->data(), aCryptReturnP->length());
                return true;
            }
        }
    }
    return false;
}
WONStatus PeerAuthServer::GetChallenge1(ByteBufferPtr &theChallenge)
{
	WriteBuffer aChallenge(mLengthFieldSize);

	aChallenge.AppendLong(203);					// Auth peer to peer service
	aChallenge.AppendLong(51);					// Challenge1

	mSecretB.Create(8);
	WriteBuffer aChallengeSecret;
	aChallengeSecret.AppendShort(mSecretB.GetKeyLen());
	aChallengeSecret.AppendBytes(mSecretB.GetKey(),mSecretB.GetKeyLen());

	ByteBufferPtr anEncrypt = mClientCertificate->GetPubKey().Encrypt(aChallengeSecret.data(),aChallengeSecret.length());
	if(anEncrypt.get()==NULL)
		return WS_PeerAuthServer_FailedToEncryptWithClientPubKey;

	aChallenge.AppendShort(anEncrypt->length());
	aChallenge.AppendBytes(anEncrypt->data(),anEncrypt->length());

	if(mUseAuth2)
		aChallenge.AppendBuffer(mPeerData->GetCertificate2()->GetRawBuf(),2);
	else
		aChallenge.AppendBuffer(mPeerData->GetCertificate()->GetRawBuf(),2);

	theChallenge = aChallenge.ToByteBuffer();
	return WS_Success;
}
void InitLogic::GetHTTPDocCompletion(AsyncOp *theOp)
{
	GetHTTPDocumentOp *anOp = (GetHTTPDocumentOp*)theOp;
	LobbyEvent::BroadcastEvent(new GotHTTPDocumentEvent(anOp));

	switch(anOp->GetDocType())
	{
		case HTTPDocType_MOTD: break;
		
		case HTTPDocType_TOU: HandleTOU(anOp); break;

		case HTTPDocType_ADV:
			{
				ByteBufferPtr aDoc = anOp->GetDocument(HTTPDocOwner_Game);
				if(aDoc->length()>1)
				{
					ProcessCrossPromotionDoc(aDoc);
					break;
				}
				else
					LobbyEvent::BroadcastEvent(new SetCrossPromotionEvent(NULL,""));
			}
			break;
		default:
			break;
	}
}
Esempio n. 7
0
WONStatus AuthSession::Decrypt(ByteBufferPtr &theMsg)
{
	mLastUseTime = time(NULL);

	try
	{
		if(mAuthType==AUTH_TYPE_NONE || mAuthType==AUTH_TYPE_PERSISTENT_NOCRYPT)
			return WS_Success;

		ReadBuffer anIn(theMsg->data(),theMsg->length());
		WriteBuffer anOut;
		unsigned char headerType = anIn.ReadByte();
		switch (headerType)
		{
			case 2:							break;	//WONMsg::EncryptedService:
			case 4:	anOut.AppendByte(3);	break;	//WONMsg::MiniEncryptedService:
			case 6:	anOut.AppendByte(5);	break;	//WONMsg::SmallEncryptedService:
			case 8:	anOut.AppendByte(7);	break;	//WONMsg::LargeEncryptedService:
			case 12:						break;	//WONMsg::HeaderEncryptedService:

			default:
				return WS_Success;
		}

		bool sessioned = mAuthType==AUTH_TYPE_SESSION;

		if(sessioned)
		{
			unsigned short aSessionId = anIn.ReadShort();
			if(aSessionId!=mId)
				return WS_AuthSession_DecryptSessionIdMismatch;
		}

		ByteBufferPtr aDecrypt = mKey.Decrypt(anIn.data() + anIn.pos(), anIn.length() - anIn.pos());
		if(aDecrypt.get()==NULL)
			return WS_AuthSession_DecryptFailure;

		if(sessioned)
		{
			if(aDecrypt->length()<2)
				return WS_AuthSession_DecryptBadLen;

			if(++mInSeq!=ShortFromLittleEndian(*(unsigned short*)aDecrypt->data())) // sequence mismatch
				return WS_AuthSession_DecryptInvalidSequenceNum;

			anOut.AppendBytes(aDecrypt->data()+2,aDecrypt->length()-2);
		}
		else
			anOut.AppendBytes(aDecrypt->data(),aDecrypt->length());

		theMsg = anOut.ToByteBuffer();
		return WS_Success;
	}
	catch(ReadBufferException&)
	{
		return WS_AuthSession_DecryptUnpackFailure;
	}
}
Esempio n. 8
0
ShaderPtr ShaderLoader::Load(const Path & vertex_file_name, const Path & fragment_file_name, bool replaceCached)
{
	Path resourceName = vertex_file_name.filename().generic_string() + fragment_file_name.filename().generic_string();

	Resource<Shader> existingResource = this->GetResource(resourceName);

	if (existingResource.resource && !replaceCached)
	{
		GetContext().GetLogger()->log(LOG_LOG, "Shader returned from cache.");
		return existingResource.resource;
	}

	FilePtr vertexFile = GetContext().GetFileSystem()->OpenRead(vertex_file_name);
	FilePtr fragmentFile = GetContext().GetFileSystem()->OpenRead(fragment_file_name);

	if (!vertexFile->IsOpen() || !fragmentFile->IsOpen())
	{
		return ShaderPtr();
	}

	GetContext().GetLogger()->log(LOG_LOG, "Shader resource name: %s", resourceName.generic_string().c_str());

	ByteBufferPtr vertexBuffer = vertexFile->ReadText();
	ByteBufferPtr fragmentBuffer = fragmentFile->ReadText();

	Shader * shader = new Shader(resourceName.generic_string(), (char*)vertexBuffer->data(), (char*)fragmentBuffer->data(), "");
	shader->Compile();

	if (shader->IsCompiledAndLinked())
	{
		if (existingResource.resource)
		{
			RemoveResource(existingResource.path);
			GetContext().GetLogger()->log(LOG_LOG, "Removed cached shader: '%s'.", resourceName.c_str());
		}

		GetContext().GetLogger()->log(LOG_LOG, "Shader loaded: '%s'.", resourceName.c_str());

		Resource<Shader> res(ShaderPtr(shader), resourceName);
		this->AddResource(res);
		return res.resource;
	}
	else
	{
		delete shader;

		if (existingResource.resource)
			GetContext().GetLogger()->log(LOG_ERROR, "Shader failed to load: '%s', using cached version.", resourceName.generic_string().c_str());
		else
			GetContext().GetLogger()->log(LOG_ERROR, "Shader failed to load: '%s'.", resourceName.generic_string().c_str());

		return existingResource.resource;
	}
}
Esempio n. 9
0
void ImageLoader::loadImage(Texture *texture, Pixmap &image)
{
    std::string ext = texture->getFile()->getExt();

    ByteBufferPtr buf = texture->getFile()->read();

    if (ext == "png") {
        image.loadPNG(buf->getData(), buf->getSize());
    } else {
        image.loadJPEG(buf->getData(), buf->getSize());
    }
}
void SPAuthCheckPrv::ReadCheckFile()
{
	// Read check prevention file
	mGameSecondsBeforeNextCheck = 1; // default -> check

	try
	{
		FileReader aReader;
		if(!aReader.Open(gSPAuthCheck_FileName))
			return;

		unsigned short aNumBytes = aReader.ReadShort();
		if(aNumBytes==0 || aReader.Available()<aNumBytes)
			return;

		char *aBuf = new char[aNumBytes];
		std::auto_ptr<char> aDelBuf(aBuf);

		aReader.ReadBytes(aBuf,aNumBytes);
		aReader.Close();

		ByteBufferPtr aDecrypt = mEncryptKey.Decrypt(aBuf,aNumBytes);
		if(aDecrypt.get()==NULL)
			return;

		WONFile aFile(gSPAuthCheck_FileName);

		ReadBuffer aReadBuf(aDecrypt->data(),aDecrypt->length());		
		std::string aSig;
		aReadBuf.ReadString(aSig);
		if(aSig!="magic")
			return;

		time_t aCreateTime = aFile.GetCreateTime();
		time_t aCompareCreateTime = aReadBuf.ReadLong();
		if(aCompareCreateTime != aCreateTime)
			return;

		mGameSecondsBeforeNextCheck = aReadBuf.ReadLong();
		if(mGameSecondsBeforeNextCheck==0) // don't remove file in this case
			return;
		
		aFile.Remove();

	}
	catch(FileReaderException&)
	{
	}
	catch(ReadBufferException&)
	{
	}
}
Esempio n. 11
0
bool WONAPI::ReadAuthSettings(string& theAuthAddressR,
                              unsigned short& theAuthPortR,
                              string& theLoginNameR,
                              string& theCommunityNameR,
                              string& thePasswordR)
{
    RegKey aKey(REGKEY_CURRENT_USER, KEY_TOOLS_AUTH);
    if(aKey.IsOpen())
    {
        aKey.GetValue(VALUE_AUTHSERVERIP, theAuthAddressR);
        unsigned long anAuthPort(15200);
        aKey.GetValue(VALUE_AUTHSERVERPORT, anAuthPort);
        theAuthPortR = anAuthPort;
        aKey.GetValue(VALUE_USERNAME, theLoginNameR);
        aKey.GetValue(VALUE_COMMUNITY, theCommunityNameR);

        ByteBufferPtr anEncryptP;
        aKey.GetValue(VALUE_PASSWORD, anEncryptP);
        if(anEncryptP.get() != NULL)
        {
            ByteBufferPtr aCryptReturnP = gPasswordKey.Decrypt(anEncryptP->data(), anEncryptP->length());
            if(aCryptReturnP.get() != NULL)
            {
                thePasswordR.assign((char*)aCryptReturnP->data(), aCryptReturnP->length());
                return true;
            }
        }
    }
    return false;
}
WONStatus PeerAuthServer::HandleChallenge2(ReadBuffer &theChallenge, ByteBufferPtr &theComplete)
{
	unsigned short anEncryptLen = theChallenge.ReadShort();
	ByteBufferPtr aDecrypt = mPeerData->GetPrivateKey().Decrypt(theChallenge.ReadBytes(anEncryptLen),anEncryptLen);
	if(aDecrypt.get()==NULL)
		return WS_PeerAuthServer_FailedToDecryptWithPrivateKey;

	ReadBuffer aBuf(aDecrypt->data(),aDecrypt->length());
	unsigned short aSecretBLen = aBuf.ReadShort();
	if(aSecretBLen!=mSecretB.GetKeyLen() || memcmp(mSecretB.GetKey(),aBuf.ReadBytes(aSecretBLen),aSecretBLen)!=0)
		return WS_PeerAuthServer_InvalidSecretB;

	if(!mSecretA.SetKey(aBuf.data()+aBuf.pos(),aBuf.Available()))
		return WS_PeerAuthServer_InvalidSecretA;

	return GetComplete(WS_Success, theComplete);
}
void PeerAuthServerOp::RunHook()
{	
	mLengthFieldSize = mSocket->GetLengthFieldSize();
	mPeerAuthServer.Start(mAuthContext->GetPeerData(), mLengthFieldSize);

	// Asynchronous operation
	if(IsAsync())
	{
		AsyncRun();
		return;
	}

	// Blocking operation
	WONStatus aStatus;

	// Receive AuthRequest
	ByteBufferPtr aRecvMsg;
	aStatus = mSocket->RecvMsg(aRecvMsg, RecvTime());
	if(CheckStatus(aStatus))
		return;

	ByteBufferPtr aSendMsg;
	aStatus = mPeerAuthServer.HandleRecvMsg(aRecvMsg->data(), aRecvMsg->length(), aSendMsg);
	CheckStatus(aStatus);
	if(aSendMsg.get()==NULL)
		return;

	// Send Challenge1 (or Complete if error)
	aStatus = mSocket->SendMsg(aSendMsg, SendTime());
	CheckStatus(aStatus);

	if(!Pending())
		return;


	// Receive Challenge2
	aStatus = mSocket->RecvMsg(aRecvMsg, RecvTime());
	if(CheckStatus(aStatus))
		return;
	
	aStatus = mPeerAuthServer.HandleRecvMsg(aRecvMsg->data(), aRecvMsg->length(), aSendMsg);
	CheckStatus(aStatus);
	if(aSendMsg.get()==NULL)
		return;

	// Send Complete
	aStatus = mSocket->SendMsg(aSendMsg, SendTime());
	if(aStatus==WS_Success)
		Success();
	else
		Finish(aStatus);
}
bool WIMDecoder::EncodeToFile(RawImagePtr theImage, const char *theFilePath)
{
	FileWriter aWriter;
	if(!aWriter.Open(theFilePath,true))
		return false;

	ByteBufferPtr aBuf = EncodeToBuffer(theImage);
	if(aBuf.get()==NULL)
		return false;

	try
	{
		aWriter.WriteBytes(aBuf->data(),aBuf->length());
	}
	catch(FileWriterException&)
	{
	}

	return true;
}
Esempio n. 15
0
void InitLogic::HandleTOU(GetHTTPDocumentOp *theOp)
{
	time_t oldSysTime, oldGameTime;
	LobbyMisc::GetTOUTimes(oldSysTime, oldGameTime);

	bool needSetTimes = false;


	// Copy SysTOU if newer
	if(theOp->GetDocumentStatus(HTTPDocOwner_Sys)==WS_Success && theOp->GetModifiedTime(HTTPDocOwner_Sys)>oldSysTime)
	{
		// write the sys document
		FileWriter aWriter;
		try
		{
			if(aWriter.Open(LobbyMisc::GetSysTOUPath().c_str(),true))
			{
				ByteBufferPtr aDoc = theOp->GetDocument(HTTPDocOwner_Sys);
				if(aDoc->length()>1)
					aWriter.WriteBytes(aDoc->data(), aDoc->length()-1); // don't write the null character at the end
			}
			needSetTimes = true;
		}
		catch(FileWriterException&)
		{
		}
	}

	// Copy GameTOU if newer
	if(theOp->GetDocumentStatus(HTTPDocOwner_Game)==WS_Success && theOp->GetModifiedTime(HTTPDocOwner_Game)>oldGameTime)
	{
		// write the game document
		FileWriter aWriter;
		try
		{
			if(aWriter.Open(LobbyMisc::GetGameTOUPath().c_str(),true))
			{
				ByteBufferPtr aDoc = theOp->GetDocument(HTTPDocOwner_Game);
				if(aDoc->length()>1)
					aWriter.WriteBytes(aDoc->data(), aDoc->length()-1); // don't write the null character at the end
			}
			needSetTimes = true;
		}
		catch(FileWriterException&)
		{
		}
	}

	if(needSetTimes)
		SetTOUTimes();
}
Esempio n. 16
0
WONStatus AuthSession::Encrypt(ByteBufferPtr &theMsg)
{
	mLastUseTime = time(NULL);

	if(mAuthType==AUTH_TYPE_NONE || mAuthType==AUTH_TYPE_PERSISTENT_NOCRYPT)
		return WS_Success;

	WriteBuffer aMsg(mLengthFieldSize);
	aMsg.AppendByte(12); // encrypted message

	WriteBuffer aSeqBuf;
	const char *aBuf = theMsg->data() + mLengthFieldSize;
	unsigned short aLen = theMsg->length() - mLengthFieldSize;

	if(mAuthType==AUTH_TYPE_SESSION)
	{
		aMsg.AppendShort(mId);
		aSeqBuf.AppendShort(++mOutSeq);
		aSeqBuf.AppendBytes(aBuf,aLen);
		aBuf = aSeqBuf.data();
		aLen = aSeqBuf.length();
	}

	ByteBufferPtr anEncrypt = mKey.Encrypt(aBuf,aLen);
	if(anEncrypt.get()==NULL)
		return WS_AuthSession_EncryptFailure;
	
	aMsg.AppendBytes(anEncrypt->data(),anEncrypt->length());
	theMsg = aMsg.ToByteBuffer();
	return WS_Success;
}
Esempio n. 17
0
WONStatus PeerAuthClient::HandleChallenge1(ReadBuffer &theChallenge, ByteBufferPtr &challenge2)
{
	unsigned short aSecretLenWithLen = theChallenge.ReadShort();
	ByteBufferPtr aSecretBuf = mPeerData->GetPrivateKey().Decrypt(theChallenge.ReadBytes(aSecretLenWithLen),aSecretLenWithLen);
	if(aSecretBuf.get()==NULL)
		return WS_PeerAuthClient_Challenge1DecryptFailure;
		
	unsigned short aSecretLen = aSecretBuf->data()[0] | (aSecretBuf->data()[1]<<8);
	if(aSecretLen>aSecretBuf->length()-2)
		return WS_PeerAuthClient_Challenge1InvalidSecretLen;
		
	mSecretA.Create(8);		
	if(!mSecretB.SetKey(aSecretBuf->data()+2, aSecretLen))
		return WS_PeerAuthClient_Challenge1InvalidSecretKey;

	unsigned short aCertLen = theChallenge.ReadShort();

	if(mUseAuth2)
	{
		mServerCertificate = new Auth2Certificate(theChallenge.ReadBytes(aCertLen),aCertLen);
		if(!mServerCertificate->IsValid())
			return WS_PeerAuthClient_Challenge1CertificateUnpackFailure;
	}
	else
	{
		mServerCertificate = new AuthCertificate(theChallenge.ReadBytes(aCertLen),aCertLen);
		if(!mServerCertificate->IsValid())
			return WS_PeerAuthClient_Challenge1CertificateUnpackFailure;
	}

	if(!mPeerData->Verify(mServerCertificate.get()))
		return WS_PeerAuthClient_Challenge1CertificateVerifyFailure;

	return GetChallenge2(challenge2);
}
Esempio n. 18
0
WONStatus PeerAuthClient::GetChallenge2(ByteBufferPtr &challenge2)
{
	mState = STATE_AWAITING_COMPLETE;

	WriteBuffer aMsg(mLengthFieldSize);
		
	aMsg.AppendLong(203);								// Auth1 Peer To Peer
	aMsg.AppendLong(52);								// Auth1 Challenge 2

	WriteBuffer anEncryptBuf;
	anEncryptBuf.AppendShort(mSecretB.GetKeyLen());
	anEncryptBuf.AppendBytes(mSecretB.GetKey(), mSecretB.GetKeyLen());
	anEncryptBuf.AppendBytes(mSecretA.GetKey(), mSecretA.GetKeyLen());

	ByteBufferPtr anEncrypt = mServerCertificate->GetPubKey().Encrypt(anEncryptBuf.data(),anEncryptBuf.length());
	if(anEncrypt.get()==NULL)
		return WS_PeerAuthClient_Challenge2EncryptFailure;

	aMsg.AppendShort(anEncrypt->length());
	aMsg.AppendBytes(anEncrypt->data(),anEncrypt->length());
	challenge2 = aMsg.ToByteBuffer();
	return WS_Success;
}
void SPAuthCheckPrv::WriteCheckFile()
{
	
	if(mGameSecondsBeforeNextCheck==1) // Remove file to force check next time
	{
		WONFile aFile(gSPAuthCheck_FileName);
		aFile.Remove();
		return;
	}

	// Write new file
	try
	{
		FileWriter aWriter;
		if(!aWriter.Open(gSPAuthCheck_FileName))
			return;

		WONFile aFile(gSPAuthCheck_FileName);

		WriteBuffer anEncrypt;
		anEncrypt.AppendString("magic");
		anEncrypt.AppendLong(aFile.GetCreateTime()); // file creation time
		anEncrypt.AppendLong(mGameSecondsBeforeNextCheck);

		ByteBufferPtr aBuf = mEncryptKey.Encrypt(anEncrypt.data(),anEncrypt.length());
		if(aBuf.get()==NULL)
			return;

		aWriter.WriteShort(aBuf->length());
		aWriter.WriteBytes(aBuf->data(),aBuf->length());
	}
	catch(FileWriterException&)
	{
	}


}
void StagingLogic::HandleJoinGameRequest(ReadBuffer &theMsg, LobbyClient *theSender)
{
	if(theSender->IsPlayer())
		return;

	ByteBufferPtr aReply = mGame->HandleJoinGameRequest(theMsg,theSender);
	if(aReply.get()==NULL)
		return;

	SendGameMessageToClient(theSender,aReply);
	
	LobbyPlayer *aPlayer = theSender->GetPlayer();
	if(aPlayer!=NULL) // client successfully joined the game, tell everyone else
	{
		WriteBuffer aPlayerJoined;
		aPlayerJoined.AppendByte(LobbyGameMsg_PlayerJoined);
		aPlayerJoined.AppendShort(theSender->GetClientId());
		aPlayer->WriteData(aPlayerJoined);
		BroadcastGameMessage(aPlayerJoined.ToByteBuffer());
		LobbyStaging::UpdateGameSummary();
		return;
	}

}
Esempio n. 21
0
WONStatus PeerAuthClient::HandleComplete(ReadBuffer &theComplete)
{
	short aStatus = theComplete.ReadShort();
	if(aStatus<0)
	{		
		unsigned short aNumErrors = theComplete.ReadShort();
		for(int i=0; i<aNumErrors; i++)
		{
			string anError;
			theComplete.ReadString(anError);
		}
		
		return (WONStatus)aStatus;
	}
		
	unsigned short aLen = theComplete.ReadShort();
	ByteBufferPtr aDecrypt = mPeerData->GetPrivateKey().Decrypt(theComplete.ReadBytes(aLen),aLen);
	if(aDecrypt.get()==NULL)
		return WS_PeerAuthClient_CompleteDecryptFailure;

	if(aDecrypt->length()<2)
		return WS_PeerAuthClient_CompleteInvalidSecretLen;
	
	aLen = (aDecrypt->data()[0] | (aDecrypt->data()[1]<<8));
	if(aLen>aDecrypt->length()-2 || aLen!=mSecretA.GetKeyLen() || memcmp(mSecretA.GetKey(),aDecrypt->data()+2,aLen)!=0)
		return WS_PeerAuthClient_CompleteInvalidSecretKey;	

	unsigned short aSessionId = 0;
	if(mAuthType==AUTH_TYPE_SESSION)
		aSessionId = theComplete.ReadShort();

	if(mAuthType!=AUTH_TYPE_PERSISTENT_NOCRYPT)
		mSession = new AuthSession(mAuthType, aSessionId, mSecretB, mLengthFieldSize);

	return WS_Success;
}
void PeerAuthOp::RunHook()
{	
	mLengthFieldSize = mSocket->GetLengthFieldSize();
	mPeerAuthClient.SetClientKeySize(mClientKeySize, mUseClientKey);

	if(mAuthType!=AUTH_TYPE_NONE)
		mPeerData = mAuthContext->GetPeerData();

	// Asynchronous operation
	if(IsAsync())
	{
		AsyncRun();
		return;
	}

	// Blocking operation

	// Refresh certificate if necessary
	if(mAuthType!=AUTH_TYPE_NONE && mPeerData->CertificateExpired(30))
	{
		mGetCertStatus = mAuthContext->RefreshBlock(TimeLeft());
		if(mGetCertStatus!=WS_Success)
		{
			Finish(WS_PeerAuth_GetCertFailure);
			return;
		}

		mPeerData = mAuthContext->GetPeerData();
	}

	for(int i=0; i<2; i++)
	{
		WONStatus aStatus;

		// Connect
		aStatus = mSocket->Connect(mConnectAddr, ConnectTime());
		if(CheckStatus(aStatus))
			return;

		// If no auth then done
		if(mAuthType==AUTH_TYPE_NONE)
		{
			Finish(WS_Success);
			return;
		}

		// Send peer auth request
		ByteBufferPtr aSendMsg = mPeerAuthClient.Start(mPeerData,mAuthType,mLengthFieldSize);
		aStatus = mSocket->SendMsg(aSendMsg, SendTime());
		if(CheckStatus(aStatus))
			return;

		// Receive challenge1
		ByteBufferPtr aRecvMsg;
		aStatus = mSocket->RecvMsg(aRecvMsg, RecvTime());
		if(CheckStatus(aStatus))
			return;

		// Check challenge 1
		aStatus = mPeerAuthClient.HandleRecvMsg(aRecvMsg->data(),aRecvMsg->length(),aSendMsg);
		if(i==0 && (aStatus==WS_CommServ_InvalidParameters || aStatus==WS_CommServ_ExpiredPeerCertificate)) // expired certificate
		{
			mPeerAuthClient.Reset();
			mGetCertStatus = mAuthContext->RefreshBlock(TimeLeft());
			if(mGetCertStatus!=WS_Success)
			{
				Finish(WS_PeerAuth_GetCertFailure);
				return;
			}

			mPeerData = mAuthContext->GetPeerData();
			continue; // try one more time
		}
		else if(CheckStatus(aStatus))
			return;


		// Send challenge 2 
		aStatus = mSocket->SendMsg(aSendMsg, SendTime());
		if(CheckStatus(aStatus))
			return;

		// Receive peer auth complete
		aStatus = mSocket->RecvMsg(aRecvMsg, RecvTime());
		if(CheckStatus(aStatus))
			return;

		// Check peer auth complete
		aStatus = mPeerAuthClient.HandleRecvMsg(aRecvMsg->data(),aRecvMsg->length(),aSendMsg);
		if(CheckStatus(aStatus))
			return;

		// Success... add encryption protocol if necessary
		Success();
		return;
	}
}
bool PeerAuthOp::CallbackHook(AsyncOp *theOp, int theParam)
{
	switch(theParam)
	{
		case PeerAuth_Track_Socket:
		{
			if(!theOp->Succeeded())
			{
				Finish(theOp->GetStatus());
				break;
			}

			if(mAuthType==AUTH_TYPE_NONE) // just connecting
			{
				Finish(WS_Success);
				break;
			}

			RecvMsgOp *aRecvOp = dynamic_cast<RecvMsgOp*>(theOp);
			if(aRecvOp==NULL)
				break;

			ByteBufferPtr aSendMsg;
			ByteBufferPtr aRecvMsg = aRecvOp->GetMsg();
			WONStatus aStatus = mPeerAuthClient.HandleRecvMsg(aRecvMsg->data(),aRecvMsg->length(),aSendMsg);
			if(aStatus==WS_CommServ_InvalidParameters || aStatus==WS_CommServ_ExpiredPeerCertificate) // expired certificate
			{
				mPeerAuthClient.Reset();
				switch(mGetCertStatus)
				{
					case WS_None: AsyncRefreshCert(); break;
					case WS_Pending: break;
					case WS_Success: AsyncRetry(); break;
					default: Finish(WS_PeerAuth_GetCertFailure);
				}	

				break;
			}
			else if(CheckStatus(aStatus))
				break;

			if(aSendMsg.get()==NULL) 
				Success(); 				// done
			else
				AsyncSend(aSendMsg); 	// Need to send more stuff
		}
		break;


		case PeerAuth_Track_GetCert:
		{
			LightGetCertOp *aGetCert = (LightGetCertOp*)theOp;
			mGetCertStatus = aGetCert->GetStatus();
			mPeerData = aGetCert->GetPeerData();
			if(mPeerAuthClient.GetState()==PeerAuthClient::STATE_NOT_STARTED)
			{
				if(mGetCertStatus!=WS_Success)
				{
					Finish(WS_PeerAuth_GetCertFailure);
					break;
				}
				else
					AsyncRetry();
			}
		}
		break;

		default:
			return false;
	}

	return true;
}
Esempio n. 24
0
ShaderPtr ShaderLoader::Load(const Path & fileName, bool replaceCached)
{
	Resource<Shader> existingResource = this->GetResource(fileName);

	if (existingResource.resource && replaceCached == false)
	{
		GetContext().GetLogger()->log(LOG_LOG, "Found shader in cache, skipping loading.");
		return existingResource.resource;
	}

	ByteBufferPtr vertexBuffer = nullptr, fragmentBuffer = nullptr, geometryBuffer = nullptr;

	FilePtr vertexFile = GetContext().GetFileSystem()->OpenRead(Path(fileName).replace_extension(".vert"));
	vertexBuffer = vertexFile->ReadText();

	FilePtr fragmentFile = GetContext().GetFileSystem()->OpenRead(Path(fileName).replace_extension(".frag"));
	fragmentBuffer = fragmentFile->ReadText();

	if (GetContext().GetFileSystem()->FileExists(Path(fileName).replace_extension(".geom")))
	{
		FilePtr geometryFile = GetContext().GetFileSystem()->OpenRead(Path(fileName).replace_extension(".geom"));

		if (geometryFile)
		{
			geometryBuffer = geometryFile->ReadText();
		}
	}

	Path resourceName = fileName.filename();
	Shader * sh = nullptr;

	if (!vertexBuffer && !fragmentBuffer)
		return existingResource.resource;

	if (geometryBuffer)
	{
		sh = new Shader(resourceName.generic_string(), (char*)vertexBuffer->data(), (char*)fragmentBuffer->data(), (char*)geometryBuffer->data());
	}
	else
	{
		sh = new Shader(resourceName.generic_string(), (char*)vertexBuffer->data(), (char*)fragmentBuffer->data());
	}

	sh->Compile();

	if (sh->IsCompiledAndLinked())
	{
		if (existingResource.resource)
		{
			RemoveResource(existingResource.path);
			GetContext().GetLogger()->log(LOG_LOG, "Removed cached shader: '%s'.", fileName.generic_string().c_str());
		}
		GetContext().GetLogger()->log(LOG_LOG, "Shader loaded: '%s'.", fileName.generic_string().c_str());

		Resource<Shader> res(ShaderPtr(sh), fileName);
		this->AddResource(res);
		return res.resource;
	}
	else
	{
		delete sh;

		if (existingResource.resource)
			GetContext().GetLogger()->log(LOG_ERROR, "Shader failed to load: '%s', using cached version.", resourceName.generic_string().c_str());
		else
			GetContext().GetLogger()->log(LOG_ERROR, "Shader failed to load: '%s'.", resourceName.generic_string().c_str());

		return existingResource.resource;
	}
}
Esempio n. 25
0
void AuthContext::AppendCommunityData(WriteBuffer &theBuf)
{
	AutoCrit aCrit(mDataCrit);
	theBuf.AppendByte(0);									// 0 community ids
	theBuf.AppendByte(mCommunityMap.size());				// num community names
	AuthLoginCommunityMap::iterator anItr = mCommunityMap.begin(); 
	while(anItr!=mCommunityMap.end())
	{
		theBuf.AppendWString(anItr->first);	// community name
		++anItr;
	}


	int aNumCommnityElementsPos = theBuf.length();
	theBuf.SkipBytes(2); 
	int aNumCommunityElements = 0;

	anItr = mCommunityMap.begin();
	while(anItr!=mCommunityMap.end()) // Append CD Keys
	{
		AuthLoginCommunityData &aData = anItr->second;
		if(aData.mCDKey.IsValid())
		{
			ByteBufferPtr aKey = anItr->second.mCDKey.GetRaw();
			if(aKey.get()!=NULL)
			{
				theBuf.AppendByte(1);			// Type = CD Key
				theBuf.AppendShort(anItr->first.length()*2 + aKey->length() + 2); // length of community + data
				theBuf.AppendWString(anItr->first);
				theBuf.AppendBytes(aKey->data(),aKey->length());
				aNumCommunityElements++;
			}
		}
		++anItr;
	}

	CDKeyCommunityJoinMap::iterator aKeyJoinItr = mCDKeyCommunityJoinMap.begin(); // Append Community Join By CDKey Info
	while(aKeyJoinItr!=mCDKeyCommunityJoinMap.end())
	{
		ByteBufferPtr aKey = aKeyJoinItr->second.GetRaw();
		if(aKey.get()!=NULL)
		{
			theBuf.AppendByte(7);			// Type = Join Community with CD Key
			theBuf.AppendShort(aKeyJoinItr->first.length()*2+2 + 4 + aKey->length()); // community name + commnityseq + key
			theBuf.AppendWString(aKeyJoinItr->first);
			theBuf.AppendLong(0);
			theBuf.AppendBytes(aKey->data(),aKey->length());
			aNumCommunityElements++;
		}
		++aKeyJoinItr;
	}

	SetCommunityUserDataMap::iterator aUserDataItr = mSetCommunityUserDataMap.begin(); // Append User Data for communities
	while(aUserDataItr!=mSetCommunityUserDataMap.end())
	{
		const ByteBuffer *aData = aUserDataItr->second;
		if(aData!=NULL)
		{
			theBuf.AppendByte(8);			// Type = SetCommunityUserData
			theBuf.AppendShort(aUserDataItr->first.length()*2+2 + 4 + aData->length()); // community name + commnityseq + key
			theBuf.AppendWString(aUserDataItr->first);
			theBuf.AppendLong(0);
			theBuf.AppendBuffer(aData);
			aNumCommunityElements++;
		}

		++aUserDataItr;
	}

	if(mSecretList.size()>0) 				// CD Keys -> append login secret
	{
		theBuf.AppendByte(6);				// Type = LoginSecret
		unsigned long aPos = theBuf.length();
		theBuf.SkipBytes(2);

		AppendLoginSecrets(theBuf);
		theBuf.SetShort(aPos,theBuf.length()-aPos-2);
		aNumCommunityElements++;
	}

	NicknameMap::iterator aNickItr = mNicknameMap.begin();
	while(aNickItr!=mNicknameMap.end())
	{
		const wstring& aKey = aNickItr->first;
		const wstring& aVal = aNickItr->second;

		theBuf.AppendByte(4); // retrieve nickname
		unsigned long aPos = theBuf.length();
		theBuf.SkipBytes(2);
		theBuf.AppendWString(aKey);
		theBuf.SetShort(aPos,theBuf.length()-aPos-2);
		aNumCommunityElements++;

		if(!aVal.empty())
		{
			theBuf.AppendByte(3); // set nickname
			unsigned long aPos = theBuf.length();
			theBuf.SkipBytes(2);
			theBuf.AppendWString(aKey);
			theBuf.AppendWString(aVal);
			theBuf.SetShort(aPos,theBuf.length()-aPos-2);

			aNumCommunityElements++;
		}

		++aNickItr;
	}

	theBuf.SetShort(aNumCommnityElementsPos,aNumCommunityElements);
}