Esempio n. 1
0
void cLuaTCPLink::OnError(int a_ErrorCode, const AString & a_ErrorMsg)
{
	// Call the callback:
	m_Callbacks->CallTableFn("OnError", this, a_ErrorCode, a_ErrorMsg);

	// Terminate all processing on the link:
	Terminated();
}
Esempio n. 2
0
void cLuaTCPLink::OnRemoteClosed(void)
{
	// Call the callback:
	m_Callbacks->CallTableFn("OnRemoteClosed", this);

	// Terminate all processing on the link:
	Terminated();
}
Esempio n. 3
0
void cLuaTCPLink::Close(void)
{
	// If the link is still open, close it:
	cTCPLinkPtr link = m_Link;
	if (link != nullptr)
	{
		link->Close();
	}

	Terminated();
}
Esempio n. 4
0
cLuaTCPLink::~cLuaTCPLink()
{
	// If the link is still open, close it:
	auto link = m_Link;
	if (link != nullptr)
	{
		link->Close();
	}

	Terminated();
}
Esempio n. 5
0
/** The Looper's Run() method - which is executed within the context
 * of the Looper's thread - is responsible for listening on the Looper's
 * port. It receives any Message and Pulse which is sent to it.
 *
 * The Looper waits on incoming IPC and handles it on a case-by-case
 * basis. The loop itself is checking Thread's Terminated() flag on
 * each iteration.  Hence, calling Terminate() on the Looper() will not
 * do much until the Looper is woken up by an IPC and it has a chance
 * to check the Terminated() flag.
 *
 * However, you don't want to do this.  Call Quit() instead. It will
 * wrap things up nicely.
 * 
 * \return 0 for a successful finish.
 */
