Esempio n. 1
0
/*
 * Set a new mapping scheme of property impact
 */
void CHarvestSource::setNewImpactScheme()
{
	H_AUTO(CHarvestSource_setNewImpactScheme);
	
	// Set mapping scheme of property impact
	if ( _IsInNewbieMode )
	{
		// Force "low dangers" for 1 newbie extractor
		_IImpactMappingScheme = (uint16)LowDangerMappings[RandomGenerator.rand( 1 )];
	}
	else
	{
		// Normal dangers
		if ( ForageForceImpactScheme.get() == -1 )
			_IImpactMappingScheme = (uint16)RandomGenerator.rand( 5 );
		else
			_IImpactMappingScheme = (uint16)ForageForceImpactScheme.get();
	}

	sendMessageToExtractors( "FORAGE_SOURCE_IMPACT_MODE", (sint32)_IImpactMappingScheme );

#ifdef NL_DEBUG
	nldebug( "FG: map scheme: %u", _IImpactMappingScheme );
#endif
}
Esempio n. 2
0
/***************************************************************************
 *   setStaticFieldFunctionObject
 ***************************************************************************/
bool CCilVm::setStaticFieldFunctionObject( const RID rid,
        const RID ridMethod )
{
    assert( TypeFromToken( ridMethod ) == MDT_METHODDEF );

    //Create function object and store it to static field
    CVmObject newobject;
    RID ridObj = getFunctionObjectRID();

    newobject.setRID( ridObj );
    newobject.setObjectName( getMetaData().getObjectNameRID( ridObj ) );
    newobject.setPrototypeObject( &getPrototypeObject( ridObj ) );
    newobject.setConstructorProperty( ridMethod );
    newobject.setCallProperty( ridMethod );

    getObjectPool().push_back( newobject );

    CVariable var;
    var.setObjectRef( &getObjectPool().back() );

    METHOD_DEF& method = getMetaData().getMethod( ridMethod );
    int32_t iLength = method.iNumArgments;
    assert( iLength >= 0 );

    CVariable varInt( iLength, OPERAND_FLAG_DONTENUM );
    var.refObject->setProperty( STRING_INTERNAL_LENGTH,
                                varInt );

    //Store the ObjectRef to a static field
    setStaticField( rid, var );

    return true;
}
Esempio n. 3
0
void CConfiguration::LoadFromFile(const CString& FileName)
{
 CStringList configuration, sub_strings;
 CStringListIterator iterator(&configuration);
 configuration.LoadFromFile(FileName);
 //
 for (int i = 0; i < configuration.GetCount(); i++)
 {
  ParseStr(configuration[i],"=;",sub_strings);
  CVariable variable = VarNamed(sub_strings[0]);
  if (variable.GetType()==VARIABLE_TYPE_CHAR)
  {
   CStringList sub_strings2;
   ParseStr(sub_strings[1],"''",sub_strings2);
   variable.SetString(sub_strings2[1]);
  }
  else if (variable.GetType()==VARIABLE_TYPE_STRING)
  {
   CStringList sub_strings2;
   ParseStr(sub_strings[1],"\"\"",sub_strings2);
   variable.SetString(sub_strings2[1]);
  }
  sub_strings.Clear();
 }
}
Esempio n. 4
0
int CConfiguration::VarIndex(const CString& Name) const
{
 for (size_t i = 0; i < m_Variables.size(); i++)
 {
  CVariable *variable = m_Variables[i];
  if (variable->GetName()==Name) return i;
 }
 return INVALID_INDEX;
}
Esempio n. 5
0
void CAddressGenerationVisitor::Visit(CVariable &AStmt)
{
	if (AStmt.GetSymbol()->GetGlobal()) {
		Asm.Add(PUSH, "$" + AStmt.GetName());
	} else {
		Asm.Add(LEA, mem(AStmt.GetSymbol()->GetOffset(), EBP), EAX);
		Asm.Add(PUSH, EAX);
	}
}
Esempio n. 6
0
/***************************************************************************
 *      call method
 ***************************************************************************/
