Exemplo n.º 1
0
void
Messenger::StartAcquisition()
{
  fPID = fork();
  std::ostringstream os; int ret;

  try {
    switch (fPID) {
      case -1:
        throw Exception(__PRETTY_FUNCTION__, "Failed to fork the current process!", JustWarning);
      case 0:
        PrintInfo("Launching the daughter acquisition process");
        ret = execl("ppsFetch", "", (char*)NULL);
        os.str("");
        os << "Failed to launch the daughter process!" << "\n\t"
           << "Return value: " << ret << "\n\t"
           << "Errno: " << errno;
        throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
      default:
        break;
    }
    SendAll(DAQ, SocketMessage(ACQUISITION_STARTED));
    
    // Send the run number to DQMonitors
    int last_run = -1;
    try { last_run = OnlineDBHandler().GetLastRun(); } catch (Exception& e) { last_run = -1; }
    try { SendAll(DQM, SocketMessage(RUN_NUMBER, last_run)); } catch (Exception& e) { e.Dump(); }

    throw Exception(__PRETTY_FUNCTION__, "Acquisition started!", Info, 30000);
  } catch (Exception& e) { e.Dump(); }
}
Exemplo n.º 2
0
// Transmit the PMP file 
// returns 0 for success, -1 for failure
int PMPTransmit(PMP_File *pmp) {
  if (SendAll(&pmp->header, sizeof(PMP_Header)) != 0) {
    return -1;
  }
  if (SendAll(&pmp->info, sizeof(PMP_Info)) != 0) {
    return -1;
  }
  if (SendAll(pmp->data, pmp->data_size) != 0) {
    return -1;
  }
  return 0;
}
Exemplo n.º 3
0
void NetworkMasterGameSocketHandler::SendChat( NetworkAction action, DestinationType desttype, unsigned char client_id, const char *message ) {
	CLog::CLog().Write( LOG_SERVER, true, message );
	switch( desttype ) {
		case TYPE_BROADCAST: {

			/* Send the meesage to all clients */
			Packet p( NETWORK_ACTION_CHAT );
			p.Send_String( message );
			SendAll( &p, PACKET_TYPE_NETWORK_CORE );
			//CLog::Get().Write( LOG_CLIENT, true, message );
			}; break;

		case TYPE_TEAM:{

			/* Send the message to all in the team */
			}; break;

		case TYPE_CLIENT: {

			/* Send the message to an individual client */			  
			}; break;

		default: {

			/* default will never be called */
			CLog::Get().Write( LOG_CLIENT, true, "Default in sendchat called." );

			}; break;
	}
}
Exemplo n.º 4
0
// ---------------------------------------------------------
bool CPartyDef::SendMemberMsg( CChar *pCharDest, PacketSend *pPacket )
{
	ADDTOCALLSTACK("CPartyDef::SendMemberMsg");
	if ( !pCharDest )
	{
		SendAll(pPacket);
		return true;
	}

	// Weirdness check.
	if ( pCharDest->m_pParty != this )
	{
		if ( DetachChar(pCharDest) != m_Chars.BadIndex() )	// this is bad!
			return false;
		return true;
	}
	if ( !m_Chars.IsCharIn(pCharDest) )
	{
		pCharDest->m_pParty = NULL;
		return true;
	}

	if ( pCharDest->m_pClient )
	{
		pPacket->send(pCharDest->m_pClient);
		if ( *pPacket->getData() == PARTYMSG_Remove )
			pCharDest->m_pClient->addReSync();
	}

	return true;
}
Exemplo n.º 5
0
void CUser::SendMagicAttackResult(int tuid, BYTE result, short sDamage, short sHP)
{
	int send_index = 0;
	int sid = -1, tid = -1;
	BYTE type, bResult;
	char buff[256];
	memset( buff, 0x00, 256 );
	float rx=0.0f, ry=0.0f, rz=0.0f;

	type = 0x01;				
	bResult = result;
	sid = m_iUserId+USER_BAND;
	tid = tuid;

	SetByte( buff, AG_MAGIC_ATTACK_RESULT, send_index );
	SetByte( buff, type, send_index );
	SetByte( buff, bResult, send_index );
	SetShort( buff, sid, send_index );
	SetShort( buff, tid, send_index );
	SetShort( buff, sDamage, send_index );
	SetShort( buff, sHP, send_index );

	//TRACE("User - SendAttackSuccess() : [sid=%d, tid=%d, result=%d], damage=%d, hp = %d\n", sid, tid, bResult, sDamage, sHP);

	SendAll(buff, send_index);   // thread 에서 send
}
Exemplo n.º 6
0
	//Here we check for special msgs that relate to host
	void DarkNetwork::CheckHostMsgs(Packet &pck)
	{
		//Check for new connection
		if (pck.buff == DN_MSG_REQUEST_CONNECTION)
		{
			Packet ack = pck;
			//ToDo : Banned users?
			if (m_peers.size() < m_maxClients)
			{				
				//Notify all of a new peer
				Buffer ip;
				DarkNet::GetIp( &(pck.address.addr), ip.buffer, ip.capacity() );

				Buffer accept_msg(DN_MSG_CONNECTION_ACCEPTED);

				Buffer ack_msg = ip + Buffer("|") + accept_msg;

				SendAll(ack_msg);

				//Now add a new peer
				AddNewPeer(pck, eClient);
				ack.buff = DN_MSG_CONNECTION_ACCEPTED;
				Send(ack);
			}
			else
			{
				ack.buff = DN_MSG_SERVER_FULL;
				Send(ack);
			}
		}
	}
