Beispiel #1
0
void CTlsSocket::OnSocketEvent(wxSocketEvent& event)
{
	wxASSERT(m_pSocket);
	if (!m_session)
		return;

	if (event.GetId() != m_pSocketBackend->GetId())
		return;

	switch (event.GetSocketEvent())
	{
	case wxSOCKET_INPUT:
		OnRead();
		break;
	case wxSOCKET_OUTPUT:
		OnSend();
		break;
	case wxSOCKET_LOST:
		{
			m_canCheckCloseSocket = true;
			char tmp[100];
			m_pSocketBackend->Peek(&tmp, 100);
			if (!m_pSocketBackend->Error())
			{
				int lastCount = m_pSocketBackend->LastCount();

				if (lastCount)
					m_pOwner->LogMessage(Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing wxSOCKET_LOST"));
				else
					m_socketClosed = true;
				OnRead();

				if (lastCount)
					return;
			}

			m_pOwner->LogMessage(Debug_Info, _T("CTlsSocket::OnSocketEvent(): wxSOCKET_LOST received"));

			//Uninit();
			wxSocketEvent evt(GetId());
			evt.m_event = wxSOCKET_LOST;
			wxPostEvent(m_pEvtHandler, evt);
		}
		break;
	default:
		break;
	}
}
Beispiel #2
0
void Socket::ReadCallback(uint32 len)
{
	if(IsDeleted() || !IsConnected())
		return;

	// We have to lock here.
	m_readMutex.Acquire();

	size_t space = readBuffer.GetSpace();
	int bytes = recv(m_fd, readBuffer.GetBuffer(), space, 0);
	if(bytes <= 0)
	{
		m_readMutex.Release();
		Disconnect();
		return;
	}
	else if(bytes > 0)
	{
		//m_readByteCount += bytes;
		readBuffer.IncrementWritten(bytes);
		// call virtual onread()
		OnRead();
	}
	m_BytesRecieved += bytes;

	m_readMutex.Release();
}
void CNetworkConnection::initializeSocket()
{
	m_pSocket->disconnect();

	connect(m_pSocket, SIGNAL(connected()),
			this, SIGNAL(connected()));
	connect(m_pSocket, SIGNAL(connected()),
			this, SIGNAL(readyToTransfer()));
	connect(m_pSocket, SIGNAL(readyRead()),
			this, SIGNAL(readyToTransfer()));
	connect(m_pSocket, SIGNAL(disconnected()),
			this, SIGNAL(disconnected()));
	connect(m_pSocket, SIGNAL(error(QAbstractSocket::SocketError)),
			this, SIGNAL(error(QAbstractSocket::SocketError)));
	connect(m_pSocket, SIGNAL(bytesWritten(qint64)),
			this, SIGNAL(bytesWritten(qint64)));
	connect(m_pSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
			this, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
	connect(m_pSocket, SIGNAL(aboutToClose()),
			this, SLOT(OnAboutToClose()));

	connect(this, SIGNAL(connected()), this, SLOT(OnConnect()), Qt::QueuedConnection);
	connect(this, SIGNAL(disconnected()), this, SLOT(OnDisconnect()), Qt::QueuedConnection);
	connect(this, SIGNAL(readyRead()), this, SLOT(OnRead()), Qt::QueuedConnection);
	connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnError(QAbstractSocket::SocketError)), Qt::QueuedConnection);
	connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(OnStateChange(QAbstractSocket::SocketState)), Qt::QueuedConnection);
}
Beispiel #4
0
void imconn_callback_sp(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
	NOTUSED_ARG(handle);
	NOTUSED_ARG(pParam);
	auto imconn_map_sp = (ConnMap_sp_t*)callback_data;
	
	auto pConn = FindImConnSp(imconn_map_sp, handle);
	if (!pConn)
		return;

	// log("msg=%d, handle=%d ", msg, handle);

	switch (msg)
	{
	case NETLIB_MSG_CONFIRM:
		pConn->OnConfirm();
		break;
	case NETLIB_MSG_READ:
		pConn->OnRead();
		break;
	case NETLIB_MSG_WRITE:
		pConn->OnWrite();
		break;
	case NETLIB_MSG_CLOSE:
		pConn->OnClose();
		break;
	default:
		loge("!!!imconn_callback error msg: %d ", msg);
		break;
	}
}
Beispiel #5
0
SocketHandler::SocketHandler(QTcpSocket *socket)
{
    m_socket = socket;
    m_packetSize = 0;

    connect(m_socket, SIGNAL(readyRead()), this, SLOT(OnRead()));
}
Beispiel #6
0
        void CTcpHandler::TcpConnect(CCommand *pCmd)
        {
	        NsqLogPrintf(LOG_DEBUG, "TcpConnect\n");
            CTcpConnectCommand *pConnectCmd = dynamic_cast<CTcpConnectCommand *>(pCmd);
            m_strHost = pConnectCmd->m_strHost;
            m_iPort = pConnectCmd->m_iPort;
            sockaddr_in sAddr;
            memset(&sAddr, 0, sizeof(sockaddr_in));
            sAddr.sin_addr.s_addr = inet_addr(pConnectCmd->m_strHost.c_str());
            sAddr.sin_port = htons(pConnectCmd->m_iPort);
            sAddr.sin_family = AF_INET;

            CNetThread *pThread = dynamic_cast<CNetThread *>(GetThread()); 
            m_pBufevt = bufferevent_socket_new(pThread->GetEventBase(), -1, BEV_OPT_THREADSAFE);
            int32_t iRet = bufferevent_socket_connect(m_pBufevt, (sockaddr*)&sAddr, sizeof(sockaddr_in));
             
            if (iRet != 0)
            {
                OnError(errno); 
                return ;
            }

            bufferevent_setcb(m_pBufevt, CNetThread::OnStaticRead, CNetThread::OnStaticWrite, CNetThread::OnStaticError, this);
            bufferevent_enable(m_pBufevt, EV_READ|EV_PERSIST|EV_ET);		

            //设置读入最低水位,防止无效回调
            bufferevent_setwatermark(m_pBufevt, EV_READ, 
                                     OnRead(NULL, 0), 0);

            SetTimeout();
        }
