Example #1
0
void CInput::ProcessInput(CString strInput)
{
	// Get the command and parameters
	size_t sSplit = strInput.Find(' ', 0);
	CString strCommand = strInput.Substring(0, sSplit++);
	CString strParameters = strInput.Substring(sSplit, (strInput.GetLength() - sSplit));

	if(strCommand.IsEmpty())
		return;
	else if(strCommand == "quit" || strCommand == "Quit" || strCommand == "exit") {
		CLogFile::Print("[Server] Server is going to shutdown NOW ....");
		g_bClose = true;
		return;

	} else if(strCommand == "help" || strCommand == "?" || strCommand == "--usage") {
		printf("========== Available console commands: ==========\n");
		printf("say <text>\n");
		printf("uptime\n");
		printf("resources\n");
		printf("players\n");
		printf("loadresource <name>\n");
		printf("reloadresource <name>\n");
		printf("unloadresource <name>\n");
		printf("exit\n");
		return;
	}
	else if (strCommand == "setSyncRate") {
		int rate = atoi(strParameters.Get());
		CServer::GetInstance()->SetSyncRate(rate);
	}
	else if (strCommand == "setMaxFPS") {
		int fps = atoi(strParameters.Get());
		CServer::GetInstance()->SetMaximumFPS(fps);
	}
}
Example #2
0
void CSettings::ParseCommandLine(char * szCommandLine)
{
	// Loop until we reach the end of the command line CString
	while(*szCommandLine)
	{
		// Is the current char not a space?
		if(!isspace(*szCommandLine))
		{
			// Is the current char a '-'?
			if(*szCommandLine == '-')
			{
				// Skip the '-'
				szCommandLine++;

				// Collect the setting CString
				CString strSetting;

				while(*szCommandLine && !isspace(*szCommandLine))
				{
					strSetting += *szCommandLine;
					szCommandLine++;
				}

				// If we have run out of command line to process break out of the loop
				if(!(*szCommandLine))
					break;

				// Skip the spaces between the option and the value
				while(*szCommandLine && isspace(*szCommandLine))
					szCommandLine++;

				// If we have run out of command line to process break out of the loop
				if(!(*szCommandLine))
					break;

				// Collect the value CString
				CString strValue;

				while(*szCommandLine && !isspace(*szCommandLine))
				{
					strValue += *szCommandLine;
					szCommandLine++;
				}

				// Set the setting and value
				if(!SetEx(strSetting, strValue))
					CLogFile::Printf("WARNING: Command line setting %s does not exist.", strSetting.Get());

				CLogFile::Printf("argv/argc command line: setting %s value %s", strSetting.Get(), strValue.Get());

				// If we have run out of command line to process break out of the loop
				if(!(*szCommandLine))
					break;
			}
		}

		// Increment the command line string pointer
		szCommandLine++;
	}
}
Example #3
0
rc_t CKDirectory::CheckAccess(const CString &path,
    bool &updated, bool isPrivate, bool verbose) const
{
    updated = false;
    const String *str = path.Get();
    if (str == NULL) {
        return 0;
    }
    uint32_t access = 0;
    if (verbose) {
        OUTMSG(("checking %S file mode... ", path.Get()));
    }
    rc_t rc = KDirectoryAccess(m_Self, &access, str->addr);
    if (rc != 0) {
        OUTMSG(("failed\n"));
    }
    else {
        if (verbose) {
            OUTMSG(("%o\n", access));
        }
        if (isPrivate) {
            if (access != m_PrivateAccess) {
                uint32_t access = 0777;
                if (verbose) {
                    OUTMSG(("updating %S to %o... ", str, access));
                }
                rc = KDirectorySetAccess(m_Self, false,
                    m_PrivateAccess, access, str->addr);
                if (rc == 0) {
                    OUTMSG(("ok\n"));
                    updated = true;
                }
                else {
                    OUTMSG(("failed\n"));
                }
            }
        }
        else {
            if ((access & m_PrivateAccess) != m_PrivateAccess) {
                uint32_t access = 0700;
                if (verbose) {
                    OUTMSG(("updating %S to %o... ", str, access));
                }
                rc = KDirectorySetAccess(m_Self, false,
                    m_PrivateAccess, access, str->addr);
                if (rc == 0) {
                    OUTMSG(("ok\n"));
                    updated = true;
                }
                else {
                    OUTMSG(("failed\n"));
                }
            }
        }
    }
    return rc;
}
Example #4
0
bool CSquirrel::LoadScript(CString script)
{
	CString scriptPath( "%s/%s", m_pResource->GetPath().Get(), script.Get());
	if(SQ_FAILED(sqstd_dofile( m_pVM, scriptPath.Get(), SQFalse, SQTrue )))
	{
		CLogFile::Printf("[%s] Failed to load file %s.", m_pResource->GetName().Get(), script.Get());
		return false;
	}
	CLogFile::Printf("\t[%s] Loaded file %s.", m_pResource->GetName().Get(), script.Get());
	return true;
}
Example #5
0
void CNetworkManager::Connect(CString strHost, unsigned short usPort, CString strPass)
{
	// Are we already connected?
	if(IsConnected())
	{
		// Disconnect
		Disconnect();
	}

	// Store the connection info
	SetLastConnection(strHost, usPort, strPass);

	// Attempt to connect
	int iConnectionResult = m_pRakPeer->Connect(strHost.Get(), usPort, strPass.Get(), strPass.GetLength());

	// Set the network state
	SetNetworkState(NETSTATE_CONNECTING);

	// Create the string for the connection message
	CString strMessage("Failed to connected!");

	// Get the result from the connection
	switch(iConnectionResult)
	{
		case 0: strMessage.Format("Connecting to %s:%d...", strHost.Get(), usPort); break;
		case 1: strMessage.Set("Failed to connect! (Invalid parameter)"); break;
		case 2: strMessage.Set("Failed to connect! (Cannot resolve domain name)"); break;
		case 3: strMessage.Set("Failed to connect! (Already connected)"); break;
		case 4: strMessage.Set("Failed to connect! (Connection attempt already in progress)"); break;
		case 5: strMessage.Set("Failed to connect! (Security initialization failed)"); break;
		case 6: strMessage.Set("Failed to connect! (No host set)"); break;
	}

	// Did we fail to connect?
	if(iConnectionResult != 0)
	{
		// Set the network state
		SetNetworkState(NETSTATE_DISCONNECTED);

		// Set the last connection try
		m_uiLastConnectionTry = (unsigned int)SharedUtility::GetTime();
	}

	CGUI* pGUI = g_pCore->GetGUI();
	if (pGUI)
	{
		//pGUI->ClearView(CGUI::GUI_SERVER);
		//pGUI->SetView(CGUI::GUI_SERVER);
	}

	// Output the connection message
	g_pCore->GetChat()->Outputf(true, "#16C5F2%s", strMessage.Get());
}
Example #6
0
bool CSquirrelVM::LoadScript(CString script)
{
		
	CString scriptPath( "%s/%s", GetResource()->GetResourceDirectoryPath().Get(), script.Get());
	
	if(!SharedUtility::Exists(script.Get()) && SQ_FAILED(sqstd_dofile( m_pVM, scriptPath.Get(), SQFalse, SQTrue )))
	{
		CLogFile::Printf("[%s] Failed to load file %s.", GetResource()->GetName().Get(), script.Get());
		return false;
	}
	CLogFile::Printf("\t[%s] Loaded file %s.", GetResource()->GetName().Get(), script.Get());
	return true;
}
Example #7
0
bool CHttpClient::Post(bool bHasResponse, CString strPath, CString strData, CString strContentType)
{
    // Connect to the host
    if (!Connect())
    {
        // Connect failed
        return false;
    }

    // Reset the header and data
    m_headerMap.clear();
    m_strData.Clear();

    // Prepare the POST command
    CString strGet("POST %s HTTP/1.0\r\n" \
                   "Host: %s\r\n" \
                   "User-Agent: %s\r\n\r\n" \
                   "Referer: %s\r\n" \
                   "Content-Type: %s\r\n" \
                   "Content-Length: %d\r\n" \
                   "Connection: close\r\n" \
                   "\r\n" \
                   "%s",
                   strPath.Get(), m_strHost.Get(), m_strUserAgent.Get(),
                   m_strReferer.Get(), strContentType.Get(), strData.GetLength(),
                   strData.Get());

    // Send the POST command
    if (!Write(strGet.C_String(), strGet.GetLength()))
    {
        // Send failed
        return false;
    }

    // Do we have a response
    if (bHasResponse)
    {
        // Set the status to get data
        m_status = HTTP_STATUS_GET_DATA;

        // Set the request start
        m_uiRequestStart = SharedUtility::GetTime();
    }
    else
    {
        // Disconnect from the host
        Disconnect();
    }

    return true;
}
const char *getValue<const char *>(CScriptVM* pVM, int idx)
{
	CString str;
	pVM->SetStackIndex(idx - (pVM->GetVMType() == LUA_VM ? 0 : 1));
	pVM->Pop(str);
	return str.Get();
}
bool CNetworkModule::Startup(void)
{
	// Create the socket descriptor
	RakNet::SocketDescriptor socketDescriptor(CVAR_GET_INTEGER("port"), CVAR_GET_STRING("hostaddress").Get());

	// Attempt to startup raknet
	bool bReturn = (m_pRakPeer->Startup(CVAR_GET_INTEGER("maxplayers"), &socketDescriptor, 1, 0) == RakNet::RAKNET_STARTED);

	// Did it start?
	if(bReturn)
	{
		// Set the maximum incoming connections
		m_pRakPeer->SetMaximumIncomingConnections(CVAR_GET_INTEGER("maxplayers"));

		// Get the password string
		CString strPassword = CVAR_GET_STRING("password");

		// Do we have a password?
		if(strPassword.GetLength() > 0)
		{
			// Set the server password
			m_pRakPeer->SetIncomingPassword(strPassword.Get(), strPassword.GetLength());
		}
	}

	// Return
	return bReturn;
}
//----------------------------------------------------------------------------------------------------------------------------------------
// constructor
//----------------------------------------------------------------------------------------------------------------------------------------
CSocketServer::CSocketServer (const CString &inFile, const CSocketServerListener *inListener)
	      :CSocket	     (inFile, inListener),
	       m_ListenTh    (::pthread_self()),
	       m_File	     (inFile)
{
	// when we try to write on a closed socket, the SIGPIPE signal is emitted and the process exists returing EPIPE... It is not
	// sended if the flag MSG_NOSIGNAL was specified when sending the data over the socket. As this definition stands for SSL too
	// and as I did not find any bypassing in the ssl api, just overwritte the default system behaviour and keep on listening
	// if such an event occurs...
	struct sigaction sa; sa.sa_handler = ::DummySigPipe; sa.sa_flags = SA_NOCLDSTOP; ::sigaction (SIGPIPE, &sa, NULL);

        // bind the address to the local socket, remove it before if any and be sure to chmod it...
	if (m_File != CString()) ::remove (m_File.Get());
        if (::bind (m_Desc, m_SockAddr, sizeof(struct sockaddr_un)) < 0)
                throw new CException ("could\'t bind to \"" + inFile + "\"");
	::chmod (inFile.Get(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);

        // prepare socket to listen for connections
        if (::listen (m_Desc, SOMAXCONN) < 0)
                throw new CException ("couldn\'t listen on \"" + inFile + "\"");

	// try to create our listener thread
	int res; if ((inListener != NULL) && ((res = ::pthread_create (&m_ListenTh, NULL, CSocketServer::m_ListenCallBack, this)) != 0))
                throw new CException ("couldn\'t create pthread");
}
//----------------------------------------------------------------------------------------------------------------------------------------
// constructor
//----------------------------------------------------------------------------------------------------------------------------------------
CSocketServer::CSocketServer (const CString &inAddress, const UInt16 inPort, const CSocketServerListener *inListener)
	      :CSocket	     (inAddress, inPort, inListener),
	       m_ListenTh    (::pthread_self())
{
	// when we try to write on a closed socket, the SIGPIPE signal is emitted and the process exists returing EPIPE... It is not
	// sended if the flag MSG_NOSIGNAL was specified when sending the data over the socket. As this definition stands for SSL too
	// and as I did not find any bypassing in the ssl api, just overwritte the default system behaviour and keep on listening
	// if such an event occurs...
	struct sigaction sa; sa.sa_handler = ::DummySigPipe; sa.sa_flags = SA_NOCLDSTOP; ::sigaction (SIGPIPE, &sa, NULL);

	// what address should we bind to ?
	if (inAddress == CString())
		((struct sockaddr_in*)m_SockAddr)->sin_addr.s_addr = INADDR_ANY;
	else if (!::inet_aton (inAddress.Get(), &((struct sockaddr_in*)m_SockAddr)->sin_addr))
		throw new CException ("invalid address \"" + inAddress + "\"");

	// set the reuse address flag so we don't get errors if restarting and keep socket alive
	int flag=1; ::setsockopt (m_Desc, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, sizeof(int));

        // bind the address to the Internet socket
        if (::bind (m_Desc, m_SockAddr, sizeof(struct sockaddr_in)) < 0)
                throw new CException ("could\'t bind to \"" + inAddress + "\"");

        // prepare socket to listen for connections
        if (::listen (m_Desc, SOMAXCONN) < 0)
                throw new CException ("couldn\'t listen on \"" + inAddress + "\"");

	// try to create our listener thread
	int res; if ((inListener != NULL) && ((res = ::pthread_create (&m_ListenTh, NULL, CSocketServer::m_ListenCallBack, this)) != 0))
                throw new CException ("couldn\'t create pthread");
}
Example #12
0
rc_t CKConfig::UpdateUserRepositoryRootPath(const CString &path) {
    const String *str = path.Get();

    if (str == NULL) {
        return 0;
    }
    return UpdateUserRepositoryRootPath(str->addr, str->size);
}
Example #13
0
bool CKDirectory::Exists(const CString &path) const {
    const String *str = path.Get();

    if (str == NULL) {
        return false;
    }
    return Exists(str->addr);
}
Example #14
0
CModule::CModule(CString strName)
{
	// Remove any illegal characters from the module name
	SharedUtility::RemoveIllegalCharacters(strName);

	// Get the module path string
	CString strModulePath(SharedUtility::GetAbsolutePath("multiplayer/modules/%s", strName.Get()));

	// Replace '/' with '\\'
	strModulePath.Substitute("/", "\\");

	// Create the libray instance
	m_pLibrary = new CLibrary();

	// Is the library instance invalid?
	if(!m_pLibrary)
		return;

	// Did the module fail to load?
	if(!m_pLibrary->Load(strModulePath.Get()))
	{
		// Delete the library instance
		SAFE_DELETE(m_pLibrary);

		return;
	}

	// Assign module name
	m_strName = strName;

	// Get the module function pointers
	m_moduleFunctions.pfnSetupFunctions = (SetupFunctions_t)m_pLibrary->GetProcedureAddress("SetupFunctions");
	m_moduleFunctions.pfnSetupInterfaces = (SetupInterfaces_t)m_pLibrary->GetProcedureAddress("SetupInterfaces");
	m_moduleFunctions.pfnSetupNewInterfaces = (SetupNewInterfaces_t)m_pLibrary->GetProcedureAddress("SetupNewInterfaces");
	m_moduleFunctions.pfnInitialiseModule = (InitialiseModule_t)m_pLibrary->GetProcedureAddress("InitModule");
	m_moduleFunctions.pfnPulse = (Pulse_t)m_pLibrary->GetProcedureAddress("Pulse");

	// Are the pointers invalid?
	if(!IsValid())
	{
		// Delete the library instance
		SAFE_DELETE(m_pLibrary);

		return;
	}

	// Setup the functions
	m_moduleFunctions.pfnSetupFunctions(FunctionContainer);

	// Setup the pointers
	InterfacesContainer[0] = (void *)g_pCore->GetNetworkManager();
	InterfacesContainer[1] = (void *)g_pCore->GetGame()->GetPlayerManager();
	InterfacesContainer[2] = (void *)g_pCore->GetGame()->GetVehicleManager();

	// Setup the container functions with the module
	m_moduleFunctions.pfnSetupInterfaces(InterfacesContainer);
}
Example #15
0
void CInput::ProcessInput(CString strInput)
{
	// Get the command and parameters
	size_t sSplit = strInput.Find(' ', 0);
	CString strCommand = strInput.Substring(0, sSplit++);
	CString strParameters = strInput.Substring(sSplit, (strInput.GetLength() - sSplit));

	if(strCommand.IsEmpty())
		return;
	else if(strCommand == "quit" || strCommand == "Quit" || strCommand == "exit") {
		CLogFile::Print("[Server] Server is going to shutdown NOW ....");
		g_bClose = true;
		return;

	} else if(strCommand == "help" || strCommand == "?" || strCommand == "--usage") {
		printf("========== Available console commands: ==========\n");
		printf("say <text>\n");
		printf("uptime\n");
		printf("resources\n");
		printf("players\n");
		printf("loadresource <name>\n");
		printf("reloadresource <name>\n");
		printf("unloadresource <name>\n");
		printf("exit\n");
		return;
	}
	else if (strCommand == "setSyncRate") {
		int rate = atoi(strParameters.Get());
		CServer::GetInstance()->SetSyncRate(rate);
	}
	else if (strCommand == "setMaxFPS") {
		int fps = atoi(strParameters.Get());
		CServer::GetInstance()->SetMaximumFPS(fps);
	}
	else if (strCommand == "test") {
		CScriptArguments args;
		CScriptPlayer* player = new CScriptPlayer();
		player->SetEntity(new CPlayerEntity());
		args.push(player);
		CEvents::GetInstance()->Call("Test", &args, CEventHandler::eEventType::GLOBAL_EVENT, 0);
		delete player;
	}
}
Example #16
0
int CZlib::Decompress(CString strFileName, CString strOutput)
{
	// Open the files
	FILE * in = fopen(strFileName.Get(), "r");
	FILE * out = fopen(strOutput.Get(), "w+");

	// Enable binary mode
	SET_BINARY_MODE(in);
	SET_BINARY_MODE(out);

	// Deflate the file
	int iReturn = Inflate(in, out);

	// Close the files
	fclose(in);
	fclose(out);

	return iReturn;
}
Example #17
0
const char *getValue<const char *>(CScriptVM* pVM, int idx)
{
	CString str;
	pVM->SetStackIndex(idx - (pVM->GetVMType() == LUA_VM ? 0 : 1));
	pVM->Pop(str);
	const char* sz = (char*)malloc(str.GetLength()+1);
	memset((void*)sz, 0, str.GetLength()+1);
	memcpy((void*)sz, (void*)str.Get(), str.GetLength());
	return sz;
}
Example #18
0
void CResourceScript::RegisterFunction ( CString strFunction, SQFUNCTION sqFunction, int iParams, CString strTemplate )
{
	// Push function name.
	sq_pushstring ( m_pVM, strFunction.Get(), -1 );

	// Push function C++ handle,
	sq_newclosure ( m_pVM, sqFunction, 0 );

	// Make params / check.
	if ( iParams != -1 )
	{
		CString strParams;
		strParams.Format( ".%s", strTemplate.Get() );

		sq_setparamscheck ( m_pVM, (iParams+1), strParams.Get() );
	}

	// Create slot for function,
	sq_createslot ( m_pVM, -3 );
}
Example #19
0
void CResourceScript::RegisterVarible ( CString strName, CSquirrelArguments* pArguments )
{
	// Push varible name.
	sq_pushstring ( m_pVM, strName.Get(), -1 );

	// Push arguments.
	pArguments->toVM(m_pVM);

	// Create new slot for varible.
	sq_createslot ( m_pVM, -3 );
}
Example #20
0
void CCommandSystem::ParseCommand ( const char * szInputB )
{
	// Warpowanie klasy string do CString
	szInput.Set(szInputB);

	// Sprawdzanie czy wpisany tekst jest napewno wpisany (Wiem bezsensowny tekst).
	if(szInput.IsNotEmpty()) 
	{
		size_t sSpace = szInput.Find(' ', 0);
		CString szCommand = szInput.CutStr(0, sSpace++);
		CString szParams = szInput.CutStr(sSpace, (szInput.GetLength() - sSpace));

		// Sprawdzanie czy komenda nadal jest pe³na. Je¿eli nie stop.
		if ( szCommand.IsEmpty( ) )
			return;

		// Komendy
		ProcessCommand ( szCommand.Get(), (!szParams.GetLength() ? "" : szParams.Get()) );
	}
}
Example #21
0
bool CLuaVM::LoadScript(CString script)
{
	(new CScriptClass<Foo>("Foo"))->AddMethod("abc", &Foo::abc).AddMethod("new", &Foo::abc).Register(this);
	CString scriptPath( "%s/%s", GetResource()->GetResourceDirectoryPath().Get(), script.Get());
	
	if(!SharedUtility::Exists(script.Get()) && luaL_loadfile(m_pVM, scriptPath.Get()) != 0)
	{
		CLogFile::Printf("[%s] Failed to load file %s.", GetResource()->GetName().Get(), script.Get());
		return false;
	} 
	else 
	{
		if (lua_pcall(m_pVM, 0, LUA_MULTRET, 0) == 0)
		{
			CLogFile::Printf("\t[%s] Loaded file %s.", GetResource()->GetName().Get(), script.Get());
			return true;
		}
		else
		{
			std::string strRes = lua_tostring(m_pVM, -1);

			std::vector <std::string> vecSplit;
			vecSplit = split(strRes, ':');

			if (vecSplit.size() >= 3)
			{
				std::string strFile = vecSplit[0];
				int     iLine = atoi(vecSplit[1].c_str());
				std::string strMsg = vecSplit[2].substr(1);

				CLogFile::Printf("ERROR: %s:%d: %s", strFile.c_str(), iLine, strMsg.c_str());
			}
			else
			{
				CLogFile::Printf(strRes.c_str());
			}
		}
	}
	CLogFile::Printf("[%s] Failed to load file %s.", GetResource()->GetName().Get(), script.Get());
	return false;
}
Example #22
0
// Send Report writes data into the header(can be readout with php://input http://php.net/manual/en/function.http-get-request-body.php
void CHttpClient::SendReport(CString strPath, CString strReport)
{
    // Connect to the host
    if (!Connect())
    {
        // Connect failed
        return;
    }

    // Reset the header and data
    m_headerMap.clear();
    m_strData.Clear();

    // Prepare the GET command
    CString strGet("GET %s HTTP/1.0\r\n" \
                   "Host: %s\r\n" \
                   "User-Agent: %s\r\n" \
                   "Referer: %s\r\n" \
                   "Connection: close\r\n" \
                   "\n%s" \
                   "\r\n",
                   strPath.Get(), m_strHost.Get(),
                   m_strUserAgent.Get(), m_strReferer.Get(), strReport.Get());

    // Send the GET command
    if (!Write(strGet.C_String(), strGet.GetLength()))
    {
        // Send failed
        return;
    }

    // Set the status to get data
    m_status = HTTP_STATUS_GET_DATA;

    // Set the request start
    m_uiRequestStart = SharedUtility::GetTime();
    return;
}
Example #23
0
void CSettings::ParseCommandLine(int argc, char ** argv)
{
	for(int i = 0; i < argc; i++)
	{
		// Is the current char a '-'?
		if(argv[i][0] == '-')
		{
			// Is there a value?
			if((i + 1) < argc)
			{
				// Get the setting and value pointers
				CString strSetting = (argv[i] + 1);
				CString strValue = argv[i + 1];

				// Set the setting and value
				if(!SetEx(strSetting, strValue))
					CLogFile::Printf("WARNING: Command line setting %s does not exist.", strSetting.Get());

				CLogFile::Printf("argv/argc command line: setting %s value %s", strSetting.Get(), strValue.Get());
			}
		}
	}
}
Example #24
0
void CSquirrelVM::RegisterFunction(const char* szFunctionName, scriptFunction pfnFunction, int iParameterCount, const char* szFunctionTemplate, bool bPushRootTable)
{
	// Push the function name onto the stack
	sq_pushstring(m_pVM, szFunctionName, -1);

	// Create a new function
	sq_newclosure(m_pVM, (SQFUNCTION)pfnFunction, 0);

	// Set the function parameter template and count
	if(iParameterCount != -1)
	{
		CString strTypeMask;

		// TODO: Change parameter
		CString strFunctionTemplate = szFunctionTemplate;
		if(strFunctionTemplate.IsNotEmpty())
			strTypeMask.Format(".%s", strFunctionTemplate.Get());

		sq_setparamscheck(m_pVM, (iParameterCount + 1), strTypeMask.Get());
	}
	sq_setnativeclosurename(m_pVM, -1, szFunctionName);
	// Create a new slot
	sq_createslot(m_pVM, -3);
}
Example #25
0
void CCore::GetLoadedModule(DWORD dwProcessId)
{
	HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                            PROCESS_VM_READ,
                            FALSE, dwProcessId );
    if (NULL == hProcess)
        return;

    if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
        for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ ) {
            TCHAR szModName[MAX_PATH];
            if ( GetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))) {
			  CString strModule;

			  std::string strModulee;
			  strModulee.append(szModName);
			  std::size_t found = strModulee.find("SYSTEM32",10);
			  std::size_t found2 = strModulee.find("system32",10);
			  std::size_t found3 = strModulee.find("AppPatch",10);
			  std::size_t found4 = strModulee.find("WinSxS", 10);

			  if(found != std::string::npos || found2 != std::string::npos || found3 != std::string::npos || found4 != std::string::npos) {/**/}
			  else {
				strModule.AppendF("--> IVModules: %s", szModName);
				CLogFile::Printf("  %s (0x%08X)",strModule.Get(), hMods[i] );
			  }
            }
        }
    }
    CloseHandle(hProcess);
    return;
}
Example #26
0
rc_t CKDirectory::CreateNonExistingDir(const CString &path,
    uint32_t access, bool verbose) const
{
    const String *str = path.Get();
    if (str == NULL) {
        return 0;
    }

    if (verbose) {
        OUTMSG(("checking whether %S exists... ", str));
    }

    if (Exists(str->addr)) {
        if (verbose) {
            OUTMSG(("found\n"));
        }
        return 0;
    }

    if (verbose) {
        OUTMSG(("creating... "));
    }

    rc_t rc = KDirectoryCreateDir(m_Self, access,
        (kcmCreate | kcmParents), str->addr);
    if (verbose) {
        if (rc == 0) {
            OUTMSG(("ok\n"));
        }
        else {
            OUTMSG(("failed\n"));
        }
    }

    return rc;
}
Example #27
0
void CSquirrelVM::Push(const CString& str)
{
	sq_pushstring(m_pVM, str.Get(), str.GetLength());
}
Example #28
0
rc_t CKDirectory::CanWriteFile(const CString &dir, bool verbose) const {
    bool ok = true;
    rc_t rc = 0;
    char path[PATH_MAX] = "";
    if (verbose) {
        OUTMSG(("checking whether %S is writable... ", dir.Get()));
    }
    for (int i = 0; i < 10000 && rc == 0; ++i) {
        size_t path_len = 0;
        rc = string_printf(path, sizeof path, &path_len,
            "%S/.tmp%d.tmp", dir.Get(), i);
        if (rc != 0) {
            break;
        }
        assert(path_len <= sizeof path);
        if (Exists(path)) {
            KDirectoryRemove(m_Self, false, path);
        }
        else {
            KFile *f = NULL;
            rc = KDirectoryCreateFile(m_Self,
                &f, false, m_PrivateAccess, kcmCreate, path);
            if (rc == 0) {
                rc = KFileWrite(f, 0, path, path_len, NULL);
            }
            RELEASE(KFile, f);
            const KFile *cf = NULL;
            if (rc == 0) {
                rc = KDirectoryOpenFileRead(m_Self, &cf, path);
            }
            char buffer[PATH_MAX] = "";
            size_t num_read = 0;
            if (rc == 0) {
                rc = KFileRead(cf, 0, buffer, sizeof buffer, &num_read);
            }
            if (rc == 0) {
                if (path_len != num_read || string_cmp(path,
                    path_len, buffer, num_read, sizeof buffer) != 0)
                {
                    if (verbose) {
                        OUTMSG(("no\n"));
                    }
                    OUTMSG(("Warning: "
                        "NCBI Home directory is not writable"));
                    ok = false;
                }
            }
            RELEASE(KFile, cf);
            if (rc == 0) {
                KDirectoryRemove(m_Self, false, path);
            }
            break;
        }
    }
    if (verbose && ok) {
        if (rc == 0) {
            OUTMSG(("yes\n"));
        }
        else {
            OUTMSG(("failed\n"));
        }
    }
    return rc;
}
Example #29
0
bool CClientCommands::HandleUserInput(CString strCommand, CString strParameters)
{
	if(strCommand == "q"  || strCommand == "quit")
	{
		// Are we connected to the network?
		if(g_pCore->GetNetworkManager()->IsConnected())
		{
			// Disconnect and shutdown RakNet
			g_pCore->GetNetworkManager()->Shutdown(500, true);
		}
		
		TerminateProcess(GetCurrentProcess(), 0);
		return true;
	}
	else if(strCommand == "qq" || strCommand == "quickquit")
	{
		TerminateProcess(GetCurrentProcess(), 0);
		return true;
	}
	else if (strCommand == "saveposition" || strCommand == "save")
	{
		FILE * file = fopen(SharedUtility::GetAbsolutePath("multiplayer//SavePositions.log"), "a");
		if (!file)
		{
			g_pCore->GetChat()->Print("Failed to open 'SavePositions.log'");
			return true;
		}

		CVector3 vecPosition;

		// Get our local player
		CLocalPlayer * pLocalPlayer = g_pCore->GetGame()->GetLocalPlayer();

		if (pLocalPlayer->IsInVehicle())
		{
			CVehicleEntity * pVehicle = pLocalPlayer->GetVehicleEntity();

			if (pVehicle)
			{
				pVehicle->GetPosition(vecPosition);
				CVector3 vecRotation;
				pVehicle->GetRotation(vecRotation);
				DWORD dwColors[5];
				pVehicle->GetColors(dwColors[0], dwColors[1], dwColors[2], dwColors[3], dwColors[4]);
				fprintf_s(file, "createVehicle(%d, %f, %f, %f, %f, %f, %f, %d, %d, %d, %d, %d);%s%s\n", CIVModelManager::ModelHashToVehicleId(pVehicle->GetModelInfo()->GetHash()), vecPosition.fX, vecPosition.fY, vecPosition.fZ, vecRotation.fX, vecRotation.fY, vecRotation.fZ, dwColors[0], dwColors[1], dwColors[2], dwColors[3], dwColors[4], strParameters.GetLength() > 0 ? " // " : "", strParameters.GetLength() > 0 ? strParameters.Get() : "");
			}
		}
		else
		{
			pLocalPlayer->GetPosition(vecPosition);
			int iModelId = pLocalPlayer->GetPlayerPed()->GetModelIndex();
			fprintf_s(file, "PlayerData(%d, %f, %f, %f, %f);%s%s\n", iModelId, vecPosition.fX, vecPosition.fY, vecPosition.fZ, pLocalPlayer->GetHeading(), strParameters.GetLength() > 0 ? " // " : "", strParameters.GetLength() > 0 ? strParameters.Get() : "");
		}

		fclose(file);
		g_pCore->GetChat()->Print("Position data saved to 'SavePositions.log'");
		return true;
	}
#ifdef _DEBUG
	else if(strCommand == "cv")
	{
		CVector3 vecCreatePos; 
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecCreatePos);
		vecCreatePos.fX += 4;

		CVehicleEntity * pVehicle = new CVehicleEntity(atoi(strParameters.Get()), vecCreatePos, 0.0f, 0x000000, 0x000000, 0x000000, 0x000000, 0xFFFFFF);
		if(pVehicle) {
			// Add our vehicle
			pVehicle->SetId(g_pCore->GetGame()->GetVehicleManager()->Add(pVehicle));
			pVehicle->Create();
			g_pCore->GetGame()->GetLocalPlayer()->WarpIntoVehicle(pVehicle);
		}
		return true;
	}
	else if(strCommand == "respawn")
	{
		g_pCore->GetGame()->GetLocalPlayer()->Respawn();
		return true;
	}
	else if(strCommand == "cp")
	{
		CVector3 vecCreatePos; 
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecCreatePos);

		CPlayerEntity * pPlayer = new CPlayerEntity(false);
		if(pPlayer) {
			pPlayer->SetModel(7);
			pPlayer->Create();
			pPlayer->Teleport(vecCreatePos);
		}
		return true;
	}
	else if(strCommand == "engine") 
	{
		if(g_pCore->GetGame()->GetLocalPlayer()->GetVehicleEntity() != NULL)
			g_pCore->GetGame()->GetLocalPlayer()->GetVehicleEntity()->SetEngineState(!g_pCore->GetGame()->GetLocalPlayer()->GetVehicleEntity()->GetEngineState());
		
		return true;
	}
	else if(strCommand == "giveweapon")
	{
		CIVScript::GiveWeaponToChar(g_pCore->GetGame()->GetLocalPlayer()->GetScriptingHandle(), (CIVScript::eWeapon)atoi(strParameters.Get()), 100, true);
		return true;
	}
	else if(strCommand == "xaxis")
	{
		CVector3 vecPositon;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPositon);

		vecPositon.fX += atoi(strParameters.Get());
		g_pCore->GetGame()->GetLocalPlayer()->SetPosition(vecPositon);
		return true;
	}
	else if(strCommand == "yaxis")
	{
		CVector3 vecPositon;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPositon);

		vecPositon.fY += atoi(strParameters.Get());
		g_pCore->GetGame()->GetLocalPlayer()->SetPosition(vecPositon);
		return true;
	}
	else if(strCommand == "zaxis")
	{
		CVector3 vecPositon;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPositon);

		vecPositon.fZ += atoi(strParameters.Get());
		g_pCore->GetGame()->GetLocalPlayer()->SetPosition(vecPositon);
		return true;
	}
	else if(strCommand == "port")
	{
		CVector3 vecPositon;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPositon);
		vecPositon.fX = 900;
		vecPositon.fY = -71;
		vecPositon.fZ += 20;
		g_pCore->GetGame()->GetLocalPlayer()->SetPosition(vecPositon);
		return true;
	}
	else if(strCommand == "time")
	{
		g_pCore->GetTimeManagementInstance()->SetTime(atoi(strParameters.Get()), 0);
		CGameFunction::SetTimeOfDay(atoi(strParameters.Get()), 0);
		return true;
	}
	else if(strCommand == "setmodel")
	{
		g_pCore->GetGame()->GetLocalPlayer()->SetModel(atoi(strParameters.Get()));
		return true;
	}
	else if(strCommand == "setclothes")
	{
		CString strParameter = CString("%s", strParameters.Get());
		g_pCore->GetChat()->Print(strParameter.Get());

		// Get the end of the command
		size_t sCommandEnd = strParameter.Find(" "); 

		// If we don't have a valid end use the end of the string
		if (sCommandEnd == std::string::npos)
		{
			sCommandEnd = strParameter.GetLength();
		}

		// Get the command name
		std::string strCommand2 = strParameter.Substring(0, (sCommandEnd));

		// Get the command parameters
		std::string strParams;

		// Do we have any parameters?
		if(sCommandEnd < strParameter.GetLength())
		{
			strParams = strParameter.Substring((sCommandEnd + 1), strParameter.GetLength());
		}

		g_pCore->GetChat()->Print(CString("Setting clothes part %d to %d", atoi(strCommand2.c_str()), atoi(strParams.c_str())));
		g_pCore->GetGame()->GetLocalPlayer()->SetPedClothes(atoi(strCommand2.c_str()), atoi(strParams.c_str()));

		return true;
	}
	else if(strCommand == "bahama")
	{
		g_pCore->GetGame()->GetLocalPlayer()->CPlayerEntity::SetPosition(CVector3(-15.9453f, -13.5865f, -11.7456f));
		return true;
	}
	else if(strCommand == "spawnvehs")
	{
		CVector3 vecPos;
		PTR_LOCALPLAYER->GetPosition(vecPos);

		for (int i = 0; i < 179; i++)
		{
			vecPos.fX += 5;
			CVehicleEntity * pVehicle = new CVehicleEntity(i, vecPos, 0.0f, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF);
			if(pVehicle)
			{
				// Add our vehicle
				g_pCore->GetGame()->GetVehicleManager()->Add(pVehicle);
				pVehicle->SetId(g_pCore->GetGame()->GetVehicleManager()->FindFreeSlot());
				pVehicle->Create();
				pVehicle->SetPosition(vecPos, true);
			}
		}
		return true;
	}
	else if(strCommand == "getvehpos")
	{
		int iVehicle = atoi(strParameters.Get());

		if(g_pCore->GetGame()->GetVehicleManager()->DoesExists(iVehicle)) {
			CVector3 vecPosition;
			g_pCore->GetGame()->GetVehicleManager()->GetAt(iVehicle)->GetPosition(vecPosition);
			PTR_CHAT->Print(CString("Position of vehicle %d: %f, %f,%f", iVehicle, vecPosition.fX, vecPosition.fY, vecPosition.fZ));
		}
		return true;
	}
	else if(strCommand == "ivhelp")
	{
		PTR_CHAT->Print("List of Default IV:N Commands...");
		PTR_CHAT->Print("** /cv /respawn /debug /weapon /cp /spawn /engine /save /giveweapon /xaxis /time");
		PTR_CHAT->Print("** /setmodel /testweapon /ready /parachute /bahama /spawnvehicles /getvehpos");
		return true;
	}
	else if(strCommand == "createtrain")
	{
		g_pCore->GetGame()->GetIVManagement()->CreateTrain(g_pCore->GetGame()->GetLocalPlayer()->GetPosition(), 3, 20.0f, 0);
		return true;
	}
	else if(strCommand == "blip")
	{
		unsigned int uiBlip;
		CIVScript_NativeInvoke::Invoke<unsigned int>(CIVScript::NATIVE_ADD_BLIP_FOR_COORD, 0, 0, 0,&uiBlip); 
		CIVScript_NativeInvoke::Invoke<unsigned int>(CIVScript::NATIVE_CHANGE_BLIP_SPRITE, 10);
		return true;
	}
	else if(strCommand == "sethealth")
	{
		g_pCore->GetGame()->GetLocalPlayer()->SetHealth(atoi(strParameters.Get()));
		return true;
	}
	else if (strCommand == "setarmour")
	{
		g_pCore->GetGame()->GetLocalPlayer()->SetArmour(atoi(strParameters.Get()));
		return true;
	}
