int DoRead(issl_session* session)
	{
		// Is this right? Not sure if the unencrypted data is garaunteed to be the same length.
		// Read into the inbuffer, offset from the beginning by the amount of data we have that insp hasn't taken yet.
		ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: SSL_read(sess, inbuf+%d, %d-%d)", session->inbufoffset, inbufsize, session->inbufoffset);
			
		int ret = SSL_read(session->sess, session->inbuf + session->inbufoffset, inbufsize - session->inbufoffset);

		if(ret == 0)
		{
			// Client closed connection.
			ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Client closed the connection");
			CloseSession(session);
			return 0;
		}
		else if(ret < 0)
		{
			int err = SSL_get_error(session->sess, ret);
				
			if(err == SSL_ERROR_WANT_READ)
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read, need to retry: %s", get_error());
				session->rstat = ISSL_READ;
				return -1;
			}
			else if(err == SSL_ERROR_WANT_WRITE)
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Not all SSL data read but the damn thing wants to write instead: %s", get_error());
				session->rstat = ISSL_WRITE;
				return -1;
			}
			else
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Error reading SSL data: %s", get_error());
				CloseSession(session);
				return 0;
			}
		}
		else
		{
			// Read successfully 'ret' bytes into inbuf + inbufoffset
			// There are 'ret' + 'inbufoffset' bytes of data in 'inbuf'
			// 'buffer' is 'count' long
			
			ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoRead: Read %d bytes, now have %d waiting to be passed up", ret, ret + session->inbufoffset);

			session->inbufoffset += ret;

			return ret;
		}
	}
	bool Handshake(StreamSocket* user)
	{
		int ret;

		if (outbound)
			ret = SSL_connect(sess);
		else
			ret = SSL_accept(sess);

		if (ret < 0)
		{
			int err = SSL_get_error(sess, ret);

			if (err == SSL_ERROR_WANT_READ)
			{
				SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
				this->status = ISSL_HANDSHAKING;
				return true;
			}
			else if (err == SSL_ERROR_WANT_WRITE)
			{
				SocketEngine::ChangeEventMask(user, FD_WANT_NO_READ | FD_WANT_SINGLE_WRITE);
				this->status = ISSL_HANDSHAKING;
				return true;
			}
			else
			{
				CloseSession();
			}

			return false;
		}
		else if (ret > 0)
		{
			// Handshake complete.
			VerifyCertificate();

			status = ISSL_OPEN;

			SocketEngine::ChangeEventMask(user, FD_WANT_POLL_READ | FD_WANT_NO_WRITE | FD_ADD_TRIAL_WRITE);

			return true;
		}
		else if (ret == 0)
		{
			CloseSession();
			return true;
		}

		return true;
	}
	void TcpNetwork::RunCheckSelectClients(fd_set& exc_set, fd_set& read_set, fd_set& write_set)
	{
		for (int i = 0; i < m_ClientSessionPool.size(); ++i)
		{
			auto& session = m_ClientSessionPool[i];

			if (session.IsConnected() == false) {
				continue;
			}

			SOCKET fd = session.SocketFD;
			auto sessionIndex = session.Index;

			// check error
			if (FD_ISSET(fd, &exc_set))
			{
				CloseSession(SOCKET_CLOSE_CASE::SELECT_ERROR, fd, sessionIndex);
				continue;
			}

			// check read
			auto retReceive = RunProcessReceive(sessionIndex, fd, read_set);
			if (retReceive == false) {
				continue;
			}

			// check write
			RunProcessWrite(sessionIndex, fd, write_set);
		}
	}
