Пример #1
0
int StructuredLearnerRpc::FindOrCreateSession(const Json::Value& root, Json::Value& response) {
  int sess_ind = -1;
  char sess_id[1000];
  char errStr[1000];
  if(strlen(root.get("session_id", "").asString().c_str()) < 1000)
    strcpy(sess_id, root.get("session_id", "").asString().c_str());
  else
    strcpy(sess_id, "");
  
  if(!strlen(sess_id)) {
    if(!NewSession(root, response) || !InitializeSession(root, response)) {
      JSON_ERROR("Failed to create new session in classify_example\n", -1);
    }
    sess_ind = num_sessions-1;//FindSession(response.get("session_id", "").asString().c_str());
    assert(sess_ind >= 0);
    //fprintf(stderr, "New Session %d\n", sess_ind);
  } else {
    sess_ind=FindSession(sess_id, true);
    if(sess_ind < 0) {
      sprintf(errStr, "Invalid session_id %s in classify_example()\n", sess_id);  JSON_ERROR(errStr, sess_ind); 
    }
    //fprintf(stderr, "Found Session %d %s\n", sess_ind, sess_id);
  }
  response["session_id"] = sessions[sess_ind].id;
  return sess_ind;
}
Пример #2
0
// Start a new session for this requester. Return nullptr if on more sessions available.
Webserver::HttpSession *Webserver::StartSession(uint32_t ip)
{
	HttpSession *s = FindSession(ip);
	if (s != nullptr)
	{
		// Abandon the existing session for this requester and start a new one
		s->nextFragment = 0;
		s->fileBeingUploaded.Close();		// TODO delete any partially-uploaded file
		return s;
	}

	// Find an empty session
	if (numSessions < maxHttpSessions)
	{
		s = &sessions[numSessions];
		s->ip = ip;
		s->isAuthenticated = false;
		s->nextFragment = 0;
		s->fileBeingUploaded.Close();			// make sure no file is open
		s->lastQueryTime = millis();
		++numSessions;
		return s;
	}
	return nullptr;
}
Пример #3
0
int EDITAPI EDITFile( char *fn, char *hlib )
/***************************************************/
{
    CurrSession = FindSession( fn );
    if( CurrSession == NULL ) {
        if( StartingSessionInProgress ) {
            return( FALSE );
        }
        StartingSessionInProgress = TRUE;
        // new session must be created before we start the editor so
        // that we can process the WM_DDE_INITIATE message properly
        CurrSession = NewSession( fn, hlib );
        if( CurrSession == NULL ) {
            return( FALSE );
        }
        LinkSession( CurrSession );
        if( spawnlp( P_NOWAIT, _Editor, _Editor, "/W", fn, NULL ) == -1 ) {
            DeleteSession( NULLHANDLE );
            CurrSession = NULL;
            return( FALSE );
        }
    }
    WinSetFocus( HWND_DESKTOP, CurrSession->hwnd );
    return( TRUE );
}
int	LSelectServer::SendData()
{
	unsigned int unSendedPacket = 0;

	t_Send_Packet tSendPacket;
	memset(&tSendPacket, 0, sizeof(tSendPacket));

	while (GetOneSendPacket(tSendPacket))
	{
		LSelectServerSession* pSession = FindSession(tSendPacket.unSessionID);
		if (pSession != NULL)
		{
			int nSendResult = pSession->SessionSend(tSendPacket.pPacketForSend);
			if (nSendResult < 0)
			{
				AddOneCloseSessionWork(tSendPacket.unSessionID);
			}
		}
		unSendedPacket++;
		if (unSendedPacket >= 2000)
		{
			break;
		}
		memset(&tSendPacket, 0, sizeof(tSendPacket));
	}
	return unSendedPacket;
}
Пример #5
0
CNetCom* CNetMgr::GetNode( const GUID *pGuid )
{_STT();
	// Acquire lock
	CTlLocalLock ll( *this );
	if ( !ll.IsLocked() ) return NULL;

	return FindSession( pGuid );
}
Пример #6
0
bool
cConnection::AddSession( SaHpiSessionIdT sid )
{
  if ( FindSession( sid ) )
       return false;

  cSession *s = new cSession( this, sid );
  m_sessions = g_list_append( m_sessions, s );

  return true;
}
Пример #7
0
void CChatCore::OnED2KMessage(CEDClient* pClient, CEDPacket* pPacket)
{
	ASSERT ( pClient != NULL );
	// Note: Null packet is valid- in that case we have no pending message, but want to open
	// a chat window.

	CSingleLock pLock( &m_pSection );
	if ( ! pLock.Lock( 250 ) ) return;
	
	CChatSession* pSession = FindSession( pClient );

	pSession->OnED2KMessage( pPacket );
}
Пример #8
0
bool
cConnection::RemSession( SaHpiSessionIdT sid )
{
  cSession *s = FindSession( sid );

  if ( s == 0 )
       return false;

  m_sessions = g_list_remove( m_sessions, s );

  delete s;

  return true;
}
Пример #9
0
int BuildSession(PLC *plc)
{	int path_size=0;
	char ip[16],path[40];
	Eip_Session *session=NULL;
	
	Log(LOG_DEBUG,"Building Session for %s (%d sessions)\n",plc->PlcName,SESSIONs.Count);
	
	if (plc->Session!=NULL) return(0);
		
	path_size=ParsePath(plc->PlcPath,ip,path);
	if (path_size>0)
	{ // Creating Sessions
		if (plc->Session==NULL)
		{ 
			session=FindSession(ip,&PLCs);
			if (session==NULL) // not found
			{
				session=OpenSession(ip);
				if (session!=NULL)
				{
					if (RegisterSession(session)<0)
					{
						CloseSession(session);
						Log(LOG_CRIT,"Unable to register session for Plc: %s (%s) \n",plc->PlcName,cip_err_msg);
					}
					AddChListe(&SESSIONs,session);
					session->References=1;
					//session->timeout=2000;
					Log(LOG_DEBUG,"Session (%p) created for PLC : %s (%d sessions)\n",session,plc->PlcName,SESSIONs.Count);
					plc->Session=session;
					return(1);
				} else 
				{
					Log(LOG_CRIT,"Unable to open session for Plc: %s (%s)\n",plc->PlcName,cip_err_msg);
					return(0);
				}
			}	else 
			{
				plc->Session=session;
				session->References++;
				Log(LOG_DEBUG,"%s Sharing Session (%p) with another PLC (%d references)\n",plc->PlcName,session,session->References);
				return(1);
			}
		} else return(0);
	} else return(0);
}
Пример #10
0
bool StructuredLearnerRpc::AddNewExample(const Json::Value& root, Json::Value& response) {
  if(learner) {
    char sess_id[1000];
    int sess_ind;
    if(strlen(root.get("session_id", "").asString().c_str()) < 1000)
      strcpy(sess_id, root.get("session_id", "").asString().c_str());
    else
      strcpy(sess_id, "");

    StructuredExample *ex = NULL;
    sess_ind = FindSession(sess_id, true);
    if(sess_ind >= 0) {
      ex = sessions[sess_ind].example;
      response["session_id"] = sessions[sess_ind].id;
    } else {
      ex = new StructuredExample;
      ex->x = learner->NewStructuredData();
      ex->y = learner->NewStructuredLabel(ex->x);
    }

    if(root.isMember("x")) {
      if(!ex->x->load(root["x"], learner)) { JSON_ERROR("Invalid 'x' parameter", sess_ind); }
    }
    if(root.isMember("y")) {
      if(!ex->y->load(root["y"], learner)) { JSON_ERROR("Invalid 'x' parameter", sess_ind); }
    } else if(sess_ind < 0) {
      delete ex;
      JSON_ERROR("No 'y' parameter specified", sess_ind); 
    }

    int ind = learner->AddExample(ex->x, ex->y);
    if(ind < 0) { JSON_ERROR("Error adding example\n", sess_ind) }
    response["index"] = ind;

    learner->SaveTrainingSet(ind);

    if(sess_ind >= 0)
      UnlockSession(sess_ind);
    else {
      delete ex;
    }

    return true;
  } else
    return false;
Пример #11
0
status_t BnChatSessionManager::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
	status_t result = 0x80000000;
	_TRACE("ChatSessionManager::onTransact[pid:%d] >>:code 0x%x",GetCallerPID(),code); //data.print();
	switch(code) {
	case ICSM_GetSessionNames: {
		CHECK_INTERFACE(IChatSessionManager, data, reply);
		Vector<String16> list = GetSessionNames();
		const size_t N = list.size();
		reply->writeInt32(N);
		for (size_t i=0; i<N; i++) {
		    reply->writeString16(list[i]);
		}
		result = NO_ERROR;
	} break;
	case ICSM_FindSession: {
		CHECK_INTERFACE(IChatSessionManager, data, reply);
		String16 name = data.readString16();
		BOOL bDontCreate = data.readInt32();
		BOOL bAllowAnonymousAccess = data.readInt32();	
		sp<IChatSession> b = FindSession(name,bDontCreate,bAllowAnonymousAccess);			
		reply->writeStrongBinder(b->asBinder());
		result =  NO_ERROR;
	} break;
	case ICSM_DeleteSession: {
		CHECK_INTERFACE(IChatSessionManager, data, reply);
		String16 name = data.readString16();
		status_t err = DeleteSession(name);
		reply->writeInt32(err);
		result =  NO_ERROR;
	} break;		
	default:
		result =  BBinder::onTransact(code, data, reply, flags);
	}
	_TRACE("ChatSessionManager::onTransact[pid:%d] <<:result %d",GetCallerPID(),result); //reply.print();
	return result;
}
Пример #12
0
// Deal with input/output from/to the client (if any)
void Webserver::Spin()
{
	if (webserverActive)
	{
		uint32_t ip;
		size_t length;
		uint32_t fragment;
		const char* request = network->GetRequest(ip, length, fragment);
		if (request != nullptr)
		{
			if (reprap.Debug(moduleWebserver))
			{
				platform->MessageF(HOST_MESSAGE, "Request: %s fragment %u\n", request, fragment);
			}

			uint32_t fragNum = fragment & ~lastFragmentFlag;
			if (fragNum == 0)
			{
				HttpSession *session = StartSession(ip);
				if (session == nullptr)
				{
					network->SendReply(ip, 400, "Too many sessions");
				}
				else
				{
					// First fragment, so parse the request
					ResetState();
					const char *error = nullptr;
					bool finished = false;
					while (!finished && length != 0)
					{
						finished = CharFromClient(*request++, error);
						--length;
					}

					if (!finished)
					{
						error = "Incomplete command";
					}

					if (error != nullptr)
					{
						network->SendReply(ip, 400, error);
					}
					else
					{
						ProcessFirstFragment(*session, clientMessage, (fragment & lastFragmentFlag) != 0);
					}
				}
			}
			else
			{
				HttpSession *session = FindSession(ip);
				if (session != nullptr)
				{
					ProcessUploadFragment(*session, request, length, fragment);
				}
				else
				{
					// Discard the message
					network->DiscardMessage();
					platform->MessageF(DEBUG_MESSAGE, "session not found, fragment=%u\n", fragment);
				}
			}
		}
	}
	CheckSessions();
	platform->ClassReport(longWait);
}
Пример #13
0
int CMain::ReceiveIpcHandler()
{
	int cmdCode = 0;
	string strCmdCode;
	CGlobal *cGlob = NULL;
	CModuleIPC *cIpc = NULL;
	CProtocol cProto;
	char chFlag = 0;
	int nRet = 0;

	cGlob = CGlobal::GetInstance();

	cIpc = cGlob->GetModuleIPC();

	nRet = cIpc->RecvMesg(cGlob->GetLocalProcNo(), cProto, -1);
	if(nRet < 0){
		CLA_LOG(CLA_ERR,false,"Message receive failed(ERR:%s)\n", cIpc->m_strErrorMsg.c_str());
		return CLA_NOK;
	}
	else if(nRet == 0){
		return CLA_OK;
	}

	chFlag = cProto.GetFlag();

	if((chFlag != CProtocol::FLAG_RESPONSE)){
		CLA_LOG(CLA_ERR,false,"Invalid Flag(flag=%d)\n",chFlag);
		return CLA_NOK;
	}

	strCmdCode = cProto.GetCommand();

	cmdCode = CGlobal::GetCmdCode(strCmdCode);

	switch(cmdCode){
		case CMD_CLI_COMMAND:
			{
				unsigned int fd = 0;
				unsigned int nSessionId = 0;
				CCliPeer *cPeer = NULL;
				CSession *cSession = NULL;
				CCliRsp decRsp;
				string strPayload;

				nSessionId = cProto.GetSequence();

				cSession = FindSession(nSessionId);
				if(cSession == NULL){
					CLA_LOG(CLA_ERR,false,"Can not find session(id=%d)\n",nSessionId);
					return CLA_NOK;
				}

				strPayload = cProto.GetPayload();

				decRsp.DecodeMessage(strPayload);

				decRsp.SetSessionId(cSession->GetClcSessionId());

				decRsp.EncodeMessage(strPayload);

				cProto.SetPayload(strPayload);
				cProto.SetSequence(cSession->GetClcSessionId());

				fd = cSession->GetPeerFd();

				cPeer = FindPeerByFd(fd);
				if(cPeer == NULL){
					CLA_LOG(CLA_ERR,false,"Can not find peer(fd=%d)\n",fd);
					delete cSession;
					return CLA_NOK;
				}

				if(cPeer->GetTimestamp() != cSession->GetPeerTimestamp()){
					CLA_LOG(CLA_ERR,false,"Can not find peer(timestamp=%lu, %lu)\n", 
							cPeer->GetTimestamp() ,cSession->GetPeerTimestamp());
					delete cSession;
					return CLA_NOK;
				}

				/* update hist */
				UpdateHist(cPeer, cSession, &decRsp);

				cPeer->Send(cProto);

				delete cSession;
			}
			break;
		default :
			CLA_LOG(CLA_ERR,false,"Invalid cmdCode(%s)\n",cProto.GetCommand().c_str());
			return CLA_NOK;

	};


	return CLA_OK;
}
Пример #14
0
/*
 * handle one request
 *
 * This loop gets called once for every HTTP connection made to WebCit.  At
 * this entry point we have an HTTP socket with a browser allegedly on the
 * other end, but we have not yet bound to a WebCit session.
 *
 * The job of this function is to locate the correct session and bind to it,
 * or create a session if necessary and bind to it, then run the WebCit
 * transaction loop.  Afterwards, we unbind from the session.  When this
 * function returns, the worker thread is then free to handle another
 * transaction.
 */
