bool LLBC_IocpPoller::HandleConnecting(int waitRet, LLBC_POverlapped ol, int errNo, int subErrNo) { if (ol->opcode != LLBC_OverlappedOpcode::Connect) return false; _Connecting::iterator it = _connecting.find(ol->sock); LLBC_AsyncConnInfo &asyncInfo = it->second; LLBC_Socket *sock = asyncInfo.socket; sock->DeleteOverlapped(ol); if (waitRet == LLBC_OK) { sock->SetOption(SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0); SetConnectedSocketDftOpts(sock); _svc->Push(LLBC_SvcEvUtil::BuildAsyncConnResultEv( true, LLBC_StrError(LLBC_ERROR_SUCCESS), asyncInfo.peerAddr)); AddSession(CreateSession(sock, asyncInfo.sessionId), false); } else { _svc->Push(LLBC_SvcEvUtil::BuildAsyncConnResultEv( false, LLBC_StrErrorEx(errNo, subErrNo), asyncInfo.peerAddr)); LLBC_Delete(asyncInfo.socket); } _connecting.erase(it); return true; }
void XnSensorServer::CheckForNewClients(XnUInt32 nTimeout) { XnStatus nRetVal = XN_STATUS_OK; // run in loop until we break due to timeout XN_SOCKET_HANDLE hClientSocket; for (;;) { nRetVal = xnOSAcceptSocket(m_hListenSocket, &hClientSocket, nTimeout); if (nRetVal == XN_STATUS_OS_NETWORK_TIMEOUT) { return; } else if (nRetVal != XN_STATUS_OK) { //Any other error beside timeout is not expected, but we treat it the same. xnLogWarning(XN_MASK_SENSOR_SERVER, "failed to accept connection: %s", xnGetStatusString(nRetVal)); } else { xnLogInfo(XN_MASK_SENSOR_SERVER, "New client trying to connect..."); //TODO: Check if we don't have too many clients nRetVal = AddSession(hClientSocket); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_SENSOR_SERVER, "Failed to add new client: %s", xnGetStatusString(nRetVal)); xnOSCloseSocket(hClientSocket); //Still in loop } } } }
// ---------------------------------------------------------------------- // Implementation of IAudioSessionNotification::OnSessionCreated // // Notifies the registered processes that the audio session has been created. // // ---------------------------------------------------------------------- HRESULT AudioVolume::OnSessionCreated(IAudioSessionControl *NewSession) { TRACE("AudioVolume::OnSessionCreated Enters\n"); m_csEndpoint.Enter(); CComQIPtr<IAudioSessionControl> spIAudioSessionControl = NewSession; if (spIAudioSessionControl != NULL) { try { // Map indicating whether a process belongs to firefox std::map<DWORD, DWORD> map; if (!BuildProcesseTree(map)) { throw "AudioVolume::GetSubProcesseMap failed!"; } AddSession(map, spIAudioSessionControl); if (g_uThread) { ::PostThreadMessage(g_uThread, MSG_USER_UPDATE_MUTE_STATUS, 0, 0); } } catch (LPCSTR szError) { TRACE("[MuterWin7] AudioVolume::OnSessionCreated: %s\n", szError); } } m_csEndpoint.Leave(); TRACE("AudioVolume::OnSessionCreated Leaves\n"); return S_OK; }
bool Machine::Load() { QString path=profile->Get(properties[STR_PROP_Path]); //STR_GEN_DataFolder)+"/"+m_class+"_"+hexid(); QDir dir(path); qDebug() << "Loading " << QDir::toNativeSeparators(path); if (!dir.exists() || !dir.isReadable()) return false; dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); dir.setSorting(QDir::Name); QFileInfoList list=dir.entryInfoList(); typedef QVector<QString> StringList; QMap<SessionID,StringList> sessfiles; QMap<SessionID,StringList>::iterator s; QString fullpath,ext_s,sesstr; int ext; SessionID sessid; bool ok; for (int i=0;i<list.size();i++) { QFileInfo fi=list.at(i); fullpath=fi.canonicalFilePath(); ext_s=fi.fileName().section(".",-1); ext=ext_s.toInt(&ok,10); if (!ok) continue; sesstr=fi.fileName().section(".",0,-2); sessid=sesstr.toLong(&ok,16); if (!ok) continue; if (sessfiles[sessid].capacity()==0) sessfiles[sessid].resize(3); sessfiles[sessid][ext]=fi.canonicalFilePath(); } int size=sessfiles.size(); int cnt=0; for (s=sessfiles.begin(); s!=sessfiles.end(); s++) { if ((++cnt % 50)==0) { // This is slow.. :-/ if (qprogress) qprogress->setValue((float(cnt)/float(size)*100.0)); QApplication::processEvents(); } Session *sess=new Session(this,s.key()); if (sess->LoadSummary(s.value()[0])) { sess->SetEventFile(s.value()[1]); //sess->OpenEvents(); AddSession(sess,profile); } else { qWarning() << "Error unpacking summary data"; delete sess; } } if (qprogress) qprogress->setValue(100); return true; }
void AudioVolume::InitAudioSessionControlList() { HRESULT hr = S_OK; if (m_spAudioSessionManager2 == NULL) return; CComQIPtr<IAudioSessionEnumerator> spAudioSessionEnumerator; try { // Get audio session enumerator hr = m_spAudioSessionManager2->GetSessionEnumerator(&spAudioSessionEnumerator); if (FAILED(hr)) { throw "Cannot get audio session enumerator!"; } // Get audio session number int nSessions = 0; hr = spAudioSessionEnumerator->GetCount(&nSessions); if (FAILED(hr)) { throw "Cannot get audio session number!"; } // Map indicating whether a process belongs to firefox std::map<DWORD, DWORD> map; if (!BuildProcesseTree(map)) { throw "AudioVolume::GetSubProcesseMap failed!"; } // Enumerate audio sessions for (int i=0; i<nSessions; i++) { CComQIPtr<IAudioSessionControl> spAudioSessionControl; try { // Get AudioSessionControl HRESULT hr = spAudioSessionEnumerator->GetSession(i, &spAudioSessionControl); if (FAILED(hr)) { throw "Cannot get AudioSessionControl!"; } AddSession(map, spAudioSessionControl); } catch (LPCSTR szError) { TRACE("[MuterWin7] AudioVolume::InitAudioSessionControlList: %s\n", szError); } } } catch (LPCSTR szError) { TRACE("[MuterWin7] AudioVolume::InitAudioSessionControlList: %s\n", szError); } SAFE_RELEASE(spAudioSessionEnumerator); }
CNetCom* CNetMgr::AddSession( const GUID *guidId ) {_STT(); // Acquire lock CTlLocalLock ll( *this ); if ( !ll.IsLocked() ) return NULL; // Create new session CNetCom* pNc = CreateNewSession(); if ( pNc == NULL ) return NULL; // Add to the list return AddSession( guidId, pNc ); }
VU_ERRCODE FalconGameEntity::Handle(VuFullUpdateEvent *event) { FalconGameEntity *tmpGame = (FalconGameEntity*)(event->expandedData_.get()); VuSessionsIterator iter(tmpGame); VuSessionEntity *ent; if (IsLocal()) return 0; int dirty = FALSE; if(FalconLocalSession->GetFlyState() == FLYSTATE_IN_UI && gMainHandler) if(memcmp( &rules, &tmpGame->rules, sizeof (class RulesClass) ) ) dirty = TRUE; // Copy in new data memcpy (&gameType, &tmpGame->gameType, sizeof (FalconGameType)); memcpy (&rules, &tmpGame->rules, sizeof (class RulesClass)); // Attach any sessions not in our list ent = iter.GetFirst(); while (ent){ #if VU_ALL_FILTERED if (!sessionCollection_->Find(ent)){ AddSession(ent); } #else if (!sessionCollection_->Find(ent->Id())){ AddSession(ent); } #endif ent = iter.GetNext(); } if(dirty) PostMessage(FalconDisplay.appWin,FM_UPDATE_RULES,NULL,NULL); // Let vu handle the rest. return (VuGameEntity::Handle(event)); }
//监听线程 void SuperNode::ListeningThread(){ try { for (;;) { SocketAddress sa; PSocket s = listenSocket.Accept(&sa); //创建一个节点收发会话 PSuperNodeConnectionSession ps= new SuperNodeConnectionSession(sa,s,this); //将会话添加到会话列表,获得会话id ps->sessionId = AddSession(ps); ps->Run(); } } catch (PException e) { std::cout << "监听异常退出:"<<e << std::endl; } }
/** @brief 获取指定地址的会话,如果不存在则建立会话并将其添加到套接字列表中*/ PSuperNodeConnectionSession SuperNode::FindOrAddConnectSession(std::string addrport) { AddressInfo af(addrport); SocketAddress const& sf = af[0].GetSocketAddressRef(); socketMapLock.Lock(); std::map<SocketAddress, Collection::PArray<PSuperNodeConnectionSession> >::iterator it = socketMap.find(sf); PSuperNodeConnectionSession ps; if (it == socketMap.end()) { PSocket soc = new Socket(SocketType::Stream, ProtocolType::TCP); std::cout << "连接远端节点" << std::endl; soc.Connect(sf); ps = new SuperNodeConnectionSession(sf, soc, this); ps->sessionId = AddSession(ps); AddConnectSession(sf,ps); ps->Run(); } else ps = it->second[PRandom::GetDefaultRef().NextInt(0, (int)it->second.size() - 1)];//有多个连接时随机选一个 socketMapLock.UnLock(); return ps; }
bool UmcFramework::ProcessRunRequest(const char* pScenarioName, const char* pProfileName) { UmcScenario* pScenario = (UmcScenario*) apr_hash_get(m_pScenarioTable,pScenarioName,APR_HASH_KEY_STRING); if(!pScenario) return false; UmcSession* pSession = pScenario->CreateSession(); if(!pSession) return false; printf("[%s]\n",pSession->GetId()); pSession->SetMrcpProfile(pProfileName); pSession->SetMrcpApplication(m_pMrcpApplication); if(!pSession->Run()) { delete pSession; return false; } AddSession(pSession); return true; }
int LSelectServer::CheckForSocketEvent() { if (!m_SelectServerSessionManager.BuildSet()) { return -1; } fd_set rdset = m_SelectServerSessionManager.GetRecvSet(); fd_set wrset = m_SelectServerSessionManager.GetSendSet(); map<int, LSelectServerSession*>* pMapSocket = m_SelectServerSessionManager.GetSessionManagerForEvent(); struct timeval val; val.tv_sec = 0; val.tv_usec = 0; int iReturn = select(m_SelectServerSessionManager.GetMaxSocketPlus1(), &rdset, &wrset, NULL, &val); if (iReturn == -1) { return -1; } else if (iReturn == 0) { return 0; } int nListenSocket = GetSocket(); if (FD_ISSET(nListenSocket, &rdset)) { int nAcceptedSocket = accept(nListenSocket, NULL, NULL); if (nAcceptedSocket != -1) { LSelectServerSession* pSession = AllocSession(); if (pSession == NULL) { #ifndef WIN32 close(nAcceptedSocket); #else closesocket(nAcceptedSocket); #endif } else { pSession->SetSocket(nAcceptedSocket); if (!AddSession(pSession)) { #ifndef WIN32 close(nAcceptedSocket); #else closesocket(nAcceptedSocket); #endif FreeSession(pSession); } else { AddOneRecvedPacket(pSession->GetSessionID(), (LPacketSingle*)0xFFFFFFFF); } } } } map<int, LSelectServerSession*>::iterator _ito = pMapSocket->begin(); while (_ito != pMapSocket->end()) { int nTempSocket = _ito->first; LSelectServerSession* pSelectServerSession = _ito->second; if (pSelectServerSession == NULL) { _ito++; continue; } if (FD_ISSET(nTempSocket, &rdset)) { int nErrorID = pSelectServerSession->SessionRecv(); if (nErrorID < 0) { pSelectServerSession->SetSendable(false); AddOneCloseSessionWork(pSelectServerSession->GetSessionID()); _ito++; continue; } } if (FD_ISSET(nTempSocket, &wrset)) { pSelectServerSession->SetSendable(true); } _ito++; } return 1; }
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; }
// // This version of StartAuthSession initializes the fields // of the session structure using the passed in // parameters, then calls StartAuthSession // with just a pointer to the session structure. // This allows all params to be set in one line of code when // the function is called; cleaner this way, for // some uses. // TPM_RC StartAuthSessionWithParams( SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ) { TPM_RC rval; SESSION_LIST_ENTRY *sessionEntry; rval = AddSession( &sessionEntry ); if( rval == TSS2_RC_SUCCESS ) { *session = &sessionEntry->session; // Copy handles to session struct. (*session)->bind = bind; (*session)->tpmKey = tpmKey; // Copy nonceCaller to nonceOlder in session struct. // This will be used as nonceCaller when StartAuthSession // is called. CopySizedByteBuffer( &(*session)->nonceOlder.b, &nonceCaller->b ); // Copy encryptedSalt CopySizedByteBuffer( &(*session)->encryptedSalt.b, &encryptedSalt->b ); // Copy sessionType. (*session)->sessionType = sessionType; // Init symmetric. (*session)->symmetric.algorithm = symmetric->algorithm; (*session)->symmetric.keyBits.sym = symmetric->keyBits.sym; (*session)->symmetric.mode.sym = symmetric->mode.sym; (*session)->authHash = algId; // Copy bind' authValue. if( bindAuth == 0 ) { (*session)->authValueBind.b.size = 0; } else { CopySizedByteBuffer( &( (*session)->authValueBind.b ), &( bindAuth->b ) ); } // Calculate sessionKey if( (*session)->tpmKey == TPM_RH_NULL ) { (*session)->salt.t.size = 0; } else { CopySizedByteBuffer( &(*session)->salt.b, &salt->b ); } if( (*session)->bind == TPM_RH_NULL ) (*session)->authValueBind.t.size = 0; rval = StartAuthSession( *session ); } else { DeleteSession( *session ); } return( rval ); }