Exemple #4
0
NET_ERROR_CODE TcpNetwork::NewSession()
{
	SOCKADDR_IN client_addr;
	int client_len = static_cast<int>(sizeof(client_addr));
	auto client_sockfd = accept(m_ServerSockfd, (SOCKADDR*)&client_addr, &client_len);

	if (client_sockfd < 0)
	{
		m_pRefLogger->Write(LOG_TYPE::L_ERROR, "%s | Wrong socket %d cannot accept", __FUNCTION__, client_sockfd);
		return NET_ERROR_CODE::ACCEPT_API_ERROR;
	}

	auto newSessionIndex = AllocClientSessionIndex(); //index pool 이용해서 여유가 있는지 체크.
	if (newSessionIndex < 0)
	{
		m_pRefLogger->Write(LOG_TYPE::L_WARN, "%s | client_sockfd(%d) >= MAX_SESSION", __FUNCTION__, client_sockfd);
		//pool에서 얻어 올 수 없었으므로 바로 짜름. 
		CloseSession(ServerConfig::SOCKET_CLOSE_CASE::SESSION_POOL_EMPTY, client_sockfd, -1);
		return NET_ERROR_CODE::ACCEPT_MAX_SESSION_COUNT;
	}

	char clientIP[ServerConfig::MAX_IP_LEN] = { 0, };
	inet_ntop(AF_INET, &(client_addr.sin_addr), clientIP, ServerConfig::MAX_IP_LEN - 1);

	SetSockOption(client_sockfd);
	FD_SET(client_sockfd, &m_Readfds);

	ConnectedSession(newSessionIndex, (int)client_sockfd, clientIP);//여기까지... 아직 미완성

	return NET_ERROR_CODE::NONE;
}
	int HandleWriteRet(StreamSocket* sock, int ret)
	{
		if (ret > 0)
		{
#ifdef INSPIRCD_GNUTLS_HAS_CORK
			gbuffersize -= ret;
			if (gbuffersize)
			{
				SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
				return 0;
			}
#endif
			return ret;
		}
		else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED || ret == 0)
		{
			SocketEngine::ChangeEventMask(sock, FD_WANT_SINGLE_WRITE);
			return 0;
		}
		else // (ret < 0)
		{
			sock->SetError(gnutls_strerror(ret));
			CloseSession();
			return -1;
		}
	}