Beispiel #7
0
void CTlsSocket::OnSocketEvent(CSocketEvent& event)
{
	wxASSERT(m_pSocket);
	if (!m_session)
		return;

	switch (event.GetType())
	{
	case CSocketEvent::read:
		OnRead();
		break;
	case CSocketEvent::write:
		OnSend();
		break;
	case CSocketEvent::close:
		{
			m_canCheckCloseSocket = true;
			char tmp[100];
			int error;
			int peeked = m_pSocketBackend->Peek(&tmp, 100, error);
			if (peeked >= 0)
			{
				if (peeked > 0)
					m_pOwner->LogMessage(Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing close event"));
				else
				{
					m_socket_eof = true;
					m_socketClosed = true;
				}
				OnRead();

				if (peeked)
					return;
			}

			m_pOwner->LogMessage(Debug_Info, _T("CTlsSocket::OnSocketEvent(): close event received"));

			//Uninit();
			CSocketEvent *evt = new CSocketEvent(m_pEvtHandler, this, CSocketEvent::close);
			CSocketEventDispatcher::Get().SendEvent(evt);
		}
		break;
	default:
		break;
	}
}
Beispiel #8
0
BOOL CTransfer::OnReadCompleted(COverlapped* pOverlapped, DWORD nLength)
{
	CAutoLock<CThreadGuard> pLock( m_pSection );
// 	
// 	ASSERT ( pOverlapped->IsCompleted() );
	m_nReference--;
	
	ioctlsocket( m_hSocket, FIONREAD, &nLength );
	if ( nLength && OnRead(0) && OnRead() ) return TRUE;
	
	if ( m_nReference ) return FALSE;
	m_bConnected = FALSE;
// 	pLock.Unlock();
// 	
// 	OnDropped( WSAGetLastError() );
	return FALSE;
}
Beispiel #9
0
void CG2Node::SetupSlots()
{
	connect(this, SIGNAL(connected()), this, SLOT(OnConnect()), Qt::QueuedConnection);
	connect(this, SIGNAL(disconnected()), this, SLOT(OnDisconnect()), Qt::QueuedConnection);
	connect(this, SIGNAL(readyRead()), this, SLOT(OnRead()), Qt::QueuedConnection);
	connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnError(QAbstractSocket::SocketError)), Qt::QueuedConnection);
	connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(OnStateChange(QAbstractSocket::SocketState)), Qt::QueuedConnection);
}
void NetworkManager::OnEvent(int numOfEvent, int threadId)
{
	int strLen = 0;
	char buffer[1024];
	for(int i=0; i<numOfEvent; i++)
	{
		int eventFd = m_epollEvent2DList[threadId][i].data.fd;
		if(eventFd == m_serverFd) // when clients attempt to connect
		{
			OnConnect();
		}
		else	// when client request service
		{
			Session* pSession = m_pSessionMap[eventFd];
			strLen = read(eventFd, pSession->buffer, MAX_BUFFER_LENGTH); // Read client request
			if(strLen == 0)	// Client request to disconnect
			{
				epoll_ctl(m_epollFdList[threadId], EPOLL_CTL_DEL, m_epollEvent2DList[threadId][i].data.fd, NULL); // remove client info from epoll instance
				close(eventFd); // disconnecd
				delete pSession;
				m_pSessionMap.erase(eventFd);
				printf("%d session disconnected\n", eventFd);
			}
			else if(strLen < 0)
			{
	/*			if(errno != EWOULDBLOCK && errno != EAGAIN)
				{
					// critical error
					fprintf(stderr, "[ERROR] read() ERROR : %s\n", strerror(errno));
					exit(1);
				}*/
			}
			else
			{
				__uint32_t events = m_epollEvent2DList[threadId][i].events;
				if(events & EPOLLIN)
				{
					OnRead(eventFd, strLen);
				}
				if(events & EPOLLOUT)
				{
					printf("EPOLLOUT\n");
				}
				if(events & EPOLLERR)
				{
					fprintf(stderr, "[ERROR] : EPOLL EVENT ERROR\n");
					exit(-1);				
				}
				//pSession->buffer[strLen] = '\0';
				//printf("%s\n", pSession->buffer);

				// service that someelse
			}
		}
	}
}
Beispiel #11
0
void CTlsSocket::OnSocketEvent(CSocketEventSource*, SocketEventType t, int error)
{
	if (!m_session)
		return;

	switch (t)
	{
	case SocketEventType::read:
		OnRead();
		break;
	case SocketEventType::write:
		OnSend();
		break;
	case SocketEventType::close:
		{
			m_canCheckCloseSocket = true;
			char tmp[100];
			int peeked = m_pSocketBackend->Peek(&tmp, 100, error);
			if (peeked >= 0) {
				if (peeked > 0)
					m_pOwner->LogMessage(MessageType::Debug_Verbose, _T("CTlsSocket::OnSocketEvent(): pending data, postponing close event"));
				else {
					m_socket_eof = true;
					m_socketClosed = true;
				}
				OnRead();

				if (peeked)
					return;
			}

			m_pOwner->LogMessage(MessageType::Debug_Info, _T("CTlsSocket::OnSocketEvent(): close event received"));

			//Uninit();
			m_pEvtHandler->send_event<CSocketEvent>(this, SocketEventType::close, 0);
		}
		break;
	default:
		break;
	}
}
Beispiel #12
0
void CHandshake::acceptFrom(int handle)
{
    m_tConnected = time(0);
    m_pSocket = new QTcpSocket();
    m_pSocket->setReadBufferSize(1024);

	connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(OnRead()), Qt::QueuedConnection);
    connect(m_pSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(deleteLater()));

    m_pSocket->setSocketDescriptor(handle);

	if( m_pSocket->peerAddress() == QHostAddress::Any || m_pSocket->peerAddress() == QHostAddress::Null )
	{
		m_pSocket->abort();
		deleteLater();
		return;
	}

    qDebug() << "Accepted an incoming connection from " << m_pSocket->peerAddress().toString().toAscii().constData();
    OnRead();
}
Beispiel #13
0
bool_t PacketHandler::HandleEvents(serial_t uidx, Session *sess, EVENT_T e)
{
	if(!sess) { ECILA_TRACE(); return FALSE; }

	switch(e)
	{
	case NS_ECILA::EVENT_OPEN	: return OnOpen(uidx, sess);
	case NS_ECILA::EVENT_CLOSE	: return OnClose(uidx, sess);
	case NS_ECILA::EVENT_READ	: return OnRead(uidx, sess);
	case NS_ECILA::EVENT_WRITE	: return OnWrite(uidx, sess);
	default						: { ECILA_TRACE(); return FALSE; }
	}
}
Beispiel #14
0
 void CTcpHandler::TcpAdd(CCommand *pCmd)
 {
     CTcpAddCommand *pConnectCmd = dynamic_cast<CTcpAddCommand *>(pCmd);
     CEventThread *pThread = dynamic_cast<CEventThread *>(GetThread()); 
     m_pBufevt = bufferevent_socket_new(pThread->GetEventBase(), 
             pConnectCmd->m_iFd, BEV_OPT_THREADSAFE);
     bufferevent_setcb(m_pBufevt, CNetThread::OnStaticRead, CNetThread::OnStaticWrite, CNetThread::OnStaticError, this);
     bufferevent_enable(m_pBufevt, EV_READ|EV_PERSIST|EV_ET);		
     bufferevent_setwatermark(m_pBufevt, EV_READ, 
                               OnRead(NULL, 0), 0);
     OnConnect();
     //告诉listen线程
     SetTimeout();
 }