Exemplo n.º 7
0
bool AddClient(int index)
{
	SOCKET ClientSocket;
	SOCKADDR_IN sockaddr;
	int addrlen = sizeof(sockaddr);
	ClientSocket = accept(SockList[index], (SOCKADDR*)&sockaddr, &addrlen);
	if(ClientSocket == SOCKET_ERROR)
	{
		DisplayMessage();	return false;
	}
	
	// 이벤트 등록
	WSAEVENT hClientEvent = WSACreateEvent();
	WSAEventSelect(ClientSocket, hClientEvent, FD_WRITE | FD_READ | FD_CLOSE);
	// 전역변수에 저장
	SockList[g_SockCnt] = ClientSocket;
	EventList[g_SockCnt] = hClientEvent;
	g_SockCnt++;
	// 접속메세지 전송
	char buf[BUFFERSIZE];
	int retByte = sprintf(buf, "\n[TCP 서버] 클라이언트 접속: IP주소=%s, 포트 번호=%d\n",
		inet_ntoa(sockaddr.sin_addr), ntohs(sockaddr.sin_port));
	SendAll(0, buf, retByte);

	return true;

}
Exemplo n.º 8
0
// returns 0 on success, non-zero on error
int
DoCallback()
{
  UniquePRFileDesc socket(PR_NewTCPSocket());
  if (!socket) {
    PrintPRError("PR_NewTCPSocket failed");
    return 1;
  }

  PRNetAddr addr;
  PR_InitializeNetAddr(PR_IpAddrLoopback, gCallbackPort, &addr);
  if (PR_Connect(socket.get(), &addr, PR_INTERVAL_NO_TIMEOUT) != PR_SUCCESS) {
    PrintPRError("PR_Connect failed");
    return 1;
  }

  const char *request = "GET / HTTP/1.0\r\n\r\n";
  SendAll(socket.get(), request, strlen(request));
  char buf[4096];
  memset(buf, 0, sizeof(buf));
  int32_t bytesRead = PR_Recv(socket.get(), buf, sizeof(buf) - 1, 0,
                              PR_INTERVAL_NO_TIMEOUT);
  if (bytesRead < 0) {
    PrintPRError("PR_Recv failed 1");
    return 1;
  }
  if (bytesRead == 0) {
    fprintf(stderr, "PR_Recv eof 1\n");
    return 1;
  }
  fprintf(stderr, "%s\n", buf);
  return 0;
}
Exemplo n.º 9
0
nsresult
ReplyToRequest(Connection *aConn)
{
  // For debugging purposes, SendAll can print out what it's sending.
  // So, any strings we give to it to send need to be null-terminated.
  char buf[2] = { aConn->mByte, 0 };
  return SendAll(aConn->mSocket, buf, 1);
}
Exemplo n.º 10
0
void NetworkClient::SendDisconnect() {
	if (socket_) {
		cure::Packet* _packet = GetPacketFactory()->Allocate();
		SendStatusMessage(socket_, 0, cure::kRemoteNoConnection, cure::MessageStatus::kInfoLogin, "", _packet);
		GetPacketFactory()->Release(_packet);
	}
	SendAll();
}
Exemplo n.º 11
0
BOOL UdpComm::Connect( ULONG targetIP,int port )
{
	SOCKADDR_IN hints;

	memset(&hints, 0, sizeof(SOCKADDR_IN));
	hints.sin_family = AF_INET;
	hints.sin_addr.s_addr = targetIP;
	hints.sin_port = htons(port);

	if (VTCP_ERROR == m_vconnect(m_sock,(sockaddr*)&hints,sizeof(hints)))
	{
		if ( m_lasterr() == 3 )
		{
			m_vclose(m_sock);
			m_sock = m_vsocketshare(m_psock);
		}
		
		return FALSE;
	}
	int timeout = 20000;
	m_vsetsockopt(m_sock,SOL_SOCKET,VTCP_SO_RECV_TIMEO,(char*)&timeout,sizeof(int));
	m_vsetsockopt(m_sock,SOL_SOCKET,VTCP_SO_SEND_TIMEO,(char*)&timeout,sizeof(int));

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

		int flag = UDP_FLAG;

		SendAll(m_sock,(LPVOID)&flag,sizeof(int));

		ReceiveAll(m_sock,&m_rsaKey,sizeof(RSA::RSA_PUBLIC_KEY));

		RSA::RSAEncrypt((char*)&m_xorKey1,(int*)&key1,m_rsaKey.d,m_rsaKey.n,1);
		RSA::RSAEncrypt((char*)&m_xorKey2,(int*)&key2,m_rsaKey.d,m_rsaKey.n,1);

		SendAll(m_sock,&key1,sizeof(int));
		SendAll(m_sock,&key2,sizeof(int));
	}

	return TRUE;

}
Exemplo n.º 12
0
        void Connection::Send(const int8_t* data, size_t len)
        {
            if (!connected)
                IGNITE_ERROR_1(IgniteError::IGNITE_ERR_ILLEGAL_STATE, "Connection is not established");

            OdbcProtocolHeader hdr;

            hdr.len = static_cast<int32_t>(len);

            size_t sent = SendAll(reinterpret_cast<int8_t*>(&hdr), sizeof(hdr));

            if (sent != sizeof(hdr))
                IGNITE_ERROR_1(IgniteError::IGNITE_ERR_GENERIC, "Can not send message header");

            sent = SendAll(data, len);

            if (sent != len)
                IGNITE_ERROR_1(IgniteError::IGNITE_ERR_GENERIC, "Can not send message body");
        }
