clang format

This commit is contained in:
Anonymous275
2022-07-26 11:43:45 +03:00
parent b26fb43746
commit 3c96bb3959
34 changed files with 1912 additions and 1832 deletions
+41
View File
@@ -0,0 +1,41 @@
---
BasedOnStyle: Google
AccessModifierOffset: 0
AlignConsecutiveAssignments: Consecutive
AlignEscapedNewlines: Right
AlignTrailingComments: true
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterReturnType: None
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeInheritanceComma: false
BreakConstructorInitializers: AfterColon
Cpp11BracedListStyle: true
DerivePointerAlignment: false
FixNamespaceComments: false
IncludeBlocks: Preserve
IndentCaseLabels: true
IndentWidth: 3
IndentAccessModifiers: false
KeepEmptyLinesAtTheStartOfBlocks: false
Language: Cpp
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
PointerAlignment: Left
ReflowComments: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesInAngles: Never
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Latest
TabWidth: 2
UseTab: Never
+4 -4
View File
@@ -4,10 +4,10 @@
/// ///
#pragma once #pragma once
#include "Memory/IPC.h"
#include "Server.h"
#include <filesystem> #include <filesystem>
#include <thread> #include <thread>
#include "Memory/IPC.h"
#include "Server.h"
namespace fs = std::filesystem; namespace fs = std::filesystem;
@@ -88,6 +88,6 @@ private: // variables
class ShutdownException : public std::runtime_error { class ShutdownException : public std::runtime_error {
public: public:
explicit ShutdownException(const std::string& message) explicit ShutdownException(const std::string& message) :
: runtime_error(message) {}; runtime_error(message){};
}; };
+6 -4
View File
@@ -4,16 +4,17 @@
/// ///
#pragma once #pragma once
#include "Memory/Hook.h"
#include "Memory/GELua.h"
#include "Memory/IPC.h"
#include <memory> #include <memory>
#include <string> #include <string>
#include "Memory/GELua.h"
#include "Memory/Hook.h"
#include "Memory/IPC.h"
class BeamNG { class BeamNG {
public: public:
static void EntryPoint(); static void EntryPoint();
static void SendIPC(const std::string& Data); static void SendIPC(const std::string& Data);
private: private:
static inline std::unique_ptr<Hook<def::GEUpdate>> TickCountDetour; static inline std::unique_ptr<Hook<def::GEUpdate>> TickCountDetour;
static inline std::unique_ptr<Hook<def::lua_open_jit>> OpenJITDetour; static inline std::unique_ptr<Hook<def::lua_open_jit>> OpenJITDetour;
@@ -23,6 +24,7 @@ private:
static inline uint64_t DllBaseAddr; static inline uint64_t DllBaseAddr;
static int lua_open_jit_D(lua_State* State); static int lua_open_jit_D(lua_State* State);
static void RegisterGEFunctions(); static void RegisterGEFunctions();
// static int GetTickCount_D(void* GEState, void* Param2, void* Param3, void* Param4); // static int GetTickCount_D(void* GEState, void* Param2, void* Param3, void*
// Param4);
static void IPCListener(); static void IPCListener();
}; };
+2 -1
View File
@@ -10,7 +10,8 @@ typedef struct lua_State lua_State;
typedef int (*lua_CFunction)(lua_State*); typedef int (*lua_CFunction)(lua_State*);
extern int lua_gettop(lua_State* L); extern int lua_gettop(lua_State* L);
namespace def { namespace def {
typedef int (*GEUpdate)(void* Param1, void* Param2, void* Param3, void* Param4); typedef int (*GEUpdate)(void* Param1, void* Param2, void* Param3,
void* Param4);
typedef uint32_t (*GetTickCount)(); typedef uint32_t (*GetTickCount)();
typedef int (*lua_open_jit)(lua_State* L); typedef int (*lua_open_jit)(lua_State* L);
typedef void (*lua_get_field)(lua_State* L, int idx, const char* k); typedef void (*lua_get_field)(lua_State* L, int idx, const char* k);
+2 -1
View File
@@ -37,7 +37,8 @@ namespace GELuaTable {
inline void EndEntry(lua_State* L) { inline void EndEntry(lua_State* L) {
GELua::lua_settable(L, -3); GELua::lua_settable(L, -3);
} }
inline void InsertFunction(lua_State* L, const char* name, lua_CFunction func) { inline void InsertFunction(lua_State* L, const char* name,
lua_CFunction func) {
BeginEntry(L, name); BeginEntry(L, name);
GELua::lua_pushcclosure(L, func, 0); GELua::lua_pushcclosure(L, func, 0);
EndEntry(L); EndEntry(L);
+8 -5
View File
@@ -3,8 +3,8 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include "Memory/Memory.h"
#include <MinHook.h> #include <MinHook.h>
#include "Memory/Memory.h"
#pragma once #pragma once
template<class FuncType> template<class FuncType>
@@ -12,10 +12,11 @@ class Hook {
FuncType targetPtr; FuncType targetPtr;
FuncType detourFunc; FuncType detourFunc;
bool Attached = false; bool Attached = false;
public:
public:
Hook(FuncType src, FuncType dest) : targetPtr(src), detourFunc(dest) { Hook(FuncType src, FuncType dest) : targetPtr(src), detourFunc(dest) {
auto status = MH_CreateHook((void*)targetPtr, (void*)detourFunc, (void**)&Original); auto status =
MH_CreateHook((void*)targetPtr, (void*)detourFunc, (void**)&Original);
if (status != MH_OK) { if (status != MH_OK) {
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status));
return; return;
@@ -26,7 +27,8 @@ public:
if (!Attached) { if (!Attached) {
auto status = MH_EnableHook((void*)targetPtr); auto status = MH_EnableHook((void*)targetPtr);
if (status != MH_OK) { if (status != MH_OK) {
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); Memory::Print(std::string("MH Error -> ") +
MH_StatusToString(status));
return; return;
} }
Attached = true; Attached = true;
@@ -37,7 +39,8 @@ public:
if (Attached) { if (Attached) {
auto status = MH_DisableHook((void*)targetPtr); auto status = MH_DisableHook((void*)targetPtr);
if (status != MH_OK) { if (status != MH_OK) {
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); Memory::Print(std::string("MH Error -> ") +
MH_StatusToString(status));
return; return;
} }
Attached = false; Attached = false;
+1
View File
@@ -22,6 +22,7 @@ public:
void receive() noexcept; void receive() noexcept;
~IPC() noexcept; ~IPC() noexcept;
static bool mem_used(uint32_t MemID) noexcept; static bool mem_used(uint32_t MemID) noexcept;
private: private:
void* SemConfHandle_; void* SemConfHandle_;
void* MemoryHandle_; void* MemoryHandle_;
+1 -1
View File
@@ -4,8 +4,8 @@
/// ///
#pragma once #pragma once
#include <string>
#include <set> #include <set>
#include <string>
class Memory { class Memory {
public: public:
+46 -35
View File
@@ -6,51 +6,62 @@
#pragma once #pragma once
namespace Patterns { namespace Patterns {
const char* GetTickCount[2]{ const char* GetTickCount[2]{
"\x48\xff\x25\x00\x00\x00\x00\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\x48\x83\xec\x00\x48\x8d\x4c\x24", "\x48\xff\x25\x00\x00\x00\x00\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\x48"
"xxx????xxxxxxxxxxxx?xxxx" "\x83\xec\x00\x48\x8d\x4c\x24",
}; "xxx????xxxxxxxxxxxx?xxxx"};
const char* open_jit[2]{ const char* open_jit[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b\x05\x00\x00\x00\x00\x48\x33\xc4\x48\x89\x44\x24\x00\x48\x8b\x71\x00\x48\x8d\x54\x24", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b"
"xxxx?xxxx?xxxx?xxx????xxxxxxx?xxx?xxxx" "\x05\x00\x00\x00\x00\x48\x33\xc4\x48\x89\x44\x24\x00\x48\x8b\x71\x00"
}; "\x48\x8d\x54\x24",
"xxxx?xxxx?xxxx?xxx????xxxxxxx?xxx?xxxx"};
const char* get_field[2]{ const char* get_field[2]{
"\x48\x89\x5c\x24\x00\x57\x48\x83\xec\x00\x4d\x8b\xd0\x48\x8b\xd9\xe8\x00\x00\x00\x00\x48\x8b\xf8\x49\xc7\xc0\x00\x00\x00\x00\x90\x49\xff\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00\x00\x00\x48\xb9\x00\x00\x00\x00\x00\x00\x00\x00\x4c\x8d\x44\x24\x00\x48\x0b\xc1\x48\x8b\xd7\x48\x8b\xcb\x48\x89\x44\x24\x00\xe8\x00\x00\x00\x00\x48\x85\xc0", "\x48\x89\x5c\x24\x00\x57\x48\x83\xec\x00\x4d\x8b\xd0\x48\x8b\xd9\xe8"
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?xxxxxxxxxxxxx?x????xxx" "\x00\x00\x00\x00\x48\x8b\xf8\x49\xc7\xc0\x00\x00\x00\x00\x90\x49\xff"
}; "\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00"
"\x00\x00\x48\xb9\x00\x00\x00\x00\x00\x00\x00\x00\x4c\x8d\x44\x24\x00"
"\x48\x0b\xc1\x48\x8b\xd7\x48\x8b\xcb\x48\x89\x44\x24\x00\xe8\x00\x00"
"\x00\x00\x48\x85\xc0",
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?"
"xxxxxxxxxxxxx?x????xxx"};
const char* push_fstring[2]{ const char* push_fstring[2]{
"\x48\x89\x54\x24\x00\x4c\x89\x44\x24\x00\x4c\x89\x4c\x24\x00\x53\x48\x83\xec\x00\x4c\x8b\x41", "\x48\x89\x54\x24\x00\x4c\x89\x44\x24\x00\x4c\x89\x4c\x24\x00\x53\x48"
"xxxx?xxxx?xxxx?xxxx?xxx" "\x83\xec\x00\x4c\x8b\x41",
}; "xxxx?xxxx?xxxx?xxxx?xxx"};
const char* p_call[2]{ const char* p_call[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b\x59\x00\x41\x8b\xf0\x4c\x63\xda", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b"
"xxxx?xxxx?xxxx?xxx?xxxxxx" "\x59\x00\x41\x8b\xf0\x4c\x63\xda",
}; "xxxx?xxxx?xxxx?xxx?xxxxxx"};
const char* lua_setfield[2]{ const char* lua_setfield[2]{
"\x48\x89\x5c\x24\x00\x57\x48\x83\xec\x00\x4d\x8b\xd0\x48\x8b\xd9\xe8\x00\x00\x00\x00\x48\x8b\xf8\x49\xc7\xc0\x00\x00\x00\x00\x90\x49\xff\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00\x00\x00\x48\xb9\x00\x00\x00\x00\x00\x00\x00\x00\x4c\x8d\x44\x24\x00\x48\x0b\xc1\x48\x8b\xd7\x48\x8b\xcb\x48\x89\x44\x24\x00\xe8\x00\x00\x00\x00\x48\x8b\x53", "\x48\x89\x5c\x24\x00\x57\x48\x83\xec\x00\x4d\x8b\xd0\x48\x8b\xd9\xe8"
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?xxxxxxxxxxxxx?x????xxx" "\x00\x00\x00\x00\x48\x8b\xf8\x49\xc7\xc0\x00\x00\x00\x00\x90\x49\xff"
}; "\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00"
"\x00\x00\x48\xb9\x00\x00\x00\x00\x00\x00\x00\x00\x4c\x8d\x44\x24\x00"
"\x48\x0b\xc1\x48\x8b\xd7\x48\x8b\xcb\x48\x89\x44\x24\x00\xe8\x00\x00"
"\x00\x00\x48\x8b\x53",
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?"
"xxxxxxxxxxxxx?x????xxx"};
const char* lua_createtable[2]{ const char* lua_createtable[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x4c\x8b\x49\x00\x41\x8b\xf8", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x4c\x8b"
"xxxx?xxxx?xxxx?xxx?xxx" "\x49\x00\x41\x8b\xf8",
}; "xxxx?xxxx?xxxx?xxx?xxx"};
const char* lua_settable[2]{ const char* lua_settable[2]{
"\x40\x53\x48\x83\xec\x00\x48\x8b\xd9\xe8\x00\x00\x00\x00\x4c\x8b\x43\x00\x48\x8b\xd0\x49\x83\xe8\x00\x48\x8b\xcb\xe8\x00\x00\x00\x00\x48\x8b\x53", "\x40\x53\x48\x83\xec\x00\x48\x8b\xd9\xe8\x00\x00\x00\x00\x4c\x8b\x43"
"xxxxx?xxxx????xxx?xxxxxx?xxxx????xxx" "\x00\x48\x8b\xd0\x49\x83\xe8\x00\x48\x8b\xcb\xe8\x00\x00\x00\x00\x48"
}; "\x8b\x53",
"xxxxx?xxxx????xxx?xxxxxx?xxxx????xxx"};
const char* lua_pushcclosure[2]{ const char* lua_pushcclosure[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b\xd9\x49\x63\xf8\x48\x8b\x49\x00\x48\x8b\xf2", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b"
"xxxx?xxxx?xxxx?xxxxxxxxx?xxx" "\xd9\x49\x63\xf8\x48\x8b\x49\x00\x48\x8b\xf2",
}; "xxxx?xxxx?xxxx?xxxxxxxxx?xxx"};
const char* lua_tolstring[2]{ const char* lua_tolstring[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x49\x8b\xf8\x8b\xda\x48\x8b\xf1\xe8", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x49\x8b"
"xxxx?xxxx?xxxx?xxxxxxxxx" "\xf8\x8b\xda\x48\x8b\xf1\xe8",
}; "xxxx?xxxx?xxxx?xxxxxxxxx"};
const char* GEUpdate[2]{ const char* GEUpdate[2]{
"\x48\x89\x5c\x24\x00\x48\x89\x6c\x24\x00\x56\x57\x41\x56\x48\x83\xec\x00\x4c\x8b\x31\x49\x8b\xf0", "\x48\x89\x5c\x24\x00\x48\x89\x6c\x24\x00\x56\x57\x41\x56\x48\x83\xec"
"xxxx?xxxx?xxxxxxx?xxxxxx" "\x00\x4c\x8b\x31\x49\x8b\xf0",
}; "xxxx?xxxx?xxxxxxx?xxxxxx"};
const char* lua_settop[2]{ const char* lua_settop[2]{
"\x4c\x8b\xc1\x85\xd2\x7e\x00\x48\x8b\x41\x00\x48\x8b\x49", "\x4c\x8b\xc1\x85\xd2\x7e\x00\x48\x8b\x41\x00\x48\x8b\x49",
"xxxxxx?xxx?xxx" "xxxxxx?xxx?xxx"};
};
} }
+4 -2
View File
@@ -30,8 +30,10 @@ public:
void Close(); void Close();
private: private:
std::chrono::time_point<std::chrono::high_resolution_clock> PingStart, PingEnd; std::chrono::time_point<std::chrono::high_resolution_clock> PingStart,
std::string MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name); PingEnd;
std::string MultiDownload(uint64_t DSock, uint64_t Size,
const std::string& Name);
void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name); void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name);
std::atomic<bool> Terminate{false}, ModLoaded{false}; std::atomic<bool> Terminate{false}, ModLoaded{false};
char* TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size); char* TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size);
+3 -7
View File
@@ -12,8 +12,7 @@ class atomic_queue {
public: public:
bool try_pop(T& val) { bool try_pop(T& val) {
lock_guard guard(semaphore); lock_guard guard(semaphore);
if (queue.empty()) if (queue.empty()) return false;
return false;
val = queue.front(); val = queue.front();
queue.pop(); queue.pop();
full.release(); full.release();
@@ -45,13 +44,10 @@ private:
private: private:
struct lock_guard { struct lock_guard {
explicit lock_guard(std::binary_semaphore& lock) explicit lock_guard(std::binary_semaphore& lock) : lock(lock) {
: lock(lock) {
lock.acquire(); lock.acquire();
} }
~lock_guard() { ~lock_guard() { lock.release(); }
lock.release();
}
private: private:
std::binary_semaphore& lock; std::binary_semaphore& lock;
+5 -11
View File
@@ -3,9 +3,9 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include <tomlplusplus/toml.hpp>
#include "Launcher.h" #include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include <tomlplusplus/toml.hpp>
void Launcher::LoadConfig() { void Launcher::LoadConfig() {
if (fs::exists("Launcher.toml")) { if (fs::exists("Launcher.toml")) {
@@ -14,24 +14,18 @@ void Launcher::LoadConfig() {
auto build = config["Build"]; auto build = config["Build"];
if (ui.is_boolean()) { if (ui.is_boolean()) {
EnableUI = ui.as_boolean()->get(); EnableUI = ui.as_boolean()->get();
} else } else LOG(ERROR) << "Failed to get 'UI' boolean from config";
LOG(ERROR) << "Failed to get 'UI' boolean from config";
// Default -1 / Release 1 / EA 2 / Dev 3 / Custom 3 // Default -1 / Release 1 / EA 2 / Dev 3 / Custom 3
if (build.is_string()) { if (build.is_string()) {
TargetBuild = build.as_string()->get(); TargetBuild = build.as_string()->get();
for (char& c : TargetBuild) for (char& c : TargetBuild) c = char(tolower(c));
c = char(tolower(c)); } else LOG(ERROR) << "Failed to get 'Build' string from config";
} else
LOG(ERROR) << "Failed to get 'Build' string from config";
} else { } else {
std::ofstream tml("Launcher.toml"); std::ofstream tml("Launcher.toml");
if (tml.is_open()) { if (tml.is_open()) {
tml << tml << "UI = true\n Build = \"Default\"";
R"(UI = true
Build = "Default"
)";
tml.close(); tml.close();
} else { } else {
LOG(FATAL) << "Failed to write config on disk!"; LOG(FATAL) << "Failed to write config on disk!";
+2 -2
View File
@@ -3,10 +3,10 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#ifndef DEBUG #ifndef DEBUG
#include <discord_rpc.h>
#include <ctime>
#include "Launcher.h" #include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include <ctime>
#include <discord_rpc.h>
void handleReady(const DiscordUser* u) {} void handleReady(const DiscordUser* u) {}
void handleDisconnected(int errcode, const char* message) {} void handleDisconnected(int errcode, const char* message) {}
+13 -18
View File
@@ -11,8 +11,7 @@
void Launcher::HandleIPC(const std::string& Data) { void Launcher::HandleIPC(const std::string& Data) {
char Code = Data.at(0), SubCode = 0; char Code = Data.at(0), SubCode = 0;
if (Data.length() > 1) if (Data.length() > 1) SubCode = Data.at(1);
SubCode = Data.at(1);
switch (Code) { switch (Code) {
case 'A': case 'A':
ServerHandler.StartUDP(); ServerHandler.StartUDP();
@@ -25,20 +24,18 @@ void Launcher::HandleIPC(const std::string& Data) {
case 'C': case 'C':
ServerHandler.Close(); ServerHandler.Close();
ServerHandler.Connect(Data); ServerHandler.Connect(Data);
while (ServerHandler.getModList().empty() && !ServerHandler.Terminated()) { while (ServerHandler.getModList().empty() &&
!ServerHandler.Terminated()) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if (ServerHandler.getModList() == "-") if (ServerHandler.getModList() == "-") SendIPC("L");
SendIPC("L"); else SendIPC("L" + ServerHandler.getModList());
else
SendIPC("L" + ServerHandler.getModList());
break; break;
case 'U': case 'U':
SendIPC("Ul" + ServerHandler.getUIStatus()); SendIPC("Ul" + ServerHandler.getUIStatus());
if (ServerHandler.getPing() > 800) { if (ServerHandler.getPing() > 800) {
SendIPC("Up-2"); SendIPC("Up-2");
} else } else SendIPC("Up" + std::to_string(ServerHandler.getPing()));
SendIPC("Up" + std::to_string(ServerHandler.getPing()));
break; break;
case 'M': case 'M':
SendIPC(ServerHandler.getMap()); SendIPC(ServerHandler.getMap());
@@ -47,8 +44,7 @@ void Launcher::HandleIPC(const std::string& Data) {
if (SubCode == 'S') { if (SubCode == 'S') {
ServerHandler.Close(); ServerHandler.Close();
} }
if (SubCode == 'G') if (SubCode == 'G') exit(2);
exit(2);
break; break;
case 'R': // will send mod name case 'R': // will send mod name
ServerHandler.setModLoaded(); ServerHandler.setModLoaded();
@@ -69,18 +65,17 @@ void Launcher::HandleIPC(const std::string& Data) {
} }
void Server::ServerParser(const std::string& Data) { void Server::ServerParser(const std::string& Data) {
if (Data.empty()) if (Data.empty()) return;
return;
char Code = Data.at(0), SubCode = 0; char Code = Data.at(0), SubCode = 0;
if (Data.length() > 1) if (Data.length() > 1) SubCode = Data.at(1);
SubCode = Data.at(1);
switch (Code) { switch (Code) {
case 'p': case 'p':
PingEnd = std::chrono::high_resolution_clock::now(); PingEnd = std::chrono::high_resolution_clock::now();
if (PingStart > PingEnd) if (PingStart > PingEnd) Ping = 0;
Ping = 0;
else else
Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd - PingStart).count()); Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(
PingEnd - PingStart)
.count());
return; return;
case 'M': case 'M':
MStatus = Data; MStatus = Data;
+42 -28
View File
@@ -5,24 +5,25 @@
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include "Launcher.h" #include "Launcher.h"
#include <ShlObj.h>
#include <comutil.h>
#include <shellapi.h>
#include <windows.h>
#include <csignal>
#include <mutex>
#include "HttpAPI.h" #include "HttpAPI.h"
#include "Logger.h" #include "Logger.h"
#include "Memory/Memory.h" #include "Memory/Memory.h"
#include <ShlObj.h>
#include <comutil.h>
#include <csignal>
#include <mutex>
#include <shellapi.h>
#include <windows.h>
LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) { LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) {
LOG(ERROR) << "CAUGHT EXCEPTION! Code 0x" << std::hex << std::uppercase << p->ExceptionRecord->ExceptionCode; LOG(ERROR) << "CAUGHT EXCEPTION! Code 0x" << std::hex << std::uppercase
<< p->ExceptionRecord->ExceptionCode;
return EXCEPTION_EXECUTE_HANDLER; return EXCEPTION_EXECUTE_HANDLER;
} }
Launcher::Launcher(int argc, char* argv[]) Launcher::Launcher(int argc, char* argv[]) :
: CurrentPath(std::filesystem::path(argv[0])) CurrentPath(std::filesystem::path(argv[0])),
, DiscordMessage("Just launched") { DiscordMessage("Just launched") {
Launcher::StaticAbort(this); Launcher::StaticAbort(this);
DiscordTime = std::time(nullptr); DiscordTime = std::time(nullptr);
Log::Init(); Log::Init();
@@ -89,22 +90,30 @@ void Launcher::WindowsInit() {
void Launcher::LaunchGame() { void Launcher::LaunchGame() {
VersionParser GameVersion(BeamVersion); VersionParser GameVersion(BeamVersion);
if (GameVersion.data[1] > SupportedVersion.data[1]) { if (GameVersion.data[1] > SupportedVersion.data[1]) {
LOG(FATAL) << "BeamNG V" << BeamVersion << " not yet supported, please wait until we update BeamMP!"; LOG(FATAL) << "BeamNG V" << BeamVersion
<< " not yet supported, please wait until we update BeamMP!";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} else if (GameVersion.data[1] < SupportedVersion.data[1]) { } else if (GameVersion.data[1] < SupportedVersion.data[1]) {
LOG(FATAL) << "BeamNG V" << BeamVersion << " not supported, please update and launch the new update!"; LOG(FATAL) << "BeamNG V" << BeamVersion
<< " not supported, please update and launch the new update!";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} else if (GameVersion > SupportedVersion) { } else if (GameVersion > SupportedVersion) {
LOG(WARNING) << "BeamNG V" << BeamVersion << " is slightly newer than recommended, this might cause issues!"; LOG(WARNING)
<< "BeamNG V" << BeamVersion
<< " is slightly newer than recommended, this might cause issues!";
} else if (GameVersion < SupportedVersion) { } else if (GameVersion < SupportedVersion) {
LOG(WARNING) << "BeamNG V" << BeamVersion << " is slightly older than recommended, this might cause issues!"; LOG(WARNING)
<< "BeamNG V" << BeamVersion
<< " is slightly older than recommended, this might cause issues!";
} }
if (Memory::GetBeamNGPID({}) == 0) { if (Memory::GetBeamNGPID({}) == 0) {
LOG(INFO) << "Launching BeamNG from steam"; LOG(INFO) << "Launching BeamNG from steam";
ShellExecuteA(nullptr, nullptr, "steam://rungameid/284160", nullptr, nullptr, SW_SHOWNORMAL); ShellExecuteA(nullptr, nullptr, "steam://rungameid/284160", nullptr,
nullptr, SW_SHOWNORMAL);
// ShowWindow(GetConsoleWindow(), HIDE_WINDOW); // ShowWindow(GetConsoleWindow(), HIDE_WINDOW);
} }
LOG(INFO) << "Waiting for a game process, please start BeamNG manually in case of steam issues"; LOG(INFO) << "Waiting for a game process, please start BeamNG manually in "
"case of steam issues";
} }
void Launcher::WaitForGame() { void Launcher::WaitForGame() {
@@ -118,8 +127,7 @@ void Launcher::WaitForGame() {
} }
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} while (GamePID == 0 && !Shutdown.load()); } while (GamePID == 0 && !Shutdown.load());
if (Shutdown.load()) if (Shutdown.load()) return;
return;
if (GamePID == 0) { if (GamePID == 0) {
LOG(FATAL) << "Game process not found! aborting"; LOG(FATAL) << "Game process not found! aborting";
@@ -159,10 +167,8 @@ void Launcher::ListenIPC() {
void Launcher::SendIPC(const std::string& Data, bool core) { void Launcher::SendIPC(const std::string& Data, bool core) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
if (core) if (core) IPCToGame->send("C" + Data);
IPCToGame->send("C" + Data); else IPCToGame->send("G" + Data);
else
IPCToGame->send("G" + Data);
if (IPCToGame->send_timed_out()) { if (IPCToGame->send_timed_out()) {
LOG(WARNING) << "Timed out while sending \"" << Data << "\""; LOG(WARNING) << "Timed out while sending \"" << Data << "\"";
} }
@@ -171,7 +177,8 @@ void Launcher::SendIPC(const std::string& Data, bool core) {
std::string QueryValue(HKEY& hKey, const char* Name) { std::string QueryValue(HKEY& hKey, const char* Name) {
DWORD keySize; DWORD keySize;
BYTE buffer[16384]; BYTE buffer[16384];
if (RegQueryValueExA(hKey, Name, nullptr, nullptr, buffer, &keySize) == ERROR_SUCCESS) { if (RegQueryValueExA(hKey, Name, nullptr, nullptr, buffer, &keySize) ==
ERROR_SUCCESS) {
return {(char*)buffer, keySize - 1}; return {(char*)buffer, keySize - 1};
} }
return {}; return {};
@@ -179,7 +186,8 @@ std::string QueryValue(HKEY& hKey, const char* Name) {
std::string Launcher::GetLocalAppdata() { std::string Launcher::GetLocalAppdata() {
PWSTR folderPath = nullptr; PWSTR folderPath = nullptr;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &folderPath); HRESULT hr =
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &folderPath);
if (!SUCCEEDED(hr)) { if (!SUCCEEDED(hr)) {
LOG(FATAL) << "Failed to get path of localAppData"; LOG(FATAL) << "Failed to get path of localAppData";
@@ -200,7 +208,9 @@ std::string Launcher::GetLocalAppdata() {
} }
void Launcher::QueryRegistry() { void Launcher::QueryRegistry() {
HKEY BeamNG; HKEY BeamNG;
LONG RegRes = RegOpenKeyExA(HKEY_CURRENT_USER, R"(Software\BeamNG\BeamNG.drive)", 0, KEY_READ, &BeamNG); LONG RegRes =
RegOpenKeyExA(HKEY_CURRENT_USER, R"(Software\BeamNG\BeamNG.drive)", 0,
KEY_READ, &BeamNG);
if (RegRes == ERROR_SUCCESS) { if (RegRes == ERROR_SUCCESS) {
BeamRoot = QueryValue(BeamNG, "rootpath"); BeamRoot = QueryValue(BeamNG, "rootpath");
BeamVersion = QueryValue(BeamNG, "version"); BeamVersion = QueryValue(BeamNG, "version");
@@ -218,19 +228,23 @@ void Launcher::QueryRegistry() {
if (!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty()) if (!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty())
return; return;
} }
LOG(FATAL) << "Please launch the game at least once, failed to read registry key Software\\BeamNG\\BeamNG.drive"; LOG(FATAL)
<< "Please launch the game at least once, failed to read registry "
"key Software\\BeamNG\\BeamNG.drive";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} }
void Launcher::AdminRelaunch() { void Launcher::AdminRelaunch() {
system("cls"); system("cls");
ShellExecuteA(nullptr, "runas", CurrentPath.string().c_str(), nullptr, nullptr, SW_SHOWNORMAL); ShellExecuteA(nullptr, "runas", CurrentPath.string().c_str(), nullptr,
nullptr, SW_SHOWNORMAL);
ShowWindow(GetConsoleWindow(), 0); ShowWindow(GetConsoleWindow(), 0);
throw ShutdownException("Relaunching"); throw ShutdownException("Relaunching");
} }
void Launcher::Relaunch() { void Launcher::Relaunch() {
ShellExecuteA(nullptr, "open", CurrentPath.string().c_str(), nullptr, nullptr, SW_SHOWNORMAL); ShellExecuteA(nullptr, "open", CurrentPath.string().c_str(), nullptr,
nullptr, SW_SHOWNORMAL);
ShowWindow(GetConsoleWindow(), 0); ShowWindow(GetConsoleWindow(), 0);
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
throw ShutdownException("Relaunching"); throw ShutdownException("Relaunching");
+4 -2
View File
@@ -9,8 +9,10 @@ using namespace el;
void Log::Init() { void Log::Init() {
Configurations Conf; Configurations Conf;
Conf.setToDefault(); Conf.setToDefault();
std::string DFormat("%datetime{[%d/%M/%y %H:%m:%s]} %fbase:%line [%level] %msg"); std::string DFormat(
Conf.setGlobally(ConfigurationType::Format, "%datetime{[%d/%M/%y %H:%m:%s]} [%level] %msg"); "%datetime{[%d/%M/%y %H:%m:%s]} %fbase:%line [%level] %msg");
Conf.setGlobally(ConfigurationType::Format,
"%datetime{[%d/%M/%y %H:%m:%s]} [%level] %msg");
Conf.setGlobally(ConfigurationType::LogFlushThreshold, "2"); Conf.setGlobally(ConfigurationType::LogFlushThreshold, "2");
Conf.set(Level::Verbose, ConfigurationType::Format, DFormat); Conf.set(Level::Verbose, ConfigurationType::Format, DFormat);
Conf.set(Level::Debug, ConfigurationType::Format, DFormat); Conf.set(Level::Debug, ConfigurationType::Format, DFormat);
+7 -5
View File
@@ -26,7 +26,8 @@ void BeamNG::EntryPoint() {
GELua::FindAddresses(); GELua::FindAddresses();
/*GameBaseAddr = Memory::GetModuleBase(GameModule); /*GameBaseAddr = Memory::GetModuleBase(GameModule);
DllBaseAddr = Memory::GetModuleBase(DllModule);*/ DllBaseAddr = Memory::GetModuleBase(DllModule);*/
OpenJITDetour = std::make_unique<Hook<def::lua_open_jit>>(GELua::lua_open_jit, lua_open_jit_D); OpenJITDetour = std::make_unique<Hook<def::lua_open_jit>>(
GELua::lua_open_jit, lua_open_jit_D);
OpenJITDetour->Enable(); OpenJITDetour->Enable();
IPCFromLauncher = std::make_unique<IPC>(PID, 0x1900000); IPCFromLauncher = std::make_unique<IPC>(PID, 0x1900000);
IPCToLauncher = std::make_unique<IPC>(PID + 1, 0x1900000); IPCToLauncher = std::make_unique<IPC>(PID + 1, 0x1900000);
@@ -37,7 +38,8 @@ int Core(lua_State* L) {
if (lua_gettop(L) == 1) { if (lua_gettop(L) == 1) {
size_t Size; size_t Size;
const char* Data = GELua::lua_tolstring(L, 1, &Size); const char* Data = GELua::lua_tolstring(L, 1, &Size);
// Memory::Print("Core -> " + std::string(Data) + " - " + std::to_string(Size)); // Memory::Print("Core -> " + std::string(Data) + " - " +
// std::to_string(Size));
std::string msg(Data, Size); std::string msg(Data, Size);
BeamNG::SendIPC("C" + msg); BeamNG::SendIPC("C" + msg);
} }
@@ -48,7 +50,8 @@ int Game(lua_State* L) {
if (lua_gettop(L) == 1) { if (lua_gettop(L) == 1) {
size_t Size; size_t Size;
const char* Data = GELua::lua_tolstring(L, 1, &Size); const char* Data = GELua::lua_tolstring(L, 1, &Size);
// Memory::Print("Game -> " + std::string(Data) + " - " + std::to_string(Size)); // Memory::Print("Game -> " + std::string(Data) + " - " +
// std::to_string(Size));
std::string msg(Data, Size); std::string msg(Data, Size);
BeamNG::SendIPC("G" + msg); BeamNG::SendIPC("G" + msg);
} }
@@ -86,8 +89,7 @@ void BeamNG::IPCListener() {
TimeOuts = 0; TimeOuts = 0;
Queue->push(IPCFromLauncher->msg()); Queue->push(IPCFromLauncher->msg());
IPCFromLauncher->confirm_receive(); IPCFromLauncher->confirm_receive();
} else } else TimeOuts++;
TimeOuts++;
} }
Memory::Print("IPC System shutting down"); Memory::Print("IPC System shutting down");
} }
+48 -24
View File
@@ -19,28 +19,52 @@ std::string GetHex(uint64_t num) {
void GELua::FindAddresses() { void GELua::FindAddresses() {
GELua::State = nullptr; GELua::State = nullptr;
auto Base = Memory::GetModuleBase(GameModule); auto Base = Memory::GetModuleBase(GameModule);
GetTickCount = reinterpret_cast<def::GetTickCount>(Memory::FindPattern(GameModule, Patterns::GetTickCount)); GetTickCount = reinterpret_cast<def::GetTickCount>(
Memory::Print("GetTickCount -> " + GetHex(reinterpret_cast<uint64_t>(GetTickCount) - Base)); Memory::FindPattern(GameModule, Patterns::GetTickCount));
lua_open_jit = reinterpret_cast<def::lua_open_jit>(Memory::FindPattern(GameModule, Patterns::open_jit)); Memory::Print("GetTickCount -> " +
Memory::Print("lua_open_jit -> " + GetHex(reinterpret_cast<uint64_t>(lua_open_jit) - Base)); GetHex(reinterpret_cast<uint64_t>(GetTickCount) - Base));
lua_push_fstring = reinterpret_cast<def::lua_push_fstring>(Memory::FindPattern(GameModule, Patterns::push_fstring)); lua_open_jit = reinterpret_cast<def::lua_open_jit>(
Memory::Print("lua_push_fstring -> " + GetHex(reinterpret_cast<uint64_t>(lua_push_fstring) - Base)); Memory::FindPattern(GameModule, Patterns::open_jit));
lua_get_field = reinterpret_cast<def::lua_get_field>(Memory::FindPattern(GameModule, Patterns::get_field)); Memory::Print("lua_open_jit -> " +
Memory::Print("lua_get_field -> " + GetHex(reinterpret_cast<uint64_t>(lua_get_field) - Base)); GetHex(reinterpret_cast<uint64_t>(lua_open_jit) - Base));
lua_p_call = reinterpret_cast<def::lua_p_call>(Memory::FindPattern(GameModule, Patterns::p_call)); lua_push_fstring = reinterpret_cast<def::lua_push_fstring>(
Memory::Print("lua_p_call -> " + GetHex(reinterpret_cast<uint64_t>(lua_p_call) - Base)); Memory::FindPattern(GameModule, Patterns::push_fstring));
lua_createtable = reinterpret_cast<def::lua_createtable>(Memory::FindPattern(GameModule, Patterns::lua_createtable)); Memory::Print("lua_push_fstring -> " +
Memory::Print("lua_createtable -> " + GetHex(reinterpret_cast<uint64_t>(lua_createtable) - Base)); GetHex(reinterpret_cast<uint64_t>(lua_push_fstring) - Base));
lua_pushcclosure = reinterpret_cast<def::lua_pushcclosure>(Memory::FindPattern(GameModule, Patterns::lua_pushcclosure)); lua_get_field = reinterpret_cast<def::lua_get_field>(
Memory::Print("lua_pushcclosure -> " + GetHex(reinterpret_cast<uint64_t>(lua_pushcclosure) - Base)); Memory::FindPattern(GameModule, Patterns::get_field));
lua_setfield = reinterpret_cast<def::lua_setfield>(Memory::FindPattern(GameModule, Patterns::lua_setfield)); Memory::Print("lua_get_field -> " +
Memory::Print("lua_setfield -> " + GetHex(reinterpret_cast<uint64_t>(lua_setfield) - Base)); GetHex(reinterpret_cast<uint64_t>(lua_get_field) - Base));
lua_settable = reinterpret_cast<def::lua_settable>(Memory::FindPattern(GameModule, Patterns::lua_settable)); lua_p_call = reinterpret_cast<def::lua_p_call>(
Memory::Print("lua_settable -> " + GetHex(reinterpret_cast<uint64_t>(lua_settable) - Base)); Memory::FindPattern(GameModule, Patterns::p_call));
lua_tolstring = reinterpret_cast<def::lua_tolstring>(Memory::FindPattern(GameModule, Patterns::lua_tolstring)); Memory::Print("lua_p_call -> " +
Memory::Print("lua_tolstring -> " + GetHex(reinterpret_cast<uint64_t>(lua_tolstring) - Base)); GetHex(reinterpret_cast<uint64_t>(lua_p_call) - Base));
GEUpdate = reinterpret_cast<def::GEUpdate>(Memory::FindPattern(GameModule, Patterns::GEUpdate)); lua_createtable = reinterpret_cast<def::lua_createtable>(
Memory::Print("GEUpdate -> " + GetHex(reinterpret_cast<uint64_t>(GEUpdate) - Base)); Memory::FindPattern(GameModule, Patterns::lua_createtable));
lua_settop = reinterpret_cast<def::lua_settop>(Memory::FindPattern(GameModule, Patterns::lua_settop)); Memory::Print("lua_createtable -> " +
Memory::Print("lua_settop -> " + GetHex(reinterpret_cast<uint64_t>(lua_settop) - Base)); GetHex(reinterpret_cast<uint64_t>(lua_createtable) - Base));
lua_pushcclosure = reinterpret_cast<def::lua_pushcclosure>(
Memory::FindPattern(GameModule, Patterns::lua_pushcclosure));
Memory::Print("lua_pushcclosure -> " +
GetHex(reinterpret_cast<uint64_t>(lua_pushcclosure) - Base));
lua_setfield = reinterpret_cast<def::lua_setfield>(
Memory::FindPattern(GameModule, Patterns::lua_setfield));
Memory::Print("lua_setfield -> " +
GetHex(reinterpret_cast<uint64_t>(lua_setfield) - Base));
lua_settable = reinterpret_cast<def::lua_settable>(
Memory::FindPattern(GameModule, Patterns::lua_settable));
Memory::Print("lua_settable -> " +
GetHex(reinterpret_cast<uint64_t>(lua_settable) - Base));
lua_tolstring = reinterpret_cast<def::lua_tolstring>(
Memory::FindPattern(GameModule, Patterns::lua_tolstring));
Memory::Print("lua_tolstring -> " +
GetHex(reinterpret_cast<uint64_t>(lua_tolstring) - Base));
GEUpdate = reinterpret_cast<def::GEUpdate>(
Memory::FindPattern(GameModule, Patterns::GEUpdate));
Memory::Print("GEUpdate -> " +
GetHex(reinterpret_cast<uint64_t>(GEUpdate) - Base));
lua_settop = reinterpret_cast<def::lua_settop>(
Memory::FindPattern(GameModule, Patterns::lua_settop));
Memory::Print("lua_settop -> " +
GetHex(reinterpret_cast<uint64_t>(lua_settop) - Base));
} }
+9 -7
View File
@@ -7,23 +7,25 @@
#include "Memory/IPC.h" #include "Memory/IPC.h"
#include <windows.h> #include <windows.h>
IPC::IPC(uint32_t ID, size_t Size) noexcept IPC::IPC(uint32_t ID, size_t Size) noexcept : Size_(Size) {
: Size_(Size) {
std::string Sem{"MP_S" + std::to_string(ID)}, std::string Sem{"MP_S" + std::to_string(ID)},
SemConf { "MP_SC" + std::to_string(ID) }, SemConf{"MP_SC" + std::to_string(ID)}, Mem{"MP_IO" + std::to_string(ID)};
Mem { "MP_IO" + std::to_string(ID) };
SemHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, Sem.c_str()); SemHandle_ =
OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, Sem.c_str());
if (SemHandle_ == nullptr) { if (SemHandle_ == nullptr) {
SemHandle_ = CreateSemaphoreA(nullptr, 0, 1, Sem.c_str()); SemHandle_ = CreateSemaphoreA(nullptr, 0, 1, Sem.c_str());
} }
SemConfHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, SemConf.c_str()); SemConfHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE,
SemConf.c_str());
if (SemConfHandle_ == nullptr) { if (SemConfHandle_ == nullptr) {
SemConfHandle_ = CreateSemaphoreA(nullptr, 0, 1, SemConf.c_str()); SemConfHandle_ = CreateSemaphoreA(nullptr, 0, 1, SemConf.c_str());
} }
MemoryHandle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str()); MemoryHandle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str());
if (MemoryHandle_ == nullptr) { if (MemoryHandle_ == nullptr) {
MemoryHandle_ = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(Size), Mem.c_str()); MemoryHandle_ =
CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0,
DWORD(Size), Mem.c_str());
} }
Data_ = (char*)MapViewOfFile(MemoryHandle_, FILE_MAP_ALL_ACCESS, 0, 0, Size); Data_ = (char*)MapViewOfFile(MemoryHandle_, FILE_MAP_ALL_ACCESS, 0, 0, Size);
} }
+38 -18
View File
@@ -6,10 +6,10 @@
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#undef UNICODE #undef UNICODE
#include "Memory/Memory.h" #include "Memory/Memory.h"
#include "Memory/BeamNG.h"
#include <psapi.h> #include <psapi.h>
#include <string>
#include <tlhelp32.h> #include <tlhelp32.h>
#include <string>
#include "Memory/BeamNG.h"
uint32_t Memory::GetBeamNGPID(const std::set<uint32_t>& BL) { uint32_t Memory::GetBeamNGPID(const std::set<uint32_t>& BL) {
SetLastError(0); SetLastError(0);
@@ -19,9 +19,9 @@ uint32_t Memory::GetBeamNGPID(const std::set<uint32_t>& BL) {
if (Process32First(Snapshot, &pe32)) { if (Process32First(Snapshot, &pe32)) {
do { do {
if (std::string("BeamNG.drive.x64.exe") == pe32.szExeFile if (std::string("BeamNG.drive.x64.exe") == pe32.szExeFile &&
&& BL.find(pe32.th32ProcessID) == BL.end() BL.find(pe32.th32ProcessID) == BL.end() &&
&& BL.find(pe32.th32ParentProcessID) == BL.end()) { BL.find(pe32.th32ParentProcessID) == BL.end()) {
break; break;
} }
} while (Process32Next(Snapshot, &pe32)); } while (Process32Next(Snapshot, &pe32));
@@ -31,8 +31,7 @@ uint32_t Memory::GetBeamNGPID(const std::set<uint32_t>& BL) {
CloseHandle(Snapshot); CloseHandle(Snapshot);
} }
if (GetLastError() != 0) if (GetLastError() != 0) return 0;
return 0;
return pe32.th32ProcessID; return pe32.th32ProcessID;
} }
@@ -46,14 +45,16 @@ uint32_t Memory::GetPID() {
uint64_t Memory::FindPattern(const char* module, const char* Pattern[]) { uint64_t Memory::FindPattern(const char* module, const char* Pattern[]) {
MODULEINFO mInfo{nullptr}; MODULEINFO mInfo{nullptr};
GetModuleInformation(GetCurrentProcess(), GetModuleHandleA(module), &mInfo, sizeof(MODULEINFO)); GetModuleInformation(GetCurrentProcess(), GetModuleHandleA(module), &mInfo,
sizeof(MODULEINFO));
auto base = uint64_t(mInfo.lpBaseOfDll); auto base = uint64_t(mInfo.lpBaseOfDll);
auto size = uint32_t(mInfo.SizeOfImage); auto size = uint32_t(mInfo.SizeOfImage);
auto len = strlen(Pattern[1]); auto len = strlen(Pattern[1]);
for (auto i = 0; i < size - len; i++) { for (auto i = 0; i < size - len; i++) {
bool found = true; bool found = true;
for (auto j = 0; j < len && found; j++) { for (auto j = 0; j < len && found; j++) {
found &= Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base + i + j); found &=
Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base + i + j);
} }
if (found) { if (found) {
return base + i; return base + i;
@@ -86,31 +87,50 @@ typedef struct BASE_RELOCATION_ENTRY {
void Memory::Inject(uint32_t PID) { void Memory::Inject(uint32_t PID) {
PVOID imageBase = GetModuleHandle(nullptr); PVOID imageBase = GetModuleHandle(nullptr);
auto dosHeader = (PIMAGE_DOS_HEADER)imageBase; auto dosHeader = (PIMAGE_DOS_HEADER)imageBase;
auto ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)imageBase + dosHeader->e_lfanew); auto ntHeader =
(PIMAGE_NT_HEADERS)((DWORD_PTR)imageBase + dosHeader->e_lfanew);
PVOID localImage = VirtualAlloc(nullptr, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_READWRITE); PVOID localImage =
VirtualAlloc(nullptr, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT,
PAGE_READWRITE);
memcpy(localImage, imageBase, ntHeader->OptionalHeader.SizeOfImage); memcpy(localImage, imageBase, ntHeader->OptionalHeader.SizeOfImage);
HANDLE targetProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, PID); HANDLE targetProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, PID);
PVOID targetImage = VirtualAllocEx(targetProcess, nullptr, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE); PVOID targetImage = VirtualAllocEx(targetProcess, nullptr,
ntHeader->OptionalHeader.SizeOfImage,
MEM_COMMIT, PAGE_EXECUTE_READWRITE);
DWORD_PTR deltaImageBase = DWORD_PTR(targetImage) - DWORD_PTR(imageBase); DWORD_PTR deltaImageBase = DWORD_PTR(targetImage) - DWORD_PTR(imageBase);
auto relocationTable = (PIMAGE_BASE_RELOCATION)((DWORD_PTR)localImage + ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); auto relocationTable =
(PIMAGE_BASE_RELOCATION)((DWORD_PTR)localImage +
ntHeader->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC]
.VirtualAddress);
PDWORD_PTR patchedAddress; PDWORD_PTR patchedAddress;
while (relocationTable->SizeOfBlock > 0) { while (relocationTable->SizeOfBlock > 0) {
DWORD relocationEntriesCount = (relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); DWORD relocationEntriesCount =
(relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) /
sizeof(USHORT);
auto relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1); auto relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1);
for (uint32_t i = 0; i < relocationEntriesCount; i++) { for (uint32_t i = 0; i < relocationEntriesCount; i++) {
if (relocationRVA[i].Offset) { if (relocationRVA[i].Offset) {
patchedAddress = PDWORD_PTR(DWORD_PTR(localImage) + relocationTable->VirtualAddress + relocationRVA[i].Offset); patchedAddress = PDWORD_PTR(DWORD_PTR(localImage) +
relocationTable->VirtualAddress +
relocationRVA[i].Offset);
*patchedAddress += deltaImageBase; *patchedAddress += deltaImageBase;
} }
} }
relocationTable = PIMAGE_BASE_RELOCATION(DWORD_PTR(relocationTable) + relocationTable->SizeOfBlock); relocationTable = PIMAGE_BASE_RELOCATION(DWORD_PTR(relocationTable) +
relocationTable->SizeOfBlock);
} }
WriteProcessMemory(targetProcess, targetImage, localImage, ntHeader->OptionalHeader.SizeOfImage, nullptr); WriteProcessMemory(targetProcess, targetImage, localImage,
CreateRemoteThread(targetProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)((DWORD_PTR)EntryPoint + deltaImageBase), nullptr, 0, nullptr); ntHeader->OptionalHeader.SizeOfImage, nullptr);
CreateRemoteThread(
targetProcess, nullptr, 0,
(LPTHREAD_START_ROUTINE)((DWORD_PTR)EntryPoint + deltaImageBase),
nullptr, 0, nullptr);
CloseHandle(targetProcess); CloseHandle(targetProcess);
} }
+15 -18
View File
@@ -4,13 +4,13 @@
/// ///
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
#include "HttpAPI.h" #include "HttpAPI.h"
#include "Launcher.h"
#include "Logger.h"
#include <cmath>
#include <cpp-httplib/httplib.h> #include <cpp-httplib/httplib.h>
#include <cmath>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <mutex> #include <mutex>
#include "Launcher.h"
#include "Logger.h"
bool HTTP::isDownload = false; bool HTTP::isDownload = false;
std::atomic<httplib::Client*> CliRef = nullptr; std::atomic<httplib::Client*> CliRef = nullptr;
@@ -29,8 +29,7 @@ std::string HTTP::Get(const std::string& IP) {
if (res.error() == httplib::Error::Success) { if (res.error() == httplib::Error::Success) {
if (res->status == 200) { if (res->status == 200) {
Ret = res->body; Ret = res->body;
} else } else LOG(ERROR) << res->reason;
LOG(ERROR) << res->reason;
} else { } else {
if (isDownload) { if (isDownload) {
@@ -54,7 +53,8 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
std::string Ret; std::string Ret;
if (!Fields.empty()) { if (!Fields.empty()) {
httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json"); httplib::Result res =
cli.Post(IP.substr(pos).c_str(), Fields, "application/json");
if (res.error() == httplib::Error::Success) { if (res.error() == httplib::Error::Success) {
if (res->status != 200) { if (res->status != 200) {
@@ -62,7 +62,8 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
} }
Ret = res->body; Ret = res->body;
} else { } else {
LOG(ERROR) << "HTTP Post failed on " << httplib::to_string(res.error()); LOG(ERROR) << "HTTP Post failed on "
<< httplib::to_string(res.error());
} }
} else { } else {
httplib::Result res = cli.Post(IP.substr(pos).c_str()); httplib::Result res = cli.Post(IP.substr(pos).c_str());
@@ -72,14 +73,13 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
} }
Ret = res->body; Ret = res->body;
} else { } else {
LOG(ERROR) << "HTTP Post failed on " << httplib::to_string(res.error()); LOG(ERROR) << "HTTP Post failed on "
<< httplib::to_string(res.error());
} }
} }
CliRef.store(nullptr); CliRef.store(nullptr);
if (Ret.empty()) if (Ret.empty()) return "-1";
return "-1"; else return Ret;
else
return Ret;
} }
bool HTTP::ProgressBar(size_t c, size_t t) { bool HTTP::ProgressBar(size_t c, size_t t) {
@@ -91,10 +91,8 @@ bool HTTP::ProgressBar(size_t c, size_t t) {
std::cout << round(double(c) / double(t) * 100); std::cout << round(double(c) / double(t) * 100);
std::cout << "% ] ["; std::cout << "% ] [";
int i; int i;
for (i = 0; i <= progress_bar_adv; i++) for (i = 0; i <= progress_bar_adv; i++) std::cout << "#";
std::cout << "#"; for (i = 0; i < 25 - progress_bar_adv; i++) std::cout << ".";
for (i = 0; i < 25 - progress_bar_adv; i++)
std::cout << ".";
std::cout << "]"; std::cout << "]";
} }
if (Launcher::Terminated()) { if (Launcher::Terminated()) {
@@ -114,8 +112,7 @@ bool HTTP::Download(const std::string& IP, const std::string& Path) {
std::string Ret = Get(IP); std::string Ret = Get(IP);
isDownload = false; isDownload = false;
if (Ret.empty()) if (Ret.empty()) return false;
return false;
std::cout << "\n"; std::cout << "\n";
std::ofstream File(Path, std::ios::binary); std::ofstream File(Path, std::ios::binary);
if (File.is_open()) { if (File.is_open()) {
+10 -7
View File
@@ -50,7 +50,9 @@ std::string Launcher::Login(const std::string& fields) {
if (Buffer.at(0) != '{' || d.is_discarded()) { if (Buffer.at(0) != '{' || d.is_discarded()) {
LOG(ERROR) << Buffer; LOG(ERROR) << Buffer;
return GetFail("Invalid answer from authentication servers, please try again later!"); return GetFail(
"Invalid answer from authentication servers, please try again "
"later!");
} }
if (!d["success"].is_null() && d["success"].get<bool>()) { if (!d["success"].is_null() && d["success"].get<bool>()) {
@@ -62,8 +64,7 @@ std::string Launcher::Login(const std::string& fields) {
PublicKey = d["public_key"].get<std::string>(); PublicKey = d["public_key"].get<std::string>();
} }
LOG(INFO) << "Authentication successful!"; LOG(INFO) << "Authentication successful!";
} else } else LOG(WARNING) << "Authentication failed!";
LOG(WARNING) << "Authentication failed!";
if (!d["message"].is_null()) { if (!d["message"].is_null()) {
d.erase("private_key"); d.erase("private_key");
@@ -82,12 +83,15 @@ void Launcher::CheckKey() {
Key.read(&Buffer[0], std::streamsize(Size)); Key.read(&Buffer[0], std::streamsize(Size));
Key.close(); Key.close();
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}"); Buffer = HTTP::Post("https://auth.beammp.com/userlogin",
R"({"pk":")" + Buffer + "\"}");
Json d = Json::parse(Buffer, nullptr, false); Json d = Json::parse(Buffer, nullptr, false);
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) { if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
LOG(DEBUG) << Buffer; LOG(DEBUG) << Buffer;
LOG(FATAL) << "Invalid answer from authentication servers, please try again later!"; LOG(FATAL)
<< "Invalid answer from authentication servers, please try "
"again later!";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} }
if (d["success"].get<bool>()) { if (d["success"].get<bool>()) {
@@ -104,6 +108,5 @@ void Launcher::CheckKey() {
LOG(WARNING) << "Could not open saved key!"; LOG(WARNING) << "Could not open saved key!";
UpdateKey(""); UpdateKey("");
} }
} else } else UpdateKey("");
UpdateKey("");
} }
+50 -53
View File
@@ -3,9 +3,7 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include "Launcher.h" #include <ws2tcpip.h>
#include "Logger.h"
#include "Server.h"
#include <atomic> #include <atomic>
#include <cstring> #include <cstring>
#include <filesystem> #include <filesystem>
@@ -14,21 +12,22 @@
#include <string> #include <string>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include <ws2tcpip.h> #include "Launcher.h"
#include "Logger.h"
#include "Server.h"
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::vector<std::string> Split(const std::string& String, const std::string& delimiter) { std::vector<std::string> Split(const std::string& String,
const std::string& delimiter) {
std::vector<std::string> Val; std::vector<std::string> Val;
size_t pos; size_t pos;
std::string token, s = String; std::string token, s = String;
while ((pos = s.find(delimiter)) != std::string::npos) { while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos); token = s.substr(0, pos);
if (!token.empty()) if (!token.empty()) Val.push_back(token);
Val.push_back(token);
s.erase(0, pos + delimiter.length()); s.erase(0, pos + delimiter.length());
} }
if (!s.empty()) if (!s.empty()) Val.push_back(s);
Val.push_back(s);
return Val; return Val;
} }
@@ -61,8 +60,7 @@ std::string Server::Auth() {
} }
TCPSend(LauncherInstance->getPublicKey()); TCPSend(LauncherInstance->getPublicKey());
if (Terminate) if (Terminate) return "";
return "";
Res = TCPRcv(); Res = TCPRcv();
if (Res.empty() || Res[0] != 'P') { if (Res.empty() || Res[0] != 'P') {
@@ -79,8 +77,7 @@ std::string Server::Auth() {
return ""; return "";
} }
TCPSend("SR"); TCPSend("SR");
if (Terminate) if (Terminate) return "";
return "";
Res = TCPRcv(); Res = TCPRcv();
@@ -100,13 +97,12 @@ std::string Server::Auth() {
} }
void Server::UpdateUl(bool D, const std::string& msg) { void Server::UpdateUl(bool D, const std::string& msg) {
if (D) if (D) UStatus = "UlDownloading Resource " + msg;
UStatus = "UlDownloading Resource " + msg; else UStatus = "UlLoading Resource " + msg;
else
UStatus = "UlLoading Resource " + msg;
} }
void Server::AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name) { void Server::AsyncUpdate(uint64_t& Rcv, uint64_t Size,
const std::string& Name) {
do { do {
double pr = double(Rcv) / double(Size) * 100; double pr = double(Rcv) / double(Size) * 100;
std::string Per = std::to_string(trunc(pr * 10) / 10); std::string Per = std::to_string(trunc(pr * 10) / 10);
@@ -125,8 +121,7 @@ char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) {
uint64_t Rcv = 0; uint64_t Rcv = 0;
do { do {
int Len = int(Size - Rcv); int Len = int(Size - Rcv);
if (Len > 1000000) if (Len > 1000000) Len = 1000000;
Len = 1000000;
int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL); int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
if (Temp < 1) { if (Temp < 1) {
UUl("Socket Closed Code 1"); UUl("Socket Closed Code 1");
@@ -172,13 +167,14 @@ uint64_t Server::InitDSock() {
return DSock; return DSock;
} }
std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name) { std::string Server::MultiDownload(uint64_t DSock, uint64_t Size,
const std::string& Name) {
uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize; uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize;
std::thread Au(&Server::AsyncUpdate, this, std::ref(GRcv), Size, Name); std::thread Au(&Server::AsyncUpdate, this, std::ref(GRcv), Size, Name);
std::packaged_task<char*()> task([&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); }); std::packaged_task<char*()> task(
[&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); });
std::future<char*> f1 = task.get_future(); std::future<char*> f1 = task.get_future();
std::thread Dt(std::move(task)); std::thread Dt(std::move(task));
Dt.detach(); Dt.detach();
@@ -198,8 +194,7 @@ std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::stri
return ""; return "";
} }
if (Au.joinable()) if (Au.joinable()) Au.join();
Au.join();
/// omg yes very ugly my god but i was in a rush will revisit /// omg yes very ugly my god but i was in a rush will revisit
std::string Ret(Size, 0); std::string Ret(Size, 0);
@@ -214,20 +209,22 @@ std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::stri
void Server::InvalidResource(const std::string& File) { void Server::InvalidResource(const std::string& File) {
UUl("Invalid mod \"" + File + "\""); UUl("Invalid mod \"" + File + "\"");
LOG(WARNING) << "The server tried to sync \"" << File << "\" that is not a .zip file!"; LOG(WARNING) << "The server tried to sync \"" << File
<< "\" that is not a .zip file!";
Terminate = true; Terminate = true;
} }
void Server::SyncResources() { void Server::SyncResources() {
std::string Ret = Auth(); std::string Ret = Auth();
if (Ret.empty()) if (Ret.empty()) return;
return;
LOG(INFO) << "Checking Resources..."; LOG(INFO) << "Checking Resources...";
CheckForDir(); CheckForDir();
std::vector<std::string> list = Split(Ret, ";"); std::vector<std::string> list = Split(Ret, ";");
std::vector<std::string> FNames(list.begin(), list.begin() + (list.size() / 2)); std::vector<std::string> FNames(list.begin(),
std::vector<std::string> FSizes(list.begin() + (list.size() / 2), list.end()); list.begin() + (list.size() / 2));
std::vector<std::string> FSizes(list.begin() + (list.size() / 2),
list.end());
list.clear(); list.clear();
Ret.clear(); Ret.clear();
@@ -238,43 +235,42 @@ void Server::SyncResources() {
t += name.substr(name.find_last_of('/') + 1) + ";"; t += name.substr(name.find_last_of('/') + 1) + ";";
} }
} }
if (t.empty()) if (t.empty()) ModList = "-";
ModList = "-"; else ModList = t;
else
ModList = t;
t.clear(); t.clear();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { for (auto FN = FNames.begin(), FS = FSizes.begin();
FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
auto ZIP = FN->find(".zip"); auto ZIP = FN->find(".zip");
if (ZIP == std::string::npos || FN->length() - ZIP != 4) { if (ZIP == std::string::npos || FN->length() - ZIP != 4) {
InvalidResource(*FN); InvalidResource(*FN);
return; return;
} }
if (pos == std::string::npos) if (pos == std::string::npos) continue;
continue;
Amount++; Amount++;
} }
if (!FNames.empty()) if (!FNames.empty()) LOG(INFO) << "Syncing...";
LOG(INFO) << "Syncing...";
SOCKET DSock = InitDSock(); SOCKET DSock = InitDSock();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { for (auto FN = FNames.begin(), FS = FSizes.begin();
FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
if (pos != std::string::npos) { if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos); a = "Resources" + FN->substr(pos);
} else } else continue;
continue;
Pos++; Pos++;
if (fs::exists(a)) { if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit)) if (!std::all_of(FS->begin(), FS->end(), isdigit)) continue;
continue;
if (fs::file_size(a) == std::stoull(*FS)) { if (fs::file_size(a) == std::stoull(*FS)) {
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/'))); UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) +
": " + a.substr(a.find_last_of('/')));
std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::this_thread::sleep_for(std::chrono::milliseconds(50));
try { try {
if (!fs::exists(LauncherInstance->getMPUserPath())) { if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath()); fs::create_directories(LauncherInstance->getMPUserPath());
} }
fs::copy_file(a, LauncherInstance->getMPUserPath() + a.substr(a.find_last_of('/')), fs::copy_file(a,
LauncherInstance->getMPUserPath() +
a.substr(a.find_last_of('/')),
fs::copy_options::overwrite_existing); fs::copy_options::overwrite_existing);
} catch (std::exception& e) { } catch (std::exception& e) {
LOG(ERROR) << "Failed copy to the mods folder! " << e.what(); LOG(ERROR) << "Failed copy to the mods folder! " << e.what();
@@ -283,8 +279,7 @@ void Server::SyncResources() {
} }
WaitForConfirm(); WaitForConfirm();
continue; continue;
} else } else remove(a.c_str());
remove(a.c_str());
} }
CheckForDir(); CheckForDir();
std::string FName = a.substr(a.find_last_of('/')); std::string FName = a.substr(a.find_last_of('/'));
@@ -298,13 +293,14 @@ void Server::SyncResources() {
break; break;
} }
std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName; std::string Name =
std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
Data = MultiDownload(DSock, std::stoull(*FS), Name); Data = MultiDownload(DSock, std::stoull(*FS), Name);
if (Terminate) if (Terminate) break;
break; UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) +
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName); ": " + FName);
std::ofstream LFS; std::ofstream LFS;
LFS.open(a.c_str(), std::ios_base::app | std::ios::binary); LFS.open(a.c_str(), std::ios_base::app | std::ios::binary);
if (LFS.is_open()) { if (LFS.is_open()) {
@@ -317,7 +313,8 @@ void Server::SyncResources() {
if (!fs::exists(LauncherInstance->getMPUserPath())) { if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath()); fs::create_directories(LauncherInstance->getMPUserPath());
} }
fs::copy_file(a, LauncherInstance->getMPUserPath() + FName, fs::copy_options::overwrite_existing); fs::copy_file(a, LauncherInstance->getMPUserPath() + FName,
fs::copy_options::overwrite_existing);
} }
WaitForConfirm(); WaitForConfirm();
} }
+27 -46
View File
@@ -6,15 +6,14 @@
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include "Server.h" #include "Server.h"
#include "Compressor.h"
#include "Launcher.h"
#include "Logger.h"
#include <windows.h> #include <windows.h>
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#include "Compressor.h"
#include "Launcher.h"
#include "Logger.h"
Server::Server(Launcher* Instance) Server::Server(Launcher* Instance) : LauncherInstance(Instance) {
: LauncherInstance(Instance) {
WSADATA wsaData; WSADATA wsaData;
int iRes = WSAStartup(514, &wsaData); // 2.2 int iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes != 0) { if (iRes != 0) {
@@ -36,7 +35,8 @@ void Server::TCPClientMain() {
return; return;
} }
const char optval = 0; const char optval = 0;
int status = ::setsockopt(TCPSocket, SOL_SOCKET, SO_DONTLINGER, &optval, sizeof(optval)); int status = ::setsockopt(TCPSocket, SOL_SOCKET, SO_DONTLINGER, &optval,
sizeof(optval));
if (status < 0) { if (status < 0) {
LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError(); LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError();
} }
@@ -73,15 +73,14 @@ void Server::StartUDP() {
} }
void Server::UDPSend(std::string Data) { void Server::UDPSend(std::string Data) {
if (ClientID == -1 || UDPSocket == -1) if (ClientID == -1 || UDPSocket == -1) return;
return;
if (Data.length() > 400) { if (Data.length() > 400) {
std::string CMP(Zlib::Comp(Data)); std::string CMP(Zlib::Comp(Data));
Data = "ABG:" + CMP; Data = "ABG:" + CMP;
} }
std::string Packet = char(ClientID + 1) + std::string(":") + Data; std::string Packet = char(ClientID + 1) + std::string(":") + Data;
int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)UDPSockAddress.get(), int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0,
sizeof(sockaddr_in)); (sockaddr*)UDPSockAddress.get(), sizeof(sockaddr_in));
if (sendOk == SOCKET_ERROR) if (sendOk == SOCKET_ERROR)
LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError(); LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError();
} }
@@ -98,11 +97,10 @@ void Server::UDPRcv() {
int clientLength = sizeof(FromServer); int clientLength = sizeof(FromServer);
ZeroMemory(&FromServer, clientLength); ZeroMemory(&FromServer, clientLength);
std::string Ret(10240, 0); std::string Ret(10240, 0);
if (UDPSocket == -1) if (UDPSocket == -1) return;
return; int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr*)&FromServer,
int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength); &clientLength);
if (Rcv == SOCKET_ERROR) if (Rcv == SOCKET_ERROR) return;
return;
UDPParser(Ret.substr(0, Rcv)); UDPParser(Ret.substr(0, Rcv));
} }
@@ -114,8 +112,7 @@ void Server::UDPClient() {
LauncherInstance->SendIPC("P" + std::to_string(ClientID), false); LauncherInstance->SendIPC("P" + std::to_string(ClientID), false);
TCPSend("H"); TCPSend("H");
UDPSend("p"); UDPSend("p");
while (!Terminate) while (!Terminate) UDPRcv();
UDPRcv();
KillSocket(UDPSocket); KillSocket(UDPSocket);
} }
@@ -133,12 +130,9 @@ void Server::Connect(const std::string& Data) {
std::string port = Data.substr(Data.find(':') + 1); std::string port = Data.substr(Data.find(':') + 1);
bool ValidPort = std::all_of(port.begin(), port.end(), ::isdigit); bool ValidPort = std::all_of(port.begin(), port.end(), ::isdigit);
if (IP.find('.') == -1 || !ValidPort) { if (IP.find('.') == -1 || !ValidPort) {
if (IP == "DNS") if (IP == "DNS") UStatus = "Connection Failed! (DNS Lookup Failed)";
UStatus = "Connection Failed! (DNS Lookup Failed)"; else if (!ValidPort) UStatus = "Connection Failed! (Invalid Port)";
else if (!ValidPort) else UStatus = "Connection Failed! (WSA failed to start)";
UStatus = "Connection Failed! (Invalid Port)";
else
UStatus = "Connection Failed! (WSA failed to start)";
ModList = "-"; ModList = "-";
Terminate.store(true); Terminate.store(true);
return; return;
@@ -169,12 +163,8 @@ std::string Server::GetSocketApiError() {
err = WSAGetLastError(); err = WSAGetLastError();
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
err, msgbuf, sizeof(msgbuf), nullptr);
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf,
sizeof(msgbuf),
nullptr);
if (*msgbuf) { if (*msgbuf) {
return std::to_string(WSAGetLastError()) + " - " + std::string(msgbuf); return std::to_string(WSAGetLastError()) + " - " + std::string(msgbuf);
@@ -184,22 +174,17 @@ std::string Server::GetSocketApiError() {
} }
void Server::ServerSend(std::string Data, bool Rel) { void Server::ServerSend(std::string Data, bool Rel) {
if (Terminate || Data.empty()) if (Terminate || Data.empty()) return;
return;
char C = 0; char C = 0;
int DLen = int(Data.length()); int DLen = int(Data.length());
if (DLen > 3) if (DLen > 3) C = Data.at(0);
C = Data.at(0);
bool Ack = C == 'O' || C == 'T'; bool Ack = C == 'O' || C == 'T';
if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C') if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')
Rel = true; Rel = true;
if (Ack || Rel) { if (Ack || Rel) {
if (Ack || DLen > 1000) if (Ack || DLen > 1000) SendLarge(Data);
SendLarge(Data); else TCPSend(Data);
else } else UDPSend(Data);
TCPSend(Data);
} else
UDPSend(Data);
} }
void Server::PingLoop() { void Server::PingLoop() {
@@ -247,8 +232,7 @@ const std::string& Server::getUIStatus() {
} }
std::string Server::GetAddress(const std::string& Data) { std::string Server::GetAddress(const std::string& Data) {
if (Data.find_first_not_of("0123456789.") == -1) if (Data.find_first_not_of("0123456789.") == -1) return Data;
return Data;
hostent* host; hostent* host;
host = gethostbyname(Data.c_str()); host = gethostbyname(Data.c_str());
if (!host) { if (!host) {
@@ -260,8 +244,7 @@ std::string Server::GetAddress(const std::string& Data) {
} }
int Server::KillSocket(uint64_t Dead) { int Server::KillSocket(uint64_t Dead) {
if (Dead == (SOCKET)-1) if (Dead == (SOCKET)-1) return 0;
return 0;
shutdown(Dead, SD_BOTH); shutdown(Dead, SD_BOTH);
return closesocket(Dead); return closesocket(Dead);
} }
@@ -289,7 +272,6 @@ bool Server::CheckBytes(int32_t Bytes) {
} }
void Server::TCPSend(const std::string& Data) { void Server::TCPSend(const std::string& Data) {
if (TCPSocket == -1) { if (TCPSocket == -1) {
Terminate = true; Terminate = true;
UUl("Invalid Socket"); UUl("Invalid Socket");
@@ -363,7 +345,6 @@ std::string Server::TCPRcv() {
Ret = Zlib::DeComp(Ret.substr(4)); Ret = Zlib::DeComp(Ret.substr(4));
} }
if (Ret[0] == 'E') if (Ret[0] == 'E') UUl(Ret.substr(1));
UUl(Ret.substr(1));
return Ret; return Ret;
} }
+28 -33
View File
@@ -17,22 +17,17 @@ VersionParser::VersionParser(const std::string& from_string) {
} }
} }
std::strong_ordering VersionParser::operator<=>(const VersionParser& rhs) const noexcept { std::strong_ordering VersionParser::operator<=>(
const VersionParser& rhs) const noexcept {
size_t const fields = std::min(data.size(), rhs.data.size()); size_t const fields = std::min(data.size(), rhs.data.size());
for (size_t i = 0; i != fields; ++i) { for (size_t i = 0; i != fields; ++i) {
if (data[i] == rhs.data[i]) if (data[i] == rhs.data[i]) continue;
continue; else if (data[i] < rhs.data[i]) return std::strong_ordering::less;
else if (data[i] < rhs.data[i]) else return std::strong_ordering::greater;
return std::strong_ordering::less;
else
return std::strong_ordering::greater;
} }
if (data.size() == rhs.data.size()) if (data.size() == rhs.data.size()) return std::strong_ordering::equal;
return std::strong_ordering::equal; else if (data.size() > rhs.data.size()) return std::strong_ordering::greater;
else if (data.size() > rhs.data.size()) else return std::strong_ordering::less;
return std::strong_ordering::greater;
else
return std::strong_ordering::less;
} }
bool VersionParser::operator==(const VersionParser& rhs) const noexcept { bool VersionParser::operator==(const VersionParser& rhs) const noexcept {
@@ -41,10 +36,12 @@ bool VersionParser::operator==(const VersionParser& rhs) const noexcept {
void Launcher::UpdateCheck() { void Launcher::UpdateCheck() {
std::string link; std::string link;
std::string HTTP = HTTP::Get("https://beammp.com/builds/launcher?version=true"); std::string HTTP =
HTTP::Get("https://beammp.com/builds/launcher?version=true");
bool fallback = false; bool fallback = false;
if (HTTP.find_first_of("0123456789") == std::string::npos) { if (HTTP.find_first_of("0123456789") == std::string::npos) {
HTTP = HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true"); HTTP =
HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true");
fallback = true; fallback = true;
if (HTTP.find_first_of("0123456789") == std::string::npos) { if (HTTP.find_first_of("0123456789") == std::string::npos) {
LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!"; LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!";
@@ -53,13 +50,12 @@ void Launcher::UpdateCheck() {
} }
if (fallback) { if (fallback) {
link = "https://backup1.beammp.com/builds/launcher?download=true"; link = "https://backup1.beammp.com/builds/launcher?download=true";
} else } else link = "https://beammp.com/builds/launcher?download=true";
link = "https://beammp.com/builds/launcher?download=true";
std::string EP(CurrentPath.string()), Back(CurrentPath.parent_path().string() + "\\BeamMP-Launcher.back"); std::string EP(CurrentPath.string()),
Back(CurrentPath.parent_path().string() + "\\BeamMP-Launcher.back");
if (fs::exists(Back)) if (fs::exists(Back)) remove(Back.c_str());
remove(Back.c_str());
std::string RemoteVer; std::string RemoteVer;
for (char& c : HTTP) { for (char& c : HTTP) {
if (std::isdigit(c) || c == '.') { if (std::isdigit(c) || c == '.') {
@@ -85,12 +81,12 @@ void Launcher::UpdateCheck() {
} }
} }
Relaunch(); Relaunch();
} else } else LOG(INFO) << "Launcher version is up to date";
LOG(INFO) << "Launcher version is up to date";
} }
size_t DirCount(const std::filesystem::path& path) { size_t DirCount(const std::filesystem::path& path) {
return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {}); return (size_t)std::distance(std::filesystem::directory_iterator{path},
std::filesystem::directory_iterator{});
} }
void Launcher::ResetMods() { void Launcher::ResetMods() {
@@ -99,7 +95,8 @@ void Launcher::ResetMods() {
return; return;
} }
if (DirCount(fs::path(MPUserPath)) > 3) { if (DirCount(fs::path(MPUserPath)) > 3) {
LOG(WARNING) << "mods/multiplayer will be cleared in 15 seconds, close to abort"; LOG(WARNING)
<< "mods/multiplayer will be cleared in 15 seconds, close to abort";
std::this_thread::sleep_for(std::chrono::seconds(15)); std::this_thread::sleep_for(std::chrono::seconds(15));
} }
fs::remove_all(MPUserPath); fs::remove_all(MPUserPath);
@@ -108,19 +105,16 @@ void Launcher::ResetMods() {
void Launcher::EnableMP() { void Launcher::EnableMP() {
std::string File(BeamUserPath + "mods\\db.json"); std::string File(BeamUserPath + "mods\\db.json");
if (!fs::exists(File)) if (!fs::exists(File)) return;
return;
auto Size = fs::file_size(File); auto Size = fs::file_size(File);
if (Size < 2) if (Size < 2) return;
return;
std::ifstream db(File); std::ifstream db(File);
if (db.is_open()) { if (db.is_open()) {
std::string Data(Size, 0); std::string Data(Size, 0);
db.read(&Data[0], std::streamsize(Size)); db.read(&Data[0], std::streamsize(Size));
db.close(); db.close();
Json d = Json::parse(Data, nullptr, false); Json d = Json::parse(Data, nullptr, false);
if (Data.at(0) != '{' || d.is_discarded()) if (Data.at(0) != '{' || d.is_discarded()) return;
return;
if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) { if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) {
d["mods"]["multiplayerbeammp"]["active"] = true; d["mods"]["multiplayerbeammp"]["active"] = true;
std::ofstream ofs(File); std::ofstream ofs(File);
@@ -138,8 +132,9 @@ void Launcher::SetupMOD() {
ResetMods(); ResetMods();
EnableMP(); EnableMP();
LOG(INFO) << "Downloading mod please wait"; LOG(INFO) << "Downloading mod please wait";
HTTP::Download("https://backend.beammp.com/builds/client?download=true" HTTP::Download(
"&pk=" "https://backend.beammp.com/builds/client?download=true"
+ PublicKey + "&branch=" + TargetBuild, "&pk=" +
PublicKey + "&branch=" + TargetBuild,
MPUserPath + "\\BeamMP.zip"); MPUserPath + "\\BeamMP.zip");
} }
+8 -11
View File
@@ -4,13 +4,13 @@
/// ///
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS
#include <set>
#include <wx/wxprec.h> #include <wx/wxprec.h>
#include <set>
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "gifs.h"
#include <wx/animate.h> #include <wx/animate.h>
#include <wx/mstream.h> #include <wx/mstream.h>
#include <wx/wx.h> #include <wx/wx.h>
#include "gifs.h"
#endif #endif
class MyApp : public wxApp { class MyApp : public wxApp {
@@ -27,9 +27,7 @@ private:
void OnAbout(wxCommandEvent& event); void OnAbout(wxCommandEvent& event);
static wxSize FixedSize; static wxSize FixedSize;
}; };
enum { enum { ID_Hello = 1 };
ID_Hello = 1
};
wxSize MyFrame::FixedSize(370, 400); wxSize MyFrame::FixedSize(370, 400);
bool MyApp::OnInit() { bool MyApp::OnInit() {
@@ -38,8 +36,8 @@ bool MyApp::OnInit() {
return true; return true;
} }
MyFrame::MyFrame() MyFrame::MyFrame() :
: wxFrame(nullptr, wxID_ANY, "BeamMP V3.0", wxDefaultPosition, FixedSize) { wxFrame(nullptr, wxID_ANY, "BeamMP V3.0", wxDefaultPosition, FixedSize) {
// SetMaxSize(FixedSize); // SetMaxSize(FixedSize);
// SetMinSize(FixedSize); // SetMinSize(FixedSize);
Center(); Center();
@@ -65,8 +63,7 @@ MyFrame::MyFrame()
auto* m_ani = new wxAnimationCtrl(this, wxID_ANY); auto* m_ani = new wxAnimationCtrl(this, wxID_ANY);
wxMemoryInputStream stream(gif::Logo, sizeof(gif::Logo)); wxMemoryInputStream stream(gif::Logo, sizeof(gif::Logo));
if (m_ani->Load(stream)) if (m_ani->Load(stream)) m_ani->Play();
m_ani->Play();
Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello); Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT); Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
@@ -76,8 +73,8 @@ void MyFrame::OnExit(wxCommandEvent& event) {
Close(true); Close(true);
} }
void MyFrame::OnAbout(wxCommandEvent& event) { void MyFrame::OnAbout(wxCommandEvent& event) {
wxMessageBox("This is a wxWidgets Hello World example", wxMessageBox("This is a wxWidgets Hello World example", "About Hello World",
"About Hello World", wxOK | wxICON_INFORMATION); wxOK | wxICON_INFORMATION);
} }
void MyFrame::OnHello(wxCommandEvent& event) { void MyFrame::OnHello(wxCommandEvent& event) {
wxLogMessage("Hello world from wxWidgets!"); wxLogMessage("Hello world from wxWidgets!");
+1 -2
View File
@@ -2541,5 +2541,4 @@ const unsigned char gif::Logo[30427] = {
0x54, 0x60, 0x2a, 0x56, 0xf9, 0x40, 0x72, 0x48, 0xd1, 0x81, 0x5e, 0x5e, 0x54, 0x60, 0x2a, 0x56, 0xf9, 0x40, 0x72, 0x48, 0xd1, 0x81, 0x5e, 0x5e,
0x63, 0x02, 0x28, 0x40, 0x8a, 0x55, 0x48, 0x70, 0x02, 0x61, 0x96, 0x92, 0x63, 0x02, 0x28, 0x40, 0x8a, 0x55, 0x48, 0x70, 0x02, 0x61, 0x96, 0x92,
0x02, 0x96, 0xe1, 0x40, 0x62, 0x2e, 0x40, 0x1a, 0x86, 0x60, 0x00, 0x30, 0x02, 0x96, 0xe1, 0x40, 0x62, 0x2e, 0x40, 0x1a, 0x86, 0x60, 0x00, 0x30,
0xd5, 0x7c, 0x4a, 0x20, 0x00, 0x00, 0x3b 0xd5, 0x7c, 0x4a, 0x20, 0x00, 0x00, 0x3b};
};