void CErrorObject::call( CCilVm* const pVm,
									const int32_t iNumArguments, 
									CVariable* pArguments )
{
	CVariable obj;

	CVmObject* pObj = pVm->createObject( pVm->getErrorObjectRID() );
	obj.setObjectRef( pObj );

	//Set prototype: String prototype object
	obj.refObject->setPrototypeObject( 
		&pVm->getPrototypeObject( pVm->getErrorObjectRID() ) );

	if( iNumArguments > 2 )
	{
		pArguments ++;
		CVariable& var = *pArguments;
		var.setFlag( OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_NUMBER, var ) ;
		
		pArguments ++;
		var = *pArguments;
		var.convertToString( pVm );
		var.setFlag( OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_MESSAGE, var );
	} else if( iNumArguments > 1 )
	{
		pArguments ++;
		CVariable& var = *pArguments;
		var.convertToString( pVm );
		var.setFlag( OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_MESSAGE, var );

		CVariable varError( ERROR_PROPERTY_NUMBER_DEFAULT,
					  OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_NUMBER, varError );
	}
	else
	{
		CVariable varString( L"",
							OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		CVariable varError( ERROR_PROPERTY_NUMBER_DEFAULT,
						   OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_MESSAGE, varString );
		obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_NUMBER, varError );
	}

	CVariable var( L"",
				  OPERAND_FLAG( OPERAND_FLAG_DONTENUM | OPERAND_FLAG_DONTDELETE ) );
	obj.refObject->setProperty( NAME_BUILTIN_ERROR_PROPERTY_NAME, var );

	//Push the ObjectRef to a eval stack
	pVm->pushEvalStackVariable( obj );
	return;
}
Esempio n. 7
0
/***************************************************************************
 *      Create a prototype object
 ***************************************************************************/
bool CSystemObject::InitializeVm( CCilVm& vm )
{
    int32_t iIndex = IndexFromBuiltinRid( vm.getSystemObjectRID() );
    RID ridObjectName = vm.getMetaData().getBuiltinObjectTable()[ iIndex ].getObjectName();
    assert( ridObjectName != RID_NOTDEFINED );


    RID rid = vm.createPrototypeObject( vm.getSystemObjectRID(),
                                        ridObjectName,
                                        vm.getObjectRID() );

    assert( rid == vm.getSystemObjectRID() );

    VMOBJECTREF objref = vm.createObject( vm.getObjectRID() );
    CVariable var;
    var.setObjectRef( objref );

    //Set true as an object value..
    CVariable varBool( true );
    objref->setValue( varBool );

    //Create ExitCode property
    CVariable varExitCode( 0 );
    objref->setProperty( NAME_BUILTIN_SYSTEM_PROPERTY_EXITCODE, varExitCode );

    //Create Environment property
    //Add properties of prototype object here
    vm.getPrototypeObject( vm.getSystemObjectRID() ).setProperty( NAME_BUILTIN_SYSTEM_PROPERTY_ENVIRONMENT,
            var );

    //---------------------------------------------------------------------------
    // Bind System functions
    //---------------------------------------------------------------------------
    for( int32_t i = 0; i<sizeof( initParams ) / sizeof( initParams[ 0 ] ); ++i )
    {
        int32_t iParams;
        iParams = (int32_t)RidFromToken( initParams[ i ].ridParam );
        if( isBuiltinRid( initParams[ i ].ridParam ) )
        {
            iParams = RidFromToken( -iParams ) - 1;
        }
        //-----------------------------------------------------------------------
        //Register methods
        //-----------------------------------------------------------------------
        bool b = vm.bindBuiltinMethod(
                     wstring( initParams[ i ].pStrSymbol ),
                     initParams[ i ].pMethod,
                     iParams );
        if( !b )
            return false;
    }

    return true;
}
Esempio n. 8
0
void CCodeGenerationVisitor::Visit(CVariable &AStmt)
{
	if (AStmt.GetSymbol()->GetType()->IsArray()) {
		AStmt.Accept(Addr);
	} else {
		if (AStmt.GetSymbol()->GetGlobal()) {
			Asm.Add(PUSH, AStmt.GetSymbol()->GetName());
		} else {
			Asm.Add(PUSH, mem(AStmt.GetSymbol()->GetOffset(), EBP));
		}
	}
}
Esempio n. 9
0
/***************************************************************************
 * Convert var and store to type constraint var
 * Src is on the top of eval stack
 ***************************************************************************/