void context_loop(ParsedHttpHdrs *Hdr)
{
	int isbogus = 0;
	wcsession *TheSession;
	struct timeval tx_start;
	struct timeval tx_finish;
	int session_may_be_reused = 1;
	time_t now;
	
	gettimeofday(&tx_start, NULL);		/* start a stopwatch for performance timing */

	/*
	 * Find out what it is that the web browser is asking for
	 */
	isbogus = ReadHTTPRequest(Hdr);

	Hdr->HR.dav_depth = 32767; /* TODO: find a general way to have non-0 defaults */

	if (!isbogus) {
		isbogus = AnalyseHeaders(Hdr);
	}

	if (	(isbogus)
		|| ((Hdr->HR.Handler != NULL)
		&& ((Hdr->HR.Handler->Flags & BOGUS) != 0))
	) {
		wcsession *Bogus;
		Bogus = CreateSession(0, 1, NULL, Hdr, NULL);
		do_404();
		syslog(LOG_WARNING, "HTTP: 404 [%ld.%06ld] %s %s",
			((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
			((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
			ReqStrs[Hdr->HR.eReqType],
			ChrPtr(Hdr->this_page)
			);
		session_detach_modules(Bogus);
		session_destroy_modules(&Bogus);
		return;
	}

	if ((Hdr->HR.Handler != NULL) && ((Hdr->HR.Handler->Flags & ISSTATIC) != 0))
	{
		wcsession *Static;
		Static = CreateSession(0, 1, NULL, Hdr, NULL);
		
		Hdr->HR.Handler->F();

		/* How long did this transaction take? */
		gettimeofday(&tx_finish, NULL);
		
		if (verbose)
			syslog(LOG_DEBUG, "HTTP: 200 [%ld.%06ld] %s %s",
			       ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
			       ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
			       ReqStrs[Hdr->HR.eReqType],
			       ChrPtr(Hdr->this_page)
		);
		session_detach_modules(Static);
		session_destroy_modules(&Static);
		return;
	}

	if (Hdr->HR.got_auth == AUTH_BASIC) {
		CheckAuthBasic(Hdr);
	}

	if (Hdr->HR.got_auth) {
		session_may_be_reused = 0;
	}

	/*
	 * See if there's an existing session open with any of:
	 * - The desired Session ID
	 * - A matching http-auth username and password
	 * - An unbound session flagged as reusable
	 */
	TheSession = FindSession(&SessionList, Hdr, &SessionListMutex);

	/*
	 * If there were no qualifying sessions, then create a new one.
	 */
	if ((TheSession == NULL) || (TheSession->killthis != 0)) {
		TheSession = CreateSession(1, 0, &SessionList, Hdr, &SessionListMutex);
	}

	/*
	 * Reject transactions which require http-auth, if http-auth was not provided
	 */
	if (	(StrLength(Hdr->c_username) == 0)
		&& (!Hdr->HR.DontNeedAuth)
		&& (Hdr->HR.Handler != NULL)
		&& ((XHTTP_COMMANDS & Hdr->HR.Handler->Flags) == XHTTP_COMMANDS)
	) {
		syslog(LOG_DEBUG, "http-auth required but not provided");
		OverrideRequest(Hdr, HKEY("GET /401 HTTP/1.0"));
		Hdr->HR.prohibit_caching = 1;				
	}

	/*
	 * A future improvement might be to check the session integrity
	 * at this point before continuing.
	 */

	/*
	 * Bind to the session and perform the transaction
	 */
	now = time(NULL);;
	CtdlLogResult(pthread_mutex_lock(&TheSession->SessionMutex));
	pthread_setspecific(MyConKey, (void *)TheSession);
	
	TheSession->inuse = 1;				/* mark the session as bound */
	TheSession->lastreq = now;			/* log */
	TheSession->Hdr = Hdr;

	/*
	 * If a language was requested via a cookie, select that language now.
	 */
	if (StrLength(Hdr->c_language) > 0) {
		if (verbose)
			syslog(LOG_DEBUG, "Session cookie requests language '%s'", ChrPtr(Hdr->c_language));
		set_selected_language(ChrPtr(Hdr->c_language));
		go_selected_language();
	}

	/*
	 * do the transaction
	 */
	session_attach_modules(TheSession);
	session_loop();

	/* How long did this transaction take? */
	gettimeofday(&tx_finish, NULL);

	if (verbose || strstr(ChrPtr(Hdr->this_page), "sslg") == NULL) {
		syslog(LOG_INFO, "HTTP: 200 [%ld.%06ld] %s %s",
		       ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
		       ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
		       ReqStrs[Hdr->HR.eReqType],
		       ChrPtr(Hdr->this_page)
			);
	}
	session_detach_modules(TheSession);

	/* If *this* very transaction did not explicitly specify a session cookie,
	 * and it did not log in, we want to flag the session as a candidate for
	 * re-use by the next unbound client that comes along.  This keeps our session
	 * table from getting bombarded with new sessions when, for example, a web
	 * spider crawls the site without using cookies.
	 */
	if ((session_may_be_reused) && (!TheSession->logged_in)) {
		TheSession->wc_session = 0;		/* flag as available for re-use */
		TheSession->selected_language = -1;	/* clear any non-default language setting */
	}

	TheSession->Hdr = NULL;
	TheSession->inuse = 0;					/* mark the session as unbound */
	CtdlLogResult(pthread_mutex_unlock(&TheSession->SessionMutex));
}
void WHartNetworkData::TransmitIndicate(const WHartLocalStatus& localStatus, WHartPriority priority,
		const WHartDllAddress& dllSrc, WHartPayload& npdu)
{
//	LOG_DEBUG("TransmitIndicate: localStatus=" << localStatus.status << ", priority=" << priority << ", dllSrc="
//			<< dllSrc << ", NPDU=" << npdu);

	BinaryStream stream;
	STREAM_INIT(&stream, npdu.data, npdu.dataLen);

	//parse network header
	uint8_t controlByte;
	STREAM_READ_UINT8(&stream, &controlByte);
	uint8_t ttl;
	STREAM_READ_UINT8(&stream, &ttl);
	uint16_t asn;
	STREAM_READ_UINT16(&stream, &asn);

	//HACK:[andrei.petrut] - write ASN to common data so it can be used in the next packet...
	commonData.lastReadASN = asn;

	uint16_t graphID;
	STREAM_READ_UINT16(&stream, &graphID);
	WHartAddress dest;
	StreamReadNetAddress(&stream, dest, (controlByte & CONTROLTYPE_DESTADDRESS_MASK) == 0);
	WHartAddress src;
	StreamReadNetAddress(&stream, src, (controlByte & CONTROLTYPE_SRCADDRESS_MASK) == 0);

	//TODO:[andy] - implement isBroadcast
	bool isForMe = (dest == commonData.myNickname || dest == commonData.myUniqueID);
	bool isBroadcast = false;
	bool isSourceRoute = ((controlByte & CONTROLTYPE_1STSOURCEROUTE_MASK) != 0);

	WHartShortAddress proxy = 0;
	if (controlByte & CONTROLTYPE_PROXYROUTE_MASK)
	{
		STREAM_READ_UINT16(&stream, &proxy);
	}

	Route tempRoute;
	if (isSourceRoute)
	{
		tempRoute.destinationType = Route::dtSourceRoute;
		tempRoute.graphID = graphID;
		for (int i = 0; i < 4; i++)
		{
			WHartShortAddress addr;
			STREAM_READ_UINT16(&stream, &addr);
			if (addr != 0xFFFF)
			{
				tempRoute.sourceRoutePath.push_back(addr);
			}
		}
		if (controlByte & CONTROLTYPE_2NDSOURCEROUTE_MASK)
		{
			for (int i = 0; i < 4; i++)
			{
				WHartShortAddress addr;
				STREAM_READ_UINT16(&stream, &addr);
				if (addr != 0xFFFF)
				{
					tempRoute.sourceRoutePath.push_back(addr);
				}
			}
		}
	}

//	LOG_DEBUG("TransmitIndicate: isForMe=" << (int) isForMe << ", isBroadcast=" << (int) isBroadcast << ", isSourceRoute=" << (int)isSourceRoute << ", destAddress="
//			<< dest << ", TTL=" << ToStringHexa(ttl) << ", ASN=" << ToStringHexa(asn) << ", graphID="
//			<< ToStringHexa(graphID));

	if (isForMe || isBroadcast)
	{
		uint8_t securityControl; //contain session
		STREAM_READ_UINT8(&stream, &securityControl);

		WHartSessionKey::SessionKeyCode sessionKey = (WHartSessionKey::SessionKeyCode) (securityControl & 0x0F);
        uint8_t sessionType = securityControl & SECURITYCONTROL_SECURITYTYPE_MASK;

        //if join flow detected OnJoinCalback is called, in order to create session with the new device/ap if it is
        //provisioned correctly
        if ((sessionType == WHartSessionKey::joinKeyed) && (OnJoinCallback))
        {
            OnJoinCallback(src);
        }

		SessionTable::iterator session = FindSession(src, sessionKey);
		if (session == sessionTable.end())
		{
			LOG_WARN("Session for Dest=" << src << "with type=" << (int) sessionKey
					<< " not found! packet droped.");
			return;//invalid session
		}
		else
		{
//			LOG_DEBUG("Session used for packet is=" << sessionKey << " and dest=" << src << " and sessionID=" << (int)session->sessionID);
		}



		uint32_t counter;
		if (sessionType == WHartSessionKey::sessionKeyed)
		{
			uint8_t lsbNonce;
			STREAM_READ_UINT8(&stream, &lsbNonce);
//			LOG_DEBUG("Read small nonce counter = " << (int)lsbNonce << " . Need to reconstruct nonce counter...");
//			LOG_DEBUG("Session counter = " << session->receiveNonceCounter <<
//					" Session history size = " << sizeof(session->nonceCounterHistory)<<
//					" and compare value=" << ((1 + ((int)session->receiveNonceCounter & 0xFF) - (int)sizeof(session->nonceCounterHistory) * 8)));
			counter = ReconstructNonceCounter(*session, lsbNonce);
//			LOG_DEBUG("Reconstructed nonce counter=" << counter);
		} else
		{
			STREAM_READ_UINT32(&stream, &counter);
//			LOG_DEBUG("Read entire nonce counter=" << counter);
		}


		// reconstruct nonce counter end

		WHartPayload spdu(stream.nextByte, stream.remainingBytes);

		uint8_t dataTPDU[CommonData::MAX_PAYLOAD];
		WHartPayload tpdu(dataTPDU, sizeof(dataTPDU));

//		LOG_DEBUG("Creating PDU with size=" << stream.nextByte - npdu.data << " with stream next byte="
//				<< nlib::detail::BytesToString(stream.nextByte, stream.nextByte - npdu.data));
		CryptoStatus decryptStatus = EncryptDecrypt(*session, counter, WHartPayload(npdu.data, stream.nextByte - npdu.data), spdu,
				tpdu, src, dest, false);

		if (decryptStatus != whartcsSuccess)
		{
			LOG_WARN("transmitIndicate failed to decrypt Error=" << CryptoStatusToString(decryptStatus));
			return;
		}

		//reconstruct nonce counter
		if (sessionType == WHartSessionKey::joinKeyed) // join flow
		{
			LOG_DEBUG("Join flow detected.");
			session->receiveNonceCounter = counter;

		} else
		{
			int noncePosition = session->receiveNonceCounter - counter;
			if (noncePosition > (int) (NONCECOUNTERHISTORY_BIT_LENGTH))
			{
				//discard packet
				LOG_INFO("Received packet with nonce counter outside of the sliding window (nonce=" << counter
						<< ", windowStart=" << session->receiveNonceCounter << ", windowSize="
						<< (int) NONCECOUNTERHISTORY_BIT_LENGTH << "). Discarding packet...");
				return;
			}

			if (noncePosition < 0)
			{
//				LOG_DEBUG("New nonce received (old=" << session->receiveNonceCounter << ", new=" << counter << ". Sliding window to accommodate new nonce (with steps=" << -noncePosition << ")...");
				if (noncePosition <= -32)
				{
					session->nonceCounterHistory = 0;
				}
				else
				{
					session->nonceCounterHistory = session->nonceCounterHistory >> (-noncePosition);
				}

				noncePosition = 0;
				session->receiveNonceCounter = counter;
			}

			uint32_t mask = 0x01 << (NONCECOUNTERHISTORY_BIT_LENGTH - noncePosition - 1);
			if (session->nonceCounterHistory & mask)
			{
				// already received packet with this nonce, discard
				LOG_WARN("Already received packet with nonce=" << counter << " from src=" << src << ". Discarding...");
				return;
			}

			// mark nonce in history
			session->nonceCounterHistory = session->nonceCounterHistory | mask;
		}


		//forward to upper
		++nextRoutedHandler;
		WHartHandle handle = MAKE_WHARTHANDLE(1, nextRoutedHandler);

//		LOG_DEBUG("transmitIndicate forward to TL" << " handle=" << handle << ", src=" << src << ", priority="
//				<< priority << ", TPDU=" << tpdu);
		upper->TransmitIndicate(handle, src, priority, tpdu, (WHartSessionKey::SessionKeyCode) (securityControl & 0x0F));
	} else
Пример #16
0
// Parses Ecmt packets
void CEcmtMidpDebugPlugin::HandleNotifyL(const CEcmtMessageEvent& aEvent)
{
    static const TInt KMinMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MIN_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    static const TInt KMaxMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MAX_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    const TPtrC8 msg = iMessaging->Message(aEvent);
    TInt msglen = msg.Length();
    if (msglen >= ECMT_MIDP_DEBUG_HEADER_SIZE)
    {
        // Decode the header
        TUint opcode = msg[ECMT_MIDP_DEBUG_HEADER_OPCODE_OFFSET];
        TUint sid = (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET] << 24) | 
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+1] << 16) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+2] << 8) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+3]);

        // Check opcode
        if (opcode < ECMT_MIDP_DEBUG_OPCODE_MIN ||
            opcode > ECMT_MIDP_DEBUG_OPCODE_MAX)
        {
            TRACE1("invalid opcode: %u",opcode);
            return;
        }

        // Check message size
        if (msglen < KMinMsgSize[opcode] || 
            msglen > KMaxMsgSize[opcode])
        {
            TRACE2("opcode %u, invalid message size %u",opcode,msglen);
            return;
        }

        // Try to find existing session
        TInt index = -1;
        CEcmtMidpDebugSession* session = FindSession(sid, index);
        switch (opcode) {
        case ECMT_MIDP_DEBUG_OPCODE_OPEN:
            if (session)
            {
                TRACE2("OPEN: destroying session %08X (%d)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            session = CEcmtMidpDebugSession::NewL(sid,this,iMessaging);
            CleanupStack::PushL(session);
            LEAVE_IF_ERROR(iSessions.Append(session));
            CleanupStack::Pop(session);
            TRACE2("OPEN: created new session %08X (%u)",session,sid);
            break;
                
        case ECMT_MIDP_DEBUG_OPCODE_CLOSE:
            if (session)
            {
                TRACE2("CLOSE: destroying session %08X (%u)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            else
            {
                TRACE1("CLOSE: no such session: %u",sid); 
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_SEND:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+3]);
                TUint seq = (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+3]);
                session->Send(cid, seq,
                    msg.Right(msglen - ECMT_MIDP_DEBUG_SEND_DATA_OFFSET));
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("SEND: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_CONNECT:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+3]);
                TUint port = (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET] << 8) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET+1]);
                session->ConnectL(cid, port);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("CONNECT: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;


        case ECMT_MIDP_DEBUG_OPCODE_RESET:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+3]);
                session->Reset(cid);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("RESET: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        }
    }
}
int LSelectServer::ThreadDoing(void* pParam)
{ 
	while (1)
	{
		unsigned short usProcessedCloseWorkCount = 0;
		unsigned int unSessionIDForClose = 0;
		while (GetOneCloseSessionWork(unSessionIDForClose))
		{
			LSelectServerSession* pSession = FindSession(unSessionIDForClose);	
			if (pSession != NULL)
			{
				bool bReconnect = pSession->GetReconnect();
				pSession->ReleaseAllPacketInSendQueue();
#ifndef WIN32
				close(pSession->GetSocket());
#else
				closesocket(pSession->GetSocket());
#endif
				RemoveSession(unSessionIDForClose);
				FreeSession(pSession);
				AddOneRecvedPacket(unSessionIDForClose, NULL);
				if (bReconnect)
				{
					char szIP[32];
					unsigned short usPort = 0;
#ifndef WIN32
					pthread_mutex_lock(&m_mutexForConnectToServer);
#else
					EnterCriticalSection(&m_mutexForConnectToServer);
#endif
					if (!m_ConnectorWorkManager.AddConnectWork(szIP, usPort, NULL, 0))
					{
						//	error print
					}
#ifndef WIN32
					pthread_mutex_unlock(&m_mutexForConnectToServer);
#else
					LeaveCriticalSection(&m_mutexForConnectToServer);
#endif
				}
			}
			usProcessedCloseWorkCount++;
			if (usProcessedCloseWorkCount >= 200)
			{
				break;
			}
		}
		t_Connector_Work_Result cwr;
		memset(&cwr, 0, sizeof(cwr));
		int nProcessConnecttedWorkCount = 0;
		while (GetOneConnectedSession(cwr))
		{ 
			LSelectServerSession* pSession = AllocSession();
			if (pSession == NULL)
			{
#ifndef WIN32
				close(cwr.nSocket);
				pthread_mutex_lock(&m_mutexForConnectToServer);
#else
				closesocket(cwr.nSocket);
				EnterCriticalSection(&m_mutexForConnectToServer);
#endif

				
				if (!m_ConnectorWorkManager.AddConnectWork(cwr.szIP, cwr.usPort, NULL, 0))
				{
					//	error print
				}
#ifndef WIN32
				pthread_mutex_unlock(&m_mutexForConnectToServer);
#else
				LeaveCriticalSection(&m_mutexForConnectToServer);
#endif
				nProcessConnecttedWorkCount++;
				if (nProcessConnecttedWorkCount >= 200)
				{
					break;
				}
				continue;
			}
			else
			{
				pSession->SetSocket(cwr.nSocket);
				if (!AddSession(pSession))
				{
#ifndef WIN32
					close(cwr.nSocket);
					pthread_mutex_lock(&m_mutexForConnectToServer);
#else
					closesocket(cwr.nSocket);
					EnterCriticalSection(&m_mutexForConnectToServer);
#endif
					
					if (!m_ConnectorWorkManager.AddConnectWork(cwr.szIP, cwr.usPort, NULL, 0))
					{
						//	error print
					}
#ifndef WIN32
					pthread_mutex_unlock(&m_mutexForConnectToServer);
#else
					LeaveCriticalSection(&m_mutexForConnectToServer);
#endif
					FreeSession(pSession);
				}
				else
				{ 
					pSession->SetReconnect(true);
					AddOneRecvedPacket(pSession->GetSessionID(), (LPacketSingle*)0xFFFFFFFF);
				}
			}
			nProcessConnecttedWorkCount++;
			if (nProcessConnecttedWorkCount >= 200)
			{
				break;
			}
		}

		int nWorkCount = CheckForSocketEvent();
		if (nWorkCount < 0)
		{
			return 0;
		}
		int nSendWorkCount = SendData();
		if (nWorkCount == 0 && nSendWorkCount == 0)
		{
			//	sched_yield();
#ifndef WIN32
			struct timespec timeReq;
			timeReq.tv_sec 	= 0;
			timeReq.tv_nsec = 10;
			nanosleep(&timeReq, NULL);
#else
			Sleep(0);
#endif
		}
		if (CheckForStop())
		{
			return 0;
		} 
	}
	return 0; 
}