int Looper::Run()
{
   int source_pid;
   int source_port;
   int dest_port;
   uint32 d1,d2,d3,d4,d5,d6;
   int length;


   while ( Terminated() == false  )
   {
      smk_go_dormant();

		// Check for pulses		
      if ( smk_recv_pulse( &source_pid, 
  		    			  &source_port, 
						  &dest_port,
                          &d1, &d2, &d3, &d4, &d5, &d6) == 0 )
      {
      
         Pulse p( d1,d2,d3,d4,d5,d6 );
	       p.source_pid  = source_pid;
	       p.source_port = source_port;
	       p.dest_port   = dest_port;

		   PulseReceived( &p );
      }

      if ( smk_peek_message( &source_pid, &source_port, &dest_port, &length ) == 0 )
      {
	     void *data = malloc( length );

	     if ( smk_recv_message( &source_pid, &source_port, &dest_port, length, data ) >= 0 )
	     {
	        Message *msg = new Message();
			if ( msg->Unflatten( (const char*)data ) != -1 )
			{
			  msg->_source_pid   = source_pid;
			  msg->_source_port  = source_port;
			  msg->_dest_port    = dest_port;
		
			  MessageReceived( msg );
	        }
			delete msg;
	     }

	     free( data );
      }
	   
   }

     return 0;
}
Esempio n. 6
0
void CCoFAHost::Execute(void*)
{
    Log.Add(_MESSAGE_,_T("CCoFAHost::Execute()"));

    CoInitializeEx(NULL,COINIT_MULTITHREADED);
    SET_THREAD_LS;

    TRY_CATCH

    MSG msg;
    HRESULT result;
    if(!m_brokerEvents.m_dwCookie)
        throw MCException("_IBrokerClientEvents has not set. Call IBrokerClient::Init() method at first");

    //CComPtr<_IBrokerClientEvents> brokerEvents;
    //if(S_OK!=(result=m_brokerEvents.CopyTo(&brokerEvents)))
    //	throw CExceptionBase(__LINE__,_T(__FILE__),_T(__DATE__),tstring(_T("IBrokerClientEvents obtaining failed in Broker")),result);

    while(!Terminated() && GetMessage(&msg, NULL, 0, 0))
    {
        switch(msg.message)
        {
        case WM_USER:
        {
            Log.Add(_MESSAGE_,_T("CCoFAHost::Execute(WM_USER)"));

            CComPtr<_IBrokerClientEvents> brokerEvents;
            if(S_OK!=(result=m_brokerEvents.CopyTo(&brokerEvents)))
                throw CExceptionBase(__LINE__,_T(__FILE__),_T(__DATE__),tstring(_T("IBrokerClientEvents obtaining failed in Broker")),result);

            boost::shared_ptr<TCHAR> str;
            str.reset(reinterpret_cast<PTCHAR>(msg.wParam), free);
            tstring activity(str.get());
            tstring params = activity.empty()?_T("File manager"):Format(_T("File manager;;%s"),activity.c_str());

            if(NULL != brokerEvents.p)
            {
                //TODO error handling
                brokerEvents->RequestSent(CComBSTR(BUSERIDPDV_LOCAL),BSVCIDPDV_JS,CComBSTR(BUSERIDPDV_AUTOSET),BSVCIDPDV_AUTOSET,0/*rid*/,BRT_SRV_STATE_CHANGED,ESM_SERVICE_ACTIVITY_CHANGED,CComBSTR(params.c_str()));
            }
        }
        break;
        default:
            Log.Add(_WARNING_,_T("Unexpected message %d received"), msg.message);
        }
    }
    CATCH_LOG()
    CoUninitialize();
}
Esempio n. 7
0
function<void()> ThreadPool::nextjob()
{
    unique_lock<mutex> lock(m_lock);
    while (!m_terminate)
    {
        if (!m_jobs.empty())
        {
            function<void()> job = m_jobs.front();
            m_jobs.pop();
            return job;
        }
        m_queued.wait(lock);
    }
    throw Terminated();
}
Esempio n. 8
0
void CComUDPListener::Execute(void*)
{
	DISABLE_TRACE;
	SET_THREAD_LS;
	
	try
	{
		while(!Terminated())
		{
			// Wait for incoming messages
			if(!m_socket.ReadSelect(NETLOG_UDP_SELECT_TIME))
				continue;

			tstring remoteAddr;
			unsigned int remotePort;
			memset(m_buffer, 0, NETLOG_UDP_BUFFER_SIZE);

			// Receive message
			unsigned int received = m_socket.ReceiveFrom(remoteAddr, remotePort, m_buffer, NETLOG_UDP_BUFFER_SIZE);

			if(!received)
				continue;

			// Validating message
			tstring msg(m_buffer);
			if(msg == NETLOG_UDP_SERVER_REQUEST)
			{
				try
				{
					// Standard event mechanism
					//USES_CONVERSION;
					// Raise event
					//BSTR addr = ::SysAllocString(T2OLE(remoteAddr.c_str()));
					//OnDatagramReceived(addr, remotePort);
					//SysFreeString(addr);

					InvokeOnDatagramReceived(remoteAddr, remotePort);
				}
				catch(...)
				{
				}
			}
		}
	}
	catch(...)
	{
	}
}
Esempio n. 9
0
static value caml_thread_new_descriptor(value clos)
{
  value mu = Val_unit;
  value descr;
  Begin_roots2 (clos, mu)
    /* Create and initialize the termination semaphore */
    mu = caml_threadstatus_new();
    /* Create a descriptor for the new thread */
    descr = alloc_small(3, 0);
    Ident(descr) = Val_long(thread_next_ident);
    Start_closure(descr) = clos;
    Terminated(descr) = mu;
    thread_next_ident++;
  End_roots();
  return descr;
}
Esempio n. 10
0
static void caml_thread_stop(void)
{
#ifndef NATIVE_CODE
  /* PR#5188: update curr_thread->stack_low because the stack may have
     been reallocated since the last time we entered a blocking section */
  curr_thread->stack_low = stack_low;
#endif
  /* Signal that the thread has terminated */
  caml_threadstatus_terminate(Terminated(curr_thread->descr));
  /* Remove th from the doubly-linked list of threads and free its info block */
  caml_thread_remove_info(curr_thread);
  /* OS-specific cleanups */
  st_thread_cleanup();
  /* Release the runtime system */
  st_masterlock_release(&caml_master_lock);
}
Esempio n. 11
0
void cLuaTCPLink::OnRemoteClosed(void)
{
	// Check if we're still valid:
	if (!m_Callbacks.IsValid())
	{
		return;
	}

	// Call the callback:
	cPluginLua::cOperation Op(m_Plugin);
	if (!Op().Call(cLuaState::cTableRef(m_Callbacks, "OnRemoteClosed"), this))
	{
		LOGINFO("cTCPLink OnRemoteClosed() callback failed in plugin %s.", m_Plugin.GetName().c_str());
	}

	Terminated();
}
Esempio n. 12
0
void cLuaTCPLink::Close(void)
{
	// If the link is still open, close it:
	cTCPLinkPtr Link = m_Link;
	if (Link != nullptr)
	{
		if (m_SslContext != nullptr)
		{
			m_SslContext->NotifyClose();
			m_SslContext->ResetSelf();
			m_SslContext.reset();
		}
		Link->Close();
	}

	Terminated();
}
Esempio n. 13
0
void cLuaTCPLink::OnError(int a_ErrorCode, const AString & a_ErrorMsg)
{
	// Check if we're still valid:
	if (!m_Callbacks.IsValid())
	{
		return;
	}

	// Call the callback:
	cPluginLua::cOperation Op(m_Plugin);
	if (!Op().Call(cLuaState::cTableRef(m_Callbacks, "OnError"), this, a_ErrorCode, a_ErrorMsg))
	{
		LOGINFO("cTCPLink OnError() callback failed in plugin %s; the link error is %d (%s).",
			m_Plugin.GetName().c_str(), a_ErrorCode, a_ErrorMsg.c_str()
		);
	}

	Terminated();
}
Esempio n. 14
0
 void Emitter::Update(float deltaSeconds)
 {
     int &activeParticles = pimpl->activeParticles;
     int &maximumParticles = pimpl->maximumParticles;
     
     for(int particleIndex = 0; particleIndex < activeParticles; ++particleIndex)
     {
         Particle &p = pimpl->particles[particleIndex];
         p.time += deltaSeconds;
         
         if(p.time >= p.lifetime)
         {
             std::swap(p, pimpl->particles[activeParticles - 1]);
             particleIndex--;
             activeParticles--;
             continue;
         }
         
         p.position += p.velocity * deltaSeconds;
         p.angle += p.rotationSpeed * deltaSeconds;
     }
     
     if(!Terminated() && !Paused())
     {
         int count = Emit(&pimpl->particles[activeParticles], maximumParticles - activeParticles, deltaSeconds);
         
         if(count > 0)
         {
             for(auto p : pimpl->emitModifiers)
             {
                 p->Process(&pimpl->particles[activeParticles], count);
             }
             
             activeParticles += count;
         }
     }
     
     for(auto p : pimpl->modifiers)
     {
         p->Process(deltaSeconds, pimpl->particles.get(), activeParticles);
     }
 }