void CCilVm::storeAsRestrictedType( CVariable& varDest )
{
	assert( varDest.getFlag() & OPERAND_FLAG_STRICT );

	switch( varDest.iOperandType )
	{
	case OPERAND_UNDEFINED:
	case OPERAND_NULL:
	case OPERAND_NAN:
		//Throw TypeError
		ThrowExceptionFromVm( &wstring( ERRORSTRING_TYPEERROR_STORESTATICFIELD ),
			&wstring( NAME_BUILTIN_ERROR_OBJECT ),
			ERROR_TYPEERROR_STORESTATICFIELD );
		break;
	case OPERAND_INT:
		varDest.iValue = getEvalStackFirstEntry().toInt();
		break;
	case OPERAND_INT64:
		varDest.i64Value = getEvalStackFirstEntry().toInt64();
		break;
	case OPERAND_FLOAT:
		varDest.fValue = getEvalStackFirstEntry().toFloat();
		break;
	case OPERAND_DOUBLE:
		varDest.dValue = getEvalStackFirstEntry().toDouble();
		break;
	case OPERAND_BOOLEAN:
		varDest.bValue = getEvalStackFirstEntry().toBoolean();
		break;
	case OPERAND_STRING:
		varDest.pString = getEvalStackFirstEntry().toString( this );
		break;
	case OPERAND_OBJECTREF:
		{
			//Try object conversion
			CObjectTypeInfo& info = getMetaData().getObject( varDest.GetConstraintRid() );
			RID ridCtor = info.getConstructor();
			CVariable vars[ 2 ];
			vars[ 0 ] = varDest;
			vars[ 1 ] = getEvalStackFirstEntry();
			CVariable* pVar = invokeMethod( ridCtor, 2, vars );
			delete( pVar );
		}
		break;
	case OPERAND_UNSIGNEDINT:
	case OPERAND_UNSIGNEDINT64:
	case OPERAND_SYSTEM_DELETION:
	default:
		Debug_Fatal( "Unhandled type constraint");
		break;
	}
}
Esempio n. 10
0
void CTeslaAPIVariables::Serialize (CArchive& ar) {
	CaImAPICollection<CVariable>::Serialize (ar);
	uvar32_64 n, size;
	if (ar.IsLoading ()) {
		ar.Read (&size, sizeof (uvar32_64));
		CVariable *var = new CVariable (m_pTesla, "", "");
		for (n = 0; n < size; ++n) {
			var->Serialize (ar);
			Add (*var);
		}
		delete var;
	}
}
Esempio n. 11
0
void CConfiguration::SetCharVariable(const CString& Name, const char Value)
{
 int index = VarIndex(Name);
 if (ValidIndex(index))
 {
  CVariable *variable = m_Variables[index];
  variable->SetChar(Value);
 }
 else
 {
  InsertCharVariable(Name,Value);
 }
}
Esempio n. 12
0
// ----------------------------------------------------------------------------
void CMissionQueueManager::saveToFile()
{
	H_AUTO(CMissionQueueManagerSaveToFile);

	if( _InitOk )
	{
		string sFilename = MissionQueueFile.get();
		
		// save file via Backup Service (BS)
		try
		{
			static CPersistentDataRecordRyzomStore	pdr;
			pdr.clear();
			store(pdr);

			CBackupMsgSaveFile msg( sFilename, CBackupMsgSaveFile::SaveFile, Bsi );
			{
				std::string s;
				pdr.toString(s);
				msg.DataMsg.serialBuffer((uint8*)&s[0], (uint)s.size());
			}
			Bsi.sendFile( msg );
		}
		catch(const Exception &)
		{
			nlwarning("(EGS)<CMissionQueueManager::saveToFile>  :  Can't serial file %s (connection with BS service down ?)",sFilename.c_str());
			return;
		}
	}
}
Esempio n. 13
0
/**
 * updateShardOpenFromFile()
 * Update ShardOpen from a file.
 * Read a line of text in the file, converts it to int (atoi), then casts into bool for ShardOpen.
 */
void	updateShardOpenFromFile(const std::string& filename)
{
	CIFile	f;

	if (!f.open(filename))
	{
		nlwarning("Failed to update ShardOpen from file '%s', couldn't open file", filename.c_str());
		return;
	}

	try
	{
		char	readBuffer[256];
		f.getline(readBuffer, 256);
		sint state;
		NLMISC::fromString(std::string(readBuffer), state);

		setShardOpenState((TShardOpenState)state);

		nlinfo("Updated ShardOpen state to '%u' from file '%s'", ShardOpen.get(), filename.c_str());
	}
	catch (const Exception& e)
	{
		nlwarning("Failed to update ShardOpen from file '%s', exception raised while getline() '%s'", filename.c_str(), e.what());
	}
}
Esempio n. 14
0
void CConfiguration::SaveToFile(const CString& FileName)
{
 FILE *stream = fopen(FileName.GetCString(),"wt");
 for (size_t i = 0; i < m_Variables.size(); i++)
 {
  CVariable *variable = m_Variables[i];
  CString string = variable->GetName()+"=";
  if ((variable->GetType()==VARIABLE_TYPE_STRING)||
      (variable->GetType()==VARIABLE_TYPE_CHAR))
  { string+="\""+variable->GetString()+"\""; }
  else
  { string+=variable->GetString(); }
  string.Append(';').AppendEOL();
  fwrite(string.GetCString(),string.GetLength(),1,stream);
 }
 fclose(stream);
}
/***************************************************************************
 *      Load array literal onto the stack
 ***************************************************************************/