#endif
#ifdef SYNC_TEST
	else if (strCommand == "syncTest")
	{
		// Add the player
		CPlayerEntity * pPlayer = new CPlayerEntity;
		pPlayer->SetModel(0); // Set temporary to nico lol
		pPlayer->Create();
		pPlayer->SetNick("Keks");
		pPlayer->SetId(1);
		pPlayer->SetColor(0xFFFFFFFF);
		g_pCore->GetGame()->GetPlayerManager()->Add(1, pPlayer);

		CVector3 vecPosition;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPosition);
		vecPosition.fX += 2.0f;
		pPlayer->SetPosition(vecPosition);
	}
	else if (strCommand == "getP")
	{
		CVector3 vecPosition;
		g_pCore->GetGame()->GetLocalPlayer()->GetPosition(vecPosition);
		vecPosition.fX += 2.0f;
		g_pCore->GetGame()->GetPlayerManager()->GetAt(1)->SetPosition(vecPosition);
	}
	else if (strCommand = "vehicleSync")
	{
		g_pCore->GetGame()->GetLocalPlayer()->PutInVehicle(g_pCore->GetGame()->GetVehicleManager()->GetAt(0), 0);
		CVector3 vecPosition;
		g_pCore->GetGame()->GetPlayerManager()->GetAt(1)->GetPosition(vecPosition);
		CVehicleEntity * pVehicle = new CVehicleEntity(90, vecPosition, 90, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF);
		if (pVehicle)
		{
			//	// Add our vehicle
			g_pCore->GetGame()->GetVehicleManager()->Add(1, pVehicle);
			pVehicle->SetId(1);
			pVehicle->Create();
			pVehicle->SetPosition(vecPosition, true);
		}
		//g_pCore->GetGame()->GetPlayerManager()->GetAt(1)->PutInVehicle(g_pCore->GetGame()->GetVehicleManager()->GetAt(0), 0);

		//CVehicleEntity * pVehicle = new CVehicleEntity(90, vecPosition, 90, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF);
		//if (pVehicle)
		//{
		//	//	// Add our vehicle
		//	g_pCore->GetGame()->GetVehicleManager()->Add(vehicleId, pVehicle);
		//	pVehicle->SetId(vehicleId);
		//	pVehicle->Create();
		//	pVehicle->SetPosition(vecPosition, true);
		//}
	}