Esempio n. 15
0
void cLuaTCPLink::OnRemoteClosed(void)
{
	// Check if we're still valid:
	if (!m_Callbacks.IsValid())
	{
		return;
	}

	// If running in SSL mode and there's data left in the SSL contect, report it:
	auto sslContext = m_SslContext;
	if (sslContext != nullptr)
	{
		sslContext->FlushBuffers();
	}

	// Call the callback:
	cPluginLua::cOperation Op(m_Plugin);
	if (!Op().Call(cLuaState::cTableRef(m_Callbacks, "OnRemoteClosed"), this))
	{
		LOGINFO("cTCPLink OnRemoteClosed() callback failed in plugin %s.", m_Plugin.GetName().c_str());
	}

	Terminated();
}
Esempio n. 16
0
void CNetLogViewer::Execute(void*)
{
TRY_CATCH

	/// Adding internal clients for tests
	/*{
		INetLogClient* newClient;
		tstring clientName;
		clientName = Format(_T("%s:%s"),"192.168.0.5","iexplore.exe");
		SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow().AddCountDays(0));
		DATE date;
		SystemTimeToVariantTime(&sysTime,&date);
		CNetLogClient::CreateInstance(&newClient);
		newClient->put_RecentReply(date);
		newClient->put_Name(CComBSTR(clientName.c_str()));
		newClient->put_IP(CComBSTR("192.168.0.5"));
		m_clients[clientName] = newClient;
		OnClientFound(newClient);
	}
	{
		INetLogClient* newClient;
		tstring clientName;
		clientName = Format(_T("%s:%s"),"192.168.0.3","NWLTest.exe");
		SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow().AddCountDays(1));
		DATE date;
		SystemTimeToVariantTime(&sysTime,&date);
		CNetLogClient::CreateInstance(&newClient);
		newClient->put_RecentReply(date);
		newClient->put_Name(CComBSTR(clientName.c_str()));
		newClient->put_IP(CComBSTR("192.168.0.3"));
		m_clients[clientName] = newClient;
		OnClientFound(newClient);
	}*/

	
	/// Last bCast send time
	cDate lastBCast;
	tstring fromIp;
	unsigned int fromPort;
	char buf[MAX_PATH + 1];
	buf[MAX_PATH] = 0;
	INetLogClient* newClient;
	tstring clientName;
	std::map<tstring, CComPtr<INetLogClient> >::iterator client;
	while(!Terminated())
	{
		/// Freing time quant
		/// Sleep is used instead of SwitchToThread(), cause it forces Dispatcher to switch context
		/// while SwitchToThread switches context only there are scheduled threads
		/// and whis is totally not what we want, cause it will result in 100% CPU usage
		Sleep(1); 	
		
		/// Sending broadcast request
		if (lastBCast < cDate().GetNow().AddMilliSecs(0 - REQUESTS_INTERVAL))
		{
			SendBroadCastRequest();
			lastBCast.GetNow();
			//(cMsgBoxLog()).Add(_MESSAGE_,"BCast sent");

			if (Terminated())
				break;
			/// Cleaning up timed out clients
			CleanUpTimedOutClients();
		}

		if (Terminated())
			break;
		/// Receiving alive replys from clients
		SUDPListenerMsg *msg;
		while (m_udpSocket.GetReadyDataCount())
		{
			memset(buf,0,MAX_PATH); /// TODO:remove
			if (SOCKET_ERROR == m_udpSocket.ReceiveFrom(fromIp, fromPort, buf, MAX_PATH))
			{
				Log.Add(MCSocketStreamException(_T("failed to m_udpSocket.ReceiveFrom")));
				break;
			}
			/// Creating client
			msg = reinterpret_cast<SUDPListenerMsg*>(buf);
			clientName = Format(_T("%s:%d at %s"), msg->m_data, msg->m_process, fromIp.c_str());
			client = m_clients.find(clientName);
			if (client != m_clients.end())
			{
				SYSTEMTIME sysTime = static_cast<SYSTEMTIME>(cDate().GetNow());
				DATE date;
				SystemTimeToVariantTime(&sysTime,&date);
				client->second->put_RecentReply(date);
				client->second->put_TCPPort(msg->m_tcpPort);
				//client
			} else
			{
				CNetLogClient::CreateInstance(&newClient);
				newClient->put_Name(CComBSTR(clientName.c_str()));
				newClient->put_IP(CComBSTR(fromIp.c_str()));
				newClient->put_TCPPort(msg->m_tcpPort);
				m_clients[clientName] = newClient;
				OnClientFound(newClient);
			}
		}
	}

CATCH_LOG()
}
Esempio n. 17
0
void CZQWorkThread::Execute()
{
	DWORD dwBytestransferred;
	HANDLE  hIOCP = (HANDLE)m_parentsocket->m_hCompletionPort;
	SOCKET tsocket = INVALID_SOCKET;
	pBlock block = NULL;

	while (!Terminated())
	{
		DWORD NumberOfBytesRevced = 0;
		DWORD flag = 0;
		CZQCustomClient * client = NULL;

		BOOL ret = GetQueuedCompletionStatus(hIOCP, &dwBytestransferred, (PULONG_PTR)&client, (LPOVERLAPPED*)&block, INFINITE);

		if ((DWORD)block == SHUTDOWN_FLAG)
		{
			Terminate();
		}
		if (Terminated())
		{
			if (client != NULL)
				client->ForceClose();
			break;
		}
		if ((!ret) && dwBytestransferred == 0)
		{
			if (client != NULL)
				client->ForceClose();
			continue;
		}
// 		if ((DWORD)block == DISCONNECT_FLAG)
// 		{
// 			client->ForceClose();
// 			delete(client);
// 		}
		if (((DWORD)block == DISCONNECT_FLAG) && (client != NULL))
		{
			//释放这个客户端
			m_parentsocket->FreeClient(client);
			continue;
		}

		if ((dwBytestransferred != 0) && (ret))
		{
			switch (block->OperatorType)
			{
			case ioRead:
				client->DoRevice(block,dwBytestransferred);
				break;
			case ioWrite:
				client->DoSend(block, dwBytestransferred);
				break;
			default:
				break;
			}
		}
	}

	PostQueuedCompletionStatus(m_parentsocket->m_hCompletionPort, 0, 0, LPOVERLAPPED(SHUTDOWN_FLAG));
}
Esempio n. 18
0
CAMLprim value caml_thread_join(value th)          /* ML */
{
  st_retcode rc = caml_threadstatus_wait(Terminated(th));
  st_check_error(rc, "Thread.join");
  return Val_unit;
}
 void Application::OnTerminated( EventArgs& e )
 {
     Terminated( e );
 }