diff --git a/include/HttpAPI.h b/include/HttpAPI.h index 7be6ce3..39f88f9 100644 --- a/include/HttpAPI.h +++ b/include/HttpAPI.h @@ -8,10 +8,11 @@ class HTTP { 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 Get(const std::string &IP); + static std::string Get(const std::string& IP); static bool ProgressBar(size_t c, size_t t); + public: static bool isDownload; }; \ No newline at end of file diff --git a/include/Json.h b/include/Json.h index b341884..1bcfdbf 100644 --- a/include/Json.h +++ b/include/Json.h @@ -6,4 +6,3 @@ #pragma once #include using Json = nlohmann::json; - diff --git a/include/Launcher.h b/include/Launcher.h index b0d4fb1..6615411 100644 --- a/include/Launcher.h +++ b/include/Launcher.h @@ -5,11 +5,10 @@ #pragma once #include "Memory/IPC.h" -#include #include "Server.h" +#include #include - namespace fs = std::filesystem; struct VersionParser { @@ -21,10 +20,11 @@ struct VersionParser { }; class Launcher { -public: //constructors +public: // constructors Launcher(int argc, char* argv[]); ~Launcher(); -public: //available functions + +public: // available functions static void StaticAbort(Launcher* Instance = nullptr); std::string Login(const std::string& fields); void SendIPC(const std::string& Data, bool core = true); @@ -35,7 +35,8 @@ public: //available functions void LaunchGame(); void CheckKey(); void SetupMOD(); -public: //Getters and Setters + +public: // Getters and Setters void setDiscordMessage(const std::string& message); static void setExit(bool exit) noexcept; const std::string& getFullVersion(); @@ -46,7 +47,7 @@ public: //Getters and Setters const std::string& getVersion(); static bool getExit() noexcept; -private: //functions +private: // functions void HandleIPC(const std::string& Data); std::string GetLocalAppdata(); void UpdatePresence(); @@ -59,32 +60,34 @@ private: //functions void Relaunch(); void ListenIPC(); void Abort(); -private: //variables - uint32_t GamePID{0}; + +private: // variables + uint32_t GamePID { 0 }; bool EnableUI = true; - int64_t DiscordTime{}; + int64_t DiscordTime {}; bool LoginAuth = false; - fs::path CurrentPath{}; - std::string BeamRoot{}; - std::string UserRole{}; - std::string PublicKey{}; - std::thread IPCSystem{}; - std::thread DiscordRPC{}; - std::string MPUserPath{}; - std::string BeamVersion{}; - std::string BeamUserPath{}; - std::string DiscordMessage{}; - std::string Version{"2.0"}; - Server ServerHandler{this}; - std::string TargetBuild{"default"}; - static inline std::atomic Shutdown{false}, Exit{false}; - std::string FullVersion{Version + ".99"}; - VersionParser SupportedVersion{"0.25.4.0"}; - std::unique_ptr IPCToGame{}; - std::unique_ptr IPCFromGame{}; + fs::path CurrentPath {}; + std::string BeamRoot {}; + std::string UserRole {}; + std::string PublicKey {}; + std::thread IPCSystem {}; + std::thread DiscordRPC {}; + std::string MPUserPath {}; + std::string BeamVersion {}; + std::string BeamUserPath {}; + std::string DiscordMessage {}; + std::string Version { "2.0" }; + Server ServerHandler { this }; + std::string TargetBuild { "default" }; + static inline std::atomic Shutdown { false }, Exit { false }; + std::string FullVersion { Version + ".99" }; + VersionParser SupportedVersion { "0.25.4.0" }; + std::unique_ptr IPCToGame {}; + std::unique_ptr IPCFromGame {}; }; class ShutdownException : public std::runtime_error { public: - explicit ShutdownException(const std::string& message): runtime_error(message){}; + explicit ShutdownException(const std::string& message) + : runtime_error(message) {}; }; diff --git a/include/Server.h b/include/Server.h index 627cba8..6ff2138 100644 --- a/include/Server.h +++ b/include/Server.h @@ -4,10 +4,10 @@ /// #pragma once -#include #include -#include #include +#include +#include struct sockaddr_in; class Launcher; @@ -16,6 +16,7 @@ public: Server() = delete; explicit Server(Launcher* Instance); ~Server(); + public: void ServerSend(std::string Data, bool Rel); void Connect(const std::string& Data); @@ -27,11 +28,12 @@ public: bool Terminated(); int getPing() const; void Close(); + private: std::chrono::time_point PingStart, PingEnd; std::string MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name); - void AsyncUpdate(uint64_t& Rcv,uint64_t Size,const std::string& Name); - std::atomic Terminate{false}, ModLoaded{false}; + void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name); + std::atomic Terminate { false }, ModLoaded { false }; char* TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size); std::string GetAddress(const std::string& Data); void InvalidResource(const std::string& File); @@ -54,21 +56,21 @@ private: uint64_t TCPSocket = -1; uint64_t UDPSocket = -1; void WaitForConfirm(); - std::string UStatus{}; - std::string MStatus{}; - std::string ModList{}; + std::string UStatus {}; + std::string MStatus {}; + std::string ModList {}; void TCPClientMain(); void SyncResources(); std::string TCPRcv(); uint64_t InitDSock(); std::string Auth(); - std::string IP{}; + std::string IP {}; void UDPClient(); void PingLoop(); - int ClientID{0}; + int ClientID { 0 }; void UDPMain(); void UDPRcv(); void Abort(); - int Port{0}; - int Ping{0}; + int Port { 0 }; + int Ping { 0 }; }; diff --git a/include/atomic_queue.h b/include/atomic_queue.h index e1f4b25..48dde8b 100644 --- a/include/atomic_queue.h +++ b/include/atomic_queue.h @@ -1,17 +1,19 @@ -// -// Created by Anonymous275 on 24/07/22. -// +/// +/// Created by Anonymous275 on 7/26/22 +/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. +/// #pragma once -#include #include +#include template class atomic_queue { public: bool try_pop(T& val) { lock_guard guard(semaphore); - if(queue.empty())return false; + if (queue.empty()) + return false; val = queue.front(); queue.pop(); full.release(); @@ -33,24 +35,27 @@ public: lock_guard guard(semaphore); return queue.empty(); } + private: void check_full() { - if(size() >= Size) { + if (size() >= Size) { full.acquire(); } } + private: struct lock_guard { - explicit lock_guard(std::binary_semaphore& lock) : lock(lock){ + explicit lock_guard(std::binary_semaphore& lock) + : lock(lock) { lock.acquire(); } ~lock_guard() { lock.release(); } + private: std::binary_semaphore& lock; }; - std::binary_semaphore semaphore{1}, full{0}; - std::queue queue{}; + std::binary_semaphore semaphore { 1 }, full { 0 }; + std::queue queue {}; }; - diff --git a/src/Config.cpp b/src/Config.cpp index b3e4c14..a6ed58e 100644 --- a/src/Config.cpp +++ b/src/Config.cpp @@ -3,35 +3,37 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// - -#include #include "Launcher.h" #include "Logger.h" +#include void Launcher::LoadConfig() { - if(fs::exists("Launcher.toml")) { + if (fs::exists("Launcher.toml")) { toml::parse_result config = toml::parse_file("Launcher.toml"); auto ui = config["UI"]; auto build = config["Build"]; - if(ui.is_boolean()) { + if (ui.is_boolean()) { EnableUI = ui.as_boolean()->get(); - } else LOG(ERROR) << "Failed to get 'UI' boolean from config"; + } else + LOG(ERROR) << "Failed to get 'UI' boolean from config"; - //Default -1 / Release 1 / EA 2 / Dev 3 / Custom 3 - if(build.is_string()) { + // Default -1 / Release 1 / EA 2 / Dev 3 / Custom 3 + if (build.is_string()) { TargetBuild = build.as_string()->get(); - for(char& c : TargetBuild)c = char(tolower(c)); - } else LOG(ERROR) << "Failed to get 'Build' string from config"; + for (char& c : TargetBuild) + c = char(tolower(c)); + } else + LOG(ERROR) << "Failed to get 'Build' string from config"; } else { std::ofstream tml("Launcher.toml"); - if(tml.is_open()){ + if (tml.is_open()) { tml << R"(UI = true Build = "Default" )"; tml.close(); - }else{ + } else { LOG(FATAL) << "Failed to write config on disk!"; throw ShutdownException("Fatal Error"); } diff --git a/src/Discord.cpp b/src/Discord.cpp index 627cf81..f72c10a 100644 --- a/src/Discord.cpp +++ b/src/Discord.cpp @@ -3,14 +3,13 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// #ifndef DEBUG -#include #include "Launcher.h" #include "Logger.h" #include +#include - -void handleReady(const DiscordUser* u) {} -void handleDisconnected(int errcode, const char* message) {} +void handleReady(const DiscordUser* u) { } +void handleDisconnected(int errcode, const char* message) { } void handleError(int errcode, const char* message) { LOG(ERROR) << "Discord error: " << message; } @@ -40,7 +39,7 @@ void Launcher::RichPresence() { handlers.disconnected = handleDisconnected; Discord_Initialize("629743237988352010", &handlers, 1, nullptr); UpdatePresence(); - while(!Shutdown.load()) { + while (!Shutdown.load()) { Discord_RunCallbacks(); std::this_thread::sleep_for(std::chrono::seconds(1)); } diff --git a/src/Handler.cpp b/src/Handler.cpp index b82366d..d712eb3 100644 --- a/src/Handler.cpp +++ b/src/Handler.cpp @@ -3,88 +3,95 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// - -#include "Memory/Memory.h" -#include "Memory/BeamNG.h" -#include "Launcher.h" #include "HttpAPI.h" +#include "Launcher.h" #include "Logger.h" - +#include "Memory/BeamNG.h" +#include "Memory/Memory.h" void Launcher::HandleIPC(const std::string& Data) { char Code = Data.at(0), SubCode = 0; - if(Data.length() > 1)SubCode = Data.at(1); + if (Data.length() > 1) + SubCode = Data.at(1); switch (Code) { - case 'A': - ServerHandler.StartUDP(); - break; - case 'B': + case 'A': + ServerHandler.StartUDP(); + break; + case 'B': + ServerHandler.Close(); + SendIPC(Code + HTTP::Post("https://backend.beammp.com/servers", "")); + LOG(INFO) << "Sent Server List"; + break; + case 'C': + ServerHandler.Close(); + ServerHandler.Connect(Data); + while (ServerHandler.getModList().empty() && !ServerHandler.Terminated()) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + if (ServerHandler.getModList() == "-") + SendIPC("L"); + else + SendIPC("L" + ServerHandler.getModList()); + break; + case 'U': + SendIPC("Ul" + ServerHandler.getUIStatus()); + if (ServerHandler.getPing() > 800) { + SendIPC("Up-2"); + } else + SendIPC("Up" + std::to_string(ServerHandler.getPing())); + break; + case 'M': + SendIPC(ServerHandler.getMap()); + break; + case 'Q': + if (SubCode == 'S') { ServerHandler.Close(); - SendIPC(Code + HTTP::Post("https://backend.beammp.com/servers","")); - LOG(INFO) << "Sent Server List"; - break; - case 'C': - ServerHandler.Close(); - ServerHandler.Connect(Data); - while(ServerHandler.getModList().empty() && !ServerHandler.Terminated()){ - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - if(ServerHandler.getModList() == "-")SendIPC("L"); - else SendIPC("L"+ServerHandler.getModList()); - break; - case 'U': - SendIPC("Ul" + ServerHandler.getUIStatus()); - if(ServerHandler.getPing() > 800) { - SendIPC("Up-2"); - }else SendIPC("Up" + std::to_string(ServerHandler.getPing())); - break; - case 'M': - SendIPC(ServerHandler.getMap()); - break; - case 'Q': - if(SubCode == 'S') { - ServerHandler.Close(); - } - if(SubCode == 'G')exit(2); - break; - case 'R': //will send mod name - ServerHandler.setModLoaded(); - break; - case 'Z': - SendIPC("Z" + Version); - break; - case 'N': - if(SubCode == 'c') { - SendIPC("N{\"Auth\":"+std::to_string(LoginAuth)+"}"); - } else { - SendIPC("N" + Login(Data.substr(Data.find(':') + 1))); - } - break; - default: - break; + } + if (SubCode == 'G') + exit(2); + break; + case 'R': // will send mod name + ServerHandler.setModLoaded(); + break; + case 'Z': + SendIPC("Z" + Version); + break; + case 'N': + if (SubCode == 'c') { + SendIPC("N{\"Auth\":" + std::to_string(LoginAuth) + "}"); + } else { + SendIPC("N" + Login(Data.substr(Data.find(':') + 1))); + } + break; + default: + break; } } void Server::ServerParser(const std::string& Data) { - if(Data.empty())return; - char Code = Data.at(0),SubCode = 0; - if(Data.length() > 1)SubCode = Data.at(1); + if (Data.empty()) + return; + char Code = Data.at(0), SubCode = 0; + if (Data.length() > 1) + SubCode = Data.at(1); switch (Code) { - case 'p': - PingEnd = std::chrono::high_resolution_clock::now(); - if(PingStart > PingEnd)Ping = 0; - else Ping = int(std::chrono::duration_cast(PingEnd-PingStart).count()); - return; - case 'M': - MStatus = Data; - UStatus = "done"; - return; - case 'K': - Terminate = true; - UStatus = Data.substr(1); - return; - default: - break; + case 'p': + PingEnd = std::chrono::high_resolution_clock::now(); + if (PingStart > PingEnd) + Ping = 0; + else + Ping = int(std::chrono::duration_cast(PingEnd - PingStart).count()); + return; + case 'M': + MStatus = Data; + UStatus = "done"; + return; + case 'K': + Terminate = true; + UStatus = Data.substr(1); + return; + default: + break; } LauncherInstance->SendIPC(Data, false); } diff --git a/src/Launcher.cpp b/src/Launcher.cpp index a23bb24..8667c9f 100644 --- a/src/Launcher.cpp +++ b/src/Launcher.cpp @@ -4,23 +4,25 @@ /// #define WIN32_LEAN_AND_MEAN -#include "Memory/Memory.h" #include "Launcher.h" -#include "Logger.h" -#include #include "HttpAPI.h" -#include -#include +#include "Logger.h" +#include "Memory/Memory.h" #include #include +#include #include +#include +#include LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) { LOG(ERROR) << "CAUGHT EXCEPTION! Code 0x" << std::hex << std::uppercase << p->ExceptionRecord->ExceptionCode; return EXCEPTION_EXECUTE_HANDLER; } -Launcher::Launcher(int argc, char* argv[]) : CurrentPath(std::filesystem::path(argv[0])), DiscordMessage("Just launched") { +Launcher::Launcher(int argc, char* argv[]) + : CurrentPath(std::filesystem::path(argv[0])) + , DiscordMessage("Just launched") { Launcher::StaticAbort(this); DiscordTime = std::time(nullptr); Log::Init(); @@ -33,16 +35,16 @@ Launcher::Launcher(int argc, char* argv[]) : CurrentPath(std::filesystem::path(a void Launcher::Abort() { Shutdown.store(true); ServerHandler.Close(); - if(DiscordRPC.joinable()) { + if (DiscordRPC.joinable()) { DiscordRPC.join(); } - if(IPCSystem.joinable()) { + if (IPCSystem.joinable()) { IPCSystem.join(); } - if(!MPUserPath.empty()) { + if (!MPUserPath.empty()) { ResetMods(); } - if(GamePID != 0) { + if (GamePID != 0) { auto Handle = OpenProcess(PROCESS_TERMINATE, false, DWORD(GamePID)); TerminateProcess(Handle, 0); CloseHandle(Handle); @@ -50,25 +52,25 @@ void Launcher::Abort() { } Launcher::~Launcher() { - if(!Shutdown.load()) { + if (!Shutdown.load()) { Abort(); } } void ShutdownHandler(int sig) { Launcher::StaticAbort(); - while(HTTP::isDownload) { + while (HTTP::isDownload) { std::this_thread::sleep_for(std::chrono::seconds(1)); } LOG(INFO) << "Got termination signal (" << sig << ")"; - while(!Launcher::getExit()) { + while (!Launcher::getExit()) { std::this_thread::sleep_for(std::chrono::seconds(1)); } } void Launcher::StaticAbort(Launcher* Instance) { static Launcher* Address; - if(Instance) { + if (Instance) { Address = Instance; return; } @@ -86,21 +88,21 @@ void Launcher::WindowsInit() { void Launcher::LaunchGame() { 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!"; throw ShutdownException("Fatal Error"); - } else if(GameVersion.data[1] < SupportedVersion.data[1]) { + } else if (GameVersion.data[1] < SupportedVersion.data[1]) { LOG(FATAL) << "BeamNG V" << BeamVersion << " not supported, please update and launch the new update!"; throw ShutdownException("Fatal Error"); - } else if(GameVersion > SupportedVersion) { + } else if (GameVersion > SupportedVersion) { LOG(WARNING) << "BeamNG V" << BeamVersion << " is slightly newer than recommended, this might cause issues!"; - } else if(GameVersion < SupportedVersion) { + } else if (GameVersion < SupportedVersion) { LOG(WARNING) << "BeamNG V" << BeamVersion << " is slightly older than recommended, this might cause issues!"; } - if(Memory::GetBeamNGPID({}) == 0) { + if (Memory::GetBeamNGPID({}) == 0) { LOG(INFO) << "Launching BeamNG from steam"; ShellExecuteA(nullptr, nullptr, "steam://rungameid/284160", nullptr, nullptr, SW_SHOWNORMAL); - //ShowWindow(GetConsoleWindow(), HIDE_WINDOW); + // ShowWindow(GetConsoleWindow(), HIDE_WINDOW); } LOG(INFO) << "Waiting for a game process, please start BeamNG manually in case of steam issues"; } @@ -109,16 +111,17 @@ void Launcher::WaitForGame() { std::set BlackList; do { auto PID = Memory::GetBeamNGPID(BlackList); - if(PID != 0 && IPC::mem_used(PID)) { + if (PID != 0 && IPC::mem_used(PID)) { BlackList.emplace(PID); } else { GamePID = PID; } std::this_thread::sleep_for(std::chrono::seconds(1)); - } while(GamePID == 0 && !Shutdown.load()); - if(Shutdown.load())return; + } while (GamePID == 0 && !Shutdown.load()); + if (Shutdown.load()) + return; - if(GamePID == 0) { + if (GamePID == 0) { LOG(FATAL) << "Game process not found! aborting"; throw ShutdownException("Fatal Error"); } @@ -126,12 +129,12 @@ void Launcher::WaitForGame() { LOG(INFO) << "Game found! PID " << GamePID; IPCToGame = std::make_unique(GamePID, 0x1900000); - IPCFromGame = std::make_unique(GamePID+1, 0x1900000); + IPCFromGame = std::make_unique(GamePID + 1, 0x1900000); IPCSystem = std::thread(&Launcher::ListenIPC, this); Memory::Inject(GamePID); 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)); } LOG(INFO) << "Game process was lost"; @@ -139,11 +142,11 @@ void Launcher::WaitForGame() { } void Launcher::ListenIPC() { - while(!Shutdown.load()) { + while (!Shutdown.load()) { IPCFromGame->receive(); - if(!IPCFromGame->receive_timed_out()) { + if (!IPCFromGame->receive_timed_out()) { auto& MSG = IPCFromGame->msg(); - if(MSG[0] == 'C') { + if (MSG[0] == 'C') { HandleIPC(IPCFromGame->msg().substr(1)); } else { ServerHandler.ServerSend(IPCFromGame->msg().substr(1), false); @@ -153,12 +156,14 @@ void Launcher::ListenIPC() { } } -void Launcher::SendIPC(const std::string& Data, bool core) { +void Launcher::SendIPC(const std::string& Data, bool core) { static std::mutex Lock; std::scoped_lock Guard(Lock); - if(core)IPCToGame->send("C" + Data); - else IPCToGame->send("G" + Data); - if(IPCToGame->send_timed_out()) { + if (core) + IPCToGame->send("C" + Data); + else + IPCToGame->send("G" + Data); + if (IPCToGame->send_timed_out()) { LOG(WARNING) << "Timed out while sending \"" << Data << "\""; } } @@ -166,8 +171,8 @@ void Launcher::SendIPC(const std::string& Data, bool core) { std::string QueryValue(HKEY& hKey, const char* Name) { DWORD keySize; BYTE buffer[16384]; - if(RegQueryValueExA(hKey, Name, nullptr, nullptr, buffer, &keySize) == ERROR_SUCCESS) { - return {(char*)buffer, keySize-1}; + if (RegQueryValueExA(hKey, Name, nullptr, nullptr, buffer, &keySize) == ERROR_SUCCESS) { + return { (char*)buffer, keySize - 1 }; } return {}; } @@ -185,7 +190,7 @@ std::string Launcher::GetLocalAppdata() { std::string Path((char*)bstrPath); CoTaskMemFree(folderPath); - if(!Path.empty()) { + if (!Path.empty()) { Path += "\\BeamNG.drive\\"; VersionParser GameVer(BeamVersion); Path += GameVer.split[0] + '.' + GameVer.split[1] + '\\'; @@ -196,21 +201,22 @@ std::string Launcher::GetLocalAppdata() { void Launcher::QueryRegistry() { HKEY BeamNG; LONG RegRes = RegOpenKeyExA(HKEY_CURRENT_USER, R"(Software\BeamNG\BeamNG.drive)", 0, KEY_READ, &BeamNG); - if(RegRes == ERROR_SUCCESS) { + if (RegRes == ERROR_SUCCESS) { BeamRoot = QueryValue(BeamNG, "rootpath"); BeamVersion = QueryValue(BeamNG, "version"); BeamUserPath = QueryValue(BeamNG, "userpath_override"); RegCloseKey(BeamNG); - if(BeamUserPath.empty() && !BeamVersion.empty()) { + if (BeamUserPath.empty() && !BeamVersion.empty()) { BeamUserPath = GetLocalAppdata(); - } else if(!BeamUserPath.empty() && !BeamVersion.empty()) { + } else if (!BeamUserPath.empty() && !BeamVersion.empty()) { VersionParser GameVer(BeamVersion); BeamUserPath += GameVer.split[0] + '.' + GameVer.split[1] + '\\'; } - if(!BeamUserPath.empty()) { + if (!BeamUserPath.empty()) { MPUserPath = BeamUserPath + "mods\\multiplayer"; } - if(!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty())return; + if (!BeamRoot.empty() && !BeamVersion.empty() && !BeamUserPath.empty()) + return; } LOG(FATAL) << "Please launch the game at least once, failed to read registry key Software\\BeamNG\\BeamNG.drive"; throw ShutdownException("Fatal Error"); @@ -219,13 +225,13 @@ void Launcher::QueryRegistry() { void Launcher::AdminRelaunch() { system("cls"); ShellExecuteA(nullptr, "runas", CurrentPath.string().c_str(), nullptr, nullptr, SW_SHOWNORMAL); - ShowWindow(GetConsoleWindow(),0); + ShowWindow(GetConsoleWindow(), 0); throw ShutdownException("Relaunching"); } void Launcher::Relaunch() { ShellExecuteA(nullptr, "open", CurrentPath.string().c_str(), nullptr, nullptr, SW_SHOWNORMAL); - ShowWindow(GetConsoleWindow(),0); + ShowWindow(GetConsoleWindow(), 0); std::this_thread::sleep_for(std::chrono::seconds(1)); throw ShutdownException("Relaunching"); } @@ -258,6 +264,6 @@ const std::string& Launcher::getMPUserPath() { return MPUserPath; } -const std::string &Launcher::getPublicKey() { +const std::string& Launcher::getPublicKey() { return PublicKey; } diff --git a/src/Logger.cpp b/src/Logger.cpp index 913665f..a7c246b 100644 --- a/src/Logger.cpp +++ b/src/Logger.cpp @@ -12,10 +12,10 @@ void Log::Init() { std::string DFormat("%datetime{[%d/%M/%y %H:%m:%s]} %fbase:%line [%level] %msg"); Conf.setGlobally(ConfigurationType::Format, "%datetime{[%d/%M/%y %H:%m:%s]} [%level] %msg"); Conf.setGlobally(ConfigurationType::LogFlushThreshold, "2"); - Conf.set(Level::Verbose,ConfigurationType::Format, DFormat); - Conf.set(Level::Debug,ConfigurationType::Format, DFormat); - Conf.set(Level::Trace,ConfigurationType::Format, DFormat); - Conf.set(Level::Fatal,ConfigurationType::Format, DFormat); + Conf.set(Level::Verbose, ConfigurationType::Format, DFormat); + Conf.set(Level::Debug, ConfigurationType::Format, DFormat); + Conf.set(Level::Trace, ConfigurationType::Format, DFormat); + Conf.set(Level::Fatal, ConfigurationType::Format, DFormat); Conf.setGlobally(ConfigurationType::Filename, "Launcher.log"); Conf.setGlobally(ConfigurationType::MaxLogFileSize, "7340032"); Loggers::reconfigureAllLoggers(Conf); diff --git a/src/Memory/BeamNG.cpp b/src/Memory/BeamNG.cpp index 636d49f..59525f1 100644 --- a/src/Memory/BeamNG.cpp +++ b/src/Memory/BeamNG.cpp @@ -3,10 +3,9 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// - -#include "atomic_queue.h" #include "Memory/BeamNG.h" #include "Memory/Memory.h" +#include "atomic_queue.h" std::unique_ptr> Queue; @@ -21,7 +20,8 @@ void BeamNG::EntryPoint() { Queue = std::make_unique>(); uint32_t PID = Memory::GetPID(); auto status = MH_Initialize(); - if(status != MH_OK)Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); + if (status != MH_OK) + Memory::Print(std::string("MH Error -> ") + MH_StatusToString(status)); Memory::Print("PID : " + std::to_string(PID)); GELua::FindAddresses(); /*GameBaseAddr = Memory::GetModuleBase(GameModule); @@ -29,15 +29,15 @@ void BeamNG::EntryPoint() { OpenJITDetour = std::make_unique>(GELua::lua_open_jit, lua_open_jit_D); OpenJITDetour->Enable(); IPCFromLauncher = std::make_unique(PID, 0x1900000); - IPCToLauncher = std::make_unique(PID+1, 0x1900000); + IPCToLauncher = std::make_unique(PID + 1, 0x1900000); IPCListener(); } int Core(lua_State* L) { - if(lua_gettop(L) == 1) { + if (lua_gettop(L) == 1) { size_t Size; const char* Data = GELua::lua_tolstring(L, 1, &Size); - //Memory::Print("Core -> " + std::string(Data) + " - " + std::to_string(Size)); + // Memory::Print("Core -> " + std::string(Data) + " - " + std::to_string(Size)); std::string msg(Data, Size); BeamNG::SendIPC("C" + msg); } @@ -45,10 +45,10 @@ int Core(lua_State* L) { } int Game(lua_State* L) { - if(lua_gettop(L) == 1) { + if (lua_gettop(L) == 1) { size_t Size; const char* Data = GELua::lua_tolstring(L, 1, &Size); - //Memory::Print("Game -> " + std::string(Data) + " - " + std::to_string(Size)); + // Memory::Print("Game -> " + std::string(Data) + " - " + std::to_string(Size)); std::string msg(Data, Size); BeamNG::SendIPC("G" + msg); } @@ -80,13 +80,14 @@ void BeamNG::SendIPC(const std::string& Data) { void BeamNG::IPCListener() { int TimeOuts = 0; - while(TimeOuts < 20) { + while (TimeOuts < 20) { IPCFromLauncher->receive(); if (!IPCFromLauncher->receive_timed_out()) { TimeOuts = 0; Queue->push(IPCFromLauncher->msg()); IPCFromLauncher->confirm_receive(); - } else TimeOuts++; + } else + TimeOuts++; } Memory::Print("IPC System shutting down"); } diff --git a/src/Memory/Definitions.cpp b/src/Memory/Definitions.cpp index 868db88..7297d4d 100644 --- a/src/Memory/Definitions.cpp +++ b/src/Memory/Definitions.cpp @@ -4,13 +4,13 @@ /// #include "Memory/Definitions.h" -#include "lua/lj_strscan.h" #include "lua/lj_arch.h" -#include "lua/lj_obj.h" +#include "lua/lj_bc.h" #include "lua/lj_def.h" #include "lua/lj_gc.h" -#include "lua/lj_bc.h" +#include "lua/lj_obj.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); } diff --git a/src/Memory/GELua.cpp b/src/Memory/GELua.cpp index 838c38e..44568cc 100644 --- a/src/Memory/GELua.cpp +++ b/src/Memory/GELua.cpp @@ -3,9 +3,9 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// -#include "Memory/Patterns.h" -#include "Memory/Memory.h" #include "Memory/GELua.h" +#include "Memory/Memory.h" +#include "Memory/Patterns.h" const char* GameModule = "BeamNG.drive.x64.exe"; const char* DllModule = "libbeamng.x64.dll"; @@ -13,7 +13,7 @@ const char* DllModule = "libbeamng.x64.dll"; std::string GetHex(uint64_t num) { char buffer[30]; sprintf(buffer, "%llx", num); - return std::string{buffer}; + return std::string { buffer }; } void GELua::FindAddresses() { diff --git a/src/Memory/IPC.cpp b/src/Memory/IPC.cpp index 728c8eb..03dd56f 100644 --- a/src/Memory/IPC.cpp +++ b/src/Memory/IPC.cpp @@ -4,24 +4,25 @@ /// #define WIN32_LEAN_AND_MEAN -#include #include "Memory/IPC.h" +#include -IPC::IPC(uint32_t ID, size_t Size) noexcept : Size_(Size) { - std::string Sem{"MP_S" + std::to_string(ID)}, - SemConf{"MP_SC" + std::to_string(ID)}, - Mem{"MP_IO" + std::to_string(ID)}; +IPC::IPC(uint32_t ID, size_t Size) noexcept + : Size_(Size) { + std::string Sem { "MP_S" + 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()); - if(SemHandle_ == nullptr) { + if (SemHandle_ == nullptr) { SemHandle_ = CreateSemaphoreA(nullptr, 0, 1, Sem.c_str()); } SemConfHandle_ = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, SemConf.c_str()); - if(SemConfHandle_ == nullptr) { + if (SemConfHandle_ == nullptr) { SemConfHandle_ = CreateSemaphoreA(nullptr, 0, 1, SemConf.c_str()); } MemoryHandle_ = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, Mem.c_str()); - if(MemoryHandle_ == nullptr) { + if (MemoryHandle_ == nullptr) { MemoryHandle_ = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(Size), Mem.c_str()); } Data_ = (char*)MapViewOfFile(MemoryHandle_, FILE_MAP_ALL_ACCESS, 0, 0, Size); @@ -82,11 +83,9 @@ IPC::~IPC() 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()); bool used = MEM != nullptr; UnmapViewOfFile(MEM); return used; } - - diff --git a/src/Memory/Memory.cpp b/src/Memory/Memory.cpp index 0c9ca6d..583c3cd 100644 --- a/src/Memory/Memory.cpp +++ b/src/Memory/Memory.cpp @@ -7,9 +7,9 @@ #undef UNICODE #include "Memory/Memory.h" #include "Memory/BeamNG.h" +#include #include #include -#include uint32_t Memory::GetBeamNGPID(const std::set& BL) { SetLastError(0); @@ -17,21 +17,22 @@ uint32_t Memory::GetBeamNGPID(const std::set& BL) { pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - if(Process32First(Snapshot, &pe32)) { - do{ - if(std::string("BeamNG.drive.x64.exe") == pe32.szExeFile - && BL.find(pe32.th32ProcessID) == BL.end() - && BL.find(pe32.th32ParentProcessID) == BL.end()) { + if (Process32First(Snapshot, &pe32)) { + do { + if (std::string("BeamNG.drive.x64.exe") == pe32.szExeFile + && BL.find(pe32.th32ProcessID) == BL.end() + && BL.find(pe32.th32ParentProcessID) == BL.end()) { break; } - }while(Process32Next(Snapshot, &pe32)); + } while (Process32Next(Snapshot, &pe32)); } - if(Snapshot != INVALID_HANDLE_VALUE) { + if (Snapshot != INVALID_HANDLE_VALUE) { CloseHandle(Snapshot); } - if(GetLastError() != 0)return 0; + if (GetLastError() != 0) + return 0; return pe32.th32ProcessID; } @@ -44,24 +45,23 @@ uint32_t Memory::GetPID() { } uint64_t Memory::FindPattern(const char* module, const char* Pattern[]) { - MODULEINFO mInfo{nullptr}; + MODULEINFO mInfo { nullptr }; GetModuleInformation(GetCurrentProcess(), GetModuleHandleA(module), &mInfo, sizeof(MODULEINFO)); auto base = uint64_t(mInfo.lpBaseOfDll); auto size = uint32_t(mInfo.SizeOfImage); auto len = strlen(Pattern[1]); - for(auto i = 0; i < size - len; i++) { + for (auto i = 0; i < size - len; i++) { bool found = true; - for(auto j = 0; j < len && found; j++) { - found &= Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base+i+j); + for (auto j = 0; j < len && found; j++) { + found &= Pattern[1][j] == '?' || Pattern[0][j] == *(char*)(base + i + j); } - if(found) { - return base+i; + if (found) { + return base + i; } } return 0; } - void* operator new(size_t size) { return GlobalAlloc(GPTR, size); } @@ -98,11 +98,11 @@ void Memory::Inject(uint32_t PID) { auto relocationTable = (PIMAGE_BASE_RELOCATION)((DWORD_PTR)localImage + ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); PDWORD_PTR patchedAddress; - while (relocationTable->SizeOfBlock > 0){ + while (relocationTable->SizeOfBlock > 0) { DWORD relocationEntriesCount = (relocationTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(USHORT); auto relocationRVA = (PBASE_RELOCATION_ENTRY)(relocationTable + 1); - for (uint32_t i = 0; i < relocationEntriesCount; i++){ - if (relocationRVA[i].Offset){ + for (uint32_t i = 0; i < relocationEntriesCount; i++) { + if (relocationRVA[i].Offset) { patchedAddress = PDWORD_PTR(DWORD_PTR(localImage) + relocationTable->VirtualAddress + relocationRVA[i].Offset); *patchedAddress += deltaImageBase; } @@ -110,7 +110,7 @@ void Memory::Inject(uint32_t PID) { 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); + CreateRemoteThread(targetProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)((DWORD_PTR)EntryPoint + deltaImageBase), nullptr, 0, nullptr); CloseHandle(targetProcess); } diff --git a/src/Network/Compressor.cpp b/src/Network/Compressor.cpp index a7e5f78..343b786 100644 --- a/src/Network/Compressor.cpp +++ b/src/Network/Compressor.cpp @@ -7,46 +7,46 @@ #include #define Biggest 30000 -std::string Zlib::Comp(std::string Data){ - char*C = new char[Biggest]; +std::string Zlib::Comp(std::string Data) { + char* C = new char[Biggest]; memset(C, 0, Biggest); z_stream defstream; defstream.zalloc = Z_NULL; defstream.zfree = Z_NULL; defstream.opaque = Z_NULL; defstream.avail_in = (uInt)Data.length(); - defstream.next_in = (Bytef *)&Data[0]; + defstream.next_in = (Bytef*)&Data[0]; defstream.avail_out = Biggest; - defstream.next_out = reinterpret_cast(C); + defstream.next_out = reinterpret_cast(C); deflateInit(&defstream, Z_BEST_COMPRESSION); deflate(&defstream, Z_SYNC_FLUSH); deflate(&defstream, Z_FINISH); deflateEnd(&defstream); uint32_t TO = defstream.total_out; - std::string Ret(TO,0); - memcpy_s(&Ret[0],TO,C,TO); - delete [] C; + std::string Ret(TO, 0); + memcpy_s(&Ret[0], TO, C, TO); + delete[] C; return Ret; } -std::string Zlib::DeComp(std::string Compressed){ - char*C = new char[Biggest]; +std::string Zlib::DeComp(std::string Compressed) { + char* C = new char[Biggest]; memset(C, 0, Biggest); z_stream infstream; infstream.zalloc = Z_NULL; infstream.zfree = Z_NULL; infstream.opaque = Z_NULL; infstream.avail_in = Biggest; - infstream.next_in = (Bytef *)(&Compressed[0]); + infstream.next_in = (Bytef*)(&Compressed[0]); infstream.avail_out = Biggest; - infstream.next_out = (Bytef *)(C); + infstream.next_out = (Bytef*)(C); inflateInit(&infstream); inflate(&infstream, Z_SYNC_FLUSH); inflate(&infstream, Z_FINISH); inflateEnd(&infstream); uint32_t TO = infstream.total_out; - std::string Ret(TO,0); - memcpy_s(&Ret[0],TO,C,TO); - delete [] C; + std::string Ret(TO, 0); + memcpy_s(&Ret[0], TO, C, TO); + delete[] C; return Ret; } diff --git a/src/Network/HttpAPI.cpp b/src/Network/HttpAPI.cpp index 4053092..15c0e22 100644 --- a/src/Network/HttpAPI.cpp +++ b/src/Network/HttpAPI.cpp @@ -3,22 +3,22 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// #define CPPHTTPLIB_OPENSSL_SUPPORT -#include -#include "Launcher.h" #include "HttpAPI.h" -#include +#include "Launcher.h" #include "Logger.h" -#include -#include #include +#include +#include +#include +#include bool HTTP::isDownload = false; std::atomic CliRef = nullptr; -std::string HTTP::Get(const std::string &IP) { +std::string HTTP::Get(const std::string& IP) { static std::mutex Lock; std::scoped_lock Guard(Lock); - auto pos = IP.find('/',10); + auto pos = IP.find('/', 10); httplib::Client cli(IP.substr(0, pos)); CliRef.store(&cli); @@ -26,13 +26,14 @@ std::string HTTP::Get(const std::string &IP) { auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar); std::string Ret; - if(res.error() == httplib::Error::Success){ - if(res->status == 200){ + if (res.error() == httplib::Error::Success) { + if (res->status == 200) { Ret = res->body; - }else LOG(ERROR) << res->reason; + } else + LOG(ERROR) << res->reason; - }else{ - if(isDownload) { + } else { + if (isDownload) { std::cout << "\n"; } LOG(ERROR) << "HTTP Get failed on " << httplib::to_string(res.error()); @@ -45,27 +46,27 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) { static std::mutex Lock; std::scoped_lock Guard(Lock); - auto pos = IP.find('/',10); + auto pos = IP.find('/', 10); httplib::Client cli(IP.substr(0, pos)); CliRef.store(&cli); cli.set_connection_timeout(std::chrono::seconds(5)); std::string Ret; - if(!Fields.empty()) { + if (!Fields.empty()) { httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json"); - if(res.error() == httplib::Error::Success) { - if(res->status != 200) { + if (res.error() == httplib::Error::Success) { + if (res->status != 200) { LOG(ERROR) << res->reason; } Ret = res->body; - } else{ + } else { LOG(ERROR) << "HTTP Post failed on " << httplib::to_string(res.error()); } } else { httplib::Result res = cli.Post(IP.substr(pos).c_str()); - if(res.error() == httplib::Error::Success) { + if (res.error() == httplib::Error::Success) { if (res->status != 200) { LOG(ERROR) << res->reason; } @@ -75,12 +76,14 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) { } } CliRef.store(nullptr); - if(Ret.empty())return "-1"; - else return Ret; + if (Ret.empty()) + return "-1"; + else + return Ret; } -bool HTTP::ProgressBar(size_t c, size_t t){ - if(isDownload) { +bool HTTP::ProgressBar(size_t c, size_t t) { + if (isDownload) { static double progress_bar_adv; progress_bar_adv = round(double(c) / double(t) * 25); std::cout << "\r"; @@ -88,11 +91,13 @@ bool HTTP::ProgressBar(size_t c, size_t t){ std::cout << round(double(c) / double(t) * 100); std::cout << "% ] ["; int i; - for (i = 0; i <= progress_bar_adv; i++)std::cout << "#"; - for (i = 0; i < 25 - progress_bar_adv; i++)std::cout << "."; + for (i = 0; i <= progress_bar_adv; i++) + std::cout << "#"; + for (i = 0; i < 25 - progress_bar_adv; i++) + std::cout << "."; std::cout << "]"; } - if(Launcher::Terminated()) { + if (Launcher::Terminated()) { CliRef.load()->stop(); std::cout << '\n'; isDownload = false; @@ -101,7 +106,7 @@ bool HTTP::ProgressBar(size_t c, size_t t){ 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; std::scoped_lock Guard(Lock); @@ -109,10 +114,11 @@ bool HTTP::Download(const std::string &IP, const std::string &Path) { std::string Ret = Get(IP); isDownload = false; - if(Ret.empty())return false; + if (Ret.empty()) + return false; std::cout << "\n"; std::ofstream File(Path, std::ios::binary); - if(File.is_open()) { + if (File.is_open()) { File << Ret; File.close(); LOG(INFO) << "Download complete!"; diff --git a/src/Network/Login.cpp b/src/Network/Login.cpp index cb3f684..e65aec2 100644 --- a/src/Network/Login.cpp +++ b/src/Network/Login.cpp @@ -3,22 +3,22 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// -#include "Launcher.h" #include "HttpAPI.h" -#include "Logger.h" #include "Json.h" +#include "Launcher.h" +#include "Logger.h" -void UpdateKey(const std::string& newKey){ - if(!newKey.empty()){ +void UpdateKey(const std::string& newKey) { + if (!newKey.empty()) { std::ofstream Key("key"); - if(Key.is_open()){ + if (Key.is_open()) { Key << newKey; Key.close(); } else { LOG(FATAL) << "Cannot write to disk!"; throw ShutdownException("Fatal Error"); } - }else if(fs::exists("key")){ + } else if (fs::exists("key")) { remove("key"); } } @@ -27,15 +27,15 @@ void UpdateKey(const std::string& newKey){ /// "Guest":"Name" /// "pk":"private_key" -std::string GetFail(const std::string& R){ +std::string GetFail(const std::string& R) { std::string DRet = R"({"success":false,"message":)"; - DRet += "\""+R+"\"}"; + DRet += "\"" + R + "\"}"; LOG(ERROR) << R; return DRet; } std::string Launcher::Login(const std::string& fields) { - if(fields == "LO"){ + if (fields == "LO") { LoginAuth = false; UpdateKey(""); return ""; @@ -44,7 +44,7 @@ std::string Launcher::Login(const std::string& fields) { std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields); Json d = Json::parse(Buffer, nullptr, false); - if(Buffer == "-1"){ + if (Buffer == "-1") { return GetFail("Failed to communicate with the auth system!"); } @@ -53,18 +53,19 @@ std::string Launcher::Login(const std::string& fields) { return GetFail("Invalid answer from authentication servers, please try again later!"); } - if(!d["success"].is_null() && d["success"].get()){ + if (!d["success"].is_null() && d["success"].get()) { LoginAuth = true; - if(!d["private_key"].is_null()){ + if (!d["private_key"].is_null()) { UpdateKey(d["private_key"].get()); } - if(!d["public_key"].is_null()){ + if (!d["public_key"].is_null()) { PublicKey = d["public_key"].get(); } LOG(INFO) << "Authentication successful!"; - }else LOG(WARNING) << "Authentication failed!"; + } else + LOG(WARNING) << "Authentication failed!"; - if(!d["message"].is_null()) { + if (!d["message"].is_null()) { d.erase("private_key"); d.erase("public_key"); return d.dump(); @@ -73,9 +74,9 @@ std::string Launcher::Login(const std::string& fields) { } 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"); - if(Key.is_open()) { + if (Key.is_open()) { auto Size = fs::file_size("key"); std::string Buffer(Size, 0); Key.read(&Buffer[0], std::streamsize(Size)); @@ -89,22 +90,20 @@ void Launcher::CheckKey() { LOG(FATAL) << "Invalid answer from authentication servers, please try again later!"; throw ShutdownException("Fatal Error"); } - if(d["success"].get()){ + if (d["success"].get()) { LoginAuth = true; UpdateKey(d["private_key"].get()); PublicKey = d["public_key"].get(); UserRole = d["role"].get(); LOG(INFO) << "Auto-Authentication was successful"; - }else{ + } else { LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!"; UpdateKey(""); } - }else{ + } else { LOG(WARNING) << "Could not open saved key!"; UpdateKey(""); } - }else UpdateKey(""); + } else + UpdateKey(""); } - - - diff --git a/src/Network/Resources.cpp b/src/Network/Resources.cpp index 92b0db0..c774382 100644 --- a/src/Network/Resources.cpp +++ b/src/Network/Resources.cpp @@ -3,42 +3,43 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// - -#include -#include #include "Launcher.h" -#include "Server.h" #include "Logger.h" +#include "Server.h" +#include #include +#include #include +#include #include #include -#include #include -#include +#include namespace fs = std::filesystem; -std::vector Split(const std::string& String, const std::string& delimiter){ +std::vector Split(const std::string& String, const std::string& delimiter) { std::vector Val; size_t pos; - std::string token,s = String; + std::string token, s = String; while ((pos = s.find(delimiter)) != std::string::npos) { token = s.substr(0, pos); - if(!token.empty())Val.push_back(token); + if (!token.empty()) + Val.push_back(token); s.erase(0, pos + delimiter.length()); } - if(!s.empty())Val.push_back(s); + if (!s.empty()) + Val.push_back(s); return Val; } -void CheckForDir(){ - if(!fs::exists("Resources")){ +void CheckForDir() { + if (!fs::exists("Resources")) { _wmkdir(L"Resources"); } } void Server::WaitForConfirm() { - while(!Terminate && !ModLoaded){ + while (!Terminate && !ModLoaded) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } ModLoaded = false; @@ -54,39 +55,41 @@ std::string Server::Auth() { auto Res = TCPRcv(); - if(Res.empty() || Res[0] == 'E'){ + if (Res.empty() || Res[0] == 'E') { Abort(); return ""; } TCPSend(LauncherInstance->getPublicKey()); - if(Terminate)return ""; + if (Terminate) + return ""; Res = TCPRcv(); - if(Res.empty() || Res[0] != 'P'){ + if (Res.empty() || Res[0] != 'P') { Abort(); return ""; } 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); - }else{ + } else { Abort(); UUl("Authentication failed!"); return ""; } TCPSend("SR"); - if(Terminate)return ""; + if (Terminate) + return ""; Res = TCPRcv(); - if(Res[0] == 'E'){ + if (Res[0] == 'E') { Abort(); return ""; } - if(Res.empty() || Res == "-"){ + if (Res.empty() || Res == "-") { LOG(INFO) << "Didn't Receive any mods..."; ModList = "-"; TCPSend("Done"); @@ -97,32 +100,35 @@ std::string Server::Auth() { } void Server::UpdateUl(bool D, const std::string& msg) { - if(D)UStatus = "UlDownloading Resource " + msg; - else UStatus = "UlLoading Resource " + msg; + if (D) + UStatus = "UlDownloading Resource " + msg; + else + UStatus = "UlLoading Resource " + msg; } -void Server::AsyncUpdate(uint64_t& Rcv,uint64_t Size,const std::string& Name) { +void Server::AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name) { do { double pr = double(Rcv) / double(Size) * 100; std::string Per = std::to_string(trunc(pr * 10) / 10); UpdateUl(true, Name + " (" + Per.substr(0, Per.find('.') + 2) + "%)"); std::this_thread::sleep_for(std::chrono::milliseconds(100)); - }while(!Terminate && Rcv < Size); + } while (!Terminate && Rcv < Size); } char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) { - if(Sock == -1){ + if (Sock == -1) { Terminate = true; UUl("Invalid Socket"); return nullptr; } char* File = new char[Size]; uint64_t Rcv = 0; - do{ - int Len = int(Size-Rcv); - if(Len > 1000000)Len = 1000000; + do { + int Len = int(Size - Rcv); + if (Len > 1000000) + Len = 1000000; int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL); - if(Temp < 1){ + if (Temp < 1) { UUl("Socket Closed Code 1"); KillSocket(Sock); Terminate = true; @@ -131,7 +137,7 @@ char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) { } Rcv += Temp; GRcv += Temp; - }while(Rcv < Size && !Terminate); + } while (Rcv < Size && !Terminate); return File; } @@ -144,7 +150,7 @@ void Server::MultiKill(uint64_t Sock) { uint64_t Server::InitDSock() { SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN ServerAddr; - if(DSock < 1) { + if (DSock < 1) { KillSocket(DSock); Terminate = true; return 0; @@ -152,13 +158,13 @@ uint64_t Server::InitDSock() { ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(Port); 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); Terminate = true; return 0; } - char Code[2] = {'D', char(ClientID)}; - if(send(DSock,Code,2,0) != 2){ + char Code[2] = { 'D', char(ClientID) }; + if (send(DSock, Code, 2, 0) != 2) { KillSocket(DSock); Terminate = true; return 0; @@ -168,18 +174,18 @@ uint64_t Server::InitDSock() { 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::packaged_task task([&] { return TCPRcvRaw(TCPSocket,GRcv,MSize); }); + std::packaged_task task([&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); }); std::future f1 = task.get_future(); std::thread Dt(std::move(task)); Dt.detach(); - char* DData = TCPRcvRaw(DSock,GRcv,DSize); + char* DData = TCPRcvRaw(DSock, GRcv, DSize); - if(!DData){ + if (!DData) { MultiKill(DSock); return ""; } @@ -187,21 +193,21 @@ std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::stri f1.wait(); char* MData = f1.get(); - if(!MData){ + if (!MData) { MultiKill(DSock); return ""; } - if(Au.joinable())Au.join(); + if (Au.joinable()) + Au.join(); + /// omg yes very ugly my god but i was in a rush will revisit + 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 - std::string Ret(Size,0); - memcpy_s(&Ret[0],MSize,MData,MSize); - delete[]MData; - - memcpy_s(&Ret[MSize],DSize,DData,DSize); - delete[]DData; + memcpy_s(&Ret[MSize], DSize, DData, DSize); + delete[] DData; return Ret; } @@ -214,7 +220,8 @@ void Server::InvalidResource(const std::string& File) { void Server::SyncResources() { std::string Ret = Auth(); - if(Ret.empty())return; + if (Ret.empty()) + return; LOG(INFO) << "Checking Resources..."; CheckForDir(); @@ -224,45 +231,51 @@ void Server::SyncResources() { list.clear(); Ret.clear(); - int Amount = 0,Pos = 0; - std::string a,t; - for(const std::string&name : FNames){ - if(!name.empty()){ + int Amount = 0, Pos = 0; + std::string a, t; + for (const std::string& name : FNames) { + if (!name.empty()) { t += name.substr(name.find_last_of('/') + 1) + ";"; } } - if(t.empty())ModList = "-"; - else ModList = t; + if (t.empty()) + ModList = "-"; + else + ModList = t; t.clear(); - for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) { + for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { auto pos = FN->find_last_of('/'); auto ZIP = FN->find(".zip"); if (ZIP == std::string::npos || FN->length() - ZIP != 4) { InvalidResource(*FN); return; } - if (pos == std::string::npos)continue; + if (pos == std::string::npos) + continue; Amount++; } - if(!FNames.empty())LOG(INFO) << "Syncing..."; + if (!FNames.empty()) + LOG(INFO) << "Syncing..."; SOCKET DSock = InitDSock(); - for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) { + for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { auto pos = FN->find_last_of('/'); if (pos != std::string::npos) { a = "Resources" + FN->substr(pos); - } else continue; + } 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('/'))); + 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())){ + 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); + fs::copy_options::overwrite_existing); } catch (std::exception& e) { LOG(ERROR) << "Failed copy to the mods folder! " << e.what(); Terminate = true; @@ -270,7 +283,8 @@ void Server::SyncResources() { } WaitForConfirm(); continue; - }else remove(a.c_str()); + } else + remove(a.c_str()); } CheckForDir(); std::string FName = a.substr(a.find_last_of('/')); @@ -278,7 +292,7 @@ void Server::SyncResources() { TCPSend("f" + *FN); std::string Data = TCPRcv(); - if (Data == "CO" || Terminate){ + if (Data == "CO" || Terminate) { Terminate = true; UUl("Server cannot find " + FName); break; @@ -286,10 +300,11 @@ void Server::SyncResources() { 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)break; - UpdateUl(false,std::to_string(Pos)+"/"+std::to_string(Amount)+": "+FName); + if (Terminate) + break; + UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName); std::ofstream LFS; LFS.open(a.c_str(), std::ios_base::app | std::ios::binary); if (LFS.is_open()) { @@ -297,20 +312,20 @@ void Server::SyncResources() { LFS.close(); } - }while(fs::file_size(a) != std::stoull(*FS) && !Terminate); - if(!Terminate){ - if(!fs::exists(LauncherInstance->getMPUserPath())){ + } while (fs::file_size(a) != std::stoull(*FS) && !Terminate); + if (!Terminate) { + if (!fs::exists(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(); } KillSocket(DSock); - if(!Terminate){ + if (!Terminate) { TCPSend("Done"); LOG(INFO) << "Done!"; - }else{ + } else { UStatus = "start"; LOG(INFO) << "Connection Terminated!"; } diff --git a/src/Network/Server.cpp b/src/Network/Server.cpp index fd522c5..10da784 100644 --- a/src/Network/Server.cpp +++ b/src/Network/Server.cpp @@ -5,17 +5,18 @@ #define WIN32_LEAN_AND_MEAN -#include "Compressor.h" #include "Server.h" +#include "Compressor.h" #include "Launcher.h" +#include "Logger.h" #include #include #include -#include "Logger.h" -Server::Server(Launcher *Instance) : LauncherInstance(Instance) { +Server::Server(Launcher* Instance) + : LauncherInstance(Instance) { WSADATA wsaData; - int iRes = WSAStartup(514, &wsaData); //2.2 + int iRes = WSAStartup(514, &wsaData); // 2.2 if (iRes != 0) { LOG(ERROR) << "WSAStartup failed with error: " << iRes; } @@ -42,7 +43,7 @@ void Server::TCPClientMain() { ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(Port); inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr); - status = connect(TCPSocket, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr)); + status = connect(TCPSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)); if (status != 0) { UStatus = "Connection Failed!"; LOG(ERROR) << "Connect failed! Error code: " << GetSocketApiError(); @@ -72,15 +73,17 @@ void Server::StartUDP() { } void Server::UDPSend(std::string Data) { - if (ClientID == -1 || UDPSocket == -1)return; + if (ClientID == -1 || UDPSocket == -1) + return; if (Data.length() > 400) { std::string CMP(Zlib::Comp(Data)); Data = "ABG:" + CMP; } std::string Packet = char(ClientID + 1) + std::string(":") + Data; - int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr *) UDPSockAddress.get(), - sizeof(sockaddr_in)); - if (sendOk == SOCKET_ERROR)LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError(); + int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)UDPSockAddress.get(), + sizeof(sockaddr_in)); + if (sendOk == SOCKET_ERROR) + LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError(); } void Server::UDPParser(std::string Packet) { @@ -91,13 +94,15 @@ void Server::UDPParser(std::string Packet) { } void Server::UDPRcv() { - sockaddr_in FromServer{}; + sockaddr_in FromServer {}; int clientLength = sizeof(FromServer); ZeroMemory(&FromServer, clientLength); std::string Ret(10240, 0); - if (UDPSocket == -1)return; - int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr *) &FromServer, &clientLength); - if (Rcv == SOCKET_ERROR)return; + if (UDPSocket == -1) + return; + int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength); + if (Rcv == SOCKET_ERROR) + return; UDPParser(Ret.substr(0, Rcv)); } @@ -109,7 +114,8 @@ void Server::UDPClient() { LauncherInstance->SendIPC("P" + std::to_string(ClientID), false); TCPSend("H"); UDPSend("p"); - while (!Terminate)UDPRcv(); + while (!Terminate) + UDPRcv(); KillSocket(UDPSocket); } @@ -120,16 +126,19 @@ void Server::UDPMain() { LOG(INFO) << "Connection terminated"; } -void Server::Connect(const std::string &Data) { +void Server::Connect(const std::string& Data) { ModList.clear(); Terminate.store(false); IP = GetAddress(Data.substr(1, Data.find(':') - 1)); std::string port = Data.substr(Data.find(':') + 1); bool ValidPort = std::all_of(port.begin(), port.end(), ::isdigit); if (IP.find('.') == -1 || !ValidPort) { - if (IP == "DNS") UStatus = "Connection Failed! (DNS Lookup Failed)"; - else if (!ValidPort) UStatus = "Connection Failed! (Invalid Port)"; - else UStatus = "Connection Failed! (WSA failed to start)"; + if (IP == "DNS") + UStatus = "Connection Failed! (DNS Lookup Failed)"; + else if (!ValidPort) + UStatus = "Connection Failed! (Invalid Port)"; + else + UStatus = "Connection Failed! (WSA failed to start)"; ModList = "-"; Terminate.store(true); return; @@ -160,12 +169,12 @@ std::string Server::GetSocketApiError() { err = WSAGetLastError(); FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, - err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - msgbuf, - sizeof(msgbuf), - nullptr); + nullptr, + err, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + msgbuf, + sizeof(msgbuf), + nullptr); if (*msgbuf) { return std::to_string(WSAGetLastError()) + " - " + std::string(msgbuf); @@ -175,16 +184,22 @@ std::string Server::GetSocketApiError() { } void Server::ServerSend(std::string Data, bool Rel) { - if (Terminate || Data.empty())return; + if (Terminate || Data.empty()) + return; char C = 0; int DLen = int(Data.length()); - if (DLen > 3)C = Data.at(0); + if (DLen > 3) + C = Data.at(0); bool Ack = C == 'O' || C == 'T'; - if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')Rel = true; + if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C') + Rel = true; if (Ack || Rel) { - if (Ack || DLen > 1000)SendLarge(Data); - else TCPSend(Data); - } else UDPSend(Data); + if (Ack || DLen > 1000) + SendLarge(Data); + else + TCPSend(Data); + } else + UDPSend(Data); } void Server::PingLoop() { @@ -211,7 +226,7 @@ void Server::Close() { } } -const std::string &Server::getMap() { +const std::string& Server::getMap() { return MStatus; } @@ -219,7 +234,7 @@ bool Server::Terminated() { return Terminate; } -const std::string &Server::getModList() { +const std::string& Server::getModList() { return ModList; } @@ -227,24 +242,26 @@ int Server::getPing() const { return Ping; } -const std::string &Server::getUIStatus() { +const std::string& Server::getUIStatus() { return UStatus; } -std::string Server::GetAddress(const std::string &Data) { - if (Data.find_first_not_of("0123456789.") == -1)return Data; - hostent *host; +std::string Server::GetAddress(const std::string& Data) { + if (Data.find_first_not_of("0123456789.") == -1) + return Data; + hostent* host; host = gethostbyname(Data.c_str()); if (!host) { LOG(ERROR) << "DNS lookup failed! on " << Data; 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; } int Server::KillSocket(uint64_t Dead) { - if (Dead == (SOCKET) -1)return 0; + if (Dead == (SOCKET)-1) + return 0; shutdown(Dead, SD_BOTH); return closesocket(Dead); } @@ -253,17 +270,17 @@ void Server::setModLoaded() { ModLoaded.store(true); } -void Server::UUl(const std::string &R) { +void Server::UUl(const std::string& R) { UStatus = "Disconnected: " + R; } bool Server::CheckBytes(int32_t Bytes) { if (Bytes == 0) { - //debug("(TCP) Connection closing... CheckBytes(16)"); + // debug("(TCP) Connection closing... CheckBytes(16)"); Terminate = true; return false; } else if (Bytes < 0) { - //debug("(TCP CB) recv failed with error: " + GetSocketApiError(); + // debug("(TCP CB) recv failed with error: " + GetSocketApiError(); KillSocket(TCPSocket); Terminate = true; return false; @@ -271,7 +288,7 @@ bool Server::CheckBytes(int32_t Bytes) { return true; } -void Server::TCPSend(const std::string &Data) { +void Server::TCPSend(const std::string& Data) { if (TCPSocket == -1) { Terminate = true; @@ -346,6 +363,7 @@ std::string Server::TCPRcv() { Ret = Zlib::DeComp(Ret.substr(4)); } - if (Ret[0] == 'E')UUl(Ret.substr(1)); + if (Ret[0] == 'E') + UUl(Ret.substr(1)); return Ret; } diff --git a/src/Network/Update.cpp b/src/Network/Update.cpp index a4bafac..c37ac21 100644 --- a/src/Network/Update.cpp +++ b/src/Network/Update.cpp @@ -3,12 +3,12 @@ /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// -#include "Launcher.h" #include "HttpAPI.h" -#include "Logger.h" #include "Json.h" +#include "Launcher.h" +#include "Logger.h" -VersionParser::VersionParser(const std::string &from_string) { +VersionParser::VersionParser(const std::string& from_string) { std::string token; std::istringstream tokenStream(from_string); while (std::getline(tokenStream, token, '.')) { @@ -17,19 +17,25 @@ VersionParser::VersionParser(const std::string &from_string) { } } -std::strong_ordering VersionParser::operator<=>(const VersionParser &rhs) const noexcept { +std::strong_ordering VersionParser::operator<=>(const VersionParser& rhs) const noexcept { size_t const fields = std::min(data.size(), rhs.data.size()); - for(size_t i = 0; i != fields; ++i) { - if(data[i] == rhs.data[i]) continue; - else if(data[i] < rhs.data[i]) return std::strong_ordering::less; - else return std::strong_ordering::greater; + for (size_t i = 0; i != fields; ++i) { + if (data[i] == rhs.data[i]) + continue; + else if (data[i] < rhs.data[i]) + return std::strong_ordering::less; + 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; - else return std::strong_ordering::less; + if (data.size() == rhs.data.size()) + 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); } @@ -37,51 +43,54 @@ void Launcher::UpdateCheck() { std::string link; std::string HTTP = HTTP::Get("https://beammp.com/builds/launcher?version=true"); bool fallback = false; - if(HTTP.find_first_of("0123456789") == std::string::npos){ + if (HTTP.find_first_of("0123456789") == std::string::npos) { HTTP = HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true"); fallback = true; - if(HTTP.find_first_of("0123456789") == std::string::npos) { + if (HTTP.find_first_of("0123456789") == std::string::npos) { LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!"; throw ShutdownException("Fatal Error"); } } - if(fallback){ + if (fallback) { link = "https://backup1.beammp.com/builds/launcher?download=true"; - }else link = "https://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"); - if(fs::exists(Back))remove(Back.c_str()); + if (fs::exists(Back)) + remove(Back.c_str()); std::string RemoteVer; - for(char& c : HTTP) { - if(std::isdigit(c) || c == '.') { + for (char& c : HTTP) { + if (std::isdigit(c) || c == '.') { RemoteVer += c; } } - if(VersionParser(RemoteVer) > VersionParser(FullVersion)){ + if (VersionParser(RemoteVer) > VersionParser(FullVersion)) { system("cls"); 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!"; } - if(!HTTP::Download(link, EP)){ + if (!HTTP::Download(link, EP)) { LOG(ERROR) << "Launcher Update failed! trying again..."; std::this_thread::sleep_for(std::chrono::seconds(2)); - if(!HTTP::Download(link, EP)){ + if (!HTTP::Download(link, EP)) { LOG(ERROR) << "Launcher Update failed!"; std::this_thread::sleep_for(std::chrono::seconds(5)); AdminRelaunch(); } } Relaunch(); - }else LOG(INFO) << "Launcher version is up to date"; + } else + LOG(INFO) << "Launcher version is up to date"; } -size_t DirCount(const std::filesystem::path& path){ - return (size_t)std::distance(std::filesystem::directory_iterator{path}, std::filesystem::directory_iterator{}); +size_t DirCount(const std::filesystem::path& path) { + return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {}); } void Launcher::ResetMods() { @@ -99,20 +108,23 @@ void Launcher::ResetMods() { void Launcher::EnableMP() { std::string File(BeamUserPath + "mods\\db.json"); - if(!fs::exists(File))return; + if (!fs::exists(File)) + return; auto Size = fs::file_size(File); - if(Size < 2)return; + if (Size < 2) + return; std::ifstream db(File); - if(db.is_open()) { + if (db.is_open()) { std::string Data(Size, 0); db.read(&Data[0], std::streamsize(Size)); db.close(); Json d = Json::parse(Data, nullptr, false); - if(Data.at(0) != '{' || d.is_discarded())return; - if(!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()){ + if (Data.at(0) != '{' || d.is_discarded()) + return; + if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) { d["mods"]["multiplayerbeammp"]["active"] = true; std::ofstream ofs(File); - if(ofs.is_open()){ + if (ofs.is_open()) { ofs << std::setw(4) << d; ofs.close(); } else { @@ -127,5 +139,7 @@ void Launcher::SetupMOD() { EnableMP(); LOG(INFO) << "Downloading mod please wait"; HTTP::Download("https://backend.beammp.com/builds/client?download=true" - "&pk=" + PublicKey + "&branch=" + TargetBuild, MPUserPath + "\\BeamMP.zip"); + "&pk=" + + PublicKey + "&branch=" + TargetBuild, + MPUserPath + "\\BeamMP.zip"); } diff --git a/src/gui/Gui.cpp b/src/gui/Gui.cpp index 5252d43..3ed06dd 100644 --- a/src/gui/Gui.cpp +++ b/src/gui/Gui.cpp @@ -7,10 +7,10 @@ #include #include #ifndef WX_PRECOMP -#include +#include "gifs.h" #include #include -#include "gifs.h" +#include #endif class MyApp : public wxApp { @@ -20,6 +20,7 @@ public: class MyFrame : public wxFrame { public: MyFrame(); + private: void OnHello(wxCommandEvent& event); void OnExit(wxCommandEvent& event); @@ -29,28 +30,28 @@ private: enum { ID_Hello = 1 }; -wxSize MyFrame::FixedSize(370,400); +wxSize MyFrame::FixedSize(370, 400); bool MyApp::OnInit() { - auto *frame = new MyFrame(); + auto* frame = new MyFrame(); frame->Show(true); return true; } MyFrame::MyFrame() - : wxFrame(nullptr, wxID_ANY, "BeamMP V3.0", wxDefaultPosition, FixedSize) { - //SetMaxSize(FixedSize); - //SetMinSize(FixedSize); + : wxFrame(nullptr, wxID_ANY, "BeamMP V3.0", wxDefaultPosition, FixedSize) { + // SetMaxSize(FixedSize); + // SetMinSize(FixedSize); Center(); - //27 35 35 + // 27 35 35 - wxColour Colour(27,35,35,1); + wxColour Colour(27, 35, 35, 1); SetBackgroundColour(Colour); auto* menuFile = new wxMenu; 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->Append(wxID_EXIT); auto* menuHelp = new wxMenu; @@ -60,13 +61,12 @@ MyFrame::MyFrame() menuBar->SetOwnBackgroundColour(Colour); menuBar->Append(menuFile, "&File"); menuBar->Append(menuHelp, "&Help"); - //SetMenuBar(menuBar); + // SetMenuBar(menuBar); auto* m_ani = new wxAnimationCtrl(this, wxID_ANY); wxMemoryInputStream stream(gif::Logo, sizeof(gif::Logo)); - if (m_ani->Load(stream)) m_ani->Play(); - - + if (m_ani->Load(stream)) + m_ani->Play(); Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello); Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT); @@ -77,14 +77,13 @@ void MyFrame::OnExit(wxCommandEvent& event) { } void MyFrame::OnAbout(wxCommandEvent& event) { wxMessageBox("This is a wxWidgets Hello World example", - "About Hello World", wxOK | wxICON_INFORMATION); + "About Hello World", wxOK | wxICON_INFORMATION); } void MyFrame::OnHello(wxCommandEvent& event) { wxLogMessage("Hello world from wxWidgets!"); } - -int GUIEntry (int argc, char *argv[]) { +int GUIEntry(int argc, char* argv[]) { new MyApp(); return wxEntry(argc, argv); } \ No newline at end of file diff --git a/src/gui/gifs.cpp b/src/gui/gifs.cpp index bbad8f2..186c769 100644 --- a/src/gui/gifs.cpp +++ b/src/gui/gifs.cpp @@ -5,8 +5,7 @@ #include "gifs.h" -const unsigned char gif::Logo[30427] = -{ +const unsigned char gif::Logo[30427] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x80, 0x00, 0x80, 0x00, 0xf6, 0x00, 0x00, 0x0f, 0x37, 0x57, 0x17, 0x27, 0x37, 0x17, 0x27, 0x3f, 0x0f, 0x37, 0x5f, 0x00, 0x77, 0xef, 0x07, 0x4f, 0x8f, 0x17, 0x2f, 0x47, 0x0f, 0x3f, diff --git a/src/gui/gifs.h b/src/gui/gifs.h index 015d997..b4a9f73 100644 --- a/src/gui/gifs.h +++ b/src/gui/gifs.h @@ -5,7 +5,7 @@ #pragma once -class gif{ +class gif { public: static const unsigned char Logo[30427]; }; diff --git a/src/main.cpp b/src/main.cpp index 1f4c266..c9775d9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,11 +10,11 @@ int main(int argc, char* argv[]) { try { Launcher launcher(argc, argv); launcher.RunDiscordRPC(); - launcher.LoadConfig(); //check if json (issue) + launcher.LoadConfig(); // check if json (issue) launcher.CheckKey(); launcher.QueryRegistry(); - //UI call - //launcher.SetupMOD(); + // UI call + // launcher.SetupMOD(); launcher.LaunchGame(); launcher.WaitForGame(); LOG(INFO) << "Launcher shutting down";