#endif
	return false;
}
Example #30
0
CResourceScript::CResourceScript ( CString strFile, int ScriptType, CResource *pResource )
{
	// Warp some varibles.
	m_pResource = pResource;
	m_iScriptType = ScriptType;

	// Format script localization.
	m_strFile.Format("%s\\%s\\%s", m_pResource->GetDirectory().Get(), m_pResource->GetName().Get(), strFile.Get());

	// Check if file exists.
	if(!Exists(m_strFile.Get()))
	{
		CLog::Printf( "[Resources] Script %s not found!", m_strFile.Get() );
		return;
	}

	// Check script type - default server.
	if ( ScriptType == SCRIPT_CLIENT )
	{
		/*
			TODO:
				- Warp to code WebServ,
				- Create class for client resources,
				- ..
		*/
	} else {
		// Create root stack for script.
		m_pVM = sq_open(1024);

		//Register error and print functions.
		sqstd_seterrorhandlers(m_pVM);
		sq_setprintfunc(m_pVM, PrintFunction, ErrorFunction);
		sq_setcompilererrorhandler(m_pVM, CompilerErrorFunction);

		// Push root vm table.
		sq_pushroottable(m_pVM);

		// Register basic systems.
		sqstd_register_systemlib(m_pVM);
		sqstd_register_iolib(m_pVM);
		sqstd_register_bloblib(m_pVM);
		sqstd_register_mathlib(m_pVM);
		sqstd_register_stringlib(m_pVM);

		// Register Squirrel Classes
		m_pResource->RegisterClass(this);
		
		// Register all functions.

		// Event functions.
		CEventNatives::Register(this);

		// Funkcje gracza.
		CPlayerNatives::Register(this);

		if ( SQ_FAILED ( sqstd_dofile(m_pVM, m_strFile.Get(), SQFalse, SQTrue) ) )
		{
			// cannot compile script file.
			return;
		}

		// Define basic varibles.
		CSquirrelArguments pArgs;
		pArgs.push(MAX_PLAYERS);
		RegisterVarible ( "MAX_PLAYERS", &pArgs );
		pArgs.clear();
	}
}