Exemplo n.º 13
0
void Server::CloseClient(int id){
    int fd = clients[id].fd;
    char msg[256] = {0};
    printf("id %d fd %d\n", id, clients[id].fd);
    sprintf(msg, "*** User '%s' left. ***\n", clients[id].nickname);
    SendAll(msg);
    clients[id].used = false;
    client_id.erase(id);
	epoll_del_event(epfd, fd, EPOLLIN);
	int res = close(fd);
    printf("close %d %d\n", id, res);
}
Exemplo n.º 14
0
void CUser::SendHP()
{
	if(m_bLive == USER_DEAD) return;
	// HP 변동량을 게임서버로...
	int send_index = 0;
	char buff[256];
	memset( buff, 0x00, 256 );

	SetByte(buff, AG_USER_SET_HP, send_index );
	SetShort(buff, m_iUserId, send_index );
	SetDWORD(buff, m_sHP, send_index );

	SendAll(buff, send_index);   
}
Exemplo n.º 15
0
void
Messenger::StopAcquisition()
{
  signal(SIGCHLD, SIG_IGN);
  int ret = kill(fPID, SIGINT);
  if (ret<0) {
    std::ostringstream os;
    os << "Failed to kill the acquisition process with pid=" << fPID << "\n\t"
       << "Return value: " << ret << " (errno=" << errno << ")";
    throw Exception(__PRETTY_FUNCTION__, os.str(), JustWarning);
  }
  SendAll(DAQ, SocketMessage(ACQUISITION_STOPPED));
  throw Exception(__PRETTY_FUNCTION__, "Acquisition stop signal sent!", Info, 30001);
}
Exemplo n.º 16
0
void RecvClient(int index)
{
	char buf[BUFFERSIZE];
	memset(buf, 0, BUFFERSIZE);
	SOCKADDR_IN senderaddr;
	int addrlen = sizeof(senderaddr);

	SOCKET ClientSocket = SockList[index];
	int retByte = recv(ClientSocket, buf, BUFFERSIZE, 0);
	getpeername(ClientSocket, (SOCKADDR *)&senderaddr, &addrlen);
	printf("[%s:%d] %s\n", inet_ntoa(senderaddr.sin_addr), htons(senderaddr.sin_port), buf);

	SendAll(index, buf, retByte);
}
Exemplo n.º 17
0
//  경험치를 보낸다. (레벨업일때 관련 수치를 준다)
void CUser::SendExp(int iExp, int iLoyalty, int tType)
{
	int send_index = 0;
	char buff[256];
	memset( buff, 0x00, 256 );

	SetByte(buff, AG_USER_EXP, send_index );
	SetShort(buff, m_iUserId, send_index );
	SetShort(buff, iExp, send_index );
	SetShort(buff, iLoyalty, send_index );

	//TRACE("$$ User - SendExp : %s, exp=%d, loyalty=%d $$\n", m_strUserID, iExp, iLoyalty);

	SendAll(buff, send_index);   	
}
Exemplo n.º 18
0
// ---------------------------------------------------------
bool CPartyDef::SendAddList( CChar *pCharDest )
{
	ADDTOCALLSTACK("CPartyDef::SendAddList");

	if ( m_Chars.GetCharCount() <= 0 )
		return false;

	PacketPartyList cmd(&m_Chars);
	if (pCharDest)
		SendMemberMsg(pCharDest, &cmd);
	else
		SendAll(&cmd);

	return true;
}
Exemplo n.º 19
0
void CUser::SendSystemMsg(TCHAR *pMsg, BYTE type, int nWho)
{
	int send_index = 0;
	char buff[1024];
	memset( buff, 0x00, 1024 );
	short sLength = _tcslen(pMsg);

	SetByte(buff, AG_SYSTEM_MSG, send_index );
	SetByte(buff, type, send_index );				// 채팅형식
	SetShort(buff, nWho, send_index );				// 누구에게
	SetShort(buff, m_iUserId, send_index );
	SetShort(buff, sLength, send_index );
	SetString( buff, pMsg, sLength, send_index );

	SendAll(buff, send_index);   	
}
Exemplo n.º 20
0
void NetServer::DisconnectNice( const char *message )
{
	if( Listening )
	{
		Packet disconnect( Raptor::Packet::DISCONNECT );
		
		if( message )
			disconnect.AddString( message );
		else
			disconnect.AddString( "" );
		
		SendAll( &disconnect );
	}
	
	Disconnect();
}
Exemplo n.º 21
0
// ---------------------------------------------------------
bool CPartyDef::MessageEvent( CGrayUID uidDst, CGrayUID uidSrc, const NCHAR * pText, int ilenmsg )
{
	ADDTOCALLSTACK("CPartyDef::MessageEvent");
	UNREFERENCED_PARAMETER(ilenmsg);
	if ( pText == NULL )
		return( false );

	if ( uidDst && !IsInParty( uidDst.CharFind() ) )
		return( false );

	CChar * pFrom = uidSrc.CharFind();
	CChar * pTo = NULL;
	if ( uidDst != (DWORD) 0 )
		pTo = uidDst.CharFind();

	TCHAR * szText = Str_GetTemp();
	CvtNUNICODEToSystem( szText, MAX_TALK_BUFFER, pText, MAX_TALK_BUFFER );

	if ( ! m_pSpeechFunction.IsEmpty() )
	{
		TRIGRET_TYPE tr = TRIGRET_RET_FALSE;
		CScriptTriggerArgs Args;
		Args.m_iN1 = uidSrc;
		Args.m_iN2 = uidDst;
		Args.m_s1 = szText;
		Args.m_s1_raw = szText;

		if ( r_Call(m_pSpeechFunction, &g_Serv, &Args, NULL, &tr) )
		{
			if ( tr == TRIGRET_RET_TRUE )
				return( false );
		}
	}

	if ( g_Log.IsLoggedMask( LOGM_PLAYER_SPEAK ))
		g_Log.Event( LOGM_PLAYER_SPEAK, "%lx:'%s' Says '%s' in party to '%s'\n", pFrom->GetClient()->GetSocketID(), pFrom->GetName(), szText, pTo ? pTo->GetName() : "all" );

	sprintf(szText, g_Cfg.GetDefaultMsg( DEFMSG_PARTY_MSG ), pText);
	PacketPartyChat cmd(pFrom, pText);

	if ( pTo != NULL )
		SendMemberMsg(pTo, &cmd);
	else
		SendAll(&cmd);

	return( true );
}
void NewClient(SOCKET ClientSocket)
{
    AddActiveSocket(&ClientSocket);
    int iResult;
    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    static int thcount = 1;
    int thisthread = thcount;
    thcount++;
    printf("thread %d started\n", thisthread);

    // Receive until the peer shuts down the connection
    while (1)
    {
        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0)
        {
            printf("Bytes received: %d\n", iResult);

            if (iResult < DEFAULT_BUFLEN)
                recvbuf[iResult] = '\0';
            else
                recvbuf[DEFAULT_BUFLEN - 1] = '\0';

            SendAll(recvbuf);
        }
        else if (iResult == 0)
        {
            printf("Connection closing... th=%d\n", thisthread);
            DeleteSocket(&ClientSocket);
            closesocket(ClientSocket);
            return;
        }
        else
        {
            printf("recv failed with error: %d\n", WSAGetLastError());
            DeleteSocket(&ClientSocket);
            closesocket(ClientSocket);
            return;
        }
    }

    DeleteSocket(&ClientSocket);
    printf("thread completed\n");
}
Exemplo n.º 23
0
bool NetworkClient::SendLoginRequest(const LoginId& login_id) {
	bool ok = false;
	ScopeLock lock(&lock_);
	if (socket_) {
		Packet* _packet = packet_factory_->Allocate();
		_packet->Release();
		MessageLoginRequest* login_request = (MessageLoginRequest*)packet_factory_->GetMessageFactory()->Allocate(kMessageTypeLoginRequest);
		_packet->AddMessage(login_request);	// Leave ownership of message with packet.
		login_request->Store(_packet, login_id.GetName(), login_id.GetMangledPassword());
		ok = Parent::PlaceInSendBuffer(true, socket_, _packet);
		if (ok) {
			ok = SendAll();
		}
		packet_factory_->Release(_packet);
	}
	return (ok);
}
Exemplo n.º 24
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;
}
Exemplo n.º 25
0
        void Connection::Send(const int8_t* data, size_t len)
        {
            if (!connected)
                IGNITE_ERROR_1(IgniteError::IGNITE_ERR_ILLEGAL_STATE, "Connection is not established");

            common::FixedSizeArray<int8_t> msg(len + sizeof(OdbcProtocolHeader));

            OdbcProtocolHeader *hdr = reinterpret_cast<OdbcProtocolHeader*>(msg.GetData());

            hdr->len = static_cast<int32_t>(len);

            memcpy(msg.GetData() + sizeof(OdbcProtocolHeader), data, len);

            size_t sent = SendAll(msg.GetData(), msg.GetSize());

            if (sent != len + sizeof(OdbcProtocolHeader))
                IGNITE_ERROR_1(IgniteError::IGNITE_ERR_GENERIC, "Can not send message");
        }
