Beispiel #1
0
void MythRAOPDevice::newConnection(QTcpSocket *client)
{
    QMutexLocker locker(m_lock);
    LOG(VB_GENERAL, LOG_INFO, LOC + QString("New connection from %1:%2")
        .arg(client->peerAddress().toString()).arg(client->peerPort()));

    MythNotification n(tr("New Connection"), tr("AirTunes"),
                       tr("from %1:%2").arg(client->peerAddress().toString()).arg(client->peerPort()));
    // Don't show it during playback
    n.SetVisibility(n.GetVisibility() & ~MythNotification::kPlayback);
    GetNotificationCenter()->Queue(n);

    MythRAOPConnection *obj =
            new MythRAOPConnection(this, client, m_hardwareId, 6000);

    if (obj->Init())
    {
        m_clients.append(obj);
        connect(client, SIGNAL(disconnected()), this, SLOT(deleteClient()));
        gCoreContext->RegisterForPlayback(this, SLOT(TVPlaybackStarting()));
        return;
    }

    LOG(VB_GENERAL, LOG_ERR, LOC +
        "Failed to initialise client connection - closing.");
    delete obj;
    client->disconnectFromHost();
    delete client;
}
Beispiel #2
0
//handle child
static void child_handler(int sigNum) {
	if (latest_child == 0)
		return;
	deleteClient(latest_child);
	latest_child = 0;

}
Beispiel #3
0
void checkTimeouts() {
	std::list<Client *>::iterator iterator=server.client_list.begin();
	Client *user;
	while(iterator != server.client_list.end()) {
		user=*iterator;
		if(time(NULL)-NN_PING_TIME > user->getLastPacket()) {
			deleteClient(user);
			iterator = server.client_list.begin();
			continue;
		}
		iterator++;
	}
	iterator=server.client_list.begin();
	while(iterator != server.client_list.end()) {
		user = *iterator;
		if(user->getConnected()) {
			if(!user->getConnectedAck()) {
				if(time(NULL)-5 > user->getSendConnectTime()) {
					user->trySendConnect(false);
				}
			}
		}
		iterator++;
	}
	iterator=server.client_list.begin();
	while(iterator != server.client_list.end()) {
		user=*iterator;
		if(time(NULL)-NN_DEADBEAT_TIME > user->getConnectTime()) {
			if(!user->getConnected()) {
				user->sendDeadBeatNotice();
			}
		}
		iterator++;
	}
}
Beispiel #4
0
    ServerHeartbeat::ServerHeartbeat(zmq::context_t& context, const HeartbeatSettings& settings)
        : msFrequency_(settings.msRate), msPollingFrequency_(settings.msPollRate), msTimeout_(settings.msTimeout),
        running_(true)
    {
      // Create the router's socket
      std::unique_ptr<zmq::socket_t> heartbeat(new zmq::socket_t(context, ZMQ_PAIR));
      heartbeat->connect(SERVER_HB_SOCKET_ADDR.c_str());
      router_.add_socket(SocketID::HEARTBEAT, heartbeat);

      // Specify functionality 
      auto onRcvHELLO = [&] (const Message&m)
      { insertClient(m, clients_, lastHeartbeats_);};
      auto onRcvGOODBYE = [&] (const Message&m)
      { deleteClient(m, clients_, lastHeartbeats_);};
      auto onRcvHEARTBEAT = [&] (const Message&m)
      { receiveHeartbeat(m, lastHeartbeats_);};

      auto timeouts = [&] ()
      { monitorTimeouts(clients_, lastHeartbeats_, router_, msTimeout_);};
      auto send = [&] ()
      { sendHeartbeats(clients_, lastSendTime_, router_, msFrequency_);};

      // Bind to router
      router_(SocketID::HEARTBEAT).onRcvHELLO.connect(onRcvHELLO);
      router_(SocketID::HEARTBEAT).onRcvGOODBYE.connect(onRcvGOODBYE);
      router_(SocketID::HEARTBEAT).onRcvHEARTBEAT.connect(onRcvHEARTBEAT);
      router_(SocketID::HEARTBEAT).onPoll.connect(timeouts);
      router_(SocketID::HEARTBEAT).onPoll.connect(send);
      router_(SocketID::HEARTBEAT).onFailedSend.connect(failedSendServer);
      
      LOG(INFO)<< "Server heartbeat initialising";
      lastSendTime_ = std::chrono::high_resolution_clock::now();
      router_.start(msPollingFrequency_, running_); // milliseconds between polling loops
    }
