Ejemplo n.º 1
0
/*
        Поток менеджера новых клиентов
        Функция будет пытаться подключить клиента пока не закончатся места в потоках и сами потоки
*/
void *InitialConnect(void *arg)
{
        SINF *sinf;
        SADDR client;
        socklen_t sl;
        MSG msg;
        int rez;

        sinf = (SINF *) arg;
        sl = SADDR_SIZE;
        while(1){
                if(recvfrom(sinf->sock_d, &msg, MSG_SIZE, 0, (struct sockaddr *) &client, &sl) < 0){
                        perror("InitialConnect (error recv)");
                        sleep(5);
                } else {
                        /*
                                Подключаем клиента
                        */
                        rez = AddClient(sinf, client);
                        /*
                                Исправляем ошибки
                        */
                        while( rez < 0){
                                switch(rez){
                                        case -1:
                                                if(CreatePTH(sinf) < 0)
                                                        /*
                                                                Отмена подключения
                                                        */
                                                        rez = 1;
                                                else {
                                                        /*
                                                                Попытка подключения
                                                        */
                                                        rez = AddClient(sinf, client);
                                                }
                                        break;
                                        case -2:
                                                /*
                                                        Отмена подключения
                                                */
                                                rez = 2;
                                        break;
                                }
                        }
                        /*
                                Результат
                        */
                        switch(rez){
                                case 1:
                                        printf("InitialConnect (error): Client don't connect. Error of create new PTH.\n");
                                break;
                                case 2:
                                        printf("InitialConnect (error): Client don't connect. Error of create SADDR.\n");
                                break;
                        }
                }
        }
}
Ejemplo n.º 2
0
void CClientList::RequestBuddy(Kademlia::CContact* contact, uint8 byConnectOptions)
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	// don't connect ourself
	if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return;
	CUpDownClient* pNewClient = FindClientByIP(nContactIP, contact->GetTCPPort());
	if (!pNewClient)
		pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	else if (pNewClient->GetKadState() != KS_NONE)
		return; // already busy with this client in some way (probably fw stuff), don't mess with it
	else if (IsKadFirewallCheckIP(nContactIP)){ // doing a kad firewall check with this IP, abort 
		DEBUG_ONLY( DebugLogWarning(_T("KAD tcp Firewallcheck / Buddy request collosion for IP %s"), ipstr(nContactIP)) );
		return;
	}
	//Add client to the lists to be processed.
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_QUEUED_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(ID);
	pNewClient->SetConnectOptions(byConnectOptions, true, false);
	AddToKadList(pNewClient);
	//This method checks if this is a dup already.
	AddClient(pNewClient);
}
Ejemplo n.º 3
0
void CClientList::IncomingBuddy(Kademlia::CContact* contact, Kademlia::CUInt128* buddyID )
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	//If eMule already knows this client, abort this.. It could cause conflicts.
	//Although the odds of this happening is very small, it could still happen.
	if (FindClientByIP(nContactIP, contact->GetTCPPort()))
	{
		return;
	}

	// don't connect ourself
	if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return;

	//Add client to the lists to be processed.
	CUpDownClient* pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_INCOMING_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(ID);
	buddyID->ToByteArray(ID);
	pNewClient->SetBuddyID(ID);
	AddToKadList(pNewClient);
	AddClient(pNewClient);
}
Ejemplo n.º 4
0
bool CClientList::RequestTCP(Kademlia::CContact* contact, uint8 byConnectOptions)
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	// don't connect ourself
	if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return false;

	CUpDownClient* pNewClient = FindClientByIP(nContactIP, contact->GetTCPPort());

	if (!pNewClient)
		pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	else if (pNewClient->GetKadState() != KS_NONE)
		return false; // already busy with this client in some way (probably buddy stuff), don't mess with it

	//Add client to the lists to be processed.
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_QUEUED_FWCHECK);
	if (contact->GetClientID() != 0){
		byte ID[16];
		contact->GetClientID().ToByteArray(ID);
		pNewClient->SetUserHash(ID);
		pNewClient->SetConnectOptions(byConnectOptions, true, false);
	}
	m_KadList.AddTail(pNewClient);
	//This method checks if this is a dup already.
	AddClient(pNewClient);
	return true;
}
Ejemplo n.º 5
0
std::shared_ptr<Client> ClientController::GetClientById(qint32 clientId)
{
    if(!(UserSingleton::GetInstance().GetPermissions() & PLM::PermissionsFlag::READ_CLIENTS))
    {
        return std::shared_ptr<Client>();
    }

    auto existingClient = m_cache.Lookup(clientId);
    if(existingClient)
    {
        return existingClient;
    }

    QSqlQuery query = GetDb().CreateQuery();
    query.prepare("SELECT * "
        "FROM \"Client\""
        "INNER JOIN \"ContactView\" ON \"Client\".\"ContactId\" = \"ContactView\".\"ContactId\""
        "WHERE \"Client\".\"ClientId\"=:clientId;"
    );
    query.bindValue(":clientId", clientId);
    if(!query.exec())
    {
        return std::shared_ptr<Client>();
    }

    if(!query.size() != 1)
    {
        return std::shared_ptr<Client>();
    }

    query.next();
    auto client = CreateClientFromQuery(query);
    auto sharedPtr = AddClient(std::move(client));
    return sharedPtr;
}
Ejemplo n.º 6
0
static void
ProcessMsg(HWND hwnd, PRUint32 pid, const ipcMessage *msg)
{
    LOG(("ProcessMsg [pid=%u len=%u]\n", pid, msg->MsgLen()));

    ipcClient *client = GetClientByPID(pid);

    if (client) {
        //
        // if this is an IPCM "client hello" message, then reset the client
        // instance object.
        //
        if (msg->Target().Equals(IPCM_TARGET) &&
            IPCM_GetType(msg) == IPCM_MSG_REQ_CLIENT_HELLO) {
            RemoveClient(client);
            client = NULL;
        }
    }

    if (client == NULL) {
        client = AddClient(hwnd, pid);
        if (!client)
            return;
    }

    IPC_DispatchMsg(client, msg);
}
Ejemplo n.º 7
0
QVector<std::shared_ptr<Client>> ClientController::GetClientList()
{
    QVector<std::shared_ptr<Client>> clients;

    if(!(UserSingleton::GetInstance().GetPermissions() & PLM::PermissionsFlag::READ_CLIENTS))
    {
        return clients;
    }

    QSqlQuery query = GetDb().CreateQuery();
    query.prepare("SELECT * "
        "FROM \"Client\""
        "INNER JOIN \"ContactView\" ON \"Client\".\"ContactId\" = \"ContactView\".\"ContactId\";"
    );

    if(!query.exec())
    {
        return clients;
    }

    while(query.next())
    {
        auto client = CreateClientFromQuery(query);
        auto sharedPtr = AddClient(std::move(client));

        clients.append(sharedPtr);
    }

    return clients;
}
Ejemplo n.º 8
0
HRESULT CAssemblyDownload::AddClient(IAssemblyBindSink *pAsmBindSink, 
                                     BOOL bCallStartBinding)
{
    HRESULT                             hr = S_OK;
    CClientBinding                     *pclient = NULL;

    if (!pAsmBindSink) {
        hr = E_INVALIDARG;
        goto Exit;
    }

    // Ref count released during CompleteAll
    pclient = NEW(CClientBinding(this, pAsmBindSink));
    if (!pclient) {
        hr = E_OUTOFMEMORY;
        goto Exit;
    }

    hr = AddClient(pclient, bCallStartBinding);
    if (FAILED(hr)) {
        // We failed, so we never got added to the client list.
        SAFERELEASE(pclient);
    }

Exit:
    return hr;
}
Ejemplo n.º 9
0
// 是否出错
void CStatInfo::AddVechile( const char *ip, const char *carnum, unsigned char color, bool error )
{
	if ( carnum == NULL )
		return ;

	share::Guard g( _mutex ) ;

	_ClientInfo *p = AddClient( ip, 0, 0 ) ;
	if ( p == NULL )
		return ;

	_CarInfo *info = NULL ;

	CMapCar::iterator it = p->_mpcar.find( carnum ) ;
	if ( it == p->_mpcar.end() ) {
		info = new _CarInfo ;
		info->_time     = time(NULL) ;
		info->_carnum   = carnum ;
		info->_carcolor = color ;
		info->_errcnt   = 0 ;
		if ( error ) {
			++ info->_errcnt ;
			++ p->_errcnt ;
		}
		ADD_NODE( p->_head, p->_tail, info ) ;
		p->_mpcar.insert( CMapCar::value_type( carnum, info ) ) ;
		++ p->_size ;

	} else {
		info = it->second ;
		info->_time = time(NULL) ;
		info->_errcnt = info->_errcnt + ( error ) ? 1 : 0  ;
	}
}
Ejemplo n.º 10
0
bool CClientList::IncomingBuddy(Kademlia::CContact* contact, Kademlia::CUInt128* buddyID)
{
	uint32_t nContactIP = wxUINT32_SWAP_ALWAYS(contact->GetIPAddress());
	//If aMule already knows this client, abort this.. It could cause conflicts.
	//Although the odds of this happening is very small, it could still happen.
	if (FindClientByIP(nContactIP, contact->GetTCPPort())) {
		return false;
	} else if (IsKadFirewallCheckIP(nContactIP)) { // doing a kad firewall check with this IP, abort
		AddDebugLogLineN(logKadMain, wxT("Kad TCP firewallcheck / Buddy request collision for IP ") + Uint32toStringIP(nContactIP));
		return false;
	}

	if (theApp->GetPublicIP() == nContactIP && thePrefs::GetPort() == contact->GetTCPPort()) {
		return false; // don't connect ourself
	}

	//Add client to the lists to be processed.
	CUpDownClient* pNewClient = new CUpDownClient(contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, NULL, false, true );
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_INCOMING_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(CMD4Hash(ID));
	buddyID->ToByteArray(ID);
	pNewClient->SetBuddyID(ID);
	AddToKadList(pNewClient);
	AddClient(pNewClient);
	return true;
}
Ejemplo n.º 11
0
void CClientList::RequestBuddy(Kademlia::CContact* contact, uint8_t connectOptions)
{
	uint32_t nContactIP = wxUINT32_SWAP_ALWAYS(contact->GetIPAddress());
	// Don't connect to ourself
	if (theApp->GetPublicIP() == nContactIP && thePrefs::GetPort() == contact->GetTCPPort()) {
		return;
	}

	CUpDownClient* pNewClient = FindClientByIP(nContactIP, contact->GetTCPPort());
	if (!pNewClient) {
		pNewClient = new CUpDownClient(contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, NULL, false, true );
	} else if (pNewClient->GetKadState() != KS_NONE) {
		return; // already busy with this client in some way (probably fw stuff), don't mess with it
	} else if (IsKadFirewallCheckIP(nContactIP)) { // doing a kad firewall check with this IP, abort
		AddDebugLogLineN(logKadMain, wxT("Kad TCP firewallcheck / Buddy request collision for IP ") + Uint32toStringIP(nContactIP));
		return;
	}

	//Add client to the lists to be processed.
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_QUEUED_BUDDY);
	uint8_t ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(CMD4Hash(ID));
	pNewClient->SetConnectOptions(connectOptions, true, false);
	AddToKadList(pNewClient);
	//This method checks if this is a dup already.
	AddClient(pNewClient);
}
Ejemplo n.º 12
0
bool CClientList::RequestTCP(Kademlia::CContact* contact, uint8_t connectOptions)
{
	uint32_t nContactIP = wxUINT32_SWAP_ALWAYS(contact->GetIPAddress());
	// don't connect ourself
	if (theApp->GetPublicIP() == nContactIP && thePrefs::GetPort() == contact->GetTCPPort()) {
		return false;
	}

	CUpDownClient* pNewClient = FindClientByIP(nContactIP, contact->GetTCPPort());

	if (!pNewClient) {
		//#warning Do we actually have to check friendstate here?
		pNewClient = new CUpDownClient(contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, NULL, false, true);
	} else if (pNewClient->GetKadState() != KS_NONE) {
		return false; // already busy with this client in some way (probably buddy stuff), don't mess with it
	}

	//Add client to the lists to be processed.
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_QUEUED_FWCHECK);
	if (contact->GetClientID() != 0) {
		uint8_t ID[16];
		contact->GetClientID().ToByteArray(ID);
		pNewClient->SetUserHash(CMD4Hash(ID));
		pNewClient->SetConnectOptions(connectOptions, true, false);
	}
	AddToKadList(pNewClient); // This was a direct adding, but I like to check duplicates
	//This method checks if this is a dup already.
	AddClient(pNewClient);
	return true;
}
Ejemplo n.º 13
0
bool CClientList::IncomingBuddy(Kademlia::CContact* contact, Kademlia::CUInt128* buddyID )
{
	uint32 nContactIP = ntohl(contact->GetIPAddress());
	//If eMule already knows this client, abort this.. It could cause conflicts.
	//Although the odds of this happening is very small, it could still happen.
	if (FindClientByIP(nContactIP, contact->GetTCPPort()))
		return false;
	else if (IsKadFirewallCheckIP(nContactIP)){ // doing a kad firewall check with this IP, abort 
		DEBUG_ONLY( DebugLogWarning(_T("KAD tcp Firewallcheck / Buddy request collosion for IP %s"), ipstr(nContactIP)) );
		return false;
	}
	else if (theApp.serverconnect->GetLocalIP() == nContactIP && thePrefs.GetPort() == contact->GetTCPPort())
		return false; // don't connect ourself

	//Add client to the lists to be processed.
	CUpDownClient* pNewClient = new CUpDownClient(0, contact->GetTCPPort(), contact->GetIPAddress(), 0, 0, false );
	pNewClient->SetKadPort(contact->GetUDPPort());
	pNewClient->SetKadState(KS_INCOMING_BUDDY);
	byte ID[16];
	contact->GetClientID().ToByteArray(ID);
	pNewClient->SetUserHash(ID); //??
	buddyID->ToByteArray(ID);
	pNewClient->SetBuddyID(ID);
	//MORPH START - Changed by SiRoB, Optimization
	/*
	AddToKadList(pNewClient);
	AddClient(pNewClient);
	*/
	m_KadList.AddTail(pNewClient);
	AddClient(pNewClient, true);
	//MORPH END   - Changed by SiRoB, Optimization
	return true;
}
Ejemplo n.º 14
0
void CNeighbour::OnAchnPacket(IAchnPacket* pPacket)
{
	ASSERT( m_pHomeWnd != NULL );
	
	AddClient( pPacket->ChType, pPacket->ChFirst, pPacket->ChLength );
	//m_pHomeWnd->DrawChType( pPacket->ChType );
	m_pHomeWnd->SendMessage( WM_DRAWCHTYPE, pPacket->ChType );
}
Ejemplo n.º 15
0
void ConnectionManager::HandleNewClient(int descriptor) {
  std::cout << "New client on socket " << descriptor;
  Message login(Message::kTypeLogin);
  login.Inject(Message::kMsgRequest);
  login.Inject(descriptor);
  AddClient(descriptor);
  Send(descriptor, login.GetString());
}
Ejemplo n.º 16
0
Client::Client(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this); 
    this->setWindowFlags(Qt::WindowStaysOnTopHint);
    connect(ui->cancel, SIGNAL(clicked()), this, SLOT(close()));
    connect(ui->save, SIGNAL(clicked()), this, SLOT(AddClient()));
}
Ejemplo n.º 17
0
bool CEpoll::Initalisation(SOCKET_FD fdServer)
{
    m_fdServer = fdServer;
    m_fdEpoll  = epoll_create(MAX_CLEINT_NUM);

    AddClient(fdServer, EPOLLIN|EPOLLET);
    
    return true;
}
Ejemplo n.º 18
0
void CameraObject::Setup( View * view )
{
    if( view->GetType() == THREED_VIEW_TYPE )
    {
        // turn on live video acquisition
        AddClient();

        // Make sure we receive interaction event from this view
        view->AddInteractionObject( this, 0.5 );

        PerViewElements perView;
        perView.cameraBackup = nullptr;

        vtkPolyDataMapper * camMapper = vtkPolyDataMapper::New();
        camMapper->SetInputData( m_cameraPolyData );
        perView.cameraActor = vtkActor::New();
        perView.cameraActor->SetMapper( camMapper );
        camMapper->Delete();
        perView.cameraActor->SetUserTransform( m_opticalCenterTransform );
        view->GetRenderer()->AddActor( perView.cameraActor );

        perView.cameraAxesActor = vtkAxesActor::New();
        perView.cameraAxesActor->SetTotalLength( 50, 50, 50 );
        perView.cameraAxesActor->AxisLabelsOff();
        perView.cameraAxesActor->SetUserTransform( m_opticalCenterTransform );
        view->GetRenderer()->AddActor( perView.cameraAxesActor );

        perView.cameraTrackerAxesActor = vtkAxesActor::New();
        perView.cameraTrackerAxesActor->SetTotalLength( 50, 50, 50 );
        perView.cameraTrackerAxesActor->AxisLabelsOff();
        perView.cameraTrackerAxesActor->SetUserTransform( this->m_uncalibratedWorldTransform );
        view->GetRenderer()->AddActor( perView.cameraTrackerAxesActor );

        perView.cameraImageActor = vtkSimpleProp3D::New();
        perView.cameraImageActor->SetUserTransform( m_imageTransform );

        perView.cameraImageMapper = vtkIbisImagePlaneMapper::New();
        perView.cameraImageMapper->SetGlobalOpacity( m_globalOpacity );
        perView.cameraImageMapper->SetImageCenter( m_intrinsicParams.m_center[0] * GetImageWidth(), m_intrinsicParams.m_center[1] * GetImageHeight() );
        perView.cameraImageMapper->SetLensDistortion( m_intrinsicParams.m_distorsionK1 );
        perView.cameraImageMapper->SetUseTransparency( m_useTransparency );
        perView.cameraImageMapper->SetUseGradient( m_useGradient );
        perView.cameraImageMapper->SetShowMask( m_showMask );
        perView.cameraImageMapper->SetTransparencyPosition( m_transparencyCenter[0], m_transparencyCenter[1] );
        perView.cameraImageMapper->SetTransparencyRadius( m_transparencyRadius[0], m_transparencyRadius[1] );
        perView.cameraImageActor->SetMapper( perView.cameraImageMapper );
        perView.cameraImageMapper->SetInputConnection( m_videoInputSwitch->GetOutputPort() );
        view->GetRenderer()->AddViewProp( perView.cameraImageActor );

        this->m_perViewElements[ view ] = perView;

        if( IsHidden() )
            Hide();

        connect( this, SIGNAL(ObjectModified()), view, SLOT(NotifyNeedRender()) );
    }
}
Ejemplo n.º 19
0
int main(int argc, char* argv[])
{
	WSADATA wsa;
	if(WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
	{
		printf("윈도우 소켓 초기화 실패! \n");
		return -1;
	}

	// (socket + bind + listen)
	if(!CreateListenSocket())
	{
		printf("대기 소켓 생성 실패\n");
		return -1;
	}

	// 서버처리
	//===================================================
	int index = 0;
	WSANETWORKEVENTS neEvents;
	
	while(1)
	{
		// 이벤트 시그널 감지
		index = WSAWaitForMultipleEvents(g_SockCnt, EventList,
			FALSE, WSA_INFINITE, FALSE);
		index -= WSA_WAIT_EVENT_0;
		// 이벤트 내용 가져오기 + EventList[index] 이벤트를 넌시그날로 변경
		WSAEnumNetworkEvents( SockList[index], EventList[index], &neEvents);
		if(neEvents.lNetworkEvents & FD_ACCEPT)
		{
			EVENTERRORCHECK(neEvents, FD_ACCEPT_BIT);
			if(AddClient(index) != true)
				continue;
		}
		else if(neEvents.lNetworkEvents & FD_READ || neEvents.lNetworkEvents & FD_WRITE)
		{
			if(neEvents.iErrorCode[FD_READ_BIT] != 0 && neEvents.iErrorCode[FD_WRITE_BIT] != 0)
			{
				DisplayMessage();
				return -1;
			}
			RecvClient(index);
			
		}
		else if(neEvents.lNetworkEvents & FD_CLOSE)
		{
			EVENTERRORCHECK(neEvents, FD_CLOSE_BIT);
				DeleteClient(index);
		}
	}
	//===================================================

	WSACleanup();
	return 0;
}
Ejemplo n.º 20
0
void
InitJupes()

{
	struct Jupe *tmpjupe;
	char sendstr[MAXLINE + 1];
	char **av;

	for (tmpjupe = JupeList; tmpjupe; tmpjupe = tmpjupe->next)
	{
		if (tmpjupe->isnick)
		{
#ifdef DANCER
			ircsprintf(sendstr, "NICK %s 1 1 +i juped juped.com %s :%s\r\n",
			           tmpjupe->name, Me.name, tmpjupe->reason ? tmpjupe->reason :
			           "Jupitered Nickname");
#else
			/* collide the nickname */
			ircsprintf(sendstr, "NICK %s 1 1 +i %s %s %s :%s\r\n",
			           tmpjupe->name, JUPED_USERNAME, JUPED_HOSTNAME, Me.name,
			           tmpjupe->reason ? tmpjupe->reason : "Jupitered Nickname");
#endif /* DANCER */

			toserv("%s", sendstr);

			SplitBuf(sendstr, &av);
			AddClient(av);
			MyFree(av);
		}
		else
		{
		  char *tptr;

		  /* check for wildcards */
		  for (tptr = tmpjupe->name; *tptr != '\0' && !IsMWildChar(*tptr); tptr++)
		    ;

		  if (*tptr == '\0')
		    {
			ircsprintf(sendstr, ":%s SERVER %s 2 :Juped: %s", Me.name,
			           tmpjupe->name, tmpjupe->reason);

			toserv(":%s SQUIT %s :%s (%s)\r\n%s\r\n",
			       Me.name,
			       tmpjupe->name,
			       tmpjupe->reason,
			       tmpjupe->who,
			       sendstr);

			SplitBuf(sendstr, &av);
			AddServer(5, av);
			MyFree(av);
		}
	}
	}
} /* InitJupes() */
void CQueueListCtrl::ShowQueueClients()
{
	DeleteAllItems(); 
	CUpDownClient *update = theApp.uploadqueue->GetNextClient(NULL);
	while( update )
	{
		AddClient(update, false);
		update = theApp.uploadqueue->GetNextClient(update);
	}
}
Ejemplo n.º 22
0
// 发送出去的个数
void CStatInfo::AddSend( const char *ip )
{
	share::Guard g( _mutex ) ;

	_ClientInfo *p = AddClient( ip, 0, 0 ) ;
	if ( p == NULL )
		return ;

	++ p->_send ;
}
Ejemplo n.º 23
0
CommunityServer::CommunityServer(int port)
{
	WSAData wsaData;
	int iResult;
	struct addrinfo *result = NULL, *ptr = NULL, hints;
	SOCKET ListenSocket = NULL;


	iResult = WSAStartup(MAKEWORD(2, 0), &wsaData);
	if (iResult != 0)  Error(1, "WSAStartup failed");
	
	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;
	std::string sport = std::to_string(port);
	iResult = getaddrinfo(NULL, sport.c_str(), &hints, &result);
	ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
	if (ListenSocket == INVALID_SOCKET)
	{
		Error(WSAGetLastError(), "Error processing with ListenSocket.");
		freeaddrinfo(result);
	}
	iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
	if (iResult == SOCKET_ERROR)
	{
		freeaddrinfo(result);
		closesocket(ListenSocket);
		WSACleanup();
		Error(WSAGetLastError(),"Error binding to socket.");
	}
	if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
	{
		freeaddrinfo(result);
		closesocket(ListenSocket);
		WSACleanup();
		Error(WSAGetLastError(), "Error starting listening");
	}
	u_long nbio = 1000;
	::ioctlsocket(ListenSocket, FIONBIO, &nbio);
	Handlers.push_back(new HelloHandler());
	std::cout << "Server was started successfully." << std::endl;
	while (true)
	{
		SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);
		if (ClientSocket != INVALID_SOCKET && ClientSocket!=SOCKET_ERROR) AddClient(ClientSocket);
		for (std::vector<Client*>::iterator it = Clients.begin(); it != Clients.end(); it++)
		{	
			Client* c = *it;
			c->ProcessClient();
		}
	}
	WSACleanup();
}
Ejemplo n.º 24
0
void ConnectionManager::Init() {
  if ((listen_socket_ = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    throw NetworkException("Error creating listening socket");
  }

  if (bind(listen_socket_, (struct sockaddr*)&server_address_, sizeof(server_address_)) == -1) {
    throw NetworkException("Error binding listening socket");
  }

  AddClient(listen_socket_);
  initialized_ = true;
}
Ejemplo n.º 25
0
AnimationManager::AnimationManager(AnimationClient* pInvalid)
{
	AddClient(pInvalid);

	// Create Animation Manager
    CORt(CoCreateInstance(CLSID_UIAnimationManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pAnimationManager)));
    // Create Animation Timer
    CORt(CoCreateInstance(CLSID_UIAnimationTimer, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pAnimationTimer)));
    CORt(CoCreateInstance(CLSID_UIAnimationTransitionLibrary, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pTransitionLibrary)));

	CORt(CManagerEventHandler::CreateInstance(this, &m_pHandler));
	CORt(m_pAnimationManager->SetManagerEventHandler(m_pHandler));
}
Ejemplo n.º 26
0
int main(int argc, char ** argv)
{
	int lsock;
	struct ClientNode * clients = NULL;
	int port;
	if(argc == 1) 
		port = PORT_NUM;
	else 
		return 1;
	printf("    Server v0.01\n");
	lsock = CreateSocket(port);
	if (lsock == -1)
		return 1;
	for(;;) { /**/
		fd_set readfds;
		int maxDs = lsock;
		int res;
		FD_ZERO(&readfds);
		FD_SET(lsock, &readfds);
		struct ClientNode * cl, *prev;
		for (cl = clients; cl!=NULL; cl = cl->next) {
			FD_SET(cl->fd, &readfds);
			if(cl->fd > maxDs)
				maxDs = cl->fd;
		}
		res = select(maxDs+1, &readfds, NULL, NULL, NULL);
		if(res<1) {
			/*handle error*/
		}
		if(FD_ISSET(lsock, &readfds)) {	
			clients = AddClient(lsock, clients);
			printf("new client connected\n");
		}
		prev = clients;
		for(cl = clients; cl != NULL; cl = cl->next) {
			if(FD_ISSET(cl->fd, &readfds)) {
				/*read data, process it*/
				int status;
				printf("new data arrives from client\n");
				status = ProcessClient(cl);
				if(1 == status) { 
					cl = DeleteClient(cl, prev, &clients);
					if(cl == NULL)
						break;
				}
			}
			prev = cl;
		}
	}
	return 0;
}
Ejemplo n.º 27
0
void EventLoop(int s32MainFd)
{
//	static unsigned int s32ChdCnt=0;
	static int s32ConCnt = 0;//已经连接的客户端数
	int s32Fd = -1;
	static RTSP_buffer *pRtspList=NULL;
	RTSP_buffer *p=NULL;
	unsigned int u32FdFound;

//	printf("%s\n", __FUNCTION__);
	/*接收连接,创建一个新的socket*/
	if (s32ConCnt!=-1)
	{
		s32Fd= tcp_accept(s32MainFd);
	}

	/*处理新创建的连接*/
	if (s32Fd >= 0)
	{
		/*查找列表中是否存在此连接的socket*/
		for (u32FdFound=0,p=pRtspList; p!=NULL; p=p->next)
		{
			if (p->fd == s32Fd)
			{
				u32FdFound=1;
				break;
			}
		}
		if (!u32FdFound)
		{
			/*创建一个连接,增加一个客户端*/
			if (s32ConCnt<MAX_CONNECTION)
			{
				++s32ConCnt;
				AddClient(&pRtspList,s32Fd);
			}
			else
			{
				fprintf(stderr, "exceed the MAX client, ignore this connecting\n");
				return;
			}
			num_conn++;
			fprintf(stderr, "%s Connection reached: %d\n", __FUNCTION__, num_conn);
		}
	}

	/*对已有的连接进行调度*/
	//printf("7\r\n");
	ScheduleConnections(&pRtspList,&s32ConCnt);
}
Ejemplo n.º 28
0
bool CClientList::DoRequestFirewallCheckUDP(const Kademlia::CContact& contact){
	// first make sure we don't know this IP already from somewhere
	if (FindClientByIP(ntohl(contact.GetIPAddress())) != NULL)
		return false;
	// fine, justcreate the client object, set the state and wait
	// TODO: We don't know the clients usershash, this means we cannot build an obfuscated connection, which 
	// again mean that the whole check won't work on "Require Obfuscation" setting, which is not a huge problem,
	// but certainly not nice. Only somewhat acceptable way to solve this is to use the KadID instead.
	CUpDownClient* pNewClient = new CUpDownClient(0, contact.GetTCPPort(), contact.GetIPAddress(), 0, 0, false );
	pNewClient->SetKadState(KS_QUEUED_FWCHECK_UDP);
	DebugLog(_T("Selected client for UDP Firewallcheck: %s"), ipstr(ntohl(contact.GetIPAddress())));
	AddToKadList(pNewClient);
	AddClient(pNewClient);
	ASSERT( !pNewClient->SupportsDirectUDPCallback() );
	return true;
}
Ejemplo n.º 29
0
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DonGato: show filtered list of clients
void CQueueListCtrl::ShowFilteredList()
{
	CUpDownClient	   *pClient;

	SetRedraw(FALSE);
	DeleteAllItems();
	for (POSITION pos = g_App.m_pUploadQueue->GetHeadPosition(); pos != NULL; )
	{
		pClient = g_App.m_pUploadQueue->GetNext(pos);
		if (pClient != NULL)
		{
			AddClient(pClient);
		}
	}
	SetRedraw(TRUE);
}
Ejemplo n.º 30
0
/**
 * Register Client
 */
HRESULT CDIL_CAN_i_VIEW::CAN_RegisterClient(
    BOOL    Register,
    DWORD&  ClientID,
    char*   ClientName )
{
    USES_CONVERSION;
    HRESULT hResult = S_FALSE;

    EnterCriticalSection(&m_Mutex);

    if (Register)
    {
        if (m_Clients.size() < MAX_CLIENT_ALLOWED)
        {
            pClient_t pClient= GetClient(ClientName);
            if (!pClient)
            {
                pClient = new Client(ClientName);
                ClientID = pClient->m_ClientID;
                AddClient( pClient );
                hResult = S_OK;
            }
            else
            {
                ClientID = pClient->m_ClientID;
                hResult = ERR_CLIENT_EXISTS;
            }
        }
        else
        {
            hResult = ERR_NO_MORE_CLIENT_ALLOWED;
        }
    }
    else
    {
        if (RemoveClient(ClientID))
        {
            hResult = S_OK;
        }
        else
        {
            hResult = ERR_NO_CLIENT_EXIST;
        }
    }
    LeaveCriticalSection(&m_Mutex);
    return hResult;
}