Reformat to clang-format

This commit is contained in:
Anonymous275
2022-07-26 10:43:25 +03:00
parent 54af98203f
commit b26fb43746
25 changed files with 549 additions and 475 deletions
+1
View File
@@ -12,6 +12,7 @@ public:
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;
}; };
-1
View File
@@ -6,4 +6,3 @@
#pragma once #pragma once
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
using Json = nlohmann::json; using Json = nlohmann::json;
+6 -3
View File
@@ -5,11 +5,10 @@
#pragma once #pragma once
#include "Memory/IPC.h" #include "Memory/IPC.h"
#include <filesystem>
#include "Server.h" #include "Server.h"
#include <filesystem>
#include <thread> #include <thread>
namespace fs = std::filesystem; namespace fs = std::filesystem;
struct VersionParser { struct VersionParser {
@@ -24,6 +23,7 @@ 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);
@@ -35,6 +35,7 @@ public: //available functions
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;
@@ -59,6 +60,7 @@ private: //functions
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;
@@ -86,5 +88,6 @@ private: //variables
class ShutdownException : public std::runtime_error { class ShutdownException : public std::runtime_error {
public: public:
explicit ShutdownException(const std::string& message): runtime_error(message){}; explicit ShutdownException(const std::string& message)
: runtime_error(message) {};
}; };
+4 -2
View File
@@ -4,10 +4,10 @@
/// ///
#pragma once #pragma once
#include <string>
#include <atomic> #include <atomic>
#include <thread>
#include <chrono> #include <chrono>
#include <string>
#include <thread>
struct sockaddr_in; struct sockaddr_in;
class Launcher; class Launcher;
@@ -16,6 +16,7 @@ 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);
@@ -27,6 +28,7 @@ public:
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, PingEnd;
std::string MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name); std::string MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name);
+12 -7
View File
@@ -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 #pragma once
#include <semaphore>
#include <queue> #include <queue>
#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())return false; if (queue.empty())
return false;
val = queue.front(); val = queue.front();
queue.pop(); queue.pop();
full.release(); full.release();
@@ -33,24 +35,27 @@ public:
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) : lock(lock){ explicit lock_guard(std::binary_semaphore& lock)
: lock(lock) {
lock.acquire(); lock.acquire();
} }
~lock_guard() { ~lock_guard() {
lock.release(); lock.release();
} }
private: private:
std::binary_semaphore& lock; std::binary_semaphore& lock;
}; };
std::binary_semaphore semaphore { 1 }, full { 0 }; std::binary_semaphore semaphore { 1 }, full { 0 };
std::queue<T> queue {}; std::queue<T> queue {};
}; };
+7 -5
View File
@@ -3,10 +3,9 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include <tomlplusplus/toml.hpp>
#include "Launcher.h" #include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include <tomlplusplus/toml.hpp>
void Launcher::LoadConfig() { void Launcher::LoadConfig() {
if (fs::exists("Launcher.toml")) { if (fs::exists("Launcher.toml")) {
@@ -15,13 +14,16 @@ void Launcher::LoadConfig() {
auto build = config["Build"]; auto build = config["Build"];
if (ui.is_boolean()) { if (ui.is_boolean()) {
EnableUI = ui.as_boolean()->get(); EnableUI = ui.as_boolean()->get();
} else 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 // 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)c = char(tolower(c)); for (char& c : TargetBuild)
} else LOG(ERROR) << "Failed to get 'Build' string from config"; c = char(tolower(c));
} else
LOG(ERROR) << "Failed to get 'Build' string from config";
} else { } else {
std::ofstream tml("Launcher.toml"); std::ofstream tml("Launcher.toml");
+1 -2
View File
@@ -3,11 +3,10 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#ifndef DEBUG #ifndef DEBUG
#include <discord_rpc.h>
#include "Launcher.h" #include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include <ctime> #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) { }
+21 -14
View File
@@ -3,17 +3,16 @@
/// 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 "Memory/Memory.h"
#include "Memory/BeamNG.h"
#include "Launcher.h"
#include "HttpAPI.h" #include "HttpAPI.h"
#include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include "Memory/BeamNG.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)SubCode = Data.at(1); if (Data.length() > 1)
SubCode = Data.at(1);
switch (Code) { switch (Code) {
case 'A': case 'A':
ServerHandler.StartUDP(); ServerHandler.StartUDP();
@@ -29,14 +28,17 @@ void Launcher::HandleIPC(const std::string& Data) {
while (ServerHandler.getModList().empty() && !ServerHandler.Terminated()) { while (ServerHandler.getModList().empty() && !ServerHandler.Terminated()) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if(ServerHandler.getModList() == "-")SendIPC("L"); if (ServerHandler.getModList() == "-")
else SendIPC("L"+ServerHandler.getModList()); SendIPC("L");
else
SendIPC("L" + ServerHandler.getModList());
break; break;
case 'U': case 'U':
SendIPC("Ul" + ServerHandler.getUIStatus()); SendIPC("Ul" + ServerHandler.getUIStatus());
if (ServerHandler.getPing() > 800) { if (ServerHandler.getPing() > 800) {
SendIPC("Up-2"); SendIPC("Up-2");
}else SendIPC("Up" + std::to_string(ServerHandler.getPing())); } else
SendIPC("Up" + std::to_string(ServerHandler.getPing()));
break; break;
case 'M': case 'M':
SendIPC(ServerHandler.getMap()); SendIPC(ServerHandler.getMap());
@@ -45,7 +47,8 @@ void Launcher::HandleIPC(const std::string& Data) {
if (SubCode == 'S') { if (SubCode == 'S') {
ServerHandler.Close(); ServerHandler.Close();
} }
if(SubCode == 'G')exit(2); if (SubCode == 'G')
exit(2);
break; break;
case 'R': // will send mod name case 'R': // will send mod name
ServerHandler.setModLoaded(); ServerHandler.setModLoaded();
@@ -66,14 +69,18 @@ void Launcher::HandleIPC(const std::string& Data) {
} }
void Server::ServerParser(const std::string& Data) { void Server::ServerParser(const std::string& Data) {
if(Data.empty())return; if (Data.empty())
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)
SubCode = Data.at(1);
switch (Code) { switch (Code) {
case 'p': case 'p':
PingEnd = std::chrono::high_resolution_clock::now(); PingEnd = std::chrono::high_resolution_clock::now();
if(PingStart > PingEnd)Ping = 0; if (PingStart > PingEnd)
else Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd-PingStart).count()); Ping = 0;
else
Ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd - PingStart).count());
return; return;
case 'M': case 'M':
MStatus = Data; MStatus = Data;
+16 -10
View File
@@ -4,23 +4,25 @@
/// ///
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include "Memory/Memory.h"
#include "Launcher.h" #include "Launcher.h"
#include "Logger.h"
#include <csignal>
#include "HttpAPI.h" #include "HttpAPI.h"
#include <windows.h> #include "Logger.h"
#include <shellapi.h> #include "Memory/Memory.h"
#include <ShlObj.h> #include <ShlObj.h>
#include <comutil.h> #include <comutil.h>
#include <csignal>
#include <mutex> #include <mutex>
#include <shellapi.h>
#include <windows.h>
LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) { LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) {
LOG(ERROR) << "CAUGHT EXCEPTION! Code 0x" << std::hex << std::uppercase << p->ExceptionRecord->ExceptionCode; LOG(ERROR) << "CAUGHT EXCEPTION! Code 0x" << std::hex << std::uppercase << p->ExceptionRecord->ExceptionCode;
return EXCEPTION_EXECUTE_HANDLER; return EXCEPTION_EXECUTE_HANDLER;
} }
Launcher::Launcher(int argc, char* argv[]) : 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); Launcher::StaticAbort(this);
DiscordTime = std::time(nullptr); DiscordTime = std::time(nullptr);
Log::Init(); Log::Init();
@@ -116,7 +118,8 @@ void Launcher::WaitForGame() {
} }
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} while (GamePID == 0 && !Shutdown.load()); } while (GamePID == 0 && !Shutdown.load());
if(Shutdown.load())return; if (Shutdown.load())
return;
if (GamePID == 0) { if (GamePID == 0) {
LOG(FATAL) << "Game process not found! aborting"; LOG(FATAL) << "Game process not found! aborting";
@@ -156,8 +159,10 @@ void Launcher::ListenIPC() {
void Launcher::SendIPC(const std::string& Data, bool core) { void Launcher::SendIPC(const std::string& Data, bool core) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
if(core)IPCToGame->send("C" + Data); if (core)
else IPCToGame->send("G" + Data); IPCToGame->send("C" + Data);
else
IPCToGame->send("G" + Data);
if (IPCToGame->send_timed_out()) { if (IPCToGame->send_timed_out()) {
LOG(WARNING) << "Timed out while sending \"" << Data << "\""; LOG(WARNING) << "Timed out while sending \"" << Data << "\"";
} }
@@ -210,7 +215,8 @@ void Launcher::QueryRegistry() {
if (!BeamUserPath.empty()) { if (!BeamUserPath.empty()) {
MPUserPath = BeamUserPath + "mods\\multiplayer"; 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"; LOG(FATAL) << "Please launch the game at least once, failed to read registry key Software\\BeamNG\\BeamNG.drive";
throw ShutdownException("Fatal Error"); throw ShutdownException("Fatal Error");
+5 -4
View File
@@ -3,10 +3,9 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include "atomic_queue.h"
#include "Memory/BeamNG.h" #include "Memory/BeamNG.h"
#include "Memory/Memory.h" #include "Memory/Memory.h"
#include "atomic_queue.h"
std::unique_ptr<atomic_queue<std::string, 1000>> Queue; std::unique_ptr<atomic_queue<std::string, 1000>> Queue;
@@ -21,7 +20,8 @@ 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)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)); Memory::Print("PID : " + std::to_string(PID));
GELua::FindAddresses(); GELua::FindAddresses();
/*GameBaseAddr = Memory::GetModuleBase(GameModule); /*GameBaseAddr = Memory::GetModuleBase(GameModule);
@@ -86,7 +86,8 @@ void BeamNG::IPCListener() {
TimeOuts = 0; TimeOuts = 0;
Queue->push(IPCFromLauncher->msg()); Queue->push(IPCFromLauncher->msg());
IPCFromLauncher->confirm_receive(); IPCFromLauncher->confirm_receive();
} else TimeOuts++; } else
TimeOuts++;
} }
Memory::Print("IPC System shutting down"); Memory::Print("IPC System shutting down");
} }
+3 -3
View File
@@ -4,12 +4,12 @@
/// ///
#include "Memory/Definitions.h" #include "Memory/Definitions.h"
#include "lua/lj_strscan.h"
#include "lua/lj_arch.h" #include "lua/lj_arch.h"
#include "lua/lj_obj.h" #include "lua/lj_bc.h"
#include "lua/lj_def.h" #include "lua/lj_def.h"
#include "lua/lj_gc.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); return (int)(L->top - L->base);
+2 -2
View File
@@ -3,9 +3,9 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include "Memory/Patterns.h"
#include "Memory/Memory.h"
#include "Memory/GELua.h" #include "Memory/GELua.h"
#include "Memory/Memory.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";
+3 -4
View File
@@ -4,10 +4,11 @@
/// ///
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "Memory/IPC.h" #include "Memory/IPC.h"
#include <windows.h>
IPC::IPC(uint32_t ID, size_t Size) noexcept : Size_(Size) { IPC::IPC(uint32_t ID, size_t Size) noexcept
: Size_(Size) {
std::string Sem { "MP_S" + std::to_string(ID) }, std::string Sem { "MP_S" + std::to_string(ID) },
SemConf { "MP_SC" + std::to_string(ID) }, SemConf { "MP_SC" + std::to_string(ID) },
Mem { "MP_IO" + std::to_string(ID) }; Mem { "MP_IO" + std::to_string(ID) };
@@ -88,5 +89,3 @@ bool IPC::mem_used(uint32_t MemID) noexcept {
UnmapViewOfFile(MEM); UnmapViewOfFile(MEM);
return used; return used;
} }
+3 -3
View File
@@ -7,9 +7,9 @@
#undef UNICODE #undef UNICODE
#include "Memory/Memory.h" #include "Memory/Memory.h"
#include "Memory/BeamNG.h" #include "Memory/BeamNG.h"
#include <psapi.h>
#include <string> #include <string>
#include <tlhelp32.h> #include <tlhelp32.h>
#include <psapi.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);
@@ -31,7 +31,8 @@ uint32_t Memory::GetBeamNGPID(const std::set<uint32_t>& BL) {
CloseHandle(Snapshot); CloseHandle(Snapshot);
} }
if(GetLastError() != 0)return 0; if (GetLastError() != 0)
return 0;
return pe32.th32ProcessID; return pe32.th32ProcessID;
} }
@@ -61,7 +62,6 @@ uint64_t Memory::FindPattern(const char* module, const char* Pattern[]) {
return 0; return 0;
} }
void* operator new(size_t size) { void* operator new(size_t size) {
return GlobalAlloc(GPTR, size); return GlobalAlloc(GPTR, size);
} }
+17 -11
View File
@@ -3,14 +3,14 @@
/// 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 CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
#include <cpp-httplib/httplib.h>
#include "Launcher.h"
#include "HttpAPI.h" #include "HttpAPI.h"
#include <iostream> #include "Launcher.h"
#include "Logger.h" #include "Logger.h"
#include <fstream>
#include <mutex>
#include <cmath> #include <cmath>
#include <cpp-httplib/httplib.h>
#include <fstream>
#include <iostream>
#include <mutex>
bool HTTP::isDownload = false; bool HTTP::isDownload = false;
std::atomic<httplib::Client*> CliRef = nullptr; std::atomic<httplib::Client*> CliRef = nullptr;
@@ -29,7 +29,8 @@ std::string HTTP::Get(const std::string &IP) {
if (res.error() == httplib::Error::Success) { if (res.error() == httplib::Error::Success) {
if (res->status == 200) { if (res->status == 200) {
Ret = res->body; Ret = res->body;
}else LOG(ERROR) << res->reason; } else
LOG(ERROR) << res->reason;
} else { } else {
if (isDownload) { if (isDownload) {
@@ -75,8 +76,10 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
} }
} }
CliRef.store(nullptr); CliRef.store(nullptr);
if(Ret.empty())return "-1"; if (Ret.empty())
else return Ret; return "-1";
else
return Ret;
} }
bool HTTP::ProgressBar(size_t c, size_t t) { bool HTTP::ProgressBar(size_t c, size_t t) {
@@ -88,8 +91,10 @@ bool HTTP::ProgressBar(size_t c, size_t t){
std::cout << round(double(c) / double(t) * 100); std::cout << round(double(c) / double(t) * 100);
std::cout << "% ] ["; std::cout << "% ] [";
int i; int i;
for (i = 0; i <= progress_bar_adv; i++)std::cout << "#"; for (i = 0; i <= progress_bar_adv; i++)
for (i = 0; i < 25 - progress_bar_adv; i++)std::cout << "."; std::cout << "#";
for (i = 0; i < 25 - progress_bar_adv; i++)
std::cout << ".";
std::cout << "]"; std::cout << "]";
} }
if (Launcher::Terminated()) { if (Launcher::Terminated()) {
@@ -109,7 +114,8 @@ bool HTTP::Download(const std::string &IP, const std::string &Path) {
std::string Ret = Get(IP); std::string Ret = Get(IP);
isDownload = false; isDownload = false;
if(Ret.empty())return false; if (Ret.empty())
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()) {
+6 -7
View File
@@ -3,10 +3,10 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include "Launcher.h"
#include "HttpAPI.h" #include "HttpAPI.h"
#include "Logger.h"
#include "Json.h" #include "Json.h"
#include "Launcher.h"
#include "Logger.h"
void UpdateKey(const std::string& newKey) { void UpdateKey(const std::string& newKey) {
if (!newKey.empty()) { if (!newKey.empty()) {
@@ -62,7 +62,8 @@ std::string Launcher::Login(const std::string& fields) {
PublicKey = d["public_key"].get<std::string>(); PublicKey = d["public_key"].get<std::string>();
} }
LOG(INFO) << "Authentication successful!"; LOG(INFO) << "Authentication successful!";
}else 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("private_key");
@@ -103,8 +104,6 @@ void Launcher::CheckKey() {
LOG(WARNING) << "Could not open saved key!"; LOG(WARNING) << "Could not open saved key!";
UpdateKey(""); UpdateKey("");
} }
}else UpdateKey(""); } else
UpdateKey("");
} }
+39 -24
View File
@@ -3,19 +3,18 @@
/// 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 <ws2tcpip.h>
#include <filesystem>
#include "Launcher.h" #include "Launcher.h"
#include "Server.h"
#include "Logger.h" #include "Logger.h"
#include "Server.h"
#include <atomic>
#include <cstring> #include <cstring>
#include <filesystem>
#include <fstream> #include <fstream>
#include <future>
#include <string> #include <string>
#include <thread> #include <thread>
#include <atomic>
#include <vector> #include <vector>
#include <future> #include <ws2tcpip.h>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::vector<std::string> Split(const std::string& String, const std::string& delimiter) { std::vector<std::string> Split(const std::string& String, const std::string& delimiter) {
@@ -24,10 +23,12 @@ std::vector<std::string> Split(const std::string& String, const std::string& del
std::string token, s = String; std::string token, s = String;
while ((pos = s.find(delimiter)) != std::string::npos) { while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos); token = s.substr(0, pos);
if(!token.empty())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())Val.push_back(s); if (!s.empty())
Val.push_back(s);
return Val; return Val;
} }
@@ -60,7 +61,8 @@ std::string Server::Auth() {
} }
TCPSend(LauncherInstance->getPublicKey()); TCPSend(LauncherInstance->getPublicKey());
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(); Res = TCPRcv();
if (Res.empty() || Res[0] != 'P') { if (Res.empty() || Res[0] != 'P') {
@@ -77,7 +79,8 @@ std::string Server::Auth() {
return ""; return "";
} }
TCPSend("SR"); TCPSend("SR");
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(); Res = TCPRcv();
@@ -97,8 +100,10 @@ std::string Server::Auth() {
} }
void Server::UpdateUl(bool D, const std::string& msg) { void Server::UpdateUl(bool D, const std::string& msg) {
if(D)UStatus = "UlDownloading Resource " + msg; if (D)
else UStatus = "UlLoading Resource " + msg; 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) {
@@ -120,7 +125,8 @@ char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) {
uint64_t Rcv = 0; uint64_t Rcv = 0;
do { do {
int Len = int(Size - Rcv); int Len = int(Size - Rcv);
if(Len > 1000000)Len = 1000000; if (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");
@@ -192,8 +198,8 @@ std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::stri
return ""; 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 /// omg yes very ugly my god but i was in a rush will revisit
std::string Ret(Size, 0); std::string Ret(Size, 0);
@@ -214,7 +220,8 @@ void Server::InvalidResource(const std::string& File) {
void Server::SyncResources() { void Server::SyncResources() {
std::string Ret = Auth(); std::string Ret = Auth();
if(Ret.empty())return; if (Ret.empty())
return;
LOG(INFO) << "Checking Resources..."; LOG(INFO) << "Checking Resources...";
CheckForDir(); CheckForDir();
@@ -231,8 +238,10 @@ void Server::SyncResources() {
t += name.substr(name.find_last_of('/') + 1) + ";"; t += name.substr(name.find_last_of('/') + 1) + ";";
} }
} }
if(t.empty())ModList = "-"; if (t.empty())
else ModList = t; ModList = "-";
else
ModList = t;
t.clear(); t.clear();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
@@ -241,19 +250,23 @@ void Server::SyncResources() {
InvalidResource(*FN); InvalidResource(*FN);
return; return;
} }
if (pos == std::string::npos)continue; if (pos == std::string::npos)
continue;
Amount++; Amount++;
} }
if(!FNames.empty())LOG(INFO) << "Syncing..."; if (!FNames.empty())
LOG(INFO) << "Syncing...";
SOCKET DSock = InitDSock(); SOCKET DSock = InitDSock();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
if (pos != std::string::npos) { if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos); a = "Resources" + FN->substr(pos);
} else continue; } else
continue;
Pos++; Pos++;
if (fs::exists(a)) { if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit))continue; if (!std::all_of(FS->begin(), FS->end(), isdigit))
continue;
if (fs::file_size(a) == std::stoull(*FS)) { if (fs::file_size(a) == std::stoull(*FS)) {
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/'))); UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/')));
std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::this_thread::sleep_for(std::chrono::milliseconds(50));
@@ -270,7 +283,8 @@ void Server::SyncResources() {
} }
WaitForConfirm(); WaitForConfirm();
continue; continue;
}else remove(a.c_str()); } else
remove(a.c_str());
} }
CheckForDir(); CheckForDir();
std::string FName = a.substr(a.find_last_of('/')); std::string FName = a.substr(a.find_last_of('/'));
@@ -288,7 +302,8 @@ void Server::SyncResources() {
Data = MultiDownload(DSock, std::stoull(*FS), Name); Data = MultiDownload(DSock, std::stoull(*FS), Name);
if(Terminate)break; if (Terminate)
break;
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName); UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + 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);
+38 -20
View File
@@ -5,15 +5,16 @@
#define WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN
#include "Compressor.h"
#include "Server.h" #include "Server.h"
#include "Compressor.h"
#include "Launcher.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 "Logger.h"
Server::Server(Launcher *Instance) : LauncherInstance(Instance) { Server::Server(Launcher* 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) {
@@ -72,7 +73,8 @@ void Server::StartUDP() {
} }
void Server::UDPSend(std::string Data) { void Server::UDPSend(std::string Data) {
if (ClientID == -1 || UDPSocket == -1)return; if (ClientID == -1 || UDPSocket == -1)
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;
@@ -80,7 +82,8 @@ void Server::UDPSend(std::string Data) {
std::string Packet = char(ClientID + 1) + std::string(":") + Data; std::string Packet = char(ClientID + 1) + std::string(":") + Data;
int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)UDPSockAddress.get(), int sendOk = sendto(UDPSocket, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)UDPSockAddress.get(),
sizeof(sockaddr_in)); sizeof(sockaddr_in));
if (sendOk == SOCKET_ERROR)LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError(); if (sendOk == SOCKET_ERROR)
LOG(ERROR) << "UDP Socket Error Code : " << GetSocketApiError();
} }
void Server::UDPParser(std::string Packet) { void Server::UDPParser(std::string Packet) {
@@ -95,9 +98,11 @@ void Server::UDPRcv() {
int clientLength = sizeof(FromServer); int clientLength = sizeof(FromServer);
ZeroMemory(&FromServer, clientLength); ZeroMemory(&FromServer, clientLength);
std::string Ret(10240, 0); std::string Ret(10240, 0);
if (UDPSocket == -1)return; if (UDPSocket == -1)
return;
int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength); int32_t Rcv = recvfrom(UDPSocket, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength);
if (Rcv == SOCKET_ERROR)return; if (Rcv == SOCKET_ERROR)
return;
UDPParser(Ret.substr(0, Rcv)); UDPParser(Ret.substr(0, Rcv));
} }
@@ -109,7 +114,8 @@ void Server::UDPClient() {
LauncherInstance->SendIPC("P" + std::to_string(ClientID), false); LauncherInstance->SendIPC("P" + std::to_string(ClientID), false);
TCPSend("H"); TCPSend("H");
UDPSend("p"); UDPSend("p");
while (!Terminate)UDPRcv(); while (!Terminate)
UDPRcv();
KillSocket(UDPSocket); KillSocket(UDPSocket);
} }
@@ -127,9 +133,12 @@ void Server::Connect(const std::string &Data) {
std::string port = Data.substr(Data.find(':') + 1); std::string port = Data.substr(Data.find(':') + 1);
bool ValidPort = std::all_of(port.begin(), port.end(), ::isdigit); bool ValidPort = std::all_of(port.begin(), port.end(), ::isdigit);
if (IP.find('.') == -1 || !ValidPort) { if (IP.find('.') == -1 || !ValidPort) {
if (IP == "DNS") UStatus = "Connection Failed! (DNS Lookup Failed)"; if (IP == "DNS")
else if (!ValidPort) UStatus = "Connection Failed! (Invalid Port)"; UStatus = "Connection Failed! (DNS Lookup Failed)";
else UStatus = "Connection Failed! (WSA failed to start)"; else if (!ValidPort)
UStatus = "Connection Failed! (Invalid Port)";
else
UStatus = "Connection Failed! (WSA failed to start)";
ModList = "-"; ModList = "-";
Terminate.store(true); Terminate.store(true);
return; return;
@@ -175,16 +184,22 @@ std::string Server::GetSocketApiError() {
} }
void Server::ServerSend(std::string Data, bool Rel) { void Server::ServerSend(std::string Data, bool Rel) {
if (Terminate || Data.empty())return; if (Terminate || Data.empty())
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)
C = Data.at(0);
bool Ack = C == 'O' || C == 'T'; bool Ack = C == 'O' || C == 'T';
if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')Rel = true; if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')
Rel = true;
if (Ack || Rel) { if (Ack || Rel) {
if (Ack || DLen > 1000)SendLarge(Data); if (Ack || DLen > 1000)
else TCPSend(Data); SendLarge(Data);
} else UDPSend(Data); else
TCPSend(Data);
} else
UDPSend(Data);
} }
void Server::PingLoop() { void Server::PingLoop() {
@@ -232,7 +247,8 @@ const std::string &Server::getUIStatus() {
} }
std::string Server::GetAddress(const std::string& Data) { std::string Server::GetAddress(const std::string& Data) {
if (Data.find_first_not_of("0123456789.") == -1)return Data; if (Data.find_first_not_of("0123456789.") == -1)
return Data;
hostent* host; hostent* host;
host = gethostbyname(Data.c_str()); host = gethostbyname(Data.c_str());
if (!host) { if (!host) {
@@ -244,7 +260,8 @@ std::string Server::GetAddress(const std::string &Data) {
} }
int Server::KillSocket(uint64_t Dead) { int Server::KillSocket(uint64_t Dead) {
if (Dead == (SOCKET) -1)return 0; if (Dead == (SOCKET)-1)
return 0;
shutdown(Dead, SD_BOTH); shutdown(Dead, SD_BOTH);
return closesocket(Dead); return closesocket(Dead);
} }
@@ -346,6 +363,7 @@ std::string Server::TCPRcv() {
Ret = Zlib::DeComp(Ret.substr(4)); Ret = Zlib::DeComp(Ret.substr(4));
} }
if (Ret[0] == 'E')UUl(Ret.substr(1)); if (Ret[0] == 'E')
UUl(Ret.substr(1));
return Ret; return Ret;
} }
+29 -15
View File
@@ -3,10 +3,10 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info. /// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
/// ///
#include "Launcher.h"
#include "HttpAPI.h" #include "HttpAPI.h"
#include "Logger.h"
#include "Json.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::string token;
@@ -20,13 +20,19 @@ VersionParser::VersionParser(const std::string &from_string) {
std::strong_ordering VersionParser::operator<=>(const VersionParser& rhs) const noexcept { std::strong_ordering VersionParser::operator<=>(const VersionParser& rhs) const noexcept {
size_t const fields = std::min(data.size(), rhs.data.size()); size_t const fields = std::min(data.size(), rhs.data.size());
for (size_t i = 0; i != fields; ++i) { for (size_t i = 0; i != fields; ++i) {
if(data[i] == rhs.data[i]) continue; if (data[i] == rhs.data[i])
else if(data[i] < rhs.data[i]) return std::strong_ordering::less; continue;
else return std::strong_ordering::greater; 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; if (data.size() == rhs.data.size())
else if(data.size() > rhs.data.size()) return std::strong_ordering::greater; return std::strong_ordering::equal;
else return std::strong_ordering::less; 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 {
@@ -47,11 +53,13 @@ void Launcher::UpdateCheck() {
} }
if (fallback) { if (fallback) {
link = "https://backup1.beammp.com/builds/launcher?download=true"; link = "https://backup1.beammp.com/builds/launcher?download=true";
}else 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"); 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; std::string RemoteVer;
for (char& c : HTTP) { for (char& c : HTTP) {
if (std::isdigit(c) || c == '.') { if (std::isdigit(c) || c == '.') {
@@ -77,7 +85,8 @@ void Launcher::UpdateCheck() {
} }
} }
Relaunch(); 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) { size_t DirCount(const std::filesystem::path& path) {
@@ -99,16 +108,19 @@ void Launcher::ResetMods() {
void Launcher::EnableMP() { void Launcher::EnableMP() {
std::string File(BeamUserPath + "mods\\db.json"); std::string File(BeamUserPath + "mods\\db.json");
if(!fs::exists(File))return; if (!fs::exists(File))
return;
auto Size = fs::file_size(File); auto Size = fs::file_size(File);
if(Size < 2)return; if (Size < 2)
return;
std::ifstream db(File); std::ifstream db(File);
if (db.is_open()) { if (db.is_open()) {
std::string Data(Size, 0); std::string Data(Size, 0);
db.read(&Data[0], std::streamsize(Size)); db.read(&Data[0], std::streamsize(Size));
db.close(); db.close();
Json d = Json::parse(Data, nullptr, false); Json d = Json::parse(Data, nullptr, false);
if(Data.at(0) != '{' || d.is_discarded())return; if (Data.at(0) != '{' || d.is_discarded())
return;
if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) { if (!d["mods"].is_null() && !d["mods"]["multiplayerbeammp"].is_null()) {
d["mods"]["multiplayerbeammp"]["active"] = true; d["mods"]["multiplayerbeammp"]["active"] = true;
std::ofstream ofs(File); std::ofstream ofs(File);
@@ -127,5 +139,7 @@ void Launcher::SetupMOD() {
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("https://backend.beammp.com/builds/client?download=true"
"&pk=" + PublicKey + "&branch=" + TargetBuild, MPUserPath + "\\BeamMP.zip"); "&pk="
+ PublicKey + "&branch=" + TargetBuild,
MPUserPath + "\\BeamMP.zip");
} }
+5 -6
View File
@@ -7,10 +7,10 @@
#include <set> #include <set>
#include <wx/wxprec.h> #include <wx/wxprec.h>
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include <wx/wx.h> #include "gifs.h"
#include <wx/animate.h> #include <wx/animate.h>
#include <wx/mstream.h> #include <wx/mstream.h>
#include "gifs.h" #include <wx/wx.h>
#endif #endif
class MyApp : public wxApp { class MyApp : public wxApp {
@@ -20,6 +20,7 @@ public:
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);
@@ -64,9 +65,8 @@ MyFrame::MyFrame()
auto* m_ani = new wxAnimationCtrl(this, wxID_ANY); auto* m_ani = new wxAnimationCtrl(this, wxID_ANY);
wxMemoryInputStream stream(gif::Logo, sizeof(gif::Logo)); wxMemoryInputStream stream(gif::Logo, sizeof(gif::Logo));
if (m_ani->Load(stream)) m_ani->Play(); if (m_ani->Load(stream))
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);
@@ -83,7 +83,6 @@ 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
@@ -5,8 +5,7 @@
#include "gifs.h" #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, 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x80, 0x00, 0x80, 0x00, 0xf6, 0x00,
0x00, 0x0f, 0x37, 0x57, 0x17, 0x27, 0x37, 0x17, 0x27, 0x3f, 0x0f, 0x37, 0x00, 0x0f, 0x37, 0x57, 0x17, 0x27, 0x37, 0x17, 0x27, 0x3f, 0x0f, 0x37,
0x5f, 0x00, 0x77, 0xef, 0x07, 0x4f, 0x8f, 0x17, 0x2f, 0x47, 0x0f, 0x3f, 0x5f, 0x00, 0x77, 0xef, 0x07, 0x4f, 0x8f, 0x17, 0x2f, 0x47, 0x0f, 0x3f,