Exemple #6
0
CWinHTTPUtil::~CWinHTTPUtil(void)
{
    CloseSession();
    ClearUpList();
    for( size_t i=0; i<this->dlBuffList.size(); i++ ) {
        SAFE_DELETE(this->dlBuffList[i]);
    }
    this->dlBuffList.clear();


    if( this->upStopEvent != NULL ) {
        CloseHandle(this->upStopEvent);
        this->upStopEvent = NULL;
    }
    if( this->writeCompEvent != NULL ) {
        CloseHandle(this->writeCompEvent);
        this->writeCompEvent = NULL;
    }
    if( this->responseCompEvent != NULL ) {
        CloseHandle(this->responseCompEvent);
        this->responseCompEvent = NULL;
    }

    CoUninitialize();
}
Exemple #7
0
void TcpNetwork::RunCheckSelectClients(fd_set & exc_set, fd_set & read_set, fd_set & write_set)
{
	for (int i = 0; i < m_ClientSessionPool.size(); i++)
	{
		auto& session = m_ClientSessionPool[i];

		if (session.IsConnected() == false)
			continue;

		auto fd = session.SocketFD;
		auto sessionIndex = session.Index;

		//error check
		if (FD_ISSET(fd, &exc_set))
		{
			CloseSession(ServerConfig::SOCKET_CLOSE_CASE::SELECT_ERROR, fd, sessionIndex);
			continue;
		}

		//read check
		auto retRecieve = RunProcessReceive(sessionIndex, fd, read_set);
		if (retRecieve == false) //새로 받은 데이터가 없다면 write 과정에 들어가지 않음. 
			continue;

		//write check
		if (!FD_ISSET(fd, &write_set))
			continue;
		RunProcessWrite(sessionIndex, fd, write_set);
	}
}
Exemple #8
0
bool QPlc::OpenConnection(void)
{
    bool result=true;
    char ip[16];
    Plc_Type vPlcType;
    vPlcType=(Plc_Type) m_PlcType;
    strcpy(ip,m_ip.toStdString().c_str());
    m_Session=OpenSession(ip);
    if (m_Session!=NULL)
    {
        if (RegisterSession(m_Session)<0)
        {
            CloseSession(m_Session);
            return false;
        }
    } else
    {
        return false;
    }
    m_Connection=ConnectPLCOverCNET(m_Session,vPlcType,(long)m_Session,GetSerial(),m_time_out,m_PlcPath,m_path_size);//(int)m_Session
    if (m_Connection==NULL)
    {
        return false;
    }
    qDebug("Connection OK");
    return result;
}
	TCPServerLib::NET_ERROR_CODE TCPNetwork::NewSession()
	{
		SOCKADDR_IN clientAddr;
		int addrLen = sizeof(SOCKADDR_IN);
		SOCKET clientSockFd;

		clientSockFd = accept(m_serverSocket, (SOCKADDR*)&clientAddr, &addrLen);
		if (clientSockFd < 0)
		{
			return NET_ERROR_CODE::ACCEPT_API_ERROR;
		}

		int newSessionIdx = GetClientSessionIndex();
		if (newSessionIdx < 0)
		{
			CloseSession(SOCKET_CLOSE_CASE::SESSION_POOL_EMPTY, clientSockFd, -1);
			return NET_ERROR_CODE::ACCEPT_MAX_SESSION_COUNT;
		}

		SetSockOption(clientSockFd);

		FD_SET(clientSockFd, &m_readSet);

		ConnectedSession(newSessionIdx, clientSockFd);

		return NET_ERROR_CODE::NONE;
	}
	void TCPNetwork::RunCheckSelectClient(fd_set& read_set, fd_set& write_set, fd_set& exc_set)
	{
		int size = m_clientSessionPool.size();

		for (int i = 0; i < size; i++)
		{
			auto& cs = m_clientSessionPool[i];

			if (cs.IsConnected() == false)
			{
				continue;
			}

			SOCKET sock = cs.SocketFD;
			int sIdx = cs.Index;

			if (FD_ISSET(sock, &exc_set) == true)
			{
				CloseSession(SOCKET_CLOSE_CASE::SELECT_ERROR, sock, sIdx);
				continue;
			}

			auto ret = RunProcessReceive(sIdx, sock, read_set);
			if (ret == false)
			{
				continue;
			}

			ret = RunProcessWrite(sIdx, sock, write_set);
		} //end for loop
	}