Beispiel #5
0
int doDeleteClient(int fd){
    struct _client *client = findClientByFd(fd);
	close(fd);
	if(client){
		return deleteClient(client);
	}
	return 0;
}
UtlBoolean SipProtocolServerBase::send(SipMessage* message,
                            const char* hostAddress,
                            int hostPort)
{
    UtlBoolean sendOk = FALSE;


    UtlString localIp(message->getLocalIp());
    
    if (localIp.length() < 1)
    {
        localIp = mDefaultIp;
    }

    SipClient* client = createClient(hostAddress, hostPort, localIp);
    if(client)
    {
        int isBusy = client->isInUseForWrite();
        UtlString clientNames;

        client->getClientNames(clientNames);
        OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::send %p isInUseForWrite %d, client info\n %s",
                mProtocolString.data(), client, isBusy, clientNames.data());

        sendOk = client->sendTo(*message, hostAddress, hostPort);
        if(!sendOk)
        {
            OsTask* pCallingTask = OsTask::getCurrentTask();
            OsTaskId_t callingTaskId = -1;
            OsTaskId_t clientTaskId = -1;

            if ( pCallingTask )
            {
               pCallingTask->id(callingTaskId);
            }
            client->id(clientTaskId);

            if (clientTaskId != callingTaskId)
            {
               // Do not need to clientLock.acquireWrite();
               // as deleteClient uses the locking list lock
               // which is all that is needed as the client is
               // already marked as busy when we called
               // createClient above.
               deleteClient(client);
               client = NULL;
            }
        }
    }

        if(client)
        {
            releaseClient(client);
        }

    return(sendOk);
}
Beispiel #7
0
void
CIpcServer::handleClientDisconnected(const CEvent& e, void*)
{
	CIpcClientProxy* proxy = static_cast<CIpcClientProxy*>(e.getTarget());

	CArchMutexLock lock(m_clientsMutex);
	m_clients.remove(proxy);
	deleteClient(proxy);

	LOG((CLOG_DEBUG "ipc client proxy removed, connected=%d", m_clients.size()));
}
Beispiel #8
0
CIpcServer::~CIpcServer()
{
	ARCH->lockMutex(m_clientsMutex);
	CClientList::iterator it;
	for (it = m_clients.begin(); it != m_clients.end(); it++) {
		deleteClient(*it);
	}
	m_clients.empty();
	ARCH->unlockMutex(m_clientsMutex);
	ARCH->closeMutex(m_clientsMutex);
	
	m_events->removeHandler(m_events->forIListenSocket().connecting(), &m_socket);
}
Beispiel #9
0
void ClientManager::handle(const std::shared_ptr<ClientsMap <int, ClientManager *>> &blockingMap) {
    registerThread(blockingMap);
    logger->log("Created");

    std::thread socketListenerThread(&SocketListener::handle, socketListener);
    std::thread senderThread(&Sender::handle, sender);

    socketListenerThread.join();
    sender->setConnectionClosed();
    senderThread.join();

    deleteClient();
    unregisterThread(blockingMap);
}
Beispiel #10
0
void Client::mainLoop(fd_set *rset) {
	if(!FD_ISSET(sd,rset)) return;
	memset(&buff,0,sizeof(buff));
	len = recv(sd,buff,sizeof(buff),0);
	if(len<1) goto end;
	lastPacket = time(NULL);
	if(!do_db_check()) return
	gamespy3dxor(buff, len);
	buff[len]=0;
	makeStringSafe((char *)&buff, sizeof(buff));
	parseIncoming();
	return;
end:
	 deleteClient(this);
}
Beispiel #11
0
unsigned int Server::hnbrecv(char * recvBuff, unsigned int recvLength, unsigned int clientIndex) {
	CLIENT_DATA* clientData = grabClientData(clientIndex);
	int ret;

	if(clientData == NULL)
		return false;

	ret = recv(clientData->sock, (char*)recvBuff, recvLength, 0);
	if(ret >= 1)
		bytesReceived += ret;

	if(ret == SOCKET_ERROR)
		deleteClient(clientIndex);

	return ret;
}
Beispiel #12
0
unsigned int Server::hnbsend(char * sendData, unsigned int sendLength, unsigned int clientIndex) {
	CLIENT_DATA* clientData = grabClientData(clientIndex);
	int ret;

	if(clientData == NULL)
		return false;

	ret = send(clientData->sock, (const char*)sendData, sendLength, 0);
	if(ret >= 1)
		bytesSent += ret;

	if(ret == SOCKET_ERROR)
		deleteClient(clientIndex);

	return ret;
}
Beispiel #13
0
void Server::stopServer() { //untested code but 98% sure it'll do.
	CLIENT_DATA * clientData;
	isServerStopped = true;

	if(serverSocks.size() > 0) {

		for(unsigned int x = 0; x < serverSocks.size(); x++) {
				clientData = serverSocks[x];
				deleteClient(clientData->index);
		}

		stopServer(); //recursive: we need to keep calling this until size() is zero.

	}

}
Beispiel #14
0
unsigned int Server::hnbsend(string sendData, unsigned int clientIndex) {
	CLIENT_DATA* clientData = grabClientData(clientIndex);
	int ret;

	if(clientData == NULL)
		return false;

	ret = send(clientData->sock, sendData.c_str(), sendData.length(), 0);
	if(ret >= 1)
		bytesSent += ret;

	if(ret == SOCKET_ERROR)
		deleteClient(clientIndex);

	return ret;
}
Beispiel #15
0
void KSMServer::processData( int /*socket*/ )
{
    IceConn iceConn = ((KSMConnection*)sender())->iceConn;
    IceProcessMessagesStatus status = IceProcessMessages( iceConn, 0, 0 );
    if ( status == IceProcessMessagesIOError ) {
        IceSetShutdownNegotiation( iceConn, False );
        QList<KSMClient*>::iterator it = clients.begin();
        QList<KSMClient*>::iterator const itEnd = clients.end();
        while ( ( it != itEnd ) && *it && ( SmsGetIceConnection( ( *it )->connection() ) != iceConn ) )
            ++it;
        if ( ( it != itEnd ) && *it ) {
            SmsConn smsConn = (*it)->connection();
            deleteClient( *it );
            SmsCleanUp( smsConn );
        }
        (void) IceCloseConnection( iceConn );
    }
}
void GraphicsClientItemsClient::loadState(QDataStream &stream)
{
    // delete all clients and the corresponding graphics:
    QStringList clientNames = clientItems.keys();
    for (int i = 0; i < clientNames.size(); i++) {
        QString clientName = clientNames[i];
        deleteClient(clientName);
    }
    // read client graphics positions:
    stream >> clientItemPositionMap;
    // set the positions of already existing graphics items:
    for (QMap<QString, QPointF>::iterator i = clientItemPositionMap.begin(); i != clientItemPositionMap.end(); i++) {
        GraphicsClientItem *clientItem = clientItems.value(i.key(), 0);
        if (clientItem) {
            clientItem->setPos(i.value());
        }
    }
    // read the clients' and their states:
    RecursiveJackContext::getInstance()->loadCurrentContext(stream, JackClientSerializer::getInstance());
}
Beispiel #17
0
IpcServer::~IpcServer()
{
	if (m_mock) {
		return;
	}

	if (m_socket != nullptr) {
		delete m_socket;
	}

	ARCH->lockMutex(m_clientsMutex);
	ClientList::iterator it;
	for (it = m_clients.begin(); it != m_clients.end(); it++) {
		deleteClient(*it);
	}
	m_clients.empty();
	ARCH->unlockMutex(m_clientsMutex);
	ARCH->closeMutex(m_clientsMutex);
	
	m_events->removeHandler(m_events->forIListenSocket().connecting(), m_socket);
}
Beispiel #18
0
unsigned int Server::hnbrecv(string *recvString, unsigned int clientIndex) {
	CLIENT_DATA* clientData = grabClientData(clientIndex);
	char buff[2];
	int ret;
	
	memset(buff, 0, sizeof(buff)); //mad?
	recvString->assign(""); //that should do it

	while( (ret = recv(clientData->sock, &buff[0], 1, 0)) == 1)  { //receive data until NULL data, bad connection, or blocked receive call
		
		if(buff[0] == '\x00') {
			bytesReceived++; break;
		}
		
		recvString->append(buff);
		bytesReceived++;
	}

	if(ret == SOCKET_ERROR)
		deleteClient(clientIndex);

	return recvString->length();
}
Beispiel #19
0
void Client::sendError(int sd, bool fatal, char *msg, GPErrorCode errid, int id) {
	int len = 128 + strlen(msg);
	char *errtext = (char *)malloc(len);
	sprintf_s(errtext,len,"\\error\\\\err\\%d",errid);
	if(fatal) {
		strcat(errtext,"\\fatal\\");
	}
	if(msg != NULL) {
		strcat(errtext,"\\errmsg\\");
		strcat(errtext,msg);
//		if(strchr(msg,'\\') == NULL)
//			strcat(errtext,"\\");
	}
	if(id == -1) {
		formatSend(sd,true,2,"%s",errtext);
	} else {
		formatSend(sd,true,2,"%s\\id\\%d",errtext,id);
	}
	free((void *)errtext);
	if(fatal) {
		deleteClient(this);
	}
	return;
}
Beispiel #20
0
void Server::ReceiveThread(LPVOID lparam)
{
	//应当能接受一段字节流,然后交给下层的Message处理。得到一个处理结果存到全局变量MyJson中。
	//参数lparam是接受用的ReceiveSocket。
	//还需要调用本地的Client去建立一个反向的TCP链接
	//需要有能力调用对应的Client去反向回复
	SOCKET *ReceiveSocket=(SOCKET*)lparam;//得到建立连接的那个socket
	Client *respond_client=NULL;//本机上的客户机,指向全局的一个Client,或者在此线程中创建一个全局的Client,并用这个指针操作。需要在线程结束时释放。
	SOCKADDR_IN dest_add;//和本机建立通信的Client的地址
	string rcv;//接收到的字节流。
	int x=-1;
	int nAddrLen = sizeof(dest_add);
	//通过RCVSocket获得对方的地址
	if(::getpeername(*ReceiveSocket, (SOCKADDR*)&dest_add, &nAddrLen) != 0)
	{
		mtx->lock();
		std::cout<<"Get IP address by socket failed!"<<endl;
		this->exitSocket(*ReceiveSocket);//在server中删除这个socket
		mtx->unlock();
		return;
	}

	mtx->lock();
	cout<<"IP: "<<::inet_ntoa(dest_add.sin_addr)<<"  PORT: "<<ntohs(dest_add.sin_port)<<"开始向您通话!"<<endl;
	mtx->unlock();

	mtx->lock();
	respond_client=checkClientList(dest_add);//调用回调函数,checkClientList,并完成恢复Client的赋值
	mtx->unlock();
	//主循环

	while(1)
	{
		Message mess=Message();
		MyJson infomation=MyJson();
		try
		{
			rcv=this->receiveData(*ReceiveSocket);//接收信息,在这里线程会等待到接收到为止
		}
		catch(exception e)//TODO:应当处理此类异常!
		{
			cout<<"when Receive:"<<e.what();
			system("pause");
			//mtx->lock();
			//this->exitSocket(*ReceiveSocket);
			//deleteClient(respond_client);
			//mtx->unlock();
			//respond_client=NULL;
			return;
		}
		infomation=mess.getContent(rcv);//这里完成了从字节层到信息层的解包
		if(infomation.type_s=="exit")
		{	
			mtx->lock();
			//注销这个客户端,应当由回调函数完成
			this->exitSocket(*ReceiveSocket);//在acceptsocket中删除这个socket
			deleteClient(respond_client);
			mtx->unlock();
			cout<<inet_ntoa(dest_add.sin_addr)<<"下线了!"<<endl;
			respond_client=NULL;//它只是一个无辜的指针,告诉你内容在哪里,但请不要再本函数内操作它的内容。
			return ;
		}
		else
		{
			if(infomation.type_s=="text")
			{
				mtx->lock();
				respendClient(respond_client);
				infomation.showJson_in_console();
				cout<<endl;
				mtx->unlock();
			}
			else
			{
				//TODO:对其他的包类型进行处理,如果需要操作Client,依旧请使用回调函数。
				elsefunction(respond_client);
			}
		}
	}
	mtx->lock();
	this->exitSocket(*ReceiveSocket);
	mtx->unlock();
	delete respond_client;
	respond_client=NULL;
	return ;
}
Beispiel #21
0
void
subc_CancelList (
    pool_sQlink		*lh
)
{
    qcom_sQid		tgt;
#if 0
    tree_sTable		*remove;
    sRemove		*rep;
    gdb_sNode		*np;
#endif
    pwr_tNodeId		nid;
    pwr_tSubid		sid;
    sub_sClient		*cp;
    pool_sQlink		*cl;

    gdb_AssumeLocked;

    tgt.qix = net_cProcHandler;

#if 0
    remove = tree_CreateTable(sizeof(pwr_tNodeId), offsetof(sRemove, nid),
                              sizeof(sRemove), 10, tree_eComp_nid, NULL);
#endif

    for (cl = pool_Qsucc(NULL, gdbroot->pool, lh); cl != lh;) {
        cp = pool_Qitem(cl, sub_sClient, subc_ll);
        cl = pool_Qsucc(NULL, gdbroot->pool, cl);

        cancelTimeoutWatch(cp);

        /* Get rid of the client, make it invalid for other references
           that might happen when we are unlocked
           But first: save nid and sid which we need further down.  */

        nid = cp->nid;
        sid = cp->sid;
        deleteClient(cp);

#if 0
        if (nid != pwr_cNNodeId) {
            rep = tree_Insert(remove, &nid);
            if (rep == NULL) errh_Bugcheck(GDH__WEIRD, "");

            if (rep->msg == NULL) {
                np = hash_Search(NULL, gdbroot->nid_ht, &nid);
                if (np == NULL) errh_Bugcheck(GDH__WEIRD, "");
                rep->cnt = net_cSubMaxRemove;
                rep->msg = malloc(sizeof(net_sSubRemove) + sizeof(rep->msg->sid[0]) * rep->cnt);
                rep->msg->count = 0;
            }

            rep->msg->sid[rep->msg->count++] = sid;

            if (rep->msg->count >= net_cSubMaxRemove) {
                tgt.nid = rep->nid;

                gdb_Unlock;

                net_Put(NULL, &tgt, rep->msg, net_eMsg_subRemove, 0, pwr_Offset(rep->msg, sid[rep->msg->count]), 0);

                gdb_Lock;

                rep->msg->count = 0;

            }
        } /* Remote */
#endif
    } /* For all clients in list */

#if 0
    /* Now send all unsent messages.  */

    gdb_Unlock;

    for (rep = tree_Minimum(remove); rep != NULL; rep = tree_Successor(remove, rep)) {
        if (rep->msg != NULL) {
            if (rep->msg->count > 0) {
                tgt.nid = rep->nid;
                net_Put(NULL, &tgt, rep->msg, net_eMsg_subRemove, 0, pwr_Offset(rep->msg, sid[rep->msg->count]), 0);
            }
            free(rep->msg);
        }
    }

    gdb_Lock;

    tree_DeleteTable(remove);
#endif
}
Beispiel #22
0
/*----------------------------------------------------------------------------------------
 * Purpose: Deletes an active client based on the clientId
 * Input: commandArgument - A linked list that provides all the parameters the users typed 
 * 		in. This list is in the same order as they were typed.
 * 	clientThreadArguments - A struct providing the basic address information for the 
 * 		current connection.
 * 	commandNode - A pointer to the current node in the command tree structure.
 * Output:  0 for success or 1 for failure
 * Note:        
 * Kevin Burnett @ November 10, 2008   
 * -------------------------------------------------------------------------------------*/
int cmdKillClient(commandArgument * ca, clientThreadArguments * client, commandNode * cn) {
	long clientID = 0;
	clientID = atol(ca->commandArgument);
	deleteClient(clientID, CLIENT_LISTENER_UPDATA);
	return 0;
}