Exemplo n.º 1
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 );
}
Exemplo n.º 2
0
void World::UpdateSessions(time_t diff)
{
	SessionSet::iterator itr, it2;
	PlayerSession *session;
	int result;
	for(itr = Sessions.begin(); itr != Sessions.end();)
	{
		session = (*itr);
		it2 = itr;
		++itr;
		if(!session /*|| session->GetInstance() != 0*/) //Need some sort of mapmgr implemented
		{
			Sessions.erase(it2);
			continue;
		}

		if((result = session->Update()) != 0)
		{
			if(result == 1)
			{
				// complete deletion
				DeleteSession(session);
			}
			Sessions.erase(it2);
		}
	}
}
Exemplo n.º 3
0
void World::Update(float timeelapsed)
{
	start = now();
	diff = start - last_time;
	SessionSet::iterator itr, it2;
	SFPlayerSession *session;
	int result;
	for(itr = Sessions.begin(); itr != Sessions.end();)
	{
		session = (*itr);
		it2 = itr;
		++itr;
		if(!session /*|| session->GetInstance() != 0*/) //Need some sort of mapmgr implemented
		{
			Sessions.erase(it2);
			continue;
		}

		if((result = session->Update()) != 0)
		{
			if(result == 1)
			{
				// complete deletion
				DeleteSession(session);
			}
			Sessions.erase(it2);
		}
	}
	//sSocketGarbageCollector.Update();
	last_time = now();
	etime = last_time - start;
	//if( 50 > etime )
	//	WaitForSingleObject( sCore.GetCoreThread(), 50 - etime );
}
TPM_RC EndAuthSession( SESSION *session )
{
    TPM_RC rval = TPM_RC_SUCCESS;
    
    DeleteSession( session );

    return rval;
}   
Exemplo n.º 5
0
void TestManager::TestMailProcess_Disinfect (const string& data_folder)
{
	LOG_CALL3("Test folder ",data_folder,"\n");

	GetObjects(h_Proto, h_TaskManager, h_TrafficMonitor);
	tERROR error = h_TrafficMonitor->sysRegisterMsgHandler(pmc_TASK_STATE_CHANGED, rmhLISTENER,
		h_TrafficMonitor, IID_ANY, PID_ANY, IID_ANY, PID_ANY );
	SetEvent (hProtoStateChangeExpected);
	h_Proto->SetState (TASK_REQUEST_RUN);
	WaitForSingleObject (hProtoStateChanged, INFINITE);
	_ASSERTE (m_ProtoState = TASK_STATE_RUNNING);


	SessionData* p_SD = SessionData::StartSession (this);

	auto_ptr<vector<string> > packets = aux::get_raw_packets (data_folder.c_str());
	auto_ptr<vector<aux::output_packet> > out_packets = aux::get_output_packets ((hOBJECT)g_root, data_folder.c_str());
	auto_ptr<vector<hIO> > control_files = aux::get_control_files ((hOBJECT)g_root, data_folder.c_str());

	CONFIGURE(10000,100)	

	vector<string> packets_in1;
	vector<aux::output_packet> packets_out1;

	//до FETCH включительно
	packets_in1.assign (packets->begin(), packets->begin() + 8);
	packets_out1.assign (out_packets->begin(), out_packets->begin() + 8);
	p_SD->SendBytesToProcess (&packets_in1, &packets_out1);

	//ответ на FETCH (подменим файл aka пролечили)
	bTraceMailProcess = true;

	SetEvent (hMailProcessExpected);
	mc_ToProto_flags = mcv_MESSAGE_AV_DISINFECTED;
	mc_ToProto_virname = "Mega.Virus";
	io_ToProto = aux::create_io_from_disk (std::string(data_folder).append("\\object.09.chk.mod"));

	//само сообщение
	packets_in1.assign (packets->begin()+8, packets->begin() + 9);
	packets_out1.assign (out_packets->begin()+8, out_packets->begin() + 9);
	p_SD->SendBytesToProcess (&packets_in1, &packets_out1);

	WaitForSingleObject (hMailProcessReceived, INFINITE);

	//и остальное
	bTraceMailProcess = false;
	packets_in1.assign (packets->begin()+9, packets->end() );
	packets_out1.assign (out_packets->begin()+9, out_packets->end() );
	p_SD->SendBytesToProcess (&packets_in1, &packets_out1);

	p_SD->VerifyCheckedObjects (control_files.get());
	p_SD->VerifyConnStream (out_packets.get());

	p_SD->StopSession ();
	DeleteSession (p_SD->_sessionCtx.pdwSessionCtx[TEST_PROTO]);

	//_ASSERTE(!"Halt");
}
Exemplo n.º 6
0
void Server::StopSession(STRARR& cmd)
{
	if (cmd.size()>0)
	{
		int sck = atoi(cmd[0].c_str());
		DeleteSession(sck);
	}
	else
		cout<<"stopses [sck]\n";
}
Exemplo n.º 7
0
int CleanHashTable(SFXHASH *table, u_int32_t thetime, Session *save_me, int memCheck)
{
    Session *idx;
    u_int32_t pruned = 0;
    u_int32_t timeout = s4data.timeout;

    if (thetime != 0)
    {
        char got_one;
        idx = (Session *) sfxhash_lru(table);

        if(idx == NULL)
        {
            return 0;
        }

        do
        {
            got_one = 0;            
            if(idx == save_me)
            {
                SFXHASH_NODE *lastNode = sfxhash_lru_node(table);
                sfxhash_gmovetofront(table, lastNode);
                lastNode = sfxhash_lru_node(table);
                if ((lastNode) && (lastNode->data != idx))
                {
                    idx = (Session *)lastNode->data;
                    continue;
                }
                else
                {
                    return pruned;
                }
            }

            timeout = s4data.timeout;
            if(idx->drop_traffic)
            {
                /* If we're dropping traffic on the session, keep
                 * it around longer.  */
                timeout = s4data.timeout * 2;
            }

            if((idx->last_session_time+timeout) < thetime)
            {
                Session *savidx = idx;

                if(sfxhash_count(table) > 1)
                {
                    DEBUG_WRAP(DebugMessage(DEBUG_STREAM, "pruning stale session\n"););
                    DeleteSession(savidx, thetime, SESSION_CLOSED_TIMEDOUT);
                    idx = (Session *) sfxhash_lru(table);
                    pruned++;
                    got_one = 1;
                }
Exemplo n.º 8
0
MRESULT EXPENTRY clientProc( HWND hwnd, USHORT msg, MPARAM mp1, MPARAM mp2 )
/**************************************************************************/
{
    switch( msg ) {
    case WM_DDE_INITIATE: { // editor has started
        DDEINIT *ddei = (PDDEINIT)mp2;
        if( (strcmp( "WB Editor", (char *)ddei->pszAppName ) == 0) &&
                (stricmp( CurrSession->file_name, (char *)ddei->pszTopic ) == 0) ) {
            // make sure that we are expecting a session to be started - more
            // than one application may be using the DLL (i.e. the IDE and
            // browser)
            if( StartingSessionInProgress ) {
                CurrSession->hwnd = (HWND)mp1;
                StartingSessionInProgress = FALSE;
                Connect();
            }
        }
        DosFreeMem( ddei );
        return( (MRESULT)TRUE );
    }
    case WM_DDE_INITIATEACK: { // response from EPM after WinDdeInitiate()
        DDEINIT *ddei = (PDDEINIT)mp2;
        session *sess = FindSessionByHWND( (HWND)mp1 );
        if (sess != NULL) {
            sess->connected = TRUE;
            if( sess->msg != NULL ) {
                SendData( sess->msg, TRUE );
            }
        }
        DosFreeMem( ddei );
        return( (MRESULT)TRUE );
    }
    case WM_DDE_ACK: { // acknowledgement from EPM
        DDESTRUCT *ddes = (PDDESTRUCT)mp2;
        DosFreeMem( ddes );
        break;
    }
    case WM_DDE_DATA: { // request to send "Goto" message to EPM
        session *sess = FindSessionByHWND( (HWND)mp1 );
        if (sess != NULL)
            SendData( sess->msg, FALSE );
        break;
    }
    case WM_DDE_TERMINATE: {
        WinDdePostMsg( (HWND)mp1, hwndDDE, WM_DDE_TERMINATE, NULL, 0 );
        DeleteSession( (HWND)mp1 );
        break;
    }
    default:
        return( prevClientProc( hwnd, msg, mp1, mp2 ) );
    }
    return( 0 );
}
Exemplo n.º 9
0
static	void
SessionThread(
	void	*para)
{
	SessionCtrl *ctrl;
	GHashTable *hash;
ENTER_FUNC;
	workq = NewQueue();
	hash = NewNameHash();
	RecParserInit();
	while (TRUE) {
		ctrl = (SessionCtrl *)DeQueue(workq);
		switch (ctrl->type) {
		case SESSION_CONTROL_INSERT:
			InsertSession(hash,ctrl);
			break;
		case SESSION_CONTROL_UPDATE:
			UpdateSession(hash,ctrl);
			break;
		case SESSION_CONTROL_DELETE:
			DeleteSession(hash,ctrl);
			break;
		case SESSION_CONTROL_LOOKUP:
			LookupSession(hash,ctrl);
			break;
		case SESSION_CONTROL_GET_SESSION_NUM:
			GetSessionNum(hash,ctrl);
			break;
		case SESSION_CONTROL_GET_DATA:
			GetData(hash,ctrl);
			break;
		case SESSION_CONTROL_GET_MESSAGE:
			GetMessage(hash,ctrl);
			break;
		case SESSION_CONTROL_RESET_MESSAGE:
			ResetMessage(hash,ctrl);
			break;
		case SESSION_CONTROL_SET_MESSAGE:
			SetMessage(hash,ctrl);
			break;
		case SESSION_CONTROL_SET_MESSAGE_ALL:
			SetMessageAll(hash,ctrl);
			break;
		case SESSION_CONTROL_GET_DATA_ALL:
			GetDataAll(hash,ctrl);
			break;
		}
		EnQueue(ctrl->waitq,ctrl);
	}
	pthread_exit(NULL);
LEAVE_FUNC;
}
Exemplo n.º 10
0
void SessionManager::DeleteAll()
{
    assert(num_sess == session_pool.size());
    
    if(!session_pool.empty()) {
        std::vector<SessID> ids = GetCurrentIDs();
        
        for(size_t i=0; i<ids.size(); i++) {
            kserver.syslog.print(SysLog::INFO, "Delete session %u\n", ids[i]);            
            DeleteSession(ids[i]);
        }
    }
    
    assert(num_sess == 0);
}
Exemplo n.º 11
0
void NXConnection::HandleCleanup()
{
  NX_LOG_LOGDEBUG( "cleaning up NXConnection.");
  if( pSession )
    DeleteSession( pSession );
  if( pConnection )
  {
    NX_LOG_LOGDEBUG( "deleting Server Connection");
    DeleteServerConnection( pConnection );
  }
  if( pProxy )
    DeleteProxyConnection( pProxy );
  if( pXServer )
    DeleteXServerConnection( pXServer );
  NX_LOG_LOGDEBUG( "NXConnection clean.");
}
Exemplo n.º 12
0
void TestManager::TestDD (const string& data_folder)
{
	LOG_CALL3("Test folder ",data_folder,"\n");

	SessionData* p_SD = SessionData::StartSession (this);

	auto_ptr<vector<string> > packets = aux::get_raw_packets (data_folder.c_str());
	auto_ptr<vector<aux::output_packet> > out_packets = aux::get_output_packets ((hOBJECT)g_root, data_folder.c_str());
	auto_ptr<vector<hIO> > control_files = aux::get_control_files ((hOBJECT)g_root, data_folder.c_str());

	CONFIGURE(100000,10)	//осторожнее, чтобы не попасть посередине 0D0A (баг)

	p_SD->SendBytesToProcess (packets.get(), out_packets.get(), true);

	p_SD->VerifyCheckedObjects (control_files.get());
	p_SD->VerifyConnStream (out_packets.get());

	p_SD->StopSession ();
	DeleteSession (p_SD->_sessionCtx.pdwSessionCtx[TEST_PROTO]);

}
Exemplo n.º 13
0
    //! \brief Update a session upon request from a controller
    void UpdateSession(com::xvd::neuron::scp::Control *control)
    {
        map<int,RemoteSession*>::iterator it;
		char cmdbuf[128];
		
        PrintLog("Update session %d received from %d\n",control->sessionId,control->srcId);
        
		sprintf(cmdbuf,"delete session %d",control->sessionId);
		
		if (!strcmp(control->script,cmdbuf))
		{
			DeleteSession(control->sessionId);
		} 
		else
		{
			it = rsessions.find(control->sessionId);
			if (it != rsessions.end())
			{
				it->second->Update(control);
			}
		}
    }
Exemplo n.º 14
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;
}
Exemplo n.º 15
0
void Webserver::CheckSessions()
{
	// Check if any HTTP session can be purged
	const uint32_t time = millis();
	for (size_t i = 0; i < numSessions; ++i)
	{
		if ((time - sessions[i].lastQueryTime) > httpSessionTimeout)
		{
			DeleteSession(sessions[i].ip);
			clientsServed++;	// assume the disconnected client hasn't fetched the G-Code reply yet
		}
	}

	// If we cannot send the G-Code reply to anyone, we may free up some run-time space by dumping it
	if (numSessions == 0 || clientsServed >= numSessions)
	{
		while (!gcodeReply->IsEmpty())
		{
			OutputBuffer::ReleaseAll(gcodeReply->Pop());
		}
		clientsServed = 0;
	}
}
Exemplo n.º 16
0
// Process the first fragment of input from the client.
// Return true if the session should be kept open.
bool Webserver::ProcessFirstFragment(HttpSession& session, const char* command, bool isOnlyFragment)
{
	// Process connect messages first
	if (StringEquals(command, "connect") && GetKeyValue("password") != nullptr)
	{
		OutputBuffer *response;
		if (OutputBuffer::Allocate(response))
		{
			if (session.isAuthenticated || reprap.CheckPassword(GetKeyValue("password")))
			{
				// Password is OK, see if we can update the current RTC date and time
				const char *timeVal = GetKeyValue("time");
				if (timeVal != nullptr && !platform->IsDateTimeSet())
				{
					struct tm timeInfo;
					memset(&timeInfo, 0, sizeof(timeInfo));
					if (strptime(timeVal, "%Y-%m-%dT%H:%M:%S", &timeInfo) != nullptr)
					{
						time_t newTime = mktime(&timeInfo);
						platform->SetDateTime(newTime);
					}
				}

				// Client has logged in
				session.isAuthenticated = true;
				response->printf("{\"err\":0,\"sessionTimeout\":%u,\"boardType\":\"%s\"}", httpSessionTimeout, platform->GetBoardString());
			}
			else
			{
				// Wrong password
				response->copy("{\"err\":1}");
			}
			network->SendReply(session.ip, 200 | rcJson, response);
		}
		else
		{
			// If we failed to allocate an output buffer, send back an error string
			network->SendReply(session.ip, 200 | rcJson, "{\"err\":2}");
		}
		return false;
	}

	if (StringEquals(command, "disconnect"))
	{
		network->SendReply(session.ip, 200 | rcJson, "{\"err\":0}");
		DeleteSession(session.ip);
		return false;
	}

	// Try to authorise the user automatically to retain compatibility with the old web interface
	if (!session.isAuthenticated && reprap.NoPasswordSet())
	{
		session.isAuthenticated = true;
	}

	// If the client is still not authenticated, stop here
	if (!session.isAuthenticated)
	{
		network->SendReply(session.ip, 500, "Not authorized");
		return false;
	}

	if (StringEquals(command, "reply"))
	{
		SendGCodeReply(session);
		return false;
	}

	// rr_configfile sends the config as plain text well
	if (StringEquals(command, "configfile"))
	{
		const char *configPath = platform->GetMassStorage()->CombineName(platform->GetSysDir(), platform->GetConfigFile());
		char fileName[FILENAME_LENGTH];
		strncpy(fileName, configPath, FILENAME_LENGTH);

		SendFile(fileName, session);
		return false;
	}

	if (StringEquals(command, "download") && GetKeyValue("name") != nullptr)
	{
		SendFile(GetKeyValue("name"), session);
		return false;
	}

	if (StringEquals(command, "upload"))
	{
		const char* nameVal = GetKeyValue("name");
		const char* lengthVal = GetKeyValue("length");
		const char* timeVal = GetKeyValue("time");
		if (nameVal != nullptr && lengthVal != nullptr)
		{
			// Try to obtain the last modified time
			time_t fileLastModified = 0;
			struct tm timeInfo;
			memset(&timeInfo, 0, sizeof(timeInfo));
			if (timeVal != nullptr && strptime(timeVal, "%Y-%m-%dT%H:%M:%S", &timeInfo) != nullptr)
			{
				fileLastModified = mktime(&timeInfo);
			}

			// Deal with file upload request
			uint32_t fileLength = atol(lengthVal);
			StartUpload(session, nameVal, fileLength, fileLastModified);
			if (session.uploadState == uploading)
			{
				if (isOnlyFragment)
				{
					FinishUpload(session);
					return false;
				}
				else
				{
					network->DiscardMessage();		// no reply needed yet
					return true;		// expecting more data
				}
			}
		}

		network->SendReply(session.ip, 200 | rcJson, "{\"err\":1}");	// TODO return the cause of the error
		return false;
	}

	if (StringEquals(command, "move"))
	{
		const char* response =  "{\"err\":1}";		// assume failure
		const char* const oldVal = GetKeyValue("old");
		const char* const newVal = GetKeyValue("new");
		if (oldVal != nullptr && newVal != nullptr)
		{
			const bool success = platform->GetMassStorage()->Rename(oldVal, newVal);
			if (success)
			{
				response =  "{\"err\":0}";
			}
		}
		network->SendReply(session.ip, 200 | rcJson, response);
		return false;
	}

	if (StringEquals(command, "mkdir"))
	{
		const char* response =  "{\"err\":1}";		// assume failure
		const char* dirVal = GetKeyValue("dir");
		if (dirVal != nullptr)
		{
			bool ok = (platform->GetMassStorage()->MakeDirectory(dirVal));
			if (ok)
			{
				response =  "{\"err\":0}";
			}
		}
		network->SendReply(session.ip, 200 | rcJson, response);
		return false;
	}

	if (StringEquals(command, "delete"))
	{
		const char* response =  "{\"err\":1}";		// assume failure
		const char* nameVal = GetKeyValue("name");
		if (nameVal != nullptr)
		{
			bool ok = platform->GetMassStorage()->Delete("0:/", nameVal);
			if (ok)
			{
				response =  "{\"err\":0}";
			}
		}
		network->SendReply(session.ip, 200 | rcJson, response);
		return false;
	}

	// The remaining commands use an OutputBuffer for the response
	OutputBuffer *response = nullptr;
	if (StringEquals(command, "status"))
	{
		const char* typeVal = GetKeyValue("type");
		if (typeVal != nullptr)
		{
			// New-style JSON status responses
			int type = atoi(typeVal);
			if (type < 1 || type > 3)
			{
				type = 1;
			}

			response = reprap.GetStatusResponse(type, ResponseSource::HTTP);
		}
		else
		{
			response = reprap.GetLegacyStatusResponse(1, 0);
		}
	}
	else if (StringEquals(command, "gcode"))
	{
		const char* gcodeVal = GetKeyValue("gcode");
		if (gcodeVal != nullptr)
		{
			RegularGCodeInput * const httpInput = reprap.GetGCodes()->GetHTTPInput();
			httpInput->Put(HTTP_MESSAGE, gcodeVal);
			if (OutputBuffer::Allocate(response))
			{
				response->printf("{\"buff\":%u}", httpInput->BufferSpaceLeft());
			}
		}
		else
		{
			network->SendReply(session.ip, 200 | rcJson, "{\"err\":1}");
			return false;
		}
	}
	else if (StringEquals(command, "filelist") && GetKeyValue("dir") != nullptr)
	{
		response = reprap.GetFilelistResponse(GetKeyValue("dir"));
	}
	else if (StringEquals(command, "files"))
	{
		const char* dir = GetKeyValue("dir");
		if (dir == nullptr)
		{
			dir = platform->GetGCodeDir();
		}
		const char* const flagDirsVal = GetKeyValue("flagDirs");
		const bool flagDirs = flagDirsVal != nullptr && atoi(flagDirsVal) == 1;
		response = reprap.GetFilesResponse(dir, flagDirs);
	}
	else if (StringEquals(command, "fileinfo"))
	{
		const char* const nameVal = GetKeyValue("name");
		if (reprap.GetPrintMonitor()->GetFileInfoResponse(nameVal, response))
		{
			processingDeferredRequest = false;
		}
		else
		{
			processingDeferredRequest = true;
		}
	}
	else if (StringEquals(command, "config"))
	{
		response = reprap.GetConfigResponse();
	}
	else
	{
		platform->MessageF(HOST_MESSAGE, "KnockOut request: %s not recognised\n", command);
		network->SendReply(session.ip, 400, "Unknown rr_ command");
		return false;
	}

	if (response != nullptr)
	{
		network->SendReply(session.ip, 200 | rcJson, response);
	}
	else if (!processingDeferredRequest)
	{
		network->SendReply(session.ip, 500, "No buffer available");
	}
	return processingDeferredRequest;
}
Exemplo n.º 17
0
DWORD CSerialServer::ReadProc()
{
    OVERLAPPED osReader;						// Overlapped structure for read operations
    OVERLAPPED osStatus;						// Overlapped structure for status operations
    HANDLE     arEvents[3];						// Event Array	
    DWORD      dwStoredFlags;					// Local copy of event flags
    DWORD      dwCommEvent=0;					// Result from WaitCommEvent
    DWORD 	   dwRead;							// Bytes actually read
#ifndef WINCE
    DWORD      dwResult;						// Result from WaitForSingleObject
#endif
    BOOL       fWaitingOnRead;
    BOOL       fWaitingOnStat;
    BOOL       fThreadDone;
#ifndef WINCE
    DWORD      dwOvRes;							// Result from GetOverlappedResult
#endif

	m_pSaveSession = NewSession(m_hComPort, m_szDevice);
	OnEnterSession(m_pSaveSession);

    dwStoredFlags	= 0xFFFFFFFF;
    fWaitingOnRead	= FALSE;
    fWaitingOnStat	= FALSE;
    fThreadDone		= FALSE;

    // Create two overlapped structures, one for read events
    // and another for status events
	memset(&osReader, 0, sizeof(OVERLAPPED));
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osReader.hEvent == NULL)
        XDEBUG("[CSerialServer] CreateEvent (Reader Event).\n");

	memset(&osStatus, 0, sizeof(OVERLAPPED));
    osStatus.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osStatus.hEvent == NULL)
        XDEBUG("[CSerialServer] CreateEvent (Status Event).\n");

    arEvents[0] = m_hReadStopEvent;
    arEvents[1] = osReader.hEvent;
    arEvents[2] = osStatus.hEvent;

    // Initial Check, Forces Updates
	CheckModemStatus(TRUE);
	CheckComStat(TRUE);

	m_bRecvReady = TRUE;
    while(!fThreadDone && !m_bDisconnectPending)
	{
		if (m_bPassiveMode)
		{
			Sleep(100);
			continue;
		}

		if (!ReadFile(m_hComPort, m_szBuffer, DEFAULT_SIO_BUFFER, &dwRead, &osReader))
		{
			// Read not delayed?
			if (GetLastError() != ERROR_IO_PENDING)
				XDEBUG("[CSerialComm] ReadFile in ReaderAndStatusProc.\r\n");
		}
#ifndef WINCE
		else
		{
			// Read Completed Immediately
			if ((dwRead != MAX_READ_BUFFER) && m_bDisplayTimeouts)
				XDEBUG("[CSerialComm] Read timed out immediately.\r\n");
		}

		dwResult = WaitForMultipleObjects(3, arEvents, FALSE, STATUS_CHECK_TIMEOUT);
		switch(dwResult) {
          case WAIT_OBJECT_0 : // Thread Exit Event
			   fThreadDone = TRUE;
			   break;

		  case WAIT_OBJECT_0 + 1 : // Read Completed
			   if (!GetOverlappedResult(m_hComPort, &osReader, &dwRead, FALSE))
			   {
				   if (GetLastError() == ERROR_OPERATION_ABORTED)
					   XDEBUG("[CSerialComm] Read aborted.\r\n");
				   else ErrorHandler(const_cast<char*>("[CSerialServer] GetOverlappedResult (in Reader).\r\n"));
			   }
			   else
			   {	
				   // Read Completed Successfully
				   if ((dwRead != MAX_READ_BUFFER) && m_bDisplayTimeouts)
					   XDEBUG("[CSerialComm] Read timed out overlapped.\r\n");

				   if (dwRead > 0)
						OnReceiveSession(m_pSaveSession, (char *)m_szBuffer, dwRead);
			   }
			   fWaitingOnRead = FALSE;
			   break;

		  case WAIT_OBJECT_0 + 2 : // Status Completed
			   if (!GetOverlappedResult(m_hComPort, &osStatus, &dwOvRes, FALSE))
			   {
				   if (GetLastError() == ERROR_OPERATION_ABORTED)
						XDEBUG("[CSerialServer] WaitCommEvent aborted.\n");
				   else ErrorHandler(const_cast<char*>("[CSerialServer] GetOverlappedResult (in Reader).\r\n"));
			   }
			   else
			   {
				   // status check completed successfully
				   ReportStatusEvent(dwCommEvent);
			   }
			   fWaitingOnStat = FALSE;
			   break;

            case WAIT_TIMEOUT:
                // If status checks are not allowed, then don't issue the
                // modem status check nor the com stat check
                if (!m_bNoStatus)
				{
                    CheckModemStatus(FALSE);
                    CheckComStat(FALSE);
                }
                break;                       

            default:
                XDEBUG("[CSerialServer] WaitForMultipleObjects(Reader & Status handles).\r\n");
                break;
        }
#else
		if (dwRead > 0)
			OnReceiveSession(m_pSaveSession, (char *)m_szBuffer, dwRead);
#endif
    }

	OnLeaveSession(m_pSaveSession);
	DeleteSession(m_pSaveSession);

	// Set SendThread Exit Event
	SetEvent(m_hThreadExitEvent);
	m_bExitWriter = TRUE;

	WaitForSingleObject(m_hSendTerminateEvent, 5000);

    // Close event handles
    CloseHandle(osReader.hEvent);
    CloseHandle(osStatus.hEvent);

	// Set Terminate Signal
	SetEvent(m_hReadTerminateEvent);
	return 0;
}
Exemplo n.º 18
0
static void
ChooseSessionDeleteXtProc(Widget w, XtPointer client_data, XtPointer callData)
{
    XawListReturnStruct *current;
    int longest;
    char *name;

    CheckBreakLockCancel ();

    current = XawListShowCurrent (chooseSessionListWidget);

    if (!current || !(name = current->string) || *name == '\0')
    {
	if (current)
	    XtFree ((char *) current);
#ifdef XKB
	XkbStdBell(XtDisplay(w),XtWindow(w),0,XkbBI_BadValue);
#else
	XBell (XtDisplay (topLevel), 0);
#endif
	return;
    }

    delete_session_phase++;

    if (delete_session_phase == 1)
    {
	XtVaSetValues (chooseSessionMessageLabel,
	    XtNforeground, save_message_foreground,
            NULL);

#ifdef XKB
	XkbStdBell(XtDisplay(w),XtWindow(w),0,XkbBI_BadValue);
#else
	XBell (XtDisplay (topLevel), 0);
#endif
    }
    else
    {
	XtVaSetValues (chooseSessionMessageLabel,
	    XtNforeground, save_message_background,
            NULL);

	if (DeleteSession (name))
	{
	    int i, j;

	    for (i = 0; i < sessionNameCount; i++)
	    {
		if (strcmp (sessionNamesLong[i], name) == 0)
		{
		    XtFree ((char *) sessionNamesShort[i]);

		    if (sessionsLocked[i])
			XtFree ((char *) sessionNamesLong[i]);

		    for (j = i; j < sessionNameCount - 1; j++)
		    {
			sessionNamesLong[j] = sessionNamesLong[j + 1];
			sessionNamesShort[j] = sessionNamesShort[j + 1];
			sessionsLocked[j] = sessionsLocked[j + 1];
		    }
		    sessionNameCount--;
		    break;
		}
	    }

	    if (sessionNameCount == 0)
	    {
		XtSetSensitive (chooseSessionLoadButton, 0);
		XtSetSensitive (chooseSessionDeleteButton, 0);
		XtUnmanageChild (chooseSessionListWidget);
	    }
	    else
	    {
		XtVaGetValues (chooseSessionListWidget,
		    XtNlongest, &longest,
		    NULL);

		XawListChange (chooseSessionListWidget,
		    sessionNamesLong, sessionNameCount, longest, True);

		SessionSelected (-1, False);
	    }
	}

	delete_session_phase = 0;
    }

    XtFree ((char *) current);
}
Exemplo n.º 19
0
void CSerialServer::LeaveSession(WORKSESSION *pSession)
{
	OnLeaveSession(pSession);
	DeleteSession(pSession);
}
//
// 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 );
}