Exemple #11
0
void KillConnections(void)
{
	Log(LOG_NOTICE,"There is %d Sessions and %d Connections\n",SESSIONs.Count,CONNECTIONs.Count);
	ELEMENT *elt;
	while ((elt=GetFirst(&CONNECTIONs))!=NULL)
	{
		Eip_Connection *connexion=elt->Data;
		RemoveChListe_Ex(&CONNECTIONs,elt);
		free(elt);
		if (connexion==NULL) continue;
		if (Forward_Close(connexion)>=0) 
			Log(LOG_NOTICE,"Connection (%p) Killed\n",connexion);
			else Log(LOG_WARNING,"Unable to kill Connection (%p)\n",connexion);
	}
	memset(&CONNECTIONs,0,sizeof(CONNECTIONs));
	
	while ((elt=GetFirst(&SESSIONs))!=NULL)
	{
		Eip_Session *session=elt->Data;
		RemoveChListe_Ex(&SESSIONs,elt);
		free(elt);
		if (UnRegisterSession(session)>=0) 
			Log(LOG_NOTICE,"Session (%p) Killed\n",session);
			else Log(LOG_WARNING,"Unable to kill session (%p)\n",session);
		CloseSession(session);
	}
	memset(&SESSIONs,0,sizeof(SESSIONs));
}
void CSessionThread::SenderRun(void)
{
	if (m_stop||!m_open) { CloseSession(); return; }

	++m_sender_thread_instances;

	CSingleLock
		GateKeeper(&m_SenderGateKeeper, TRUE),
		ToDo(&m_SendQueueAccess, TRUE);

	//AddEvent(EVENT_SENT, 0, _T("Fila de saida ativada"));

	while (!m_SendQueue.IsEmpty())
	{
		struct packet_s out_pkt;

		out_pkt = m_SendQueue.RemoveHead();
		ToDo.Unlock();
		//AddEvent(EVENT_SENT, 0, _T("[0x%x] Enviado"), ntohl(out_pkt.header.type));
		Send(out_pkt);
		ToDo.Lock();
	}

	--m_sender_thread_instances;
}
void CRTSecMgrSession::DispatchMessageL(const RMessage2& aMessage)
	{
	// First check for session-relative requests
	switch (aMessage.Function ())
		{
		case ESetPolicy:
			SetPolicy (aMessage);
			return;
		case EUpdatePolicy:
			UpdatePolicy (aMessage);
			return;
		case EUnsetPolicy:
			UnsetPolicy (aMessage);
			return;
		case ERegisterScript:
			RegisterScript (aMessage);
			return;
		case ERegisterScriptWithHash:
			RegisterScript (aMessage, ETrue);
			return;
		case EUnRegisterScript:
			UnregisterScript (aMessage);
			return;
		case EGetScriptSession:
			GetScriptSessionL (aMessage);
			return;
		case EGetTrustedUnRegScriptSession:
			GetTrustedUnRegScriptSessionL (aMessage);
			return;
		case ESecServCloseSession:
			CloseSession ();
			return;
			}

	// All other function codes must be subsession relative.
	// We need to find the appropriate server side subsession
	// i.e. the CRTSecMgrSubSession object. 
	// The handle value is passed as the 4th aregument.
	CRTSecMgrSubSession* subSession = SubSessionFromHandle (aMessage,
			aMessage.Int3 ());
	switch (aMessage.Function ())
		{
		case ECloseScriptSession:
			DeleteSubSession (aMessage.Int3 ());
			return;
		case EUpdatePermanentGrant:
			subSession->UpdatePermGrantL (aMessage);
			return;
		case EGetScriptFile:
			subSession->GetScriptFile (aMessage);
			return;
		case EUpdatePermanentGrantProvider:
		    subSession->UpdatePermGrantProviderL (aMessage);
		    return;
		default:
			PanicClient (aMessage, EBadRequest);
			return;
		}
	}
	void TcpNetwork::ForcingClose(const int sessionIndex)
	{
		if (m_ClientSessionPool[sessionIndex].IsConnected() == false) {
			return;
		}

		CloseSession(SOCKET_CLOSE_CASE::FORCING_CLOSE, m_ClientSessionPool[sessionIndex].SocketFD, sessionIndex);
	}