void CSystemObject::LoadarrayLiteral( CCilVm* const pVm,
										   const int32_t iNumArguments, 
										   CVariable* pArguments )
{
	assert( pVm != NULL );
	//Array parameter can be null
	assert( iNumArguments >= 1 );

	//Skip this pointer
	pArguments++;

	//Create object object
	CVmObject* pObj = pVm->createObject( pVm->getArrayObjectRID() );
	CVariable var;
	var.setObjectRef( pObj );

	wchar_t strBuffer[ 22 ];		//22=max value width of longlong

	int32_t i = 0;
	for( ; i < iNumArguments - 1; ++i )
	{
		//Argument: 1) value of the property
		swprintf( strBuffer, 22, L"%d", i );
		var.refObject->setProperty( strBuffer, *pArguments );
		pArguments++;
	}

	//Set prototype: Array prototype object
	var.refObject->setPrototypeObject( 
		&pVm->getPrototypeObject( pVm->getArrayObjectRID() ) );

	//Update 'length' property
	CVariable varInt( 0 );
	var.refObject->setProperty( STRING_INTERNAL_LENGTH, varInt );
	//-2 means, 'prototype' & 'length'
	CVariable varLength( (int32_t)var.refObject->getPropertyMap().size() - 2,
						OPERAND_FLAG( OPERAND_FLAG_DONTDELETE | OPERAND_FLAG_DONTENUM ) ); 
	var.refObject->setProperty( STRING_INTERNAL_LENGTH, varLength );

	//Push the ObjectRef to a eval stack
	pVm->pushEvalStackVariable( var );

	return;
}
/***************************************************************************
 *      Load object literal onto the stack
 ***************************************************************************/
