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
+3 -3
View File
@@ -7,7 +7,7 @@
#include <string> #include <string>
class Zlib { class Zlib {
public: public:
static std::string DeComp(std::string Compressed); static std::string DeComp(std::string Compressed);
static std::string Comp(std::string Data); static std::string Comp(std::string Data);
}; };
+7 -7
View File
@@ -7,12 +7,12 @@
#include <string> #include <string>
class HTTP { class HTTP {
public: public:
static bool Download(const std::string& IP, const std::string& Path); static bool Download(const std::string& IP, const std::string& Path);
static std::string Post(const std::string& IP, const std::string& Fields); static std::string Post(const std::string& IP, const std::string& Fields);
static std::string Get(const std::string& IP); static std::string Get(const std::string& IP);
static bool ProgressBar(size_t c, size_t t); static bool ProgressBar(size_t c, size_t t);
public: public:
static bool isDownload; static bool isDownload;
}; };
+70 -70
View File
@@ -4,90 +4,90 @@
/// ///
#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;
struct VersionParser { struct VersionParser {
explicit VersionParser(const std::string& from_string); explicit VersionParser(const std::string& from_string);
std::strong_ordering operator<=>(VersionParser const& rhs) const noexcept; std::strong_ordering operator<=>(VersionParser const& rhs) const noexcept;
bool operator==(VersionParser const& rhs) const noexcept; bool operator==(VersionParser const& rhs) const noexcept;
std::vector<std::string> split; std::vector<std::string> split;
std::vector<size_t> data; std::vector<size_t> data;
}; };
class Launcher { class Launcher {
public: // constructors public: // constructors
Launcher(int argc, char* argv[]); Launcher(int argc, char* argv[]);
~Launcher(); ~Launcher();
public: // available functions public: // available functions
static void StaticAbort(Launcher* Instance = nullptr); static void StaticAbort(Launcher* Instance = nullptr);
std::string Login(const std::string& fields); std::string Login(const std::string& fields);
void SendIPC(const std::string& Data, bool core = true); void SendIPC(const std::string& Data, bool core = true);
void RunDiscordRPC(); void RunDiscordRPC();
void QueryRegistry(); void QueryRegistry();
void WaitForGame(); void WaitForGame();
void LoadConfig(); void LoadConfig();
void LaunchGame(); void LaunchGame();
void CheckKey(); void CheckKey();
void SetupMOD(); void SetupMOD();
public: // Getters and Setters public: // Getters and Setters
void setDiscordMessage(const std::string& message); void setDiscordMessage(const std::string& message);
static void setExit(bool exit) noexcept; static void setExit(bool exit) noexcept;
const std::string& getFullVersion(); const std::string& getFullVersion();
const std::string& getMPUserPath(); const std::string& getMPUserPath();
static bool Terminated() noexcept; static bool Terminated() noexcept;
const std::string& getPublicKey(); const std::string& getPublicKey();
const std::string& getUserRole(); const std::string& getUserRole();
const std::string& getVersion(); const std::string& getVersion();
static bool getExit() noexcept; static bool getExit() noexcept;
private: // functions private: // functions
void HandleIPC(const std::string& Data); void HandleIPC(const std::string& Data);
std::string GetLocalAppdata(); std::string GetLocalAppdata();
void UpdatePresence(); void UpdatePresence();
void AdminRelaunch(); void AdminRelaunch();
void RichPresence(); void RichPresence();
void WindowsInit(); void WindowsInit();
void UpdateCheck(); void UpdateCheck();
void ResetMods(); void ResetMods();
void EnableMP(); void EnableMP();
void Relaunch(); void Relaunch();
void ListenIPC(); void ListenIPC();
void Abort(); void Abort();
private: // variables private: // variables
uint32_t GamePID { 0 }; uint32_t GamePID{0};
bool EnableUI = true; bool EnableUI = true;
int64_t DiscordTime {}; int64_t DiscordTime{};
bool LoginAuth = false; bool LoginAuth = false;
fs::path CurrentPath {}; fs::path CurrentPath{};
std::string BeamRoot {}; std::string BeamRoot{};
std::string UserRole {}; std::string UserRole{};
std::string PublicKey {}; std::string PublicKey{};
std::thread IPCSystem {}; std::thread IPCSystem{};
std::thread DiscordRPC {}; std::thread DiscordRPC{};
std::string MPUserPath {}; std::string MPUserPath{};
std::string BeamVersion {}; std::string BeamVersion{};
std::string BeamUserPath {}; std::string BeamUserPath{};
std::string DiscordMessage {}; std::string DiscordMessage{};
std::string Version { "2.0" }; std::string Version{"2.0"};
Server ServerHandler { this }; Server ServerHandler{this};
std::string TargetBuild { "default" }; std::string TargetBuild{"default"};
static inline std::atomic<bool> Shutdown { false }, Exit { false }; static inline std::atomic<bool> Shutdown{false}, Exit{false};
std::string FullVersion { Version + ".99" }; std::string FullVersion{Version + ".99"};
VersionParser SupportedVersion { "0.25.4.0" }; VersionParser SupportedVersion{"0.25.4.0"};
std::unique_ptr<IPC> IPCToGame {}; std::unique_ptr<IPC> IPCToGame{};
std::unique_ptr<IPC> IPCFromGame {}; std::unique_ptr<IPC> IPCFromGame{};
}; };
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){};
}; };
+2 -2
View File
@@ -8,6 +8,6 @@
#undef min #undef min
#undef max #undef max
class Log { class Log {
public: public:
static void Init(); static void Init();
}; };
+19 -17
View File
@@ -4,25 +4,27 @@
/// ///
#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:
static inline std::unique_ptr<Hook<def::GEUpdate>> TickCountDetour; private:
static inline std::unique_ptr<Hook<def::lua_open_jit>> OpenJITDetour; static inline std::unique_ptr<Hook<def::GEUpdate>> TickCountDetour;
static inline std::unique_ptr<IPC> IPCFromLauncher; static inline std::unique_ptr<Hook<def::lua_open_jit>> OpenJITDetour;
static inline std::unique_ptr<IPC> IPCToLauncher; static inline std::unique_ptr<IPC> IPCFromLauncher;
static inline uint64_t GameBaseAddr; static inline std::unique_ptr<IPC> IPCToLauncher;
static inline uint64_t DllBaseAddr; static inline uint64_t GameBaseAddr;
static int lua_open_jit_D(lua_State* State); static inline uint64_t DllBaseAddr;
static void RegisterGEFunctions(); static int lua_open_jit_D(lua_State* State);
// static int GetTickCount_D(void* GEState, void* Param2, void* Param3, void* Param4); static void RegisterGEFunctions();
static void IPCListener(); // static int GetTickCount_D(void* GEState, void* Param2, void* Param3, void*
// Param4);
static void IPCListener();
}; };
+14 -13
View File
@@ -8,18 +8,19 @@
typedef struct lua_State lua_State; 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,
typedef uint32_t (*GetTickCount)(); void* Param4);
typedef int (*lua_open_jit)(lua_State* L); typedef uint32_t (*GetTickCount)();
typedef void (*lua_get_field)(lua_State* L, int idx, const char* k); typedef int (*lua_open_jit)(lua_State* L);
typedef const char* (*lua_push_fstring)(lua_State* L, const char* fmt, ...); typedef void (*lua_get_field)(lua_State* L, int idx, const char* k);
typedef int (*lua_p_call)(lua_State* L, int arg, int res, int err); typedef const char* (*lua_push_fstring)(lua_State* L, const char* fmt, ...);
typedef void (*lua_pushcclosure)(lua_State* L, lua_CFunction fn, int n); typedef int (*lua_p_call)(lua_State* L, int arg, int res, int err);
typedef int (*lua_settop)(lua_State* L, int idx); typedef void (*lua_pushcclosure)(lua_State* L, lua_CFunction fn, int n);
typedef void (*lua_settable)(lua_State* L, int idx); typedef int (*lua_settop)(lua_State* L, int idx);
typedef void (*lua_createtable)(lua_State* L, int narray, int nrec); typedef void (*lua_settable)(lua_State* L, int idx);
typedef void (*lua_setfield)(lua_State* L, int idx, const char* k); typedef void (*lua_createtable)(lua_State* L, int narray, int nrec);
typedef const char* (*lua_tolstring)(lua_State* L, int idx, size_t* len); typedef void (*lua_setfield)(lua_State* L, int idx, const char* k);
typedef const char* (*lua_tolstring)(lua_State* L, int idx, size_t* len);
} }
+33 -32
View File
@@ -7,39 +7,40 @@
#include "Definitions.h" #include "Definitions.h"
class GELua { class GELua {
public: public:
static void FindAddresses(); static void FindAddresses();
static inline def::GEUpdate GEUpdate; static inline def::GEUpdate GEUpdate;
static inline def::lua_settop lua_settop; static inline def::lua_settop lua_settop;
static inline def::GetTickCount GetTickCount; static inline def::GetTickCount GetTickCount;
static inline def::lua_open_jit lua_open_jit; static inline def::lua_open_jit lua_open_jit;
static inline def::lua_push_fstring lua_push_fstring; static inline def::lua_push_fstring lua_push_fstring;
static inline def::lua_get_field lua_get_field; static inline def::lua_get_field lua_get_field;
static inline def::lua_p_call lua_p_call; static inline def::lua_p_call lua_p_call;
static inline def::lua_createtable lua_createtable; static inline def::lua_createtable lua_createtable;
static inline def::lua_pushcclosure lua_pushcclosure; static inline def::lua_pushcclosure lua_pushcclosure;
static inline def::lua_setfield lua_setfield; static inline def::lua_setfield lua_setfield;
static inline def::lua_settable lua_settable; static inline def::lua_settable lua_settable;
static inline def::lua_tolstring lua_tolstring; static inline def::lua_tolstring lua_tolstring;
static inline lua_State* State; static inline lua_State* State;
}; };
namespace GELuaTable { namespace GELuaTable {
inline void Begin(lua_State* L) { inline void Begin(lua_State* L) {
GELua::lua_createtable(L, 0, 0); GELua::lua_createtable(L, 0, 0);
} }
inline void End(lua_State* L, const char* name) { inline void End(lua_State* L, const char* name) {
GELua::lua_setfield(L, -10002, name); GELua::lua_setfield(L, -10002, name);
} }
inline void BeginEntry(lua_State* L, const char* name) { inline void BeginEntry(lua_State* L, const char* name) {
GELua::lua_push_fstring(L, "%s", name); GELua::lua_push_fstring(L, "%s", name);
} }
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,
BeginEntry(L, name); lua_CFunction func) {
GELua::lua_pushcclosure(L, func, 0); BeginEntry(L, name);
EndEntry(L); GELua::lua_pushcclosure(L, func, 0);
} EndEntry(L);
}
} }
+37 -34
View File
@@ -3,46 +3,49 @@
/// 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>
class Hook { class Hook {
FuncType targetPtr; FuncType targetPtr;
FuncType detourFunc; FuncType detourFunc;
bool Attached = false; bool Attached = false;
public:
Hook(FuncType src, FuncType dest) : targetPtr(src), detourFunc(dest) { public:
auto status = MH_CreateHook((void*)targetPtr, (void*)detourFunc, (void**)&Original); Hook(FuncType src, FuncType dest) : targetPtr(src), detourFunc(dest) {
if(status != MH_OK) { auto status =
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); MH_CreateHook((void*)targetPtr, (void*)detourFunc, (void**)&Original);
if (status != MH_OK) {
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status));
return;
}
}
void Enable() {
if (!Attached) {
auto status = MH_EnableHook((void*)targetPtr);
if (status != MH_OK) {
Memory::Print(std::string("MH Error -> ") +
MH_StatusToString(status));
return; return;
} }
} Attached = true;
}
}
void Enable() { void Disable() {
if(!Attached){ if (Attached) {
auto status = MH_EnableHook((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 -> ") +
return; MH_StatusToString(status));
} return;
Attached = true; }
} Attached = false;
} }
}
void Disable() { FuncType Original{};
if(Attached){
auto status = MH_DisableHook((void*)targetPtr);
if(status != MH_OK) {
Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status));
return;
}
Attached = false;
}
}
FuncType Original{};
}; };
+25 -24
View File
@@ -7,28 +7,29 @@
#include <string> #include <string>
class IPC { class IPC {
public: public:
IPC() = default; IPC() = default;
IPC(uint32_t ID, size_t Size) noexcept; IPC(uint32_t ID, size_t Size) noexcept;
[[nodiscard]] size_t size() const noexcept; [[nodiscard]] size_t size() const noexcept;
[[nodiscard]] char* c_str() const noexcept; [[nodiscard]] char* c_str() const noexcept;
void send(const std::string& msg) noexcept; void send(const std::string& msg) noexcept;
[[nodiscard]] void* raw() const noexcept; [[nodiscard]] void* raw() const noexcept;
[[nodiscard]] bool receive_timed_out() const noexcept; [[nodiscard]] bool receive_timed_out() const noexcept;
[[nodiscard]] bool send_timed_out() const noexcept; [[nodiscard]] bool send_timed_out() const noexcept;
const std::string& msg() noexcept; const std::string& msg() noexcept;
void confirm_receive() noexcept; void confirm_receive() noexcept;
void try_receive() noexcept; void try_receive() noexcept;
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:
void* SemConfHandle_; private:
void* MemoryHandle_; void* SemConfHandle_;
void* SemHandle_; void* MemoryHandle_;
std::string Msg_; void* SemHandle_;
bool SendTimeout; std::string Msg_;
bool RcvTimeout; bool SendTimeout;
size_t Size_; bool RcvTimeout;
char* Data_; size_t Size_;
char* Data_;
}; };
+11 -11
View File
@@ -4,17 +4,17 @@
/// ///
#pragma once #pragma once
#include <string>
#include <set> #include <set>
#include <string>
class Memory{ class Memory {
public: public:
static uint64_t FindPattern(const char* module, const char* Pattern[]); static uint64_t FindPattern(const char* module, const char* Pattern[]);
static uint32_t GetBeamNGPID(const std::set<uint32_t>& BL); static uint32_t GetBeamNGPID(const std::set<uint32_t>& BL);
static uint64_t GetModuleBase(const char* Name); static uint64_t GetModuleBase(const char* Name);
static void Print(const std::string& msg); static void Print(const std::string& msg);
static void Inject(uint32_t PID); static void Inject(uint32_t PID);
static uint32_t GetTickCount(); static uint32_t GetTickCount();
static uint32_t EntryPoint(); static uint32_t EntryPoint();
static uint32_t GetPID(); static uint32_t GetPID();
}; };
+59 -48
View File
@@ -5,52 +5,63 @@
#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",
const char* get_field[2] { "xxxx?xxxx?xxxx?xxx????xxxxxxx?xxx?xxxx"};
"\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", const char* get_field[2]{
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?xxxxxxxxxxxxx?x????xxx" "\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"
const char* push_fstring[2] { "\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00"
"\x48\x89\x54\x24\x00\x4c\x89\x44\x24\x00\x4c\x89\x4c\x24\x00\x53\x48\x83\xec\x00\x4c\x8b\x41", "\x00\x00\x48\xb9\x00\x00\x00\x00\x00\x00\x00\x00\x4c\x8d\x44\x24\x00"
"xxxx?xxxx?xxxx?xxxx?xxx" "\x48\x0b\xc1\x48\x8b\xd7\x48\x8b\xcb\x48\x89\x44\x24\x00\xe8\x00\x00"
}; "\x00\x00\x48\x85\xc0",
const char* p_call[2] { "xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?"
"\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", "xxxxxxxxxxxxx?x????xxx"};
"xxxx?xxxx?xxxx?xxx?xxxxxx" const char* push_fstring[2]{
}; "\x48\x89\x54\x24\x00\x4c\x89\x44\x24\x00\x4c\x89\x4c\x24\x00\x53\x48"
const char* lua_setfield[2] { "\x83\xec\x00\x4c\x8b\x41",
"\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", "xxxx?xxxx?xxxx?xxxx?xxx"};
"xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?xxxxxxxxxxxxx?x????xxx" const char* p_call[2]{
}; "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b"
const char* lua_createtable[2] { "\x59\x00\x41\x8b\xf0\x4c\x63\xda",
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x4c\x8b\x49\x00\x41\x8b\xf8", "xxxx?xxxx?xxxx?xxx?xxxxxx"};
"xxxx?xxxx?xxxx?xxx?xxx" const char* lua_setfield[2]{
}; "\x48\x89\x5c\x24\x00\x57\x48\x83\xec\x00\x4d\x8b\xd0\x48\x8b\xd9\xe8"
const char* lua_settable[2] { "\x00\x00\x00\x00\x48\x8b\xf8\x49\xc7\xc0\x00\x00\x00\x00\x90\x49\xff"
"\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", "\xc0\x43\x80\x3c\x02\x00\x75\x00\x49\x8b\xd2\x48\x8b\xcb\xe8\x00\x00"
"xxxxx?xxxx????xxx?xxxxxx?xxxx????xxx" "\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"
const char* lua_pushcclosure[2] { "\x00\x00\x48\x8b\x53",
"\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", "xxxx?xxxx?xxxxxxx????xxxxxx????xxxxxxxx?x?xxxxxxx????xx????????xxxx?"
"xxxx?xxxx?xxxx?xxxxxxxxx?xxx" "xxxxxxxxxxxxx?x????xxx"};
}; const char* lua_createtable[2]{
const char* lua_tolstring[2] { "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x4c\x8b"
"\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x49\x8b\xf8\x8b\xda\x48\x8b\xf1\xe8", "\x49\x00\x41\x8b\xf8",
"xxxx?xxxx?xxxx?xxxxxxxxx" "xxxx?xxxx?xxxx?xxx?xxx"};
}; const char* lua_settable[2]{
const char* GEUpdate[2] { "\x40\x53\x48\x83\xec\x00\x48\x8b\xd9\xe8\x00\x00\x00\x00\x4c\x8b\x43"
"\x48\x89\x5c\x24\x00\x48\x89\x6c\x24\x00\x56\x57\x41\x56\x48\x83\xec\x00\x4c\x8b\x31\x49\x8b\xf0", "\x00\x48\x8b\xd0\x49\x83\xe8\x00\x48\x8b\xcb\xe8\x00\x00\x00\x00\x48"
"xxxx?xxxx?xxxxxxx?xxxxxx" "\x8b\x53",
}; "xxxxx?xxxx????xxx?xxxxxx?xxxx????xxx"};
const char* lua_settop[2] { const char* lua_pushcclosure[2]{
"\x4c\x8b\xc1\x85\xd2\x7e\x00\x48\x8b\x41\x00\x48\x8b\x49", "\x48\x89\x5c\x24\x00\x48\x89\x74\x24\x00\x57\x48\x83\xec\x00\x48\x8b"
"xxxxxx?xxx?xxx" "\xd9\x49\x63\xf8\x48\x8b\x49\x00\x48\x8b\xf2",
}; "xxxx?xxxx?xxxx?xxxxxxxxx?xxx"};
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",
"xxxx?xxxx?xxxx?xxxxxxxxx"};
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",
"xxxx?xxxx?xxxxxxx?xxxxxx"};
const char* lua_settop[2]{
"\x4c\x8b\xc1\x85\xd2\x7e\x00\x48\x8b\x41\x00\x48\x8b\x49",
"xxxxxx?xxx?xxx"};
} }
+61 -59
View File
@@ -12,65 +12,67 @@
struct sockaddr_in; struct sockaddr_in;
class Launcher; class Launcher;
class Server { class Server {
public: public:
Server() = delete; Server() = delete;
explicit Server(Launcher* Instance); explicit Server(Launcher* Instance);
~Server(); ~Server();
public: public:
void ServerSend(std::string Data, bool Rel); void ServerSend(std::string Data, bool Rel);
void Connect(const std::string& Data); void Connect(const std::string& Data);
const std::string& getModList(); const std::string& getModList();
const std::string& getUIStatus(); const std::string& getUIStatus();
const std::string& getMap(); const std::string& getMap();
void StartUDP(); void StartUDP();
void setModLoaded(); void setModLoaded();
bool Terminated(); bool Terminated();
int getPing() const; int getPing() const;
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;
void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name); std::string MultiDownload(uint64_t DSock, uint64_t Size,
std::atomic<bool> Terminate { false }, ModLoaded { false }; const std::string& Name);
char* TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size); void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name);
std::string GetAddress(const std::string& Data); std::atomic<bool> Terminate{false}, ModLoaded{false};
void InvalidResource(const std::string& File); char* TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size);
void UpdateUl(bool D, const std::string& msg); std::string GetAddress(const std::string& Data);
std::unique_ptr<sockaddr_in> UDPSockAddress; void InvalidResource(const std::string& File);
void ServerParser(const std::string& Data); void UpdateUl(bool D, const std::string& msg);
static std::string GetSocketApiError(); std::unique_ptr<sockaddr_in> UDPSockAddress;
void TCPSend(const std::string& Data); void ServerParser(const std::string& Data);
void UDPParser(std::string Packet); static std::string GetSocketApiError();
void SendLarge(std::string Data); void TCPSend(const std::string& Data);
void UDPSend(std::string Data); void UDPParser(std::string Packet);
void UUl(const std::string& R); void SendLarge(std::string Data);
bool CheckBytes(int32_t Bytes); void UDPSend(std::string Data);
int KillSocket(uint64_t Dead); void UUl(const std::string& R);
void MultiKill(uint64_t Sock); bool CheckBytes(int32_t Bytes);
Launcher* LauncherInstance; int KillSocket(uint64_t Dead);
std::thread TCPConnection; void MultiKill(uint64_t Sock);
std::thread UDPConnection; Launcher* LauncherInstance;
std::thread AutoPing; std::thread TCPConnection;
uint64_t TCPSocket = -1; std::thread UDPConnection;
uint64_t UDPSocket = -1; std::thread AutoPing;
void WaitForConfirm(); uint64_t TCPSocket = -1;
std::string UStatus {}; uint64_t UDPSocket = -1;
std::string MStatus {}; void WaitForConfirm();
std::string ModList {}; std::string UStatus{};
void TCPClientMain(); std::string MStatus{};
void SyncResources(); std::string ModList{};
std::string TCPRcv(); void TCPClientMain();
uint64_t InitDSock(); void SyncResources();
std::string Auth(); std::string TCPRcv();
std::string IP {}; uint64_t InitDSock();
void UDPClient(); std::string Auth();
void PingLoop(); std::string IP{};
int ClientID { 0 }; void UDPClient();
void UDPMain(); void PingLoop();
void UDPRcv(); int ClientID{0};
void Abort(); void UDPMain();
int Port { 0 }; void UDPRcv();
int Ping { 0 }; void Abort();
int Port{0};
int Ping{0};
}; };
+40 -44
View File
@@ -7,55 +7,51 @@
#include <queue> #include <queue>
#include <semaphore> #include <semaphore>
template <class T, size_t Size> template<class T, size_t Size>
class atomic_queue { 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(); return true;
return true; }
}
void push(const T& val) { void push(const T& val) {
check_full(); check_full();
lock_guard guard(semaphore); lock_guard guard(semaphore);
queue.push(val); queue.push(val);
} }
size_t size() { size_t size() {
lock_guard guard(semaphore); lock_guard guard(semaphore);
return queue.size(); return queue.size();
} }
bool empty() { bool empty() {
lock_guard guard(semaphore); lock_guard guard(semaphore);
return queue.empty(); return queue.empty();
} }
private: private:
void check_full() { void check_full() {
if (size() >= Size) { if (size() >= Size) {
full.acquire(); full.acquire();
} }
} }
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.release(); }
~lock_guard() {
lock.release();
}
private: private:
std::binary_semaphore& lock; std::binary_semaphore& lock;
}; };
std::binary_semaphore semaphore { 1 }, full { 0 }; std::binary_semaphore semaphore{1}, full{0};
std::queue<T> queue {}; std::queue<T> queue{};
}; };
+23 -29
View File
@@ -3,39 +3,33 @@
/// 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")) {
toml::parse_result config = toml::parse_file("Launcher.toml"); toml::parse_result config = toml::parse_file("Launcher.toml");
auto ui = config["UI"]; auto ui = config["UI"];
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 tml.close();
Build = "Default" } else {
)"; LOG(FATAL) << "Failed to write config on disk!";
tml.close(); throw ShutdownException("Fatal Error");
} else { }
LOG(FATAL) << "Failed to write config on disk!"; }
throw ShutdownException("Fatal Error");
}
}
} }
+34 -34
View File
@@ -3,61 +3,61 @@
/// 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) {}
void handleError(int errcode, const char* message) { void handleError(int errcode, const char* message) {
LOG(ERROR) << "Discord error: " << message; LOG(ERROR) << "Discord error: " << message;
} }
void Launcher::UpdatePresence() { void Launcher::UpdatePresence() {
auto currentTime = std::time(nullptr); auto currentTime = std::time(nullptr);
DiscordRichPresence discordPresence; DiscordRichPresence discordPresence;
memset(&discordPresence, 0, sizeof(discordPresence)); memset(&discordPresence, 0, sizeof(discordPresence));
discordPresence.state = DiscordMessage.c_str(); discordPresence.state = DiscordMessage.c_str();
discordPresence.largeImageKey = "mainlogo"; discordPresence.largeImageKey = "mainlogo";
discordPresence.startTimestamp = currentTime - (currentTime - DiscordTime); discordPresence.startTimestamp = currentTime - (currentTime - DiscordTime);
discordPresence.endTimestamp = 0; discordPresence.endTimestamp = 0;
DiscordTime = currentTime; DiscordTime = currentTime;
Discord_UpdatePresence(&discordPresence); Discord_UpdatePresence(&discordPresence);
} }
void Launcher::setDiscordMessage(const std::string& message) { void Launcher::setDiscordMessage(const std::string& message) {
DiscordMessage = message; DiscordMessage = message;
UpdatePresence(); UpdatePresence();
} }
void Launcher::RichPresence() { void Launcher::RichPresence() {
DiscordEventHandlers handlers; DiscordEventHandlers handlers;
memset(&handlers, 0, sizeof(handlers)); memset(&handlers, 0, sizeof(handlers));
handlers.ready = handleReady; handlers.ready = handleReady;
handlers.errored = handleError; handlers.errored = handleError;
handlers.disconnected = handleDisconnected; handlers.disconnected = handleDisconnected;
Discord_Initialize("629743237988352010", &handlers, 1, nullptr); Discord_Initialize("629743237988352010", &handlers, 1, nullptr);
UpdatePresence(); UpdatePresence();
while (!Shutdown.load()) { while (!Shutdown.load()) {
Discord_RunCallbacks(); Discord_RunCallbacks();
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
Discord_ClearPresence(); Discord_ClearPresence();
Discord_Shutdown(); Discord_Shutdown();
} }
void Launcher::RunDiscordRPC() { void Launcher::RunDiscordRPC() {
DiscordRPC = std::thread(&Launcher::RichPresence, this); DiscordRPC = std::thread(&Launcher::RichPresence, this);
} }
#else #else
#include "Launcher.h" #include "Launcher.h"
void Launcher::setDiscordMessage(const std::string& message) { void Launcher::setDiscordMessage(const std::string& message) {
DiscordMessage = message; DiscordMessage = message;
} }
void Launcher::RunDiscordRPC() { void Launcher::RunDiscordRPC() {
DiscordRPC = std::thread(&Launcher::RichPresence, this); DiscordRPC = std::thread(&Launcher::RichPresence, this);
} }
void Launcher::RichPresence() {}; void Launcher::RichPresence(){};
void Launcher::UpdatePresence() {}; void Launcher::UpdatePresence(){};
#endif #endif
+71 -76
View File
@@ -10,88 +10,83 @@
#include "Memory/Memory.h" #include "Memory/Memory.h"
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(); break;
break; case 'B':
case 'B': ServerHandler.Close();
ServerHandler.Close(); SendIPC(Code + HTTP::Post("https://backend.beammp.com/servers", ""));
SendIPC(Code + HTTP::Post("https://backend.beammp.com/servers", "")); LOG(INFO) << "Sent Server List";
LOG(INFO) << "Sent Server List"; break;
break; case 'C':
case 'C': ServerHandler.Close();
ServerHandler.Close(); ServerHandler.Connect(Data);
ServerHandler.Connect(Data); while (ServerHandler.getModList().empty() &&
while (ServerHandler.getModList().empty() && !ServerHandler.Terminated()) { !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 break;
SendIPC("L" + ServerHandler.getModList()); case 'U':
break; SendIPC("Ul" + ServerHandler.getUIStatus());
case 'U': if (ServerHandler.getPing() > 800) {
SendIPC("Ul" + ServerHandler.getUIStatus());
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()); break;
break; case 'Q':
case 'Q': 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(); break;
break; case 'Z':
case 'Z': SendIPC("Z" + Version);
SendIPC("Z" + Version); break;
break; case 'N':
case 'N': if (SubCode == 'c') {
if (SubCode == 'c') {
SendIPC("N{\"Auth\":" + std::to_string(LoginAuth) + "}"); SendIPC("N{\"Auth\":" + std::to_string(LoginAuth) + "}");
} else { } else {
SendIPC("N" + Login(Data.substr(Data.find(':') + 1))); SendIPC("N" + Login(Data.substr(Data.find(':') + 1)));
} }
break; break;
default: default:
break; break;
} }
} }
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) SubCode = Data.at(1);
if (Data.length() > 1) switch (Code) {
SubCode = Data.at(1); case 'p':
switch (Code) { PingEnd = std::chrono::high_resolution_clock::now();
case 'p': if (PingStart > PingEnd) Ping = 0;
PingEnd = std::chrono::high_resolution_clock::now(); else
if (PingStart > PingEnd) Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(
Ping = 0; PingEnd - PingStart)
else .count());
Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd - PingStart).count()); return;
return; case 'M':
case 'M': MStatus = Data;
MStatus = Data; UStatus = "done";
UStatus = "done"; return;
return; case 'K':
case 'K': Terminate = true;
Terminate = true; UStatus = Data.substr(1);
UStatus = Data.substr(1); return;
return; default:
default: break;
break; }
} LauncherInstance->SendIPC(Data, false);
LauncherInstance->SendIPC(Data, false);
} }
+196 -182
View File
@@ -5,265 +5,279 @@
#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
return EXCEPTION_EXECUTE_HANDLER; << p->ExceptionRecord->ExceptionCode;
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();
WindowsInit(); WindowsInit();
SetUnhandledExceptionFilter(CrashHandler); SetUnhandledExceptionFilter(CrashHandler);
LOG(INFO) << "Starting Launcher V" << FullVersion; LOG(INFO) << "Starting Launcher V" << FullVersion;
UpdateCheck(); UpdateCheck();
} }
void Launcher::Abort() { void Launcher::Abort() {
Shutdown.store(true); Shutdown.store(true);
ServerHandler.Close(); ServerHandler.Close();
if (DiscordRPC.joinable()) { if (DiscordRPC.joinable()) {
DiscordRPC.join(); DiscordRPC.join();
} }
if (IPCSystem.joinable()) { if (IPCSystem.joinable()) {
IPCSystem.join(); IPCSystem.join();
} }
if (!MPUserPath.empty()) { if (!MPUserPath.empty()) {
ResetMods(); ResetMods();
} }
if (GamePID != 0) { if (GamePID != 0) {
auto Handle = OpenProcess(PROCESS_TERMINATE, false, DWORD(GamePID)); auto Handle = OpenProcess(PROCESS_TERMINATE, false, DWORD(GamePID));
TerminateProcess(Handle, 0); TerminateProcess(Handle, 0);
CloseHandle(Handle); CloseHandle(Handle);
} }
} }
Launcher::~Launcher() { Launcher::~Launcher() {
if (!Shutdown.load()) { if (!Shutdown.load()) {
Abort(); Abort();
} }
} }
void ShutdownHandler(int sig) { void ShutdownHandler(int sig) {
Launcher::StaticAbort(); Launcher::StaticAbort();
while (HTTP::isDownload) { while (HTTP::isDownload) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
LOG(INFO) << "Got termination signal (" << sig << ")"; LOG(INFO) << "Got termination signal (" << sig << ")";
while (!Launcher::getExit()) { while (!Launcher::getExit()) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
} }
void Launcher::StaticAbort(Launcher* Instance) { void Launcher::StaticAbort(Launcher* Instance) {
static Launcher* Address; static Launcher* Address;
if (Instance) { if (Instance) {
Address = Instance; Address = Instance;
return; return;
} }
Address->Abort(); Address->Abort();
} }
void Launcher::WindowsInit() { void Launcher::WindowsInit() {
system("cls"); system("cls");
SetConsoleTitleA(("BeamMP Launcher v" + FullVersion).c_str()); SetConsoleTitleA(("BeamMP Launcher v" + FullVersion).c_str());
signal(SIGINT, ShutdownHandler); signal(SIGINT, ShutdownHandler);
signal(SIGTERM, ShutdownHandler); signal(SIGTERM, ShutdownHandler);
signal(SIGABRT, ShutdownHandler); signal(SIGABRT, ShutdownHandler);
signal(SIGBREAK, ShutdownHandler); signal(SIGBREAK, ShutdownHandler);
} }
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
throw ShutdownException("Fatal Error"); << " not yet supported, please wait until we update BeamMP!";
} else if (GameVersion.data[1] < SupportedVersion.data[1]) { throw ShutdownException("Fatal Error");
LOG(FATAL) << "BeamNG V" << BeamVersion << " not supported, please update and launch the new update!"; } else if (GameVersion.data[1] < SupportedVersion.data[1]) {
throw ShutdownException("Fatal Error"); LOG(FATAL) << "BeamNG V" << BeamVersion
} else if (GameVersion > SupportedVersion) { << " not supported, please update and launch the new update!";
LOG(WARNING) << "BeamNG V" << BeamVersion << " is slightly newer than recommended, this might cause issues!"; throw ShutdownException("Fatal Error");
} 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
if (Memory::GetBeamNGPID({}) == 0) { << " is slightly newer than recommended, this might cause issues!";
LOG(INFO) << "Launching BeamNG from steam"; } else if (GameVersion < SupportedVersion) {
ShellExecuteA(nullptr, nullptr, "steam://rungameid/284160", nullptr, nullptr, SW_SHOWNORMAL); LOG(WARNING)
// ShowWindow(GetConsoleWindow(), HIDE_WINDOW); << "BeamNG V" << BeamVersion
} << " is slightly older than recommended, this might cause issues!";
LOG(INFO) << "Waiting for a game process, please start BeamNG manually in case of steam issues"; }
if (Memory::GetBeamNGPID({}) == 0) {
LOG(INFO) << "Launching BeamNG from steam";
ShellExecuteA(nullptr, nullptr, "steam://rungameid/284160", nullptr,
nullptr, SW_SHOWNORMAL);
// ShowWindow(GetConsoleWindow(), HIDE_WINDOW);
}
LOG(INFO) << "Waiting for a game process, please start BeamNG manually in "
"case of steam issues";
} }
void Launcher::WaitForGame() { void Launcher::WaitForGame() {
std::set<uint32_t> BlackList; std::set<uint32_t> BlackList;
do { do {
auto PID = Memory::GetBeamNGPID(BlackList); auto PID = Memory::GetBeamNGPID(BlackList);
if (PID != 0 && IPC::mem_used(PID)) { if (PID != 0 && IPC::mem_used(PID)) {
BlackList.emplace(PID); BlackList.emplace(PID);
} else { } else {
GamePID = PID; GamePID = PID;
} }
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";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} }
LOG(INFO) << "Game found! PID " << GamePID; LOG(INFO) << "Game found! PID " << GamePID;
IPCToGame = std::make_unique<IPC>(GamePID, 0x1900000); IPCToGame = std::make_unique<IPC>(GamePID, 0x1900000);
IPCFromGame = std::make_unique<IPC>(GamePID + 1, 0x1900000); IPCFromGame = std::make_unique<IPC>(GamePID + 1, 0x1900000);
IPCSystem = std::thread(&Launcher::ListenIPC, this); IPCSystem = std::thread(&Launcher::ListenIPC, this);
Memory::Inject(GamePID); Memory::Inject(GamePID);
setDiscordMessage("In menus"); setDiscordMessage("In menus");
while (!Shutdown.load() && Memory::GetBeamNGPID(BlackList) != 0) { while (!Shutdown.load() && Memory::GetBeamNGPID(BlackList) != 0) {
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(2));
} }
LOG(INFO) << "Game process was lost"; LOG(INFO) << "Game process was lost";
GamePID = 0; GamePID = 0;
} }
void Launcher::ListenIPC() { void Launcher::ListenIPC() {
while (!Shutdown.load()) { while (!Shutdown.load()) {
IPCFromGame->receive(); IPCFromGame->receive();
if (!IPCFromGame->receive_timed_out()) { if (!IPCFromGame->receive_timed_out()) {
auto& MSG = IPCFromGame->msg(); auto& MSG = IPCFromGame->msg();
if (MSG[0] == 'C') { if (MSG[0] == 'C') {
HandleIPC(IPCFromGame->msg().substr(1)); HandleIPC(IPCFromGame->msg().substr(1));
} else { } else {
ServerHandler.ServerSend(IPCFromGame->msg().substr(1), false); ServerHandler.ServerSend(IPCFromGame->msg().substr(1), false);
} }
IPCFromGame->confirm_receive(); IPCFromGame->confirm_receive();
} }
} }
} }
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 if (IPCToGame->send_timed_out()) {
IPCToGame->send("G" + Data); LOG(WARNING) << "Timed out while sending \"" << Data << "\"";
if (IPCToGame->send_timed_out()) { }
LOG(WARNING) << "Timed out while sending \"" << Data << "\"";
}
} }
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) ==
return { (char*)buffer, keySize - 1 }; ERROR_SUCCESS) {
} return {(char*)buffer, keySize - 1};
return {}; }
return {};
} }
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";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} }
_bstr_t bstrPath(folderPath); _bstr_t bstrPath(folderPath);
std::string Path((char*)bstrPath); std::string Path((char*)bstrPath);
CoTaskMemFree(folderPath); CoTaskMemFree(folderPath);
if (!Path.empty()) { if (!Path.empty()) {
Path += "\\BeamNG.drive\\"; Path += "\\BeamNG.drive\\";
VersionParser GameVer(BeamVersion); VersionParser GameVer(BeamVersion);
Path += GameVer.split[0] + '.' + GameVer.split[1] + '\\'; Path += GameVer.split[0] + '.' + GameVer.split[1] + '\\';
return Path; return Path;
} }
return {}; return {};
} }
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 =
if (RegRes == ERROR_SUCCESS) { RegOpenKeyExA(HKEY_CURRENT_USER, R"(Software\BeamNG\BeamNG.drive)", 0,
BeamRoot = QueryValue(BeamNG, "rootpath"); KEY_READ, &BeamNG);
BeamVersion = QueryValue(BeamNG, "version"); if (RegRes == ERROR_SUCCESS) {
BeamUserPath = QueryValue(BeamNG, "userpath_override"); BeamRoot = QueryValue(BeamNG, "rootpath");
RegCloseKey(BeamNG); BeamVersion = QueryValue(BeamNG, "version");
if (BeamUserPath.empty() && !BeamVersion.empty()) { BeamUserPath = QueryValue(BeamNG, "userpath_override");
BeamUserPath = GetLocalAppdata(); RegCloseKey(BeamNG);
} else if (!BeamUserPath.empty() && !BeamVersion.empty()) { if (BeamUserPath.empty() && !BeamVersion.empty()) {
VersionParser GameVer(BeamVersion); BeamUserPath = GetLocalAppdata();
BeamUserPath += GameVer.split[0] + '.' + GameVer.split[1] + '\\'; } else if (!BeamUserPath.empty() && !BeamVersion.empty()) {
} VersionParser GameVer(BeamVersion);
if (!BeamUserPath.empty()) { BeamUserPath += GameVer.split[0] + '.' + GameVer.split[1] + '\\';
MPUserPath = BeamUserPath + "mods\\multiplayer"; }
} if (!BeamUserPath.empty()) {
if (!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty()) MPUserPath = BeamUserPath + "mods\\multiplayer";
return; }
} if (!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty())
LOG(FATAL) << "Please launch the game at least once, failed to read registry key Software\\BeamNG\\BeamNG.drive"; return;
throw ShutdownException("Fatal Error"); }
LOG(FATAL)
<< "Please launch the game at least once, failed to read registry "
"key Software\\BeamNG\\BeamNG.drive";
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,
ShowWindow(GetConsoleWindow(), 0); nullptr, SW_SHOWNORMAL);
throw ShutdownException("Relaunching"); ShowWindow(GetConsoleWindow(), 0);
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,
ShowWindow(GetConsoleWindow(), 0); nullptr, SW_SHOWNORMAL);
std::this_thread::sleep_for(std::chrono::seconds(1)); ShowWindow(GetConsoleWindow(), 0);
throw ShutdownException("Relaunching"); std::this_thread::sleep_for(std::chrono::seconds(1));
throw ShutdownException("Relaunching");
} }
const std::string& Launcher::getFullVersion() { const std::string& Launcher::getFullVersion() {
return FullVersion; return FullVersion;
} }
const std::string& Launcher::getVersion() { const std::string& Launcher::getVersion() {
return Version; return Version;
} }
const std::string& Launcher::getUserRole() { const std::string& Launcher::getUserRole() {
return UserRole; return UserRole;
} }
bool Launcher::Terminated() noexcept { bool Launcher::Terminated() noexcept {
return Shutdown.load(); return Shutdown.load();
} }
bool Launcher::getExit() noexcept { bool Launcher::getExit() noexcept {
return Exit.load(); return Exit.load();
} }
void Launcher::setExit(bool exit) noexcept { void Launcher::setExit(bool exit) noexcept {
Exit.store(exit); Exit.store(exit);
} }
const std::string& Launcher::getMPUserPath() { const std::string& Launcher::getMPUserPath() {
return MPUserPath; return MPUserPath;
} }
const std::string& Launcher::getPublicKey() { const std::string& Launcher::getPublicKey() {
return PublicKey; return PublicKey;
} }
+17 -15
View File
@@ -7,19 +7,21 @@
INITIALIZE_EASYLOGGINGPP INITIALIZE_EASYLOGGINGPP
using namespace el; 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::LogFlushThreshold, "2"); Conf.setGlobally(ConfigurationType::Format,
Conf.set(Level::Verbose, ConfigurationType::Format, DFormat); "%datetime{[%d/%M/%y %H:%m:%s]} [%level] %msg");
Conf.set(Level::Debug, ConfigurationType::Format, DFormat); Conf.setGlobally(ConfigurationType::LogFlushThreshold, "2");
Conf.set(Level::Trace, ConfigurationType::Format, DFormat); Conf.set(Level::Verbose, ConfigurationType::Format, DFormat);
Conf.set(Level::Fatal, ConfigurationType::Format, DFormat); Conf.set(Level::Debug, ConfigurationType::Format, DFormat);
Conf.setGlobally(ConfigurationType::Filename, "Launcher.log"); Conf.set(Level::Trace, ConfigurationType::Format, DFormat);
Conf.setGlobally(ConfigurationType::MaxLogFileSize, "7340032"); Conf.set(Level::Fatal, ConfigurationType::Format, DFormat);
Loggers::reconfigureAllLoggers(Conf); Conf.setGlobally(ConfigurationType::Filename, "Launcher.log");
Loggers::addFlag(LoggingFlag::DisableApplicationAbortOnFatalLog); Conf.setGlobally(ConfigurationType::MaxLogFileSize, "7340032");
Loggers::addFlag(LoggingFlag::HierarchicalLogging); Loggers::reconfigureAllLoggers(Conf);
Loggers::setLoggingLevel(Level::Global); Loggers::addFlag(LoggingFlag::DisableApplicationAbortOnFatalLog);
Loggers::addFlag(LoggingFlag::HierarchicalLogging);
Loggers::setLoggingLevel(Level::Global);
} }
+61 -59
View File
@@ -10,84 +10,86 @@
std::unique_ptr<atomic_queue<std::string, 1000>> Queue; std::unique_ptr<atomic_queue<std::string, 1000>> Queue;
int BeamNG::lua_open_jit_D(lua_State* State) { int BeamNG::lua_open_jit_D(lua_State* State) {
Memory::Print("Got lua State"); Memory::Print("Got lua State");
GELua::State = State; GELua::State = State;
RegisterGEFunctions(); RegisterGEFunctions();
return OpenJITDetour->Original(State); return OpenJITDetour->Original(State);
} }
void BeamNG::EntryPoint() { void BeamNG::EntryPoint() {
Queue = std::make_unique<atomic_queue<std::string, 1000>>(); Queue = std::make_unique<atomic_queue<std::string, 1000>>();
uint32_t PID = Memory::GetPID(); uint32_t PID = Memory::GetPID();
auto status = MH_Initialize(); auto status = MH_Initialize();
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));
Memory::Print("PID : " + std::to_string(PID)); Memory::Print("PID : " + std::to_string(PID));
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>>(
OpenJITDetour->Enable(); GELua::lua_open_jit, lua_open_jit_D);
IPCFromLauncher = std::make_unique<IPC>(PID, 0x1900000); OpenJITDetour->Enable();
IPCToLauncher = std::make_unique<IPC>(PID + 1, 0x1900000); IPCFromLauncher = std::make_unique<IPC>(PID, 0x1900000);
IPCListener(); IPCToLauncher = std::make_unique<IPC>(PID + 1, 0x1900000);
IPCListener();
} }
int Core(lua_State* L) { 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::string msg(Data, Size); // std::to_string(Size));
BeamNG::SendIPC("C" + msg); std::string msg(Data, Size);
} BeamNG::SendIPC("C" + msg);
return 0; }
return 0;
} }
int Game(lua_State* L) { 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::string msg(Data, Size); // std::to_string(Size));
BeamNG::SendIPC("G" + msg); std::string msg(Data, Size);
} BeamNG::SendIPC("G" + msg);
return 0; }
return 0;
} }
int LuaPop(lua_State* L) { int LuaPop(lua_State* L) {
std::string MSG; std::string MSG;
if (Queue->try_pop(MSG)) { if (Queue->try_pop(MSG)) {
GELua::lua_push_fstring(L, "%s", MSG.c_str()); GELua::lua_push_fstring(L, "%s", MSG.c_str());
return 1; return 1;
} }
return 0; return 0;
} }
void BeamNG::RegisterGEFunctions() { void BeamNG::RegisterGEFunctions() {
Memory::Print("Registering GE Functions"); Memory::Print("Registering GE Functions");
GELuaTable::Begin(GELua::State); GELuaTable::Begin(GELua::State);
GELuaTable::InsertFunction(GELua::State, "Core", Core); GELuaTable::InsertFunction(GELua::State, "Core", Core);
GELuaTable::InsertFunction(GELua::State, "Game", Game); GELuaTable::InsertFunction(GELua::State, "Game", Game);
GELuaTable::InsertFunction(GELua::State, "try_pop", LuaPop); GELuaTable::InsertFunction(GELua::State, "try_pop", LuaPop);
GELuaTable::End(GELua::State, "MP"); GELuaTable::End(GELua::State, "MP");
Memory::Print("Registered!"); Memory::Print("Registered!");
} }
void BeamNG::SendIPC(const std::string& Data) { void BeamNG::SendIPC(const std::string& Data) {
IPCToLauncher->send(Data); IPCToLauncher->send(Data);
} }
void BeamNG::IPCListener() { void BeamNG::IPCListener() {
int TimeOuts = 0; int TimeOuts = 0;
while (TimeOuts < 20) { while (TimeOuts < 20) {
IPCFromLauncher->receive(); IPCFromLauncher->receive();
if (!IPCFromLauncher->receive_timed_out()) { if (!IPCFromLauncher->receive_timed_out()) {
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");
} }
+1 -1
View File
@@ -12,5 +12,5 @@
#include "lua/lj_strscan.h" #include "lua/lj_strscan.h"
LUA_API int lua_gettop(lua_State* L) { LUA_API int lua_gettop(lua_State* L) {
return (int)(L->top - L->base); return (int)(L->top - L->base);
} }
+54 -30
View File
@@ -8,39 +8,63 @@
#include "Memory/Patterns.h" #include "Memory/Patterns.h"
const char* GameModule = "BeamNG.drive.x64.exe"; const char* GameModule = "BeamNG.drive.x64.exe";
const char* DllModule = "libbeamng.x64.dll"; const char* DllModule = "libbeamng.x64.dll";
std::string GetHex(uint64_t num) { std::string GetHex(uint64_t num) {
char buffer[30]; char buffer[30];
sprintf(buffer, "%llx", num); sprintf(buffer, "%llx", num);
return std::string { buffer }; return std::string{buffer};
} }
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));
} }
+46 -44
View File
@@ -7,85 +7,87 @@
#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)}, Mem{"MP_IO" + std::to_string(ID)};
SemConf { "MP_SC" + std::to_string(ID) },
Mem { "MP_IO" + std::to_string(ID) };
SemHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, Sem.c_str()); SemHandle_ =
if (SemHandle_ == nullptr) { OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, Sem.c_str());
SemHandle_ = CreateSemaphoreA(nullptr, 0, 1, Sem.c_str()); if (SemHandle_ == nullptr) {
} SemHandle_ = CreateSemaphoreA(nullptr, 0, 1, Sem.c_str());
SemConfHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, SemConf.c_str()); }
if (SemConfHandle_ == nullptr) { SemConfHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE,
SemConfHandle_ = CreateSemaphoreA(nullptr, 0, 1, SemConf.c_str()); SemConf.c_str());
} if (SemConfHandle_ == nullptr) {
MemoryHandle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str()); SemConfHandle_ = CreateSemaphoreA(nullptr, 0, 1, SemConf.c_str());
if (MemoryHandle_ == nullptr) { }
MemoryHandle_ = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(Size), Mem.c_str()); MemoryHandle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str());
} if (MemoryHandle_ == nullptr) {
Data_ = (char*)MapViewOfFile(MemoryHandle_, FILE_MAP_ALL_ACCESS, 0, 0, Size); 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);
} }
void IPC::confirm_receive() noexcept { void IPC::confirm_receive() noexcept {
ReleaseSemaphore(SemConfHandle_, 1, nullptr); ReleaseSemaphore(SemConfHandle_, 1, nullptr);
} }
void IPC::send(const std::string& msg) noexcept { void IPC::send(const std::string& msg) noexcept {
size_t Size = msg.size(); size_t Size = msg.size();
memcpy(Data_, &Size, sizeof(size_t)); memcpy(Data_, &Size, sizeof(size_t));
memcpy(Data_ + sizeof(size_t), msg.c_str(), Size); memcpy(Data_ + sizeof(size_t), msg.c_str(), Size);
memset(Data_ + sizeof(size_t) + Size, 0, 3); memset(Data_ + sizeof(size_t) + Size, 0, 3);
ReleaseSemaphore(SemHandle_, 1, nullptr); ReleaseSemaphore(SemHandle_, 1, nullptr);
SendTimeout = WaitForSingleObject(SemConfHandle_, 5000) == WAIT_TIMEOUT; SendTimeout = WaitForSingleObject(SemConfHandle_, 5000) == WAIT_TIMEOUT;
} }
void IPC::receive() noexcept { void IPC::receive() noexcept {
RcvTimeout = WaitForSingleObject(SemHandle_, 5000) == WAIT_TIMEOUT; RcvTimeout = WaitForSingleObject(SemHandle_, 5000) == WAIT_TIMEOUT;
} }
void IPC::try_receive() noexcept { void IPC::try_receive() noexcept {
RcvTimeout = WaitForSingleObject(SemHandle_, 0) == WAIT_TIMEOUT; RcvTimeout = WaitForSingleObject(SemHandle_, 0) == WAIT_TIMEOUT;
} }
size_t IPC::size() const noexcept { size_t IPC::size() const noexcept {
return Size_; return Size_;
} }
char* IPC::c_str() const noexcept { char* IPC::c_str() const noexcept {
return Data_ + sizeof(size_t); return Data_ + sizeof(size_t);
} }
void* IPC::raw() const noexcept { void* IPC::raw() const noexcept {
return Data_ + sizeof(size_t); return Data_ + sizeof(size_t);
} }
const std::string& IPC::msg() noexcept { const std::string& IPC::msg() noexcept {
size_t Size; size_t Size;
memcpy(&Size, Data_, sizeof(size_t)); memcpy(&Size, Data_, sizeof(size_t));
Msg_ = std::string(c_str(), Size); Msg_ = std::string(c_str(), Size);
return Msg_; return Msg_;
} }
bool IPC::receive_timed_out() const noexcept { bool IPC::receive_timed_out() const noexcept {
return RcvTimeout; return RcvTimeout;
} }
bool IPC::send_timed_out() const noexcept { bool IPC::send_timed_out() const noexcept {
return SendTimeout; return SendTimeout;
} }
IPC::~IPC() noexcept { IPC::~IPC() noexcept {
UnmapViewOfFile(Data_); UnmapViewOfFile(Data_);
CloseHandle(SemHandle_); CloseHandle(SemHandle_);
CloseHandle(MemoryHandle_); CloseHandle(MemoryHandle_);
} }
bool IPC::mem_used(uint32_t MemID) noexcept { bool IPC::mem_used(uint32_t MemID) noexcept {
std::string Mem { "MP_IO" + std::to_string(MemID) }; std::string Mem{"MP_IO" + std::to_string(MemID)};
HANDLE MEM = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str()); HANDLE MEM = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str());
bool used = MEM != nullptr; bool used = MEM != nullptr;
UnmapViewOfFile(MEM); UnmapViewOfFile(MEM);
return used; return used;
} }
+100 -80
View File
@@ -6,131 +6,151 @@
#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);
PROCESSENTRY32 pe32; PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32); pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
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));
} }
if (Snapshot != INVALID_HANDLE_VALUE) { if (Snapshot != INVALID_HANDLE_VALUE) {
CloseHandle(Snapshot); CloseHandle(Snapshot);
} }
if (GetLastError() != 0) if (GetLastError() != 0) return 0;
return 0; return pe32.th32ProcessID;
return pe32.th32ProcessID;
} }
uint64_t Memory::GetModuleBase(const char* Name) { uint64_t Memory::GetModuleBase(const char* Name) {
return (uint64_t)GetModuleHandleA(Name); return (uint64_t)GetModuleHandleA(Name);
} }
uint32_t Memory::GetPID() { uint32_t Memory::GetPID() {
return GetCurrentProcessId(); return GetCurrentProcessId();
} }
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,
auto base = uint64_t(mInfo.lpBaseOfDll); sizeof(MODULEINFO));
auto size = uint32_t(mInfo.SizeOfImage); auto base = uint64_t(mInfo.lpBaseOfDll);
auto len = strlen(Pattern[1]); auto size = uint32_t(mInfo.SizeOfImage);
for (auto i = 0; i < size - len; i++) { auto len = strlen(Pattern[1]);
bool found = true; for (auto i = 0; i < size - len; i++) {
for (auto j = 0; j < len && found; j++) { bool found = true;
found &= Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base + i + j); for (auto j = 0; j < len && found; j++) {
} found &=
if (found) { Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base + i + j);
return base + i; }
} if (found) {
} return base + i;
return 0; }
}
return 0;
} }
void* operator new(size_t size) { void* operator new(size_t size) {
return GlobalAlloc(GPTR, size); return GlobalAlloc(GPTR, size);
} }
void* operator new[](size_t size) { void* operator new[](size_t size) {
return GlobalAlloc(GPTR, size); return GlobalAlloc(GPTR, size);
} }
void operator delete(void* p) noexcept { void operator delete(void* p) noexcept {
GlobalFree(p); GlobalFree(p);
} }
void operator delete[](void* p) noexcept { void operator delete[](void* p) noexcept {
GlobalFree(p); GlobalFree(p);
} }
typedef struct BASE_RELOCATION_ENTRY { typedef struct BASE_RELOCATION_ENTRY {
USHORT Offset : 12; USHORT Offset : 12;
USHORT Type : 4; USHORT Type : 4;
} BASE_RELOCATION_ENTRY, *PBASE_RELOCATION_ENTRY; } BASE_RELOCATION_ENTRY, *PBASE_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 =
memcpy(localImage, imageBase, ntHeader->OptionalHeader.SizeOfImage); VirtualAlloc(nullptr, ntHeader->OptionalHeader.SizeOfImage, MEM_COMMIT,
PAGE_READWRITE);
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 =
PDWORD_PTR patchedAddress; (PIMAGE_BASE_RELOCATION)((DWORD_PTR)localImage +
while (relocationTable->SizeOfBlock > 0) { ntHeader->OptionalHeader
DWORD relocationEntriesCount = (relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); .DataDirectory
auto relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1); [IMAGE_DIRECTORY_ENTRY_BASERELOC]
for (uint32_t i = 0; i < relocationEntriesCount; i++) { .VirtualAddress);
if (relocationRVA[i].Offset) { PDWORD_PTR patchedAddress;
patchedAddress = PDWORD_PTR(DWORD_PTR(localImage) + relocationTable->VirtualAddress + relocationRVA[i].Offset); while (relocationTable->SizeOfBlock > 0) {
*patchedAddress += deltaImageBase; DWORD relocationEntriesCount =
} (relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) /
} sizeof(USHORT);
relocationTable = PIMAGE_BASE_RELOCATION(DWORD_PTR(relocationTable) + relocationTable->SizeOfBlock); auto relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1);
} for (uint32_t i = 0; i < relocationEntriesCount; i++) {
WriteProcessMemory(targetProcess, targetImage, localImage, ntHeader->OptionalHeader.SizeOfImage, nullptr); if (relocationRVA[i].Offset) {
CreateRemoteThread(targetProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)((DWORD_PTR)EntryPoint + deltaImageBase), nullptr, 0, nullptr); patchedAddress = PDWORD_PTR(DWORD_PTR(localImage) +
CloseHandle(targetProcess); relocationTable->VirtualAddress +
relocationRVA[i].Offset);
*patchedAddress += deltaImageBase;
}
}
relocationTable = PIMAGE_BASE_RELOCATION(DWORD_PTR(relocationTable) +
relocationTable->SizeOfBlock);
}
WriteProcessMemory(targetProcess, targetImage, localImage,
ntHeader->OptionalHeader.SizeOfImage, nullptr);
CreateRemoteThread(
targetProcess, nullptr, 0,
(LPTHREAD_START_ROUTINE)((DWORD_PTR)EntryPoint + deltaImageBase),
nullptr, 0, nullptr);
CloseHandle(targetProcess);
} }
void Memory::Print(const std::string& msg) { void Memory::Print(const std::string& msg) {
HANDLE stdOut = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (stdOut != nullptr && stdOut != INVALID_HANDLE_VALUE) { if (stdOut != nullptr && stdOut != INVALID_HANDLE_VALUE) {
DWORD written = 0; DWORD written = 0;
WriteConsoleA(stdOut, "[BeamMP] ", 9, &written, nullptr); WriteConsoleA(stdOut, "[BeamMP] ", 9, &written, nullptr);
WriteConsoleA(stdOut, msg.c_str(), DWORD(msg.size()), &written, nullptr); WriteConsoleA(stdOut, msg.c_str(), DWORD(msg.size()), &written, nullptr);
WriteConsoleA(stdOut, "\n", 1, &written, nullptr); WriteConsoleA(stdOut, "\n", 1, &written, nullptr);
} }
} }
uint32_t Memory::EntryPoint() { uint32_t Memory::EntryPoint() {
AllocConsole(); AllocConsole();
SetConsoleTitleA("BeamMP Console"); SetConsoleTitleA("BeamMP Console");
BeamNG::EntryPoint(); BeamNG::EntryPoint();
return 0; return 0;
} }
uint32_t Memory::GetTickCount() { uint32_t Memory::GetTickCount() {
return ::GetTickCount(); return ::GetTickCount();
} }
+38 -38
View File
@@ -8,45 +8,45 @@
#define Biggest 30000 #define Biggest 30000
std::string Zlib::Comp(std::string Data) { std::string Zlib::Comp(std::string Data) {
char* C = new char[Biggest]; char* C = new char[Biggest];
memset(C, 0, Biggest); memset(C, 0, Biggest);
z_stream defstream; z_stream defstream;
defstream.zalloc = Z_NULL; defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL; defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL; defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)Data.length(); defstream.avail_in = (uInt)Data.length();
defstream.next_in = (Bytef*)&Data[0]; defstream.next_in = (Bytef*)&Data[0];
defstream.avail_out = Biggest; defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(C); defstream.next_out = reinterpret_cast<Bytef*>(C);
deflateInit(&defstream, Z_BEST_COMPRESSION); deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH); deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH); deflate(&defstream, Z_FINISH);
deflateEnd(&defstream); deflateEnd(&defstream);
uint32_t TO = defstream.total_out; uint32_t TO = defstream.total_out;
std::string Ret(TO, 0); std::string Ret(TO, 0);
memcpy_s(&Ret[0], TO, C, TO); memcpy_s(&Ret[0], TO, C, TO);
delete[] C; delete[] C;
return Ret; return Ret;
} }
std::string Zlib::DeComp(std::string Compressed) { std::string Zlib::DeComp(std::string Compressed) {
char* C = new char[Biggest]; char* C = new char[Biggest];
memset(C, 0, Biggest); memset(C, 0, Biggest);
z_stream infstream; z_stream infstream;
infstream.zalloc = Z_NULL; infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL; infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL; infstream.opaque = Z_NULL;
infstream.avail_in = Biggest; infstream.avail_in = Biggest;
infstream.next_in = (Bytef*)(&Compressed[0]); infstream.next_in = (Bytef*)(&Compressed[0]);
infstream.avail_out = Biggest; infstream.avail_out = Biggest;
infstream.next_out = (Bytef*)(C); infstream.next_out = (Bytef*)(C);
inflateInit(&infstream); inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH); inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH); inflate(&infstream, Z_FINISH);
inflateEnd(&infstream); inflateEnd(&infstream);
uint32_t TO = infstream.total_out; uint32_t TO = infstream.total_out;
std::string Ret(TO, 0); std::string Ret(TO, 0);
memcpy_s(&Ret[0], TO, C, TO); memcpy_s(&Ret[0], TO, C, TO);
delete[] C; delete[] C;
return Ret; return Ret;
} }
+94 -97
View File
@@ -4,127 +4,124 @@
/// ///
#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;
std::string HTTP::Get(const std::string& IP) { std::string HTTP::Get(const std::string& IP) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
auto pos = IP.find('/', 10); auto pos = IP.find('/', 10);
httplib::Client cli(IP.substr(0, pos)); httplib::Client cli(IP.substr(0, pos));
CliRef.store(&cli); CliRef.store(&cli);
cli.set_connection_timeout(std::chrono::seconds(5)); cli.set_connection_timeout(std::chrono::seconds(5));
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar); auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
std::string Ret; std::string Ret;
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) {
std::cout << "\n"; std::cout << "\n";
} }
LOG(ERROR) << "HTTP Get failed on " << httplib::to_string(res.error()); LOG(ERROR) << "HTTP Get failed on " << httplib::to_string(res.error());
} }
CliRef.store(nullptr); CliRef.store(nullptr);
return Ret; return Ret;
} }
std::string HTTP::Post(const std::string& IP, const std::string& Fields) { std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
auto pos = IP.find('/', 10); auto pos = IP.find('/', 10);
httplib::Client cli(IP.substr(0, pos)); httplib::Client cli(IP.substr(0, pos));
CliRef.store(&cli); CliRef.store(&cli);
cli.set_connection_timeout(std::chrono::seconds(5)); cli.set_connection_timeout(std::chrono::seconds(5));
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) {
LOG(ERROR) << res->reason; LOG(ERROR) << res->reason;
} }
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 { }
httplib::Result res = cli.Post(IP.substr(pos).c_str()); } else {
if (res.error() == httplib::Error::Success) { httplib::Result res = cli.Post(IP.substr(pos).c_str());
if (res->status != 200) { if (res.error() == httplib::Error::Success) {
LOG(ERROR) << res->reason; if (res->status != 200) {
} LOG(ERROR) << res->reason;
Ret = res->body; }
} else { Ret = res->body;
LOG(ERROR) << "HTTP Post failed on " << httplib::to_string(res.error()); } else {
} LOG(ERROR) << "HTTP Post failed on "
} << httplib::to_string(res.error());
CliRef.store(nullptr); }
if (Ret.empty()) }
return "-1"; CliRef.store(nullptr);
else if (Ret.empty()) return "-1";
return Ret; else return Ret;
} }
bool HTTP::ProgressBar(size_t c, size_t t) { bool HTTP::ProgressBar(size_t c, size_t t) {
if (isDownload) { if (isDownload) {
static double progress_bar_adv; static double progress_bar_adv;
progress_bar_adv = round(double(c) / double(t) * 25); progress_bar_adv = round(double(c) / double(t) * 25);
std::cout << "\r"; std::cout << "\r";
std::cout << "Progress: [ "; std::cout << "Progress: [ ";
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()) {
} CliRef.load()->stop();
if (Launcher::Terminated()) { std::cout << '\n';
CliRef.load()->stop(); isDownload = false;
std::cout << '\n'; throw ShutdownException("Interrupted");
isDownload = false; }
throw ShutdownException("Interrupted"); return true;
}
return true;
} }
bool HTTP::Download(const std::string& IP, const std::string& Path) { bool HTTP::Download(const std::string& IP, const std::string& Path) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
isDownload = true; isDownload = true;
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()) { File << Ret;
File << Ret; File.close();
File.close(); LOG(INFO) << "Download complete!";
LOG(INFO) << "Download complete!"; } else {
} else { LOG(ERROR) << "Failed to open file directory: " << Path;
LOG(ERROR) << "Failed to open file directory: " << Path; return false;
return false; }
} return true;
return true;
} }
+80 -77
View File
@@ -9,18 +9,18 @@
#include "Logger.h" #include "Logger.h"
void UpdateKey(const std::string& newKey) { void UpdateKey(const std::string& newKey) {
if (!newKey.empty()) { if (!newKey.empty()) {
std::ofstream Key("key"); std::ofstream Key("key");
if (Key.is_open()) { if (Key.is_open()) {
Key << newKey; Key << newKey;
Key.close(); Key.close();
} else { } else {
LOG(FATAL) << "Cannot write to disk!"; LOG(FATAL) << "Cannot write to disk!";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
} }
} else if (fs::exists("key")) { } else if (fs::exists("key")) {
remove("key"); remove("key");
} }
} }
/// "username":"value","password":"value" /// "username":"value","password":"value"
@@ -28,82 +28,85 @@ void UpdateKey(const std::string& newKey) {
/// "pk":"private_key" /// "pk":"private_key"
std::string GetFail(const std::string& R) { std::string GetFail(const std::string& R) {
std::string DRet = R"({"success":false,"message":)"; std::string DRet = R"({"success":false,"message":)";
DRet += "\"" + R + "\"}"; DRet += "\"" + R + "\"}";
LOG(ERROR) << R; LOG(ERROR) << R;
return DRet; return DRet;
} }
std::string Launcher::Login(const std::string& fields) { std::string Launcher::Login(const std::string& fields) {
if (fields == "LO") { if (fields == "LO") {
LoginAuth = false; LoginAuth = false;
UpdateKey(""); UpdateKey("");
return ""; return "";
} }
LOG(INFO) << "Attempting to authenticate..."; LOG(INFO) << "Attempting to authenticate...";
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields); std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
Json d = Json::parse(Buffer, nullptr, false); Json d = Json::parse(Buffer, nullptr, false);
if (Buffer == "-1") { if (Buffer == "-1") {
return GetFail("Failed to communicate with the auth system!"); return GetFail("Failed to communicate with the auth system!");
} }
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>()) {
LoginAuth = true; LoginAuth = true;
if (!d["private_key"].is_null()) { if (!d["private_key"].is_null()) {
UpdateKey(d["private_key"].get<std::string>()); UpdateKey(d["private_key"].get<std::string>());
} }
if (!d["public_key"].is_null()) { if (!d["public_key"].is_null()) {
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");
d.erase("public_key"); d.erase("public_key");
return d.dump(); return d.dump();
} }
return GetFail("Invalid message parsing!"); return GetFail("Invalid message parsing!");
} }
void Launcher::CheckKey() { void Launcher::CheckKey() {
if (fs::exists("key") && fs::file_size("key") < 100) { if (fs::exists("key") && fs::file_size("key") < 100) {
std::ifstream Key("key"); std::ifstream Key("key");
if (Key.is_open()) { if (Key.is_open()) {
auto Size = fs::file_size("key"); auto Size = fs::file_size("key");
std::string Buffer(Size, 0); std::string Buffer(Size, 0);
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)
throw ShutdownException("Fatal Error"); << "Invalid answer from authentication servers, please try "
} "again later!";
if (d["success"].get<bool>()) { throw ShutdownException("Fatal Error");
LoginAuth = true; }
UpdateKey(d["private_key"].get<std::string>()); if (d["success"].get<bool>()) {
PublicKey = d["public_key"].get<std::string>(); LoginAuth = true;
UserRole = d["role"].get<std::string>(); UpdateKey(d["private_key"].get<std::string>());
LOG(INFO) << "Auto-Authentication was successful"; PublicKey = d["public_key"].get<std::string>();
} else { UserRole = d["role"].get<std::string>();
LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!"; LOG(INFO) << "Auto-Authentication was successful";
UpdateKey(""); } else {
} LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!";
} else {
LOG(WARNING) << "Could not open saved key!";
UpdateKey(""); UpdateKey("");
} }
} else } else {
UpdateKey(""); LOG(WARNING) << "Could not open saved key!";
UpdateKey("");
}
} else UpdateKey("");
} }
+253 -256
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,319 +12,318 @@
#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,
std::vector<std::string> Val; const std::string& delimiter) {
size_t pos; std::vector<std::string> Val;
std::string token, s = String; size_t pos;
while ((pos = s.find(delimiter)) != std::string::npos) { std::string token, s = String;
token = s.substr(0, pos); while ((pos = s.find(delimiter)) != std::string::npos) {
if (!token.empty()) token = s.substr(0, pos);
Val.push_back(token); if (!token.empty()) 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;
} }
void CheckForDir() { void CheckForDir() {
if (!fs::exists("Resources")) { if (!fs::exists("Resources")) {
_wmkdir(L"Resources"); _wmkdir(L"Resources");
} }
} }
void Server::WaitForConfirm() { void Server::WaitForConfirm() {
while (!Terminate && !ModLoaded) { while (!Terminate && !ModLoaded) {
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
} }
ModLoaded = false; ModLoaded = false;
} }
void Server::Abort() { void Server::Abort() {
Terminate = true; Terminate = true;
LOG(INFO) << "Terminated!"; LOG(INFO) << "Terminated!";
} }
std::string Server::Auth() { std::string Server::Auth() {
TCPSend("VC" + LauncherInstance->getVersion()); TCPSend("VC" + LauncherInstance->getVersion());
auto Res = TCPRcv(); auto Res = TCPRcv();
if (Res.empty() || Res[0] == 'E') { if (Res.empty() || Res[0] == 'E') {
Abort(); Abort();
return ""; return "";
} }
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') {
Abort(); Abort();
return ""; return "";
} }
Res = Res.substr(1); Res = Res.substr(1);
if (std::all_of(Res.begin(), Res.end(), isdigit)) { if (std::all_of(Res.begin(), Res.end(), isdigit)) {
ClientID = std::stoi(Res); ClientID = std::stoi(Res);
} else { } else {
Abort(); Abort();
UUl("Authentication failed!"); UUl("Authentication failed!");
return ""; return "";
} }
TCPSend("SR"); TCPSend("SR");
if (Terminate) if (Terminate) return "";
return "";
Res = TCPRcv(); Res = TCPRcv();
if (Res[0] == 'E') { if (Res[0] == 'E') {
Abort(); Abort();
return ""; return "";
} }
if (Res.empty() || Res == "-") { if (Res.empty() || Res == "-") {
LOG(INFO) << "Didn't Receive any mods..."; LOG(INFO) << "Didn't Receive any mods...";
ModList = "-"; ModList = "-";
TCPSend("Done"); TCPSend("Done");
LOG(INFO) << "Done!"; LOG(INFO) << "Done!";
return ""; return "";
} }
return Res; return Res;
} }
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,
do { const std::string& Name) {
double pr = double(Rcv) / double(Size) * 100; do {
std::string Per = std::to_string(trunc(pr * 10) / 10); double pr = double(Rcv) / double(Size) * 100;
UpdateUl(true, Name + " (" + Per.substr(0, Per.find('.') + 2) + "%)"); std::string Per = std::to_string(trunc(pr * 10) / 10);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); UpdateUl(true, Name + " (" + Per.substr(0, Per.find('.') + 2) + "%)");
} while (!Terminate && Rcv < Size); std::this_thread::sleep_for(std::chrono::milliseconds(100));
} while (!Terminate && Rcv < Size);
} }
char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) { char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) {
if (Sock == -1) { if (Sock == -1) {
Terminate = true; Terminate = true;
UUl("Invalid Socket"); UUl("Invalid Socket");
return nullptr; return nullptr;
} }
char* File = new char[Size]; char* File = new char[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"); KillSocket(Sock);
KillSocket(Sock); Terminate = true;
Terminate = true; delete[] File;
delete[] File; return nullptr;
return nullptr; }
} Rcv += Temp;
Rcv += Temp; GRcv += Temp;
GRcv += Temp; } while (Rcv < Size && !Terminate);
} while (Rcv < Size && !Terminate); return File;
return File;
} }
void Server::MultiKill(uint64_t Sock) { void Server::MultiKill(uint64_t Sock) {
KillSocket(TCPSocket); KillSocket(TCPSocket);
KillSocket(Sock); KillSocket(Sock);
Terminate = true; Terminate = true;
} }
uint64_t Server::InitDSock() { uint64_t Server::InitDSock() {
SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN ServerAddr; SOCKADDR_IN ServerAddr;
if (DSock < 1) { if (DSock < 1) {
KillSocket(DSock); KillSocket(DSock);
Terminate = true; Terminate = true;
return 0; return 0;
} }
ServerAddr.sin_family = AF_INET; ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port); ServerAddr.sin_port = htons(Port);
inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr); inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr);
if (connect(DSock, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)) != 0) { if (connect(DSock, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)) != 0) {
KillSocket(DSock); KillSocket(DSock);
Terminate = true; Terminate = true;
return 0; return 0;
} }
char Code[2] = { 'D', char(ClientID) }; char Code[2] = {'D', char(ClientID)};
if (send(DSock, Code, 2, 0) != 2) { if (send(DSock, Code, 2, 0) != 2) {
KillSocket(DSock); KillSocket(DSock);
Terminate = true; Terminate = true;
return 0; return 0;
} }
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::future<char*> f1 = task.get_future();
std::thread Dt(std::move(task));
Dt.detach();
std::packaged_task<char*()> task([&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); }); char* DData = TCPRcvRaw(DSock, GRcv, DSize);
std::future<char*> f1 = task.get_future();
std::thread Dt(std::move(task));
Dt.detach();
char* DData = TCPRcvRaw(DSock, GRcv, DSize); if (!DData) {
MultiKill(DSock);
return "";
}
if (!DData) { f1.wait();
MultiKill(DSock); char* MData = f1.get();
return "";
}
f1.wait(); if (!MData) {
char* MData = f1.get(); MultiKill(DSock);
return "";
}
if (!MData) { if (Au.joinable()) Au.join();
MultiKill(DSock);
return "";
}
if (Au.joinable()) /// omg yes very ugly my god but i was in a rush will revisit
Au.join(); std::string Ret(Size, 0);
memcpy_s(&Ret[0], MSize, MData, MSize);
delete[] MData;
/// omg yes very ugly my god but i was in a rush will revisit memcpy_s(&Ret[MSize], DSize, DData, DSize);
std::string Ret(Size, 0); delete[] DData;
memcpy_s(&Ret[0], MSize, MData, MSize);
delete[] MData;
memcpy_s(&Ret[MSize], DSize, DData, DSize); return Ret;
delete[] DData;
return Ret;
} }
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
Terminate = true; << "\" that is not a .zip file!";
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));
list.clear(); std::vector<std::string> FSizes(list.begin() + (list.size() / 2),
Ret.clear(); list.end());
list.clear();
Ret.clear();
int Amount = 0, Pos = 0; int Amount = 0, Pos = 0;
std::string a, t; std::string a, t;
for (const std::string& name : FNames) { for (const std::string& name : FNames) {
if (!name.empty()) { if (!name.empty()) {
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 t.clear();
ModList = t; for (auto FN = FNames.begin(), FS = FSizes.begin();
t.clear(); 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) continue;
if (pos == std::string::npos) Amount++;
}
if (!FNames.empty()) LOG(INFO) << "Syncing...";
SOCKET DSock = InitDSock();
for (auto FN = FNames.begin(), FS = FSizes.begin();
FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/');
if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos);
} else continue;
Pos++;
if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit)) continue;
if (fs::file_size(a) == std::stoull(*FS)) {
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));
try {
if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath());
}
fs::copy_file(a,
LauncherInstance->getMPUserPath() +
a.substr(a.find_last_of('/')),
fs::copy_options::overwrite_existing);
} catch (std::exception& e) {
LOG(ERROR) << "Failed copy to the mods folder! " << e.what();
Terminate = true;
continue;
}
WaitForConfirm();
continue; continue;
Amount++; } else remove(a.c_str());
} }
if (!FNames.empty()) CheckForDir();
LOG(INFO) << "Syncing..."; std::string FName = a.substr(a.find_last_of('/'));
SOCKET DSock = InitDSock(); do {
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { TCPSend("f" + *FN);
auto pos = FN->find_last_of('/');
if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos);
} else
continue;
Pos++;
if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit))
continue;
if (fs::file_size(a) == std::stoull(*FS)) {
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));
try {
if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath());
}
fs::copy_file(a, LauncherInstance->getMPUserPath() + a.substr(a.find_last_of('/')),
fs::copy_options::overwrite_existing);
} catch (std::exception& e) {
LOG(ERROR) << "Failed copy to the mods folder! " << e.what();
Terminate = true;
continue;
}
WaitForConfirm();
continue;
} else
remove(a.c_str());
}
CheckForDir();
std::string FName = a.substr(a.find_last_of('/'));
do {
TCPSend("f" + *FN);
std::string Data = TCPRcv(); std::string Data = TCPRcv();
if (Data == "CO" || Terminate) { if (Data == "CO" || Terminate) {
Terminate = true; Terminate = true;
UUl("Server cannot find " + FName); UUl("Server cannot find " + FName);
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()) {
LFS.write(&Data[0], std::streamsize(Data.size())); LFS.write(&Data[0], std::streamsize(Data.size()));
LFS.close(); LFS.close();
} }
} while (fs::file_size(a) != std::stoull(*FS) && !Terminate); } while (fs::file_size(a) != std::stoull(*FS) && !Terminate);
if (!Terminate) { if (!Terminate) {
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();
KillSocket(DSock); }
if (!Terminate) { KillSocket(DSock);
TCPSend("Done"); if (!Terminate) {
LOG(INFO) << "Done!"; TCPSend("Done");
} else { LOG(INFO) << "Done!";
UStatus = "start"; } else {
LOG(INFO) << "Connection Terminated!"; UStatus = "start";
} LOG(INFO) << "Connection Terminated!";
}
} }
+250 -269
View File
@@ -6,364 +6,345 @@
#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) { LOG(ERROR) << "WSAStartup failed with error: " << iRes;
LOG(ERROR) << "WSAStartup failed with error: " << iRes; }
} UDPSockAddress = std::make_unique<sockaddr_in>();
UDPSockAddress = std::make_unique<sockaddr_in>();
} }
Server::~Server() { Server::~Server() {
Close(); Close();
WSACleanup(); WSACleanup();
} }
void Server::TCPClientMain() { void Server::TCPClientMain() {
SOCKADDR_IN ServerAddr; SOCKADDR_IN ServerAddr;
TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPSocket == -1) { if (TCPSocket == -1) {
LOG(ERROR) << "Socket failed! Error code: " << GetSocketApiError(); LOG(ERROR) << "Socket failed! Error code: " << GetSocketApiError();
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,
if (status < 0) { sizeof(optval));
LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError(); if (status < 0) {
} LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError();
ServerAddr.sin_family = AF_INET; }
ServerAddr.sin_port = htons(Port); ServerAddr.sin_family = AF_INET;
inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr); ServerAddr.sin_port = htons(Port);
status = connect(TCPSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)); inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr);
if (status != 0) { status = connect(TCPSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr));
UStatus = "Connection Failed!"; if (status != 0) {
LOG(ERROR) << "Connect failed! Error code: " << GetSocketApiError(); UStatus = "Connection Failed!";
Terminate.store(true); LOG(ERROR) << "Connect failed! Error code: " << GetSocketApiError();
return; Terminate.store(true);
} return;
}
char Code = 'C'; char Code = 'C';
if (send(TCPSocket, &Code, 1, 0) != 1) { if (send(TCPSocket, &Code, 1, 0) != 1) {
Terminate.store(true); Terminate.store(true);
return; return;
} }
LOG(INFO) << "Connected!"; LOG(INFO) << "Connected!";
SyncResources(); SyncResources();
while (!Terminate.load()) { while (!Terminate.load()) {
ServerParser(TCPRcv()); ServerParser(TCPRcv());
} }
LauncherInstance->SendIPC("T", false); LauncherInstance->SendIPC("T", false);
KillSocket(TCPSocket); KillSocket(TCPSocket);
} }
void Server::StartUDP() { void Server::StartUDP() {
if (TCPConnection.joinable() && !UDPConnection.joinable()) { if (TCPConnection.joinable() && !UDPConnection.joinable()) {
LOG(INFO) << "Connecting UDP"; LOG(INFO) << "Connecting UDP";
UDPConnection = std::thread(&Server::UDPMain, this); UDPConnection = std::thread(&Server::UDPMain, this);
} }
} }
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,
int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)UDPSockAddress.get(), (sockaddr*)UDPSockAddress.get(), sizeof(sockaddr_in));
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();
} }
void Server::UDPParser(std::string Packet) { void Server::UDPParser(std::string Packet) {
if (Packet.substr(0, 4) == "ABG:") { if (Packet.substr(0, 4) == "ABG:") {
Packet = Zlib::DeComp(Packet.substr(4)); Packet = Zlib::DeComp(Packet.substr(4));
} }
ServerParser(Packet); ServerParser(Packet);
} }
void Server::UDPRcv() { void Server::UDPRcv() {
sockaddr_in FromServer {}; sockaddr_in FromServer{};
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));
} }
void Server::UDPClient() { void Server::UDPClient() {
UDPSockAddress->sin_family = AF_INET; UDPSockAddress->sin_family = AF_INET;
UDPSockAddress->sin_port = htons(Port); UDPSockAddress->sin_port = htons(Port);
inet_pton(AF_INET, IP.c_str(), &UDPSockAddress->sin_addr); inet_pton(AF_INET, IP.c_str(), &UDPSockAddress->sin_addr);
UDPSocket = socket(AF_INET, SOCK_DGRAM, 0); UDPSocket = socket(AF_INET, SOCK_DGRAM, 0);
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);
} }
void Server::UDPMain() { void Server::UDPMain() {
AutoPing = std::thread(&Server::PingLoop, this); AutoPing = std::thread(&Server::PingLoop, this);
UDPClient(); UDPClient();
Terminate = true; Terminate = true;
LOG(INFO) << "Connection terminated"; LOG(INFO) << "Connection terminated";
} }
void Server::Connect(const std::string& Data) { void Server::Connect(const std::string& Data) {
ModList.clear(); ModList.clear();
Terminate.store(false); Terminate.store(false);
IP = GetAddress(Data.substr(1, Data.find(':') - 1)); IP = GetAddress(Data.substr(1, Data.find(':') - 1));
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)"; ModList = "-";
else Terminate.store(true);
UStatus = "Connection Failed! (WSA failed to start)"; return;
ModList = "-"; }
Terminate.store(true); Port = std::stoi(port);
return; LauncherInstance->CheckKey();
} UStatus = "Loading...";
Port = std::stoi(port); Ping = -1;
LauncherInstance->CheckKey(); TCPConnection = std::thread(&Server::TCPClientMain, this);
UStatus = "Loading..."; LOG(INFO) << "Connecting to server";
Ping = -1;
TCPConnection = std::thread(&Server::TCPClientMain, this);
LOG(INFO) << "Connecting to server";
} }
void Server::SendLarge(std::string Data) { void Server::SendLarge(std::string Data) {
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;
} }
TCPSend(Data); TCPSend(Data);
} }
std::string Server::GetSocketApiError() { std::string Server::GetSocketApiError() {
// This will provide us with the error code and an error message, all in one. // This will provide us with the error code and an error message, all in one.
// The resulting format is "<CODE> - <MESSAGE>" // The resulting format is "<CODE> - <MESSAGE>"
int err; int err;
char msgbuf[256]; char msgbuf[256];
msgbuf[0] = '\0'; msgbuf[0] = '\0';
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);
} else { } else {
return std::to_string(WSAGetLastError()); return std::to_string(WSAGetLastError());
} }
} }
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) C = Data.at(0);
if (DLen > 3) bool Ack = C == 'O' || C == 'T';
C = Data.at(0); if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')
bool Ack = C == 'O' || C == 'T'; Rel = true;
if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C') if (Ack || Rel) {
Rel = true; if (Ack || DLen > 1000) SendLarge(Data);
if (Ack || Rel) { else TCPSend(Data);
if (Ack || DLen > 1000) } else UDPSend(Data);
SendLarge(Data);
else
TCPSend(Data);
} else
UDPSend(Data);
} }
void Server::PingLoop() { void Server::PingLoop() {
while (!Terminate) { while (!Terminate) {
ServerSend("p", false); ServerSend("p", false);
PingStart = std::chrono::high_resolution_clock::now(); PingStart = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
} }
void Server::Close() { void Server::Close() {
Terminate.store(true); Terminate.store(true);
KillSocket(TCPSocket); KillSocket(TCPSocket);
KillSocket(UDPSocket); KillSocket(UDPSocket);
Ping = -1; Ping = -1;
if (TCPConnection.joinable()) { if (TCPConnection.joinable()) {
TCPConnection.join(); TCPConnection.join();
} }
if (UDPConnection.joinable()) { if (UDPConnection.joinable()) {
UDPConnection.join(); UDPConnection.join();
} }
if (AutoPing.joinable()) { if (AutoPing.joinable()) {
AutoPing.join(); AutoPing.join();
} }
} }
const std::string& Server::getMap() { const std::string& Server::getMap() {
return MStatus; return MStatus;
} }
bool Server::Terminated() { bool Server::Terminated() {
return Terminate; return Terminate;
} }
const std::string& Server::getModList() { const std::string& Server::getModList() {
return ModList; return ModList;
} }
int Server::getPing() const { int Server::getPing() const {
return Ping; return Ping;
} }
const std::string& Server::getUIStatus() { const std::string& Server::getUIStatus() {
return UStatus; return UStatus;
} }
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) { LOG(ERROR) << "DNS lookup failed! on " << Data;
LOG(ERROR) << "DNS lookup failed! on " << Data; return "DNS";
return "DNS"; }
} std::string Ret = inet_ntoa(*((struct in_addr*)host->h_addr));
std::string Ret = inet_ntoa(*((struct in_addr*)host->h_addr)); return Ret;
return Ret;
} }
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);
} }
void Server::setModLoaded() { void Server::setModLoaded() {
ModLoaded.store(true); ModLoaded.store(true);
} }
void Server::UUl(const std::string& R) { void Server::UUl(const std::string& R) {
UStatus = "Disconnected: " + R; UStatus = "Disconnected: " + R;
} }
bool Server::CheckBytes(int32_t Bytes) { bool Server::CheckBytes(int32_t Bytes) {
if (Bytes == 0) { if (Bytes == 0) {
// debug("(TCP) Connection closing... CheckBytes(16)"); // debug("(TCP) Connection closing... CheckBytes(16)");
Terminate = true; Terminate = true;
return false; return false;
} else if (Bytes < 0) { } else if (Bytes < 0) {
// debug("(TCP CB) recv failed with error: " + GetSocketApiError(); // debug("(TCP CB) recv failed with error: " + GetSocketApiError();
KillSocket(TCPSocket); KillSocket(TCPSocket);
Terminate = true; Terminate = true;
return false; return false;
} }
return true; return true;
} }
void Server::TCPSend(const std::string& Data) { void Server::TCPSend(const std::string& Data) {
if (TCPSocket == -1) {
Terminate = true;
UUl("Invalid Socket");
return;
}
if (TCPSocket == -1) { int32_t Size, Sent, Temp;
Terminate = true; std::string Send(4, 0);
UUl("Invalid Socket"); Size = int32_t(Data.size());
return; memcpy(&Send[0], &Size, sizeof(Size));
} Send += Data;
// Do not use Size before this point for anything but the header
int32_t Size, Sent, Temp; Sent = 0;
std::string Send(4, 0); Size += 4;
Size = int32_t(Data.size()); do {
memcpy(&Send[0], &Size, sizeof(Size)); if (size_t(Sent) >= Send.size()) {
Send += Data; LOG(ERROR) << "string OOB in " << std::string(__func__);
// Do not use Size before this point for anything but the header UUl("TCP Send OOB");
Sent = 0; Terminate = true;
Size += 4; return;
do { }
if (size_t(Sent) >= Send.size()) { Temp = send(TCPSocket, &Send[Sent], Size - Sent, 0);
LOG(ERROR) << "string OOB in " << std::string(__func__); if (!CheckBytes(Temp)) {
UUl("TCP Send OOB"); UUl("Socket Closed Code 2");
Terminate = true; Terminate = true;
return; return;
} }
Temp = send(TCPSocket, &Send[Sent], Size - Sent, 0); Sent += Temp;
if (!CheckBytes(Temp)) { } while (Sent < Size);
UUl("Socket Closed Code 2");
Terminate = true;
return;
}
Sent += Temp;
} while (Sent < Size);
} }
std::string Server::TCPRcv() { std::string Server::TCPRcv() {
if (TCPSocket == -1) { if (TCPSocket == -1) {
Terminate = true; Terminate = true;
UUl("Invalid Socket"); UUl("Invalid Socket");
return ""; return "";
} }
int32_t Header, BytesRcv = 0, Temp; int32_t Header, BytesRcv = 0, Temp;
std::vector<char> Data(sizeof(Header)); std::vector<char> Data(sizeof(Header));
do { do {
Temp = recv(TCPSocket, &Data[BytesRcv], 4 - BytesRcv, 0); Temp = recv(TCPSocket, &Data[BytesRcv], 4 - BytesRcv, 0);
if (!CheckBytes(Temp)) { if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 3"); UUl("Socket Closed Code 3");
Terminate = true; Terminate = true;
return ""; return "";
} }
BytesRcv += Temp; BytesRcv += Temp;
} while (BytesRcv < 4); } while (BytesRcv < 4);
memcpy(&Header, &Data[0], sizeof(Header)); memcpy(&Header, &Data[0], sizeof(Header));
if (!CheckBytes(BytesRcv)) { if (!CheckBytes(BytesRcv)) {
UUl("Socket Closed Code 4"); UUl("Socket Closed Code 4");
Terminate = true; Terminate = true;
return ""; return "";
} }
Data.resize(Header); Data.resize(Header);
BytesRcv = 0; BytesRcv = 0;
do { do {
Temp = recv(TCPSocket, &Data[BytesRcv], Header - BytesRcv, 0); Temp = recv(TCPSocket, &Data[BytesRcv], Header - BytesRcv, 0);
if (!CheckBytes(Temp)) { if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 5"); UUl("Socket Closed Code 5");
Terminate = true; Terminate = true;
return ""; return "";
} }
BytesRcv += Temp; BytesRcv += Temp;
} while (BytesRcv < Header); } while (BytesRcv < Header);
std::string Ret(Data.data(), Header); std::string Ret(Data.data(), Header);
if (Ret.substr(0, 4) == "ABG:") { if (Ret.substr(0, 4) == "ABG:") {
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;
} }
+103 -108
View File
@@ -9,137 +9,132 @@
#include "Logger.h" #include "Logger.h"
VersionParser::VersionParser(const std::string& from_string) { VersionParser::VersionParser(const std::string& from_string) {
std::string token; std::string token;
std::istringstream tokenStream(from_string); std::istringstream tokenStream(from_string);
while (std::getline(tokenStream, token, '.')) { while (std::getline(tokenStream, token, '.')) {
data.emplace_back(std::stol(token)); data.emplace_back(std::stol(token));
split.emplace_back(token); split.emplace_back(token);
} }
} }
std::strong_ordering VersionParser::operator<=>(const VersionParser& rhs) const noexcept { std::strong_ordering VersionParser::operator<=>(
size_t const fields = std::min(data.size(), rhs.data.size()); const VersionParser& rhs) const noexcept {
for (size_t i = 0; i != fields; ++i) { size_t const fields = std::min(data.size(), rhs.data.size());
if (data[i] == rhs.data[i]) for (size_t i = 0; i != fields; ++i) {
continue; if (data[i] == rhs.data[i]) continue;
else if (data[i] < rhs.data[i]) else if (data[i] < rhs.data[i]) return std::strong_ordering::less;
return std::strong_ordering::less; else return std::strong_ordering::greater;
else }
return std::strong_ordering::greater; if (data.size() == rhs.data.size()) return std::strong_ordering::equal;
} else if (data.size() > rhs.data.size()) return std::strong_ordering::greater;
if (data.size() == rhs.data.size()) else return std::strong_ordering::less;
return std::strong_ordering::equal;
else if (data.size() > rhs.data.size())
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 {
return std::is_eq(*this <=> rhs); return std::is_eq(*this <=> rhs);
} }
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 =
bool fallback = false; HTTP::Get("https://beammp.com/builds/launcher?version=true");
if (HTTP.find_first_of("0123456789") == std::string::npos) { bool fallback = false;
HTTP = HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true"); if (HTTP.find_first_of("0123456789") == std::string::npos) {
fallback = true; HTTP =
if (HTTP.find_first_of("0123456789") == std::string::npos) { HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true");
LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!"; fallback = true;
throw ShutdownException("Fatal Error"); if (HTTP.find_first_of("0123456789") == std::string::npos) {
} LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!";
} throw ShutdownException("Fatal Error");
if (fallback) { }
link = "https://backup1.beammp.com/builds/launcher?download=true"; }
} else if (fallback) {
link = "https://beammp.com/builds/launcher?download=true"; link = "https://backup1.beammp.com/builds/launcher?download=true";
} else 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 == '.') { RemoteVer += c;
RemoteVer += c; }
} }
}
if (VersionParser(RemoteVer) > VersionParser(FullVersion)) { if (VersionParser(RemoteVer) > VersionParser(FullVersion)) {
system("cls"); system("cls");
LOG(INFO) << "Update found! Downloading..."; LOG(INFO) << "Update found! Downloading...";
if (std::rename(EP.c_str(), Back.c_str())) { if (std::rename(EP.c_str(), Back.c_str())) {
LOG(ERROR) << "Failed to create a backup!"; LOG(ERROR) << "Failed to create a backup!";
} }
if (!HTTP::Download(link, EP)) { if (!HTTP::Download(link, EP)) {
LOG(ERROR) << "Launcher Update failed! trying again..."; LOG(ERROR) << "Launcher Update failed! trying again...";
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(2));
if (!HTTP::Download(link, EP)) { if (!HTTP::Download(link, EP)) {
LOG(ERROR) << "Launcher Update failed!"; LOG(ERROR) << "Launcher Update failed!";
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
AdminRelaunch(); AdminRelaunch();
} }
} }
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() {
if (!fs::exists(MPUserPath)) { if (!fs::exists(MPUserPath)) {
fs::create_directories(MPUserPath); fs::create_directories(MPUserPath);
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)
std::this_thread::sleep_for(std::chrono::seconds(15)); << "mods/multiplayer will be cleared in 15 seconds, close to abort";
} std::this_thread::sleep_for(std::chrono::seconds(15));
fs::remove_all(MPUserPath); }
fs::create_directories(MPUserPath); fs::remove_all(MPUserPath);
fs::create_directories(MPUserPath);
} }
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) return;
if (Size < 2) std::ifstream db(File);
return; if (db.is_open()) {
std::ifstream db(File); std::string Data(Size, 0);
if (db.is_open()) { db.read(&Data[0], std::streamsize(Size));
std::string Data(Size, 0); db.close();
db.read(&Data[0], std::streamsize(Size)); Json d = Json::parse(Data, nullptr, false);
db.close(); if (Data.at(0) != '{' || d.is_discarded()) return;
Json d = Json::parse(Data, nullptr, false); if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) {
if (Data.at(0) != '{' || d.is_discarded()) d["mods"]["multiplayerbeammp"]["active"] = true;
return; std::ofstream ofs(File);
if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) { if (ofs.is_open()) {
d["mods"]["multiplayerbeammp"]["active"] = true; ofs << std::setw(4) << d;
std::ofstream ofs(File); ofs.close();
if (ofs.is_open()) { } else {
ofs << std::setw(4) << d; LOG(ERROR) << "Failed to write " << File;
ofs.close(); }
} else { }
LOG(ERROR) << "Failed to write " << File; }
}
}
}
} }
void Launcher::SetupMOD() { 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=" +
MPUserPath + "\\BeamMP.zip"); PublicKey + "&branch=" + TargetBuild,
MPUserPath + "\\BeamMP.zip");
} }
+47 -50
View File
@@ -4,86 +4,83 @@
/// ///
#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 {
public: public:
virtual bool OnInit(); virtual bool OnInit();
}; };
class MyFrame : public wxFrame { class MyFrame : public wxFrame {
public: public:
MyFrame(); MyFrame();
private: private:
void OnHello(wxCommandEvent& event); void OnHello(wxCommandEvent& event);
void OnExit(wxCommandEvent& event); void OnExit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event); void OnAbout(wxCommandEvent& event);
static wxSize FixedSize; static wxSize FixedSize;
};
enum {
ID_Hello = 1
}; };
enum { ID_Hello = 1 };
wxSize MyFrame::FixedSize(370, 400); wxSize MyFrame::FixedSize(370, 400);
bool MyApp::OnInit() { bool MyApp::OnInit() {
auto* frame = new MyFrame(); auto* frame = new MyFrame();
frame->Show(true); frame->Show(true);
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();
// 27 35 35 // 27 35 35
wxColour Colour(27, 35, 35, 1); wxColour Colour(27, 35, 35, 1);
SetBackgroundColour(Colour); SetBackgroundColour(Colour);
auto* menuFile = new wxMenu; auto* menuFile = new wxMenu;
menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", menuFile->Append(ID_Hello, "&Hello...\tCtrl-H",
"Help string shown in status bar for this menu item"); "Help string shown in status bar for this menu item");
menuFile->AppendSeparator(); menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT); menuFile->Append(wxID_EXIT);
auto* menuHelp = new wxMenu; auto* menuHelp = new wxMenu;
menuHelp->Append(wxID_ABOUT); menuHelp->Append(wxID_ABOUT);
auto* menuBar = new wxMenuBar; auto* menuBar = new wxMenuBar;
menuBar->SetOwnBackgroundColour(Colour); menuBar->SetOwnBackgroundColour(Colour);
menuBar->Append(menuFile, "&File"); menuBar->Append(menuFile, "&File");
menuBar->Append(menuHelp, "&Help"); menuBar->Append(menuHelp, "&Help");
// SetMenuBar(menuBar); // SetMenuBar(menuBar);
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);
Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT); Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
} }
void MyFrame::OnExit(wxCommandEvent& event) { 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!");
} }
int GUIEntry(int argc, char* argv[]) { int GUIEntry(int argc, char* argv[]) {
new MyApp(); new MyApp();
return wxEntry(argc, argv); return wxEntry(argc, argv);
} }
+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};
};
+2 -2
View File
@@ -6,6 +6,6 @@
#pragma once #pragma once
class gif { class gif {
public: public:
static const unsigned char Logo[30427]; static const unsigned char Logo[30427];
}; };
+19 -19
View File
@@ -7,23 +7,23 @@
#include "Logger.h" #include "Logger.h"
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
try { try {
Launcher launcher(argc, argv); Launcher launcher(argc, argv);
launcher.RunDiscordRPC(); launcher.RunDiscordRPC();
launcher.LoadConfig(); // check if json (issue) launcher.LoadConfig(); // check if json (issue)
launcher.CheckKey(); launcher.CheckKey();
launcher.QueryRegistry(); launcher.QueryRegistry();
// UI call // UI call
// launcher.SetupMOD(); // launcher.SetupMOD();
launcher.LaunchGame(); launcher.LaunchGame();
launcher.WaitForGame(); launcher.WaitForGame();
LOG(INFO) << "Launcher shutting down"; LOG(INFO) << "Launcher shutting down";
} catch (const ShutdownException& e) { } catch (const ShutdownException& e) {
LOG(INFO) << "Launcher shutting down with reason: " << e.what(); LOG(INFO) << "Launcher shutting down with reason: " << e.what();
} catch (const std::exception& e) { } catch (const std::exception& e) {
LOG(FATAL) << e.what(); LOG(FATAL) << e.what();
} }
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(2));
Launcher::setExit(true); Launcher::setExit(true);
return 0; return 0;
} }