void CloseAllSessions()
{
	int i;
	
	for (i=0;i<num_sessions;i++)
		if (sessions[i].connected)
			CloseSession(i);
}
Exemple #16
0
CQuickSyncDecoder::~CQuickSyncDecoder()
{
    CloseSession();

    FreeFrameAllocator();
    delete m_pFrameAllocator;
    CloseD3D();
}
Exemple #17
0
int Connect(PLC *Plc,char *TagName, char *responseValue)
{
	int result=SUCCESS;
	int path_size=0;
	char ip[16];
	BYTE path[40];
	Eip_Session *Session=NULL;
	Eip_Connection *Connection=NULL;
	int dataType;
	
	Log(LOG_DEBUG,"[Connect] Building Session for %s\n",Plc->PlcName);
	path_size=ParsePath(Plc->PlcPath,ip,path);
	if (path_size>0)
	{
		Session=OpenSession(ip);
		if (Session!=NULL)
		{
			if (RegisterSession(Session)<0)
			{
				CloseSession(Session);
				Log(LOG_CRIT,"[Connect] Unable to register session for Plc: %s (%s) \n",Plc->PlcName,cip_err_msg);
				return ERROR;
			}
		} else
		{
			Log(LOG_CRIT,"[Connect] Unable to open session for Plc: %s (%s)\n",Plc->PlcName,cip_err_msg);
			return ERROR;
		}
		if (Plc->NetWork)
			Connection=ConnectPLCOverDHP(Session,Plc->PlcType,(int)Session,GetSerial(),MAX_SAMPLE,Plc->NetWork,path,path_size);
		else
			Connection=ConnectPLCOverCNET(Session,Plc->PlcType,(int)Session,GetSerial(),MAX_SAMPLE,path,path_size);
		if (Connection!=NULL)
		{
			Log(LOG_DEBUG,"[Connect] Connection (%p) created for PLC : %s (%s) )\n",Connection,Plc->PlcName,cip_err_msg);
		} else 
		{
			Log(LOG_CRIT,"[Connect] Unable to create connection for Plc: %s (%s)\n",Plc->PlcName,cip_err_msg);
			return ERROR;
		}
	} else Log(LOG_ERR,"[Connect] Invalid path : %s\n",Plc->PlcPath);

	Log(LOG_DEBUG,"[Connect] Connect : %s [%s](%p / %p)\n",TagName,writeValue,Session,Connection);
	if (ReadTag(Plc, Session, Connection, TagName, &dataType, responseValue)!=SUCCESS)
		return ERROR;
	else
	{
		if (isWrite)
		{
			if (WriteTag(Plc, Session, Connection, TagName,dataType)!=SUCCESS)
				return ERROR; 
			Log(LOG_DEBUG,"[Connect] %s [%s] %x (%p / %p)\n",TagName,writeValue,dataType,Session,Connection);
			if (ReadTag(Plc, Session, Connection, TagName, &dataType, responseValue)!=SUCCESS)
				return ERROR;
		}
	}
	return result;
}
/*!
 * \todo Use current_exception to log exceptions.
 */
RemoteSessionHandle::~RemoteSessionHandle()
{
    try
    {
        CloseSession();
    }
    catch (...)
    { }
}
Exemple #19
0
bool ChatLog::SetLogFile(const wxString& logname)
{
	if (logname == wxEmptyString) {
		m_logname = logname;
		CloseSession();
		return true;
	}

	m_logname.Replace(wxT(":"), wxT("_"));
	if (logname != m_logname) {
		if (m_logfile.IsOpened()) {
			CloseSession();
		}
		m_logname = logname;
		OpenLogFile();
	}
	return m_active;
}
Exemple #20
0
UA_StatusCode UA_Client_disconnect(UA_Client *client) {
    UA_StatusCode retval = UA_STATUSCODE_GOOD;
    if(client->channel.connection->state == UA_CONNECTION_ESTABLISHED){
        retval = CloseSession(client);
        if(retval == UA_STATUSCODE_GOOD)
            retval = CloseSecureChannel(client);
    }
    return retval;
}
Exemple #21
0
PKCS_11_Token::~PKCS_11_Token()
{
	OP_ASSERT(Get_Reference_Count() == 0);

	CloseSession();

	if(InList())
		Out();
}
Exemple #22
0
void InnerNet::ReadData(SESSION* pSession)
{
	int nRet = IORead(pSession->nSock, pSession, pSession->oRecvBuf, this, INNERNET_MAX_RW_PEREVENT);
	if (nRet == -1)
	{
		CloseSession(pSession->nSessionID);
		return;
	}
}
void CSessionThread::ForceClose()
{
	m_stop = TRUE;

	SendABORT();

	EmptyAllLists();

	CloseSession();
}
Exemple #24
0
int KillSession(Eip_Session *session)
{ int res=0;
	if (session==NULL) return(0);
	RemoveChListe(&SESSIONs,session);
	if ((res=_UnRegisterSession(session))>=0) 
		Log(LOG_DEBUG,"Session (%p) Killed\n",session);
		else Log(LOG_WARNING,"Unable to kill session (%p)\n",session);
	CloseSession(session);
	Log(LOG_DEBUG,"There is %d Session\n",SESSIONs.Count);
	return(res);
}
// Hangs up a session straight away, instead of posting to main loop.
void HangupSessionNow(session_node *s)
{
   if (!s->connected)
      return;

   if (s->conn.type != CONN_SOCKET)
      return;

   CloseSession(s->session_id);
   HangupSession(s);
}
Exemple #26
0
 BaseSession::~BaseSession(){
   // TODO, this delete command is not comfortable, remove this
   LOG(WARNING) << "Delete base session ... ...";
   if (packet_transmitter_){
     delete packet_transmitter_;
     packet_transmitter_ = NULL;
   }
   if (state_ == STATE_ENABLE){
     CloseSession();
   }
   //std::cout << "delete this session ... ..." << std::endl;
 };