Beispiel #15
0
bool wxTextBuffer::Open(const wxMBConv& conv)
{
    // buffer name must be either given in ctor or in Open(const wxString&)
    wxASSERT( !m_strBufferName.empty() );

    // open buffer in read-only mode
    if ( !OnOpen(m_strBufferName, ReadAccess) )
        return false;

    // read buffer into memory
    m_isOpened = OnRead(conv);

    OnClose();

    return m_isOpened;
}
Beispiel #16
0
void Socket::ReadCallback(uint32 len)
{
	int bytes = recv(m_fd, ((char*)m_readBuffer + m_readByteCount), m_readBufferSize - m_readByteCount, 0);
	if(bytes <= 0)
	{
		m_readMutex.Release();
		Disconnect();
		return;
	}    
	else if(bytes > 0)
	{
		m_readByteCount += bytes;
		// call virtual onread()
		OnRead();
	}

	m_readMutex.Release();
}
Beispiel #17
0
        void CTcpHandler::TcpRead()
        {
            //内存copy三次,太浪费,后续改进
            int iLength = evbuffer_get_length(bufferevent_get_input(m_pBufevt));
            char *pData = new char[iLength + 1];
            bufferevent_read(m_pBufevt, pData, iLength);			
            pData[iLength] = '\0';
		    NsqLogPrintf(LOG_DEBUG, "TcpRead iLength = %d\n", iLength);

            //iNeedLength 证明包处理出错,已经析构掉了handler相关的一些
            int iNeedLength = OnRead(pData, iLength); 

            if (iNeedLength > 0)
            {
                bufferevent_setwatermark(m_pBufevt, EV_READ, iNeedLength, 0);
            }

            delete pData;
        }