void CSystemObject::LoadobjectLiteral( CCilVm* const pVm,
										   const int32_t iNumArguments, 
										   CVariable* pArguments )
{
	assert( pVm != NULL );
	assert( iNumArguments >= 2 );
	assert( iNumArguments % 2 == 1 );

	//Skip this pointer
	pArguments++;
	int32_t i = iNumArguments;
	i--;
	CMetaData& Metadata = pVm->getMetaData();

	//Create object object
	CVmObject newobject;
	RID ridObject = pVm->getObjectRID();
	newobject.setRID( ridObject );
	newobject.setObjectName( pVm->getMetaData().getObjectNameRID( ridObject ) );
	newobject.setPrototypeObject( &pVm->getPrototypeObject( ridObject ) );

	pVm->getObjectPool().push_back( newobject );

	CVariable var;
	var.setObjectRef( &pVm->getObjectPool().back() );

	for( ; i > 0; i -= 2 )
	{
		//Argument: 1) value of the property
		//			2) string RID of the property

		RID ridString = pArguments->iValue;
		assert( TypeFromToken( ridString ) == MDT_STRING );
		pArguments++;

		wstring& str = Metadata.getStringConstant( ridString );
		var.refObject->setProperty( str, *pArguments );
		pArguments++;
	}

	//Push the ObjectRef to a eval stack
	pVm->pushEvalStackVariable( var );
	return;
}
Esempio n. 17
0
bool CArrayObject::CilPredicater( const CVariable& elem1,
									const CVariable& elem2 )
{
	assert( g_ridPredicater != RID_NULL );
	assert( g_pVm != NULL );
	
	//Invoke predicater
	CVariable vars[ 3 ];
	vars[ 1 ] = elem1;
	vars[ 2 ] = elem2;
	
	CVariable* pResult = g_pVm->invokeMethod( g_ridPredicater,
												3,
												vars );
	bool bReturn = (pResult->toInt() < 0);
	delete( pResult );
	
	return bReturn;
}
static void cbSyncGetFileClass( CMessage& msgin, TSockId from, CCallbackNetBase &netbase)
{
	if (!BSReadState.get())
		return;

	CMessage msgOut = getFileClassImp(msgin);

	// send the output message
	netbase.send(msgOut, from);
}
static void cbGetFileClass( CMessage& msgin, const std::string &serviceName, NLNET::TServiceId serviceId )
{
	if (!BSReadState.get())
		return;

	CMessage msgOut = getFileClassImp(msgin);

	// send the output message
	CUnifiedNetwork::getInstance()->send(serviceId, msgOut);
}
static void cbReadMode( CMessage& msgin, TSockId from, CCallbackNetBase &netbase)
{
	// encode the read mode and return
	CMessage msgout("BS_READ_MODE");
	bool readMode = BSReadState.get();
	nlWrite(msgout, serial, readMode);

	// send it back to sender
	netbase.send(msgout, from);
}
Esempio n. 21
0
void ParaEngine::CVariable::Clone(const CVariable& value)
{
	ChangeType(value.GetType());
	m_strVal = value.m_strVal;
	memcpy(m_vector4, value.m_vector4, sizeof(float) * 4);
	if (value.m_pAnimated)
	{
		// TODO: copy animated data. 
		PE_ASSERT(false);
	}
}
//-----------------------------------------------------------------------------
static void cbDisconnection( const string &serviceName, NLNET::TServiceId serviceId, void *arg )
{
	if (serviceName == "BS" && !MasterBSHost.get().empty())
	{
		nlwarning("SLAVE BS: MASTER BS IS DOWN!! File reading allowed!");
		MasterBSUp = false;
		BSReadState = true;

		IService::getInstance()->addStatusTag("MasterDown");
		IService::getInstance()->removeStatusTag("MasterRunning");
	}
} // cbDisconnection //
void	CDirectoryRateStat::writeFile(const std::string& filename, uint32 filesize)
{
	NLMISC::TTime	now = NLMISC::CTime::getLocalTime();
	if (filename.find("www") != std::string::npos)
	{
		_DirectoryMap["www"].write(now, filesize);
	}
	else if (filename.find(StatDirFilter.get()) != std::string::npos)
	{
		_DirectoryMap[NLMISC::CFile::getPath(filename)].write(now, filesize);
	}
}
Esempio n. 24
0
// ----------------------------------------------------------------------------
void CMissionQueueManager::init()
{
	string sFilename = MissionQueueFile.get();
	sFilename = Bsi.getLocalPath() + sFilename;
	
	if (CFile::fileExists(sFilename))
	{
		static CPersistentDataRecord	pdr;
		pdr.clear();
		pdr.readFromTxtFile(sFilename.c_str());
		apply(pdr);
	}
	_InitOk = true;
}
Esempio n. 25
0
// a new front end connecting to me, add it
void cbFESConnection (const std::string &serviceName, TServiceId  sid, void *arg)
{
	FESList.push_back (CFES ((TServiceId)sid));
	nldebug("new FES connection: sid %u", sid.get());
	displayFES ();

	bool	dummy;
	FESList.back().reportStateToLS(dummy);

	if (!UsePatchMode.get())
	{
		FESList.back().setToAcceptClients();
	}
}
Esempio n. 26
0
/***************************************************************************
 *      anyAccessor
 ***************************************************************************/