void
CDMProxy::RemoveSession(const nsAString& aSessionId,
                        PromiseId aPromiseId)
{
  MOZ_ASSERT(NS_IsMainThread());

  // TODO: Dispatch task to GMPThread to call CDM RemoveSession via IPC.

  // Assume CDM immediately removes session's data, then close the session
  // as per the spec.
  CloseSession(aSessionId, aPromiseId);
}
Exemple #28
0
	int DoWrite(issl_session* session)
	{
		int ret = SSL_write(session->sess, session->outbuf.data(), session->outbuf.size());
		
		if(ret == 0)
		{
			ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Client closed the connection");
			CloseSession(session);
			return 0;
		}
		else if(ret < 0)
		{
			int err = SSL_get_error(session->sess, ret);
			
			if(err == SSL_ERROR_WANT_WRITE)
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written, need to retry: %s", get_error());
				session->wstat = ISSL_WRITE;
				return -1;
			}
			else if(err == SSL_ERROR_WANT_READ)
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Not all SSL data written but the damn thing wants to read instead: %s", get_error());
				session->wstat = ISSL_READ;
				return -1;
			}
			else
			{
				ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Error writing SSL data: %s", get_error());
				CloseSession(session);
				return 0;
			}
		}
		else
		{
			ServerInstance->Log(DEBUG, "m_ssl_openssl.so: DoWrite: Successfully wrote %d bytes", ret);
			session->outbuf = session->outbuf.substr(ret);
			return ret;
		}
	}
Exemple #29
0
BOOL CCoolInet2::WorkSession()
{
	try
	{
		CreateSession();
		InitEventContainer();

		HANDLE MasEvent[2]={MarshalEvent,hExitEvent};

		SetEvent(hStartEvent);

		while(TRUE)
		{
            MSG msg ;			

			while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				DispatchMessage(&msg);
			}

			DWORD dwResult = MsgWaitForMultipleObjects(2,MasEvent,FALSE,INFINITE,QS_ALLINPUT);
			
			if((dwResult - WAIT_OBJECT_0 ) ==0)
			{
				HRESULT hr = CoMarshalInterThreadInterfaceInStream(__uuidof(ISession),p_InetSession,ppSession);
				
				if(FAILED(hr))
					ppSession = NULL;

				ResetEvent(MarshalEvent);
				SetEvent(hMarshalingEndEvent);
			}
			if((dwResult - WAIT_OBJECT_0 )==1) 
			{
				//ASSERT(FALSE);
				break;
			}
            /// Обработка Сообщений Windows...    
		}
		CloseEventContainer();
		CloseSession();
	}
	catch(...)
	{
		ASSERT(FALSE);
		return FALSE;
	}

	SetEvent(hExitWork);

	return TRUE;
}
	void TcpNetwork::RunProcessWrite(const int sessionIndex, const SOCKET fd, fd_set& write_set)
	{
		if (!FD_ISSET(fd, &write_set))
		{
			return;
		}

		auto retsend = FlushSendBuff(sessionIndex);
		if (retsend.Error != NETWORK_ERROR_CODE::NONE)
		{
			CloseSession(SOCKET_CLOSE_CASE::SOCKET_SEND_ERROR, fd, sessionIndex);
		}
	}