Beispiel #18
0
void IEventChannel::FiredEvents()
{
	ChannelEventFlags val=mFiredEvents;
	mFiredEvents = ChannelEventFlags::None;

	if (MEDUSA_FLAG_HAS(val,ChannelEventFlags::Read))
	{
		OnActive();
		OnRead();
	}
	if (!mIsAlive)
	{
		return;
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Write))
	{
		OnActive();
		OnWrite();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Timeout))
	{
		OnTimeout();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Retry))
	{
		OnRetry();
	}

	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Fault))
	{
		OnError();
	}
	
	if (MEDUSA_FLAG_HAS(val, ChannelEventFlags::Idle))
	{
		OnIdle();
	}

}
Beispiel #19
0
BOOL CConnection::OnRun()
{
	if ( INVALID_SOCKET == m_hSocket ) return FALSE;
	
	WSANETWORKEVENTS pEvents;
	WSAEnumNetworkEvents( m_hSocket, NULL, &pEvents );
	
	if ( pEvents.lNetworkEvents & FD_CONNECT )
	{
		if ( pEvents.iErrorCode[ FD_CONNECT_BIT ] != 0 )
		{
			OnDropped( TRUE );
			return FALSE;
		}

		if ( ! OnConnected() ) return FALSE;
	}
	
	BOOL bClosed = ( pEvents.lNetworkEvents & FD_CLOSE ) ? TRUE : FALSE;
	
	// if ( pEvents.lNetworkEvents & FD_WRITE )
	{
		if ( ! OnWrite() ) return FALSE;
	}

	// if ( pEvents.lNetworkEvents & FD_READ )
	{
		if ( ! OnRead() ) return FALSE;
	}
	
	if ( bClosed )
	{
		OnDropped( pEvents.iErrorCode[ FD_CLOSE_BIT ] != 0 );
		return FALSE;
	}

	return TRUE;
}
Beispiel #20
0
void APISocket::CSocket::AsyncNotifications()
{
	if (!m_sock) return;

	fd_set read_fds, write_fds;
	FD_ZERO(&read_fds);
	FD_ZERO(&write_fds);
	FD_SET(m_sock, &read_fds);
	FD_SET(m_sock, &write_fds);

	int res = select(m_sock + 1, &read_fds, &write_fds, NULL, NULL);
	if (res > 0)
	{
		if (FD_ISSET(m_sock, &read_fds))
		{
			if (ReadableByteCount())
			{
				inAsyncNotificationLoop = true;
				OnRead();
			}
			else
			{
				inAsyncNotificationLoop = true;
				OnError(GetLastError());
				shouldAsyncQuit = true;
				return;
			}
		}

		if (FD_ISSET(m_sock, &write_fds))
		{
			inAsyncNotificationLoop = true;
			OnWrite();
		}
	}
	inAsyncNotificationLoop = true;
}
Beispiel #21
0
// Talk to the other computer, write the output buffer to the socket and read from the socket to the input buffer
// Return true if this worked, false if we've lost the connection
BOOL CConnection::DoRun()
{
	// If this socket is invalid, call OnRun and return the result (do)
	if ( ! IsValid() )
		return OnRun();

	// Setup pEvents to store the socket's internal information about network events
	WSANETWORKEVENTS pEvents = {};
	if ( WSAEnumNetworkEvents( m_hSocket, NULL, &pEvents ) != 0 )
		return FALSE;

	// If the FD_CONNECT network event has occurred
	if ( pEvents.lNetworkEvents & FD_CONNECT )
	{
		// If there is a nonzero error code for the connect operation, this connection was dropped
		if ( pEvents.iErrorCode[ FD_CONNECT_BIT ] != 0 )
		{
			Statistics.Current.Connections.Errors++;

			OnDropped();
			return FALSE;
		}

		// The socket is now connected
		m_bConnected = TRUE;
		m_tConnected = m_mInput.tLast = m_mOutput.tLast = GetTickCount();	// Store the time 3 places

		// Call CShakeNeighbour::OnConnected to start reading the handshake
		if ( ! OnConnected() )
			return FALSE;

		Network.AcquireLocalAddress( m_hSocket );
	}

	// If the FD_CLOSE network event has occurred, set bClosed to true, otherwise set it to false
	BOOL bClosed = ( pEvents.lNetworkEvents & FD_CLOSE ) ? TRUE : FALSE;

	// If the close event happened, null a pointer within the TCP bandwidth meter for input (do)
	if ( bClosed )
		m_mInput.pLimit = NULL;

	// Change the queued run state to 1 (do)
	m_nQueuedRun = 1;

	// Write the contents of the output buffer to the remote computer, and read in data it sent us
	if ( ! OnWrite() )
		return FALSE;
	if ( ! OnRead() )
		return FALSE;

	// If the close event happened
	if ( bClosed )
	{
		// theApp.Message( MSG_DEBUG, _T("socket close() error %i"), pEvents.iErrorCode[ FD_CLOSE_BIT ] );
		// Call OnDropped, telling it true if there is a close error
		OnDropped();	// True if there is an nonzero error code for the close bit
		return FALSE;
	}

	// Make sure the handshake doesn't take too long
	if ( ! OnRun() )
		return FALSE;

	// If the queued run state is 2 and OnWrite returns false, leave here with false also
	if ( m_nQueuedRun == 2 && ! OnWrite() )
		return FALSE;

	// Change the queued run state back to 0 and report success (do)
	m_nQueuedRun = 0;
	return TRUE;
}
Beispiel #22
0
			inline void HandleReadEvent()
			{
				OnRead();
			}