Exemplo n.º 26
0
bool CPartyDef::SendRemoveList( CChar *pCharRemove, bool bFor )
{
	ADDTOCALLSTACK("CPartyDef::SendRemoveList");

	if ( bFor )
	{
		PacketPartyRemoveMember cmd(pCharRemove, NULL);
		SendMemberMsg(pCharRemove, &cmd);
	}
	else
	{
		if ( m_Chars.GetCharCount() <= 0 )
			return false;

		PacketPartyRemoveMember cmd(pCharRemove, &m_Chars);
		SendAll(&cmd);
	}

	return true;
}
Exemplo n.º 27
0
int QymodemTx::SendY(const char* fileName, size_t size, InStream& in, unsigned timeout)
        {
        Use1KBlocks = true;
        quint8 buffer[128];
        int result = MakeBlock0(buffer,fileName,size);
        if(result<0)
                return result;

        result = SendInitialise(timeout);
        if(result<0 && result!=ErrorBlockRetriesExceded)
                return result;
        emit Information("Sending "+QString(fileName),QymodemTx::InfoSending);
        BlockNumber = 0;
        result = SendBlock(buffer,sizeof(buffer));
        if(result<0)
                return result;

        result = InChar(SendTimeout);
        if(result<0)
                return result;
        if(result!=ModeChar)
                return ErrorReceiverNotBehaving;

        result = SendAll(in);
        if(result<0)
                return result;

        result = InChar(SendTimeout);
        if(result<0)
                return result;
        if(result!=ModeChar)
                return ErrorReceiverNotBehaving;

        memset(buffer,0,sizeof(buffer));
        BlockNumber = 0;
        result = SendBlock(buffer,sizeof(buffer));
        if(result<0)
                return result;
        emit Percent(100);
        return 0;
        }