CVariable* CArrayObject::anyAccessor(CCilVm* const pVm,
										CVmObject* const pObject, 
										const wstring* const pName,
										CVariable* const pVar,
										const bool bSet )
{
	assert( pObject != NULL );
	if( bSet )
	{
		//Getter implementation
		return NULL;
	}
	else
	{
		pObject->setProperty( *pName, *pVar );

		//Setter implementation
		int32_t iLength = 0;

		//Check existing length
		CVariable* pCurrentLengthVar = pObject->lookupProperty( STRING_PROPERTY_INTERNAL_LENGTH );

		if( pCurrentLengthVar != NULL  )
		{
			iLength = pCurrentLengthVar->toInt();
		}

		int32_t iGivenIndex = _wtoi( pName->data() ) + 1;
		
		if( iGivenIndex > iLength )
		{
			CVariable var( iGivenIndex, OPERAND_FLAG( OPERAND_FLAG_DONTDELETE | OPERAND_FLAG_DONTENUM ) ); 
			pObject->setProperty( STRING_PROPERTY_INTERNAL_LENGTH, var );
		}
		return NULL;
	}
}
Esempio n. 27
0
static void checkShutdownRequest()
{
	// a little system to prevent us from eating too much CPU on systems that have a cstly 'fileExists()'
	static uint32 count=0;
	if ((++count)<10)	return;
	count=0;

	// if there's no ctrl file to be found then giveup
	if (!NLMISC::CFile::fileExists(ShutdownRequestFileName)) return;

	// if a shutdown ctrl file exists then read it's contents (if the file doesn't exist this returns an empty string)
	CSString fileContents;
	fileContents.readFromFile(ShutdownRequestFileName.c_str());

	// see if the file exists
	if (!fileContents.empty())
	{
		NLMISC::CFile::deleteFile(ShutdownRequestFileName);
		fileContents= fileContents.strip().splitToOneOfSeparators(" \t\n\r\x1a");
		// get rid of any unwanted junk surrounding the file contents
		nlinfo("Treating shutdown request from ctrl file %s: %s",ShutdownRequestFileName.c_str(),("#.State="+fileContents).c_str());
		NLMISC::ICommand::execute("getViewAES #.State="+fileContents, *NLMISC::InfoLog);
	}
}
Esempio n. 28
0
// ----------------------------------------------------------------------------
void CMissionQueueManager::tickUpdate()
{
	if( IsRingShard ) // Temporary Fix potential problem with multi shard instance Ring unification: 
		return;	// Mission saved tick must be adapted for have relative value saved

	H_AUTO(CMissionQueueManagerUpdate);

	for ( map<uint32,CMissionQueue>::iterator it = _Queues.begin() ; it != _Queues.end() ; ++it )
	{
		(*it).second.tickUpdate();
	}

	// save file when time has come
	if (CTickEventHandler::getGameCycle() % MissionQueueSavePeriod.get() == 0)
		saveToFile();
}
Esempio n. 29
0
/*
 * Update
 */
bool	CLogAnalyserService::update()
{
	updateWebConnection();

	// erase queries that have timed out
	NLMISC::TTime	ctime = NLMISC::CTime::getLocalTime();
	std::deque<CQuery*>::iterator	it;
	for (it=_Finished.begin(); it!=_Finished.end(); )
	{
		if (ctime - (*it)->Timeout > QueryTimeout.get() * 1000)
		{
			delete (*it);
			it = _Finished.erase(it);
		}
		else
		{
			++it;
		}
	}

	// current query finished? move to finished, destroy thread
	if (_Current != NULL && _Current->Finished)
	{
		_Finished.push_front(_Current);
		_Current = NULL;

		_Thread->wait();
		delete _Thread;
		_Thread = NULL;
	}

	// no current running task? create new thread, start query
	_Mutex.enter();
	if (_Current == NULL && !_Requests.empty())
	{
		_Current = _Requests.back();
		_Requests.pop_back();

		LogTask.Query = _Current;

		_Thread = IThread::create(&LogTask);
		_Thread->start();
	}
	_Mutex.leave();

	return true;
}
//-----------------------------------------------------------------------------
void CBackupService::init()
{
	FileManager.init();

	setUpdateTimeout(100);
	_SaveStall = false;

	// set the connection and disconnection callbacks
	CUnifiedNetwork::getInstance()->setServiceUpCallback( string("*"), cbConnection, 0);
	CUnifiedNetwork::getInstance()->setServiceDownCallback( string("*"), cbDisconnection, 0);

	CUnifiedNetwork::getInstance()->setServiceUpCallback( string("BS"), cbConnection, 0);
	CUnifiedNetwork::getInstance()->setServiceDownCallback( string("BS"), cbDisconnection, 0);

	// Init the sheet Id 
	CSheetId::init(false);

	if (!MasterBSHost.get().empty())
	{
		IService::getInstance()->addStatusTag("SlaveMode");
		IService::getInstance()->setCurrentStatus("WaitingMaster");

		BSIsSlave = true;
		FileManager.forbidStall();
		// I'm a slave, try to contact master
		string	host = MasterBSHost;
		if (host.find (":") == string::npos)
			host += ":49990";

		CUnifiedNetwork::getInstance()->addService ("BS", CInetAddress(host));
	}

	// set the initial read state from the config file
	CConfigFile::CVar *readState = ConfigFile.getVarPtr("BSReadState");
	if (readState != NULL)
		BSReadState = readState->asBool();


	initWebConnection();

	_CallbackServer = new NLNET::CCallbackServer;
	_CallbackServer->addCallbackArray(cbSyncArray, sizeofarray(cbSyncArray));
	// open the layer 3 callback server if required
	if (L3ListeningPort != 0)
		_CallbackServer->init(L3ListeningPort);
}