Beispiel #23
0
void HTTPSocket::OnRawData(const char *buf,size_t len)
{
	if (!m_header)
	{
		if (m_b_chunked)
		{
			size_t ptr = 0;
			while (ptr < len)
			{
				switch (m_chunk_state)
				{
				case 4:
					while (ptr < len && (m_chunk_line.size() < 2 || m_chunk_line.substr(m_chunk_line.size() - 2) != "\r\n"))
						m_chunk_line += buf[ptr++];
					if (m_chunk_line.size() > 1 && m_chunk_line.substr(m_chunk_line.size() - 2) == "\r\n")
					{
						OnDataComplete();
						// prepare for next request(or response)
						m_b_chunked = false;
						SetLineProtocol( true );
						m_first = true;
						m_header = true;
						m_body_size_left = 0;
						if (len - ptr > 0)
						{
							char tmp[TCP_BUFSIZE_READ];
							memcpy(tmp, buf + ptr, len - ptr);
							tmp[len - ptr] = 0;
							OnRead( tmp, len - ptr );
							ptr = len;
						}
					}
					break;
				case 0:
					while (ptr < len && (m_chunk_line.size() < 2 || m_chunk_line.substr(m_chunk_line.size() - 2) != "\r\n"))
						m_chunk_line += buf[ptr++];
					if (m_chunk_line.size() > 1 && m_chunk_line.substr(m_chunk_line.size() - 2) == "\r\n")
					{
						m_chunk_line.resize(m_chunk_line.size() - 2);
						Parse pa(m_chunk_line, ";");
						std::string size_str = pa.getword();
						m_chunk_size = Utility::hex2unsigned(size_str);
						if (!m_chunk_size)
						{
							m_chunk_state = 4;
							m_chunk_line = "";
						}
						else
						{
							m_chunk_state = 1;
							m_chunk_line = "";
						}
					}
					break;
				case 1:
					{
						size_t left = len - ptr;
						size_t sz = m_chunk_size < left ? m_chunk_size : left;
						OnData(buf + ptr, sz);
						m_chunk_size -= sz;
						ptr += sz;
						if (!m_chunk_size)
						{
							m_chunk_state = 2;
						}
					}
					break;
				case 2: // skip CR
					ptr++;
					m_chunk_state = 3;
					break;
				case 3: // skip LF
					ptr++;
					m_chunk_state = 0;
					break;
				}
			}
		}
		else
		if (!m_b_http_1_1 || !m_b_keepalive)
		{
			OnData(buf, len);
			/*
				request is HTTP/1.0 _or_ HTTP/1.1 and not keep-alive

				This means we destroy the connection after the response has been delivered,
				hence no need to reset all internal state variables for a new incoming
				request.
			*/
			m_body_size_left -= len;
			if (!m_body_size_left)
			{
				OnDataComplete();
			}
		}
		else
		{
			size_t sz = m_body_size_left < len ? m_body_size_left : len;
			OnData(buf, sz);
			m_body_size_left -= sz;
			if (!m_body_size_left)
			{
				OnDataComplete();
				// prepare for next request(or response)
				SetLineProtocol( true );
				m_first = true;
				m_header = true;
				m_body_size_left = 0;
				if (len - sz > 0)
				{
					char tmp[TCP_BUFSIZE_READ];
					memcpy(tmp, buf + sz, len - sz);
					tmp[len - sz] = 0;
					OnRead( tmp, len - sz );
				}
			}
		}
	}
}
Beispiel #24
0
void MessageConnection::OnResumeRead()
{
    Log_Trace();

    OnRead();
}
Beispiel #25
0
int CSocketClient::Run()
{
	try
	{		
		HANDLE handlesToWaitFor[2];
		
		handlesToWaitFor[0] = m_shutdownEvent.GetEvent();
		handlesToWaitFor[1] = m_successConnectionsEvent.GetEvent();
		
		while ( !m_shutdownEvent.Wait( 0 ) )
		{
			DWORD waitResult = ::WaitForMultipleObjects( 2, handlesToWaitFor, false, INFINITE );
			
			if ( waitResult == WAIT_OBJECT_0 )
			{
				/*
				 * Time to shutdown
				 */
				break;
			}
			else if ( waitResult == WAIT_OBJECT_0 + 1 )
			{
				/*
				 * Allocate a buffer for required read
				 */
				CIOBuffer *pReadContext = Allocate();

				while ( !m_shutdownEvent.Wait( 0 ) && m_successConnectionsEvent.Wait( 0 ) )
				{
					if ( m_eventSelect.WaitForEnumEvent( m_connectSocket, 1000 ) )
					{
						/*
						 * Find some events and process it
						 */
						
						/*
						 * A event to connect
						 */
						if ( m_eventSelect.IsConnect() )
						{
							OnConnect();						
						}

						/*
						 * A event to close
						 */
						if ( m_eventSelect.IsClose() )
						{
							OnClose();						
						}

						/*
						 * A event to read
						 */
						if ( m_eventSelect.IsRead() )
						{
							OnRead( pReadContext );
						}

						/*
						 * A event to write
						 */
						if ( m_eventSelect.IsWrite() )
						{
							OnWrite();
						}
					}
				} // while (...

				pReadContext->Release();
			}
			else
			{
				/*
				 * Call to unqualified virtual function
				 */
				OnError( _T("CSocketClient::Run() - WaitForMultipleObjects: ") + GetLastErrorMessage( ::GetLastError() ) );
			}
			
		} // while ( ... 		
	}
	catch( const CException &e )
	{
		/*
		 * Call to unqualified virtual function
		 */
		OnError( _T("CSocketClient::Run() - Exception: ") + e.GetWhere() + _T(" - ") + e.GetMessage() );
	}
	catch(...)
	{
		/*
		 * Call to unqualified virtual function
		 */
		OnError( _T("CSocketClient::Run() - Unexpected exception") );
	}
	
	/*
	 * Call to unqualified virtual function
	 */
	OnShutdownComplete();
	
	return 0;
}
Beispiel #26
0
void Port::Body()
{
	int tag = 0;
	char *buf = NULL;
	Fragments cmd;
	OutputTarget *target = NULL, *next = NULL;
	BlockReceiver receiver;
	NewFragmentHeader hdr;
	int ok;
	int assume_data;
	int call_on_read = 0;

	YARPUniqueNameID* pid = NULL;
	name_set = 1;

	/// LATER: must actually jump to the end of the thread for proper cleanup instead of returning.
	/// this is the registration section.
	switch (protocol_type)
	{
	case YARP_QNET:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_QNET, YARPNativeEndpointManager::CreateQnetChannel()); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (qnet)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_TCP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_TCP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (tcp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_UDP:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_UDP, YARP_UDP_REGPORTS); 
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (udp)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	case YARP_MCAST:
		{
			pid = YARPNameService::RegisterName(name.c_str(), network_name.c_str(), YARP_MCAST, YARP_UDP_REGPORTS);
			if (pid->getServiceType() == YARP_NO_SERVICE_AVAILABLE)
			{
				ACE_DEBUG ((LM_DEBUG, ">>> registration failed, bailing out port thread (mcast)\n"));
				name_set = 0;
				if (asleep)
				{
					asleep = 0;
					okay_to_send.Post();
				}

				_started = false;
				return;
			}
		}
		break;

	default:
		{
			ACE_DEBUG ((LM_DEBUG, "troubles in acquiring ports (?)\n"));
			name_set = 0;
			if (asleep)
			{
				asleep = 0;
				okay_to_send.Post();
			}
			return;
		}
		break;
	}

	YARPEndpointManager::CreateInputEndpoint (*pid);
	
	/// ok, ready to create the sending thread (_strange_select).
	/// all this to avoid sending a message through the port socket.
	tsender.Begin ();

	/// registration completed. now goes the receiver/command thread.
	if (asleep)
	{
		asleep = 0;
		okay_to_send.Post();
	}

	while (!IsTerminated())
    {
		receiver.Begin(pid->getNameID());

		receiver.Get();
		out_mutex.Wait();
		assume_data = !expect_header;
		out_mutex.Post();

		/// WARNING: cmd buffer is not zeroed anywhere, in case buffer is string
		///		it might be better to do it somewhere around here.

		if (!assume_data)
		{
			ok = receiver.Get((char*)(&hdr),sizeof(hdr));
			if (ok || hdr.checker=='/')
			{
				if (hdr.checker == '~')
				{
					tag = hdr.tag;
					cmd.Require(hdr.length);
					if (tag != MSG_ID_DATA)
					{
						ok = receiver.Get(cmd.GetBuffer(),hdr.length);
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "Got some form of command ( %d, %d )\n", ((int)tag), ok));
					}
				}
				else
				{
					if (hdr.checker != '/')
					{
						ACE_DEBUG ((LM_ERROR, "Error - command received in unknown protocol ( %s )\n", name.c_str()));
						ok = 0;
					}
					else
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "%s received unsupported old format request: %s\n", name.c_str()));
					}
				}
			}

			if (!ok)
			{
				tag = MSG_ID_ERROR;
			}

			if (tag == MSG_ID_NULL)
			{
				buf = cmd.GetBuffer();
				tag = buf[0];
			}
			else
			{
				buf = cmd.GetBuffer();
			}
		}
		else
		{
			YARP_DBG(THIS_DBG) ((LM_DEBUG, "Auto assume data\n"));
			tag = MSG_ID_DATA;
		}

		if (tag != MSG_ID_DATA)
		{
			receiver.End();
		}

		list_mutex.Wait ();
		int scanned = 0;
		if (!scanned)
		{
			double now = YARPTime::GetTimeAsSeconds();
			target = targets.GetRoot();
			while (target != NULL)
			{
				next = target->GetMeshNext();
				target->WaitMutex();
				int active = target->active;
				int deactivated = target->deactivated;
				int ticking = target->ticking;
				double started = target->check_tick;
				target->PostMutex();
				int timeout = 0;
				
				if (ticking && now-started > 5)
				{
					active = 0;
					timeout = 1;
				}

				if (!active)
				{
					ACE_DEBUG ((LM_INFO, "*** disconnecting %s and %s %s%s\n",
						name.c_str(), target->GetLabel().c_str(),
						deactivated ? "" : "(target stopped responding)",
						timeout?" (timeout)":""));
					/// remove the port no, from the list of used ports.

					delete target;
				}
				target = next;
			}
			scanned = 1;
		}
		list_mutex.Post ();

		if (pid->isValid())
		{
			switch(tag)
			{
			case MSG_ID_ATTACH:
				{
					list_mutex.Wait ();
					
					/// mcast is handled differently.
					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel (buf);
						if (target == NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** connecting %s to %s\n", name.c_str(), buf));

							target = targets.NewLink(buf);
							ACE_ASSERT(target != NULL);
							
							target->network_name = network_name;
							target->target_pid = NULL;
							target->protocol_type = protocol_type;
							target->allow_shmem = allow_shmem;
							target->SetRequireAck (GetRequireAck());
							target->SetOwnName (name);

							target->Begin();
						}
						else
						{
							ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
						}
					}
					else
					{
						/// it requires an extra call to the name server.
						YARPUniqueNameID *rem_pid = YARPNameService::LocateName (buf);

						YARPString ifname;
					
						bool same_net = YARPNameService::VerifySame (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), network_name.c_str(), ifname);

#ifndef DEBUG_DISABLE_SHMEM
						char myhostname[YARP_STRING_LEN];
						getHostname (myhostname, YARP_STRING_LEN);
						ACE_INET_Addr local ((u_short)0, myhostname);
						
						char iplocal[17];
						ACE_OS::memset (iplocal, 0, 17);
						ACE_OS::strcpy (iplocal, local.get_host_addr());

						bool same_machine = YARPNameService::VerifyLocal (((YARPUniqueNameSock *)rem_pid)->getAddressRef().get_host_addr(), iplocal, network_name.c_str());

						if (same_net || same_machine)
						{
#else
						if (same_net)
						{
#endif

							
#ifndef DEBUG_DISABLE_SHMEM
							if (same_machine && allow_shmem)
							{
								/// go into TCP-SHMEM.
								target = targets.GetByLabel (buf);
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting SHMEM between %s and %s\n", name.c_str(), buf));

									target = targets.NewLink(buf);
									ACE_ASSERT(target != NULL);
		
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = YARP_UDP;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();
								}
								else
								{
									ACE_DEBUG ((LM_DEBUG, "Ignoring %s, already connected\n", buf));
								}
							}
							else
#endif
							{
								/// mcast out port thread.
								target = targets.GetByLabel ("mcast-thread");
								if (target == NULL)
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target = targets.NewLink("mcast-thread");

									ACE_ASSERT(target != NULL);
									target->network_name = network_name;
									target->target_pid = NULL;
									target->protocol_type = protocol_type;
									target->allow_shmem = allow_shmem;
									target->SetOwnName (name);

									target->Begin();

									target->ConnectMcast (buf);
								}
								else
								{
									ACE_DEBUG ((LM_INFO, "*** connecting MCAST %s to %s\n", name.c_str(), buf));
									target->ConnectMcast (buf);
								}
							}

						}	/// end if (same_net)
					}	/// if !MCAST 

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DETACH:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach request for %s\n", buf+1));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
					}
					else
					{
#ifndef DEBUG_DISABLE_SHMEM
						target = targets.GetByLabel(buf+1);
						if (target != NULL)
						{
							ACE_DEBUG ((LM_DEBUG, "Removing (SHMEM) connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
						}
						else
#endif
						{
							/// mcast
							target = targets.GetByLabel("mcast-thread");
							if (target != NULL)
							{
								ACE_DEBUG ((LM_DEBUG, "Removing connection between %s and (%s) via %s\n", name.c_str(), buf+1, target->GetLabel().c_str()));
								
								target->DeactivateMcast(buf+1);
							}
						}
					}

					/// scan the list of outputs to delete disconnected ones!

					///
					/// don't I need a wait for completion of the Deactivate procedure here?

					double now = YARPTime::GetTimeAsSeconds();
					target = targets.GetRoot();
					while (target != NULL)
					{
						next = target->GetMeshNext();
						target->WaitMutex();
						int active = target->active;
						int deactivated = target->deactivated;
						int ticking = target->ticking;
						double started = target->check_tick;
						target->PostMutex();
						int timeout = 0;
						
						if (ticking && now-started > 5)
						{
							active = 0;
							timeout = 1;
						}

						if (!active)
						{
							ACE_DEBUG ((LM_INFO, "disconnecting %s and %s %s%s\n",
								name.c_str(), target->GetLabel().c_str(),
								deactivated ? "" : "(target stopped responding)",
								timeout?" (timeout)":""));

							delete target;
						}
						target = next;
					}

					list_mutex.Post ();
				}
				break;

			case MSG_ID_DATA:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Gosh, someone sent me data! Me being %s in case you're curious\n", name.c_str()));

					out_mutex.Wait();
					receiving = 1;
					
					if (!ignore_data) 
					{
						while (p_receiver_incoming.Ptr() == NULL)
					    {
							YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Waiting for incoming space\n"));
							// HIT - should have way to convey back skip
							// request to sender
							// (can't just ignore, don't know how many)
							// (components message has)

							asleep = 1;
							out_mutex.Post();
							wakeup.Wait();
							out_mutex.Wait();
					    }

						asleep = 0;
						p_receiver_incoming.Ptr()->AddRef();
						out_mutex.Post();

						p_receiver_incoming.Ptr()->Read(receiver);
						p_receiver_incoming.Ptr()->RemoveRef();
					}
					else
					{
						out_mutex.Post();
					}

					receiver.End();

					out_mutex.Wait();
					receiving = 0;
					
					if (!ignore_data) 
					{
						YARP_DBG(THIS_DBG) ((LM_DEBUG, "&&& Received. Switching with latest space\n"));
						p_receiver_latest.Switch(p_receiver_incoming);

						if (!has_input)
						{
							has_input = 1;
							something_to_read.Post();
						}
					}

					out_mutex.Post();

					if (!ignore_data) 
					{
						call_on_read = 1;
					}
				}
				break;

			case MSG_ID_GO:
				{
					ACE_DEBUG ((LM_ERROR, "this shouldn't happen, the new version doesn't accept MSG_ID_GO\n"));
				}
				break;

			case MSG_ID_DETACH_ALL:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Received detach_all request (%s)\n", name.c_str()));

					list_mutex.Wait ();

					if (protocol_type != YARP_MCAST)
					{
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							target->Deactivate();
							target = next;
						}
					}
					else
					{
						OutputTarget *mtarget = targets.GetByLabel("mcast-thread");
#ifndef DEBUG_DISABLE_SHMEM
						/// takes care of the SHMEM connection
						target = targets.GetRoot();

						while (target != NULL)
						{
							next = target->GetMeshNext();
							ACE_DEBUG ((LM_INFO, "*** removing connection between %s and %s\n", name.c_str(), target->GetLabel().c_str()));
							if (target != mtarget && mtarget != NULL)
								target->Deactivate();
							target = next;
						}
#endif

						/// mcast
						if (mtarget != NULL)
						{
							ACE_DEBUG ((LM_INFO, "*** removing all MCAST connections\n"));
							mtarget->DeactivateMcastAll();
						}
					}

					list_mutex.Post ();

					/// signal the SelfEnd that the msg has been received.

					complete_msg_thread.Signal ();

					/// wait for closure of SelfEnd socket and relative thread.
					complete_terminate.Wait();

					/// only now asks for End.
					AskForEnd ();
				}
				break;

			case MSG_ID_DETACH_IN:
				{
					ACE_DEBUG ((LM_DEBUG, "*** received detach request for %s\n", buf+1));

					YARPUniqueNameID needclose;
					needclose = *pid;
					needclose.setName (buf+1);
					YARPEndpointManager::Close (needclose);
				}
				break;

			case MSG_ID_DUMP_CONNECTIONS:
				{
					ACE_DEBUG ((LM_INFO, "*** dumping connections for %s\n", name.c_str()));
					ACE_DEBUG ((LM_INFO, "*** output connections:\n"));

					list_mutex.Wait ();
					target = targets.GetRoot();
					int i = 0;
					while (target != NULL)
					{
						target->WaitMutex();
						ACE_DEBUG ((LM_INFO, "***   %d: %s %s:%d\n", 
							i, 
							target->GetLabel().c_str(),
							target->GetOwnAddress().get_host_addr(),
							target->GetOwnAddress().get_port_number()));
						target->PostMutex();
						next = target->GetMeshNext();
						target = next;
						i++;
					}

					list_mutex.Post ();

					ACE_DEBUG ((LM_INFO, "*** input connections:\n"));
					YARPEndpointManager::PrintConnections (*pid);
				}	
				break;

			case MSG_ID_ERROR:
				YARP_DBG(THIS_DBG) ((LM_DEBUG, "Error message received by %s!\n", name.c_str()));
				break;

			default:
				{
					YARP_DBG(THIS_DBG) ((LM_DEBUG, "Unknown message received by %s (tag is %d-->'%c', str is %s)!\n", name.c_str(), tag, tag, buf));
				}
				break;
			}
		}	/// end switch/case
      
		if (call_on_read)
		{
			OnRead();
			call_on_read = 0;
		}
	} /// if !terminated

	/// since this is started in this thread close it here.
	tsender.AskForEnd();
	tsender.pulseGo();
	tsender.Join();

	///
	/// tries to shut down the input socket threads.
	/// uses the special request for closing all input threads at once.
	///
	///
	YARPUniqueNameID needcloseall;
	needcloseall = *pid;
	needcloseall.setName ("__All__");
	YARPEndpointManager::Close (needcloseall);

	/// unregister the port name here.
	YARPNameService::UnregisterName (pid);

	/// free memory.
	YARPNameService::DeleteName (pid);
	pid = NULL;

	/// wakes up a potential thread waiting on a blocking Read().
	has_input = 1;
	something_to_read.Post();

	ACE_DEBUG ((LM_DEBUG, "***** main port thread 0x%x returning\n", GetIdentifier()));
}