Exemplo n.º 28
0
// Listener thread
void ElListenerProc(THREAD *thread, void *param)
{
	TCP_ACCEPTED_PARAM *data = (TCP_ACCEPTED_PARAM *)param;
	EL *e;
	SOCK *s;
	UCHAR rand[SHA1_SIZE];
	UCHAR pass1[SHA1_SIZE], pass2[SHA1_SIZE];
	// Validate arguments
	if (data == NULL || thread == NULL)
	{
		return;
	}

	e = (EL *)data->r->ThreadParam;
	s = data->s;
	AddRef(s->ref);
	SetTimeout(s, 5000);
	LockList(e->AdminThreadList);
	{
		AddRef(thread->ref);
		AddRef(s->ref);
		Insert(e->AdminThreadList, thread);
		Insert(e->AdminSockList, s);
	}
	UnlockList(e->AdminThreadList);
	NoticeThreadInit(thread);

	// Submit a challenge
	Rand(rand, sizeof(rand));
	SendAll(s, rand, sizeof(rand), false);

	// Receive a response
	SecurePassword(pass1, e->HashedPassword, rand);
	Zero(pass2, sizeof(pass2));
	RecvAll(s, pass2, sizeof(pass2), false);

	if (Cmp(pass1, pass2, SHA1_SIZE) != 0)
	{
		// Password incorrect
		bool code = false;
		code = Endian32(code);
		SendAll(s, &code, sizeof(code), false);
	}
	else
	{
		// Password match
		bool code = true;
		RPC *r;

		code = Endian32(code);
		SendAll(s, &code, sizeof(code), false);

		SetTimeout(s, INFINITE);

		// Start operation as a RPC server
		r = StartRpcServer(s, ElRpcServer, e);
		RpcServer(r);
		RpcFree(r);
	}

	Disconnect(s);
	ReleaseSock(s);

	LockList(e->AdminThreadList);
	{
		if (Delete(e->AdminThreadList, thread))
		{
			ReleaseThread(thread);
		}
		if (Delete(e->AdminSockList, s))
		{
			ReleaseSock(s);
		}
	}
	UnlockList(e->AdminThreadList);
}
Exemplo n.º 29
0
// RPC client connect
UINT EcConnect(char *host, UINT port, char *password, RPC **rpc)
{
	SOCK *s;
	UCHAR password_hash[SHA1_SIZE];
	UCHAR rand[SHA1_SIZE];
	UCHAR response[SHA1_SIZE];
	bool retcode;
	// Validate arguments
	if (host == NULL)
	{
		host = "localhost";
	}
	if (port == 0)
	{
		port = EL_ADMIN_PORT;
	}
	if (password == NULL)
	{
		password = "";
	}
	if (rpc == NULL)
	{
		return ERR_INTERNAL_ERROR;
	}

	// Connect to the server
	s = Connect(host, port);
	if (s == NULL)
	{
		// Connection failure
		return ERR_CONNECT_FAILED;
	}

	SetTimeout(s, 5000);

	// Hash the password
	Hash(password_hash, password, StrLen(password), true);

	// Receive the random number
	Zero(rand, sizeof(rand));
	RecvAll(s, rand, sizeof(rand), false);
	SecurePassword(response, password_hash, rand);

	// Send a response
	SendAll(s, response, sizeof(response), false);

	// Receive results
	retcode = false;
	if (RecvAll(s, &retcode, sizeof(retcode), false) == false)
	{
		// Disconnect
		ReleaseSock(s);
		return ERR_PROTOCOL_ERROR;
	}
	retcode = Endian32(retcode);

	if (retcode == false)
	{
		// Password incorrect
		ReleaseSock(s);
		return ERR_AUTH_FAILED;
	}

	// Successful connection
	SetTimeout(s, INFINITE);

	*rpc = StartRpcClient(s, NULL);

	ReleaseSock(s);

	return ERR_NO_ERROR;
}
Exemplo n.º 30
0
// VPN Azure client main thread
void AcMainThread(THREAD *thread, void *param)
{
	AZURE_CLIENT *ac = (AZURE_CLIENT *)param;
	UINT last_ip_revision = INFINITE;
	UINT64 last_reconnect_tick = 0;
	UINT64 next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
	UINT num_reconnect_retry = 0;
	UINT64 next_ddns_retry_tick = 0;
	bool last_connect_ok = false;
	// Validate arguments
	if (ac == NULL || thread == NULL)
	{
		return;
	}

	while (ac->Halt == false)
	{
		UINT64 now = Tick64();
		bool connect_was_ok = false;
		// Wait for enabling VPN Azure function
		if (ac->IsEnabled)
		{
			// VPN Azure is enabled
			DDNS_CLIENT_STATUS st;
			bool connect_now = false;
			bool azure_ip_changed = false;

			Lock(ac->Lock);
			{
				Copy(&st, &ac->DDnsStatus, sizeof(DDNS_CLIENT_STATUS));

				if (StrCmpi(st.CurrentAzureIp, ac->DDnsStatusCopy.CurrentAzureIp) != 0)
				{
					if (IsEmptyStr(st.CurrentAzureIp) == false)
					{
						// Destination IP address is changed
						connect_now = true;
						num_reconnect_retry = 0;
					}
				}

				if (StrCmpi(st.CurrentHostName, ac->DDnsStatusCopy.CurrentHostName) != 0)
				{
					// DDNS host name is changed
					connect_now = true;
					num_reconnect_retry = 0;
				}

				Copy(&ac->DDnsStatusCopy, &st, sizeof(DDNS_CLIENT_STATUS));
			}
			Unlock(ac->Lock);

			if (last_ip_revision != ac->IpStatusRevision)
			{
				last_ip_revision = ac->IpStatusRevision;

				connect_now = true;

				num_reconnect_retry = 0;
			}

			if (last_reconnect_tick == 0 || (now >= (last_reconnect_tick + next_reconnect_interval)))
			{
				UINT r;

				last_reconnect_tick = now;
				num_reconnect_retry++;
				next_reconnect_interval = (UINT64)num_reconnect_retry * AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
				next_reconnect_interval = MIN(next_reconnect_interval, AZURE_CONNECT_MAX_RETRY_INTERVAL);

				r = (UINT)next_reconnect_interval;

				r = GenRandInterval(r / 2, r);

				next_reconnect_interval = r;

				connect_now = true;
			}

			if (IsEmptyStr(st.CurrentAzureIp) == false && IsEmptyStr(st.CurrentHostName) == false)
			{
				if (connect_now)
				{
					SOCK *s;
					char *host = NULL;
					UINT port = AZURE_SERVER_PORT;

					Debug("VPN Azure: Connecting to %s...\n", st.CurrentAzureIp);

					if (ParseHostPort(st.CurrentAzureIp, &host, &port, AZURE_SERVER_PORT))
					{
						if (st.InternetSetting.ProxyType == PROXY_DIRECT)
						{
							s = ConnectEx2(host, port, 0, (bool *)&ac->Halt);
						}
						else
						{
							s = WpcSockConnect2(host, port, &st.InternetSetting, NULL, AZURE_VIA_PROXY_TIMEOUT);
						}

						if (s != NULL)
						{
							PACK *p;
							UINT64 established_tick = 0;

							Debug("VPN Azure: Connected.\n");

							SetTimeout(s, AZURE_PROTOCOL_CONTROL_TIMEOUT_DEFAULT);

							Lock(ac->Lock);
							{
								ac->CurrentSock = s;
								ac->IsConnected = true;
								StrCpy(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp), st.CurrentAzureIp);
							}
							Unlock(ac->Lock);

							SendAll(s, AZURE_PROTOCOL_CONTROL_SIGNATURE, StrLen(AZURE_PROTOCOL_CONTROL_SIGNATURE), false);

							// Receive parameter
							p = RecvPackWithHash(s);
							if (p != NULL)
							{
								UCHAR c;
								AZURE_PARAM param;
								bool hostname_changed = false;

								Zero(&param, sizeof(param));

								param.ControlKeepAlive = PackGetInt(p, "ControlKeepAlive");
								param.ControlTimeout = PackGetInt(p, "ControlTimeout");
								param.DataTimeout = PackGetInt(p, "DataTimeout");
								param.SslTimeout = PackGetInt(p, "SslTimeout");

								FreePack(p);

								param.ControlKeepAlive = MAKESURE(param.ControlKeepAlive, 1000, AZURE_SERVER_MAX_KEEPALIVE);
								param.ControlTimeout = MAKESURE(param.ControlTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.DataTimeout = MAKESURE(param.DataTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.SslTimeout = MAKESURE(param.SslTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);

								Lock(ac->Lock);
								{
									Copy(&ac->AzureParam, &param, sizeof(AZURE_PARAM));
								}
								Unlock(ac->Lock);

								SetTimeout(s, param.ControlTimeout);

								// Send parameter
								p = NewPack();
								PackAddStr(p, "CurrentHostName", st.CurrentHostName);
								PackAddStr(p, "CurrentAzureIp", st.CurrentAzureIp);
								PackAddInt64(p, "CurrentAzureTimestamp", st.CurrentAzureTimestamp);
								PackAddStr(p, "CurrentAzureSignature", st.CurrentAzureSignature);

								Lock(ac->Lock);
								{
									if (StrCmpi(st.CurrentHostName, ac->DDnsStatus.CurrentHostName) != 0)
									{
										hostname_changed = true;
									}
								}
								Unlock(ac->Lock);

								if (hostname_changed == false)
								{
									if (SendPackWithHash(s, p))
									{
										// Receive result
										if (RecvAll(s, &c, 1, false))
										{
											if (c && ac->Halt == false)
											{
												connect_was_ok = true;

												established_tick = Tick64();

												AcWaitForRequest(ac, s, &param);
											}
										}
									}
								}

								FreePack(p);
							}
							else
							{
								WHERE;
							}

							Debug("VPN Azure: Disconnected.\n");

							Lock(ac->Lock);
							{
								ac->IsConnected = false;
								ac->CurrentSock = NULL;
								ClearStr(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp));
							}
							Unlock(ac->Lock);

							if (established_tick != 0)
							{
								if ((established_tick + (UINT64)AZURE_CONNECT_MAX_RETRY_INTERVAL) <= Tick64())
								{
									// If the connected time exceeds the AZURE_CONNECT_MAX_RETRY_INTERVAL, reset the retry counter.
									last_reconnect_tick = 0;
									num_reconnect_retry = 0;
									next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
								}
							}

							Disconnect(s);
							ReleaseSock(s);
						}
						else
						{
							Debug("VPN Azure: Error: Connect Failed.\n");
						}

						Free(host);
					}
				}
			}
		}
		else
		{
			last_reconnect_tick = 0;
			num_reconnect_retry = 0;
			next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
		}

		if (ac->Halt)
		{
			break;
		}

		if (connect_was_ok)
		{
			// If connection goes out after connected, increment connection success count to urge DDNS client query
			next_ddns_retry_tick = Tick64() + MIN((UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF * (UINT64)(num_reconnect_retry + 1), (UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF_MAX);
		}

		if ((next_ddns_retry_tick != 0) && (Tick64() >= next_ddns_retry_tick))
		{
			next_ddns_retry_tick = 0;

			ac->DDnsTriggerInt++;
		}

		Wait(ac->Event, rand() % 1000);
	}
}