///
/// this is called from YARPPort::Write to actually send something.
/// Currently it wakes the Port thread up through a socket connection that
///	Paul believes to be responsible for poor performance on Linux/NT.
///
void Port::Share(Sendable *nsendable)
{
	okay_to_send.Wait();
	out_mutex.Wait();
	p_sendable.Set(nsendable);
	out_mutex.Post();

	/// this simply pulses the mutex on the sender thread.
	/// cost an additional thread but hopefully saves a costly message
	/// through the port socket.
	tsender.pulseGo ();
}
Beispiel #27
0
void Socket::ReadCallback(uint32 len)
{
	readBuffer.IncrementWritten(len);
	OnRead();
	SetupReadEvent();
}
CHandshake::CHandshake(QObject* parent)
	: CNetworkConnection(parent)
{
	connect(this, SIGNAL(readyRead()), this, SLOT(OnRead()), Qt::QueuedConnection);
	connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(deleteLater()));
}
Beispiel #29
0
HRESULT WpdObjectResources::DispatchWpdMessage(
    const PROPERTYKEY&     Command,
    IPortableDeviceValues* pParams,
    IPortableDeviceValues* pResults)
{

    HRESULT hr = S_OK;

    if (hr == S_OK)
    {
        if (Command.fmtid != WPD_CATEGORY_OBJECT_RESOURCES)
        {
            hr = E_INVALIDARG;
            CHECK_HR(hr, "This object does not support this command category %ws",CComBSTR(Command.fmtid));
        }
    }

    if (hr == S_OK)
    {
        if (IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_GET_SUPPORTED))
        {
            hr = OnGetSupportedResources(pParams, pResults);
            CHECK_HR(hr, "Failed to get supported resources");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_GET_ATTRIBUTES))
        {
            hr = OnGetAttributes(pParams, pResults);
            if(FAILED(hr))
            {
                CHECK_HR(hr, "Failed to get resource attributes");
            }
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_OPEN))
        {
            hr = OnOpen(pParams, pResults);
            CHECK_HR(hr, "Failed to open resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_READ))
        {
            hr = OnRead(pParams, pResults);
            CHECK_HR(hr, "Failed to read resource data");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_WRITE))
        {
            hr = OnWrite(pParams, pResults);
            CHECK_HR(hr, "Failed to write resource data");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_CLOSE))
        {
            hr = OnClose(pParams, pResults);
            CHECK_HR(hr, "Failed to close resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_DELETE))
        {
            hr = OnDelete(pParams, pResults);
            CHECK_HR(hr, "Failed to delete resources");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_CREATE_RESOURCE))
        {
            hr = OnCreate(pParams, pResults);
            CHECK_HR(hr, "Failed to create resource");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_REVERT))
        {
            hr = OnRevert(pParams, pResults);
            CHECK_HR(hr, "Failed to revert resource operation");
        }
        else if(IsEqualPropertyKey(Command, WPD_COMMAND_OBJECT_RESOURCES_SEEK))
        {
            hr = OnSeek(pParams, pResults);
            CHECK_HR(hr, "Failed resource seek operation");
        }
        else
        {
            hr = E_NOTIMPL;
            CHECK_HR(hr, "This object does not support this command id %d", Command.pid);
        }
    }
    return hr;
}
Beispiel #30
0
CRemote::CRemote(CConnection* pConnection)
{
	CTransfer::AttachTo( pConnection );
	m_mInput.pLimit = m_mOutput.pLimit = NULL;
	OnRead();
}