clang format

This commit is contained in:
Anonymous275
2022-07-26 11:43:45 +03:00
parent b26fb43746
commit 3c96bb3959
34 changed files with 1912 additions and 1832 deletions

View File

@@ -8,45 +8,45 @@
#define Biggest 30000
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.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(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;
return Ret;
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.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(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;
return Ret;
}
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.avail_out = Biggest;
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;
return Ret;
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.avail_out = Biggest;
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;
return Ret;
}

View File

@@ -4,127 +4,124 @@
///
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "HttpAPI.h"
#include "Launcher.h"
#include "Logger.h"
#include <cmath>
#include <cpp-httplib/httplib.h>
#include <cmath>
#include <fstream>
#include <iostream>
#include <mutex>
#include "Launcher.h"
#include "Logger.h"
bool HTTP::isDownload = false;
bool HTTP::isDownload = false;
std::atomic<httplib::Client*> CliRef = nullptr;
std::string HTTP::Get(const std::string& IP) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
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));
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
std::string Ret;
httplib::Client cli(IP.substr(0, pos));
CliRef.store(&cli);
cli.set_connection_timeout(std::chrono::seconds(5));
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
std::string Ret;
if (res.error() == httplib::Error::Success) {
if (res->status == 200) {
Ret = res->body;
} else
LOG(ERROR) << res->reason;
if (res.error() == httplib::Error::Success) {
if (res->status == 200) {
Ret = res->body;
} else LOG(ERROR) << res->reason;
} else {
if (isDownload) {
std::cout << "\n";
}
LOG(ERROR) << "HTTP Get failed on " << httplib::to_string(res.error());
}
CliRef.store(nullptr);
return Ret;
} else {
if (isDownload) {
std::cout << "\n";
}
LOG(ERROR) << "HTTP Get failed on " << httplib::to_string(res.error());
}
CliRef.store(nullptr);
return Ret;
}
std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
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;
httplib::Client cli(IP.substr(0, pos));
CliRef.store(&cli);
cli.set_connection_timeout(std::chrono::seconds(5));
std::string Ret;
if (!Fields.empty()) {
httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json");
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) {
LOG(ERROR) << res->reason;
}
Ret = res->body;
} 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->status != 200) {
LOG(ERROR) << res->reason;
}
Ret = res->body;
} else {
LOG(ERROR) << "HTTP Post failed on " << httplib::to_string(res.error());
}
}
CliRef.store(nullptr);
if (Ret.empty())
return "-1";
else
return Ret;
if (res.error() == httplib::Error::Success) {
if (res->status != 200) {
LOG(ERROR) << res->reason;
}
Ret = res->body;
} 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->status != 200) {
LOG(ERROR) << res->reason;
}
Ret = res->body;
} else {
LOG(ERROR) << "HTTP Post failed on "
<< httplib::to_string(res.error());
}
}
CliRef.store(nullptr);
if (Ret.empty()) return "-1";
else return Ret;
}
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";
std::cout << "Progress: [ ";
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 << ".";
std::cout << "]";
}
if (Launcher::Terminated()) {
CliRef.load()->stop();
std::cout << '\n';
isDownload = false;
throw ShutdownException("Interrupted");
}
return true;
if (isDownload) {
static double progress_bar_adv;
progress_bar_adv = round(double(c) / double(t) * 25);
std::cout << "\r";
std::cout << "Progress: [ ";
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 << ".";
std::cout << "]";
}
if (Launcher::Terminated()) {
CliRef.load()->stop();
std::cout << '\n';
isDownload = false;
throw ShutdownException("Interrupted");
}
return true;
}
bool HTTP::Download(const std::string& IP, const std::string& Path) {
static std::mutex Lock;
std::scoped_lock Guard(Lock);
static std::mutex Lock;
std::scoped_lock Guard(Lock);
isDownload = true;
std::string Ret = Get(IP);
isDownload = false;
isDownload = true;
std::string Ret = Get(IP);
isDownload = false;
if (Ret.empty())
return false;
std::cout << "\n";
std::ofstream File(Path, std::ios::binary);
if (File.is_open()) {
File << Ret;
File.close();
LOG(INFO) << "Download complete!";
} else {
LOG(ERROR) << "Failed to open file directory: " << Path;
return false;
}
return true;
if (Ret.empty()) return false;
std::cout << "\n";
std::ofstream File(Path, std::ios::binary);
if (File.is_open()) {
File << Ret;
File.close();
LOG(INFO) << "Download complete!";
} else {
LOG(ERROR) << "Failed to open file directory: " << Path;
return false;
}
return true;
}

View File

@@ -9,18 +9,18 @@
#include "Logger.h"
void UpdateKey(const std::string& newKey) {
if (!newKey.empty()) {
std::ofstream Key("key");
if (Key.is_open()) {
Key << newKey;
Key.close();
} else {
LOG(FATAL) << "Cannot write to disk!";
throw ShutdownException("Fatal Error");
}
} else if (fs::exists("key")) {
remove("key");
}
if (!newKey.empty()) {
std::ofstream Key("key");
if (Key.is_open()) {
Key << newKey;
Key.close();
} else {
LOG(FATAL) << "Cannot write to disk!";
throw ShutdownException("Fatal Error");
}
} else if (fs::exists("key")) {
remove("key");
}
}
/// "username":"value","password":"value"
@@ -28,82 +28,85 @@ void UpdateKey(const std::string& newKey) {
/// "pk":"private_key"
std::string GetFail(const std::string& R) {
std::string DRet = R"({"success":false,"message":)";
DRet += "\"" + R + "\"}";
LOG(ERROR) << R;
return DRet;
std::string DRet = R"({"success":false,"message":)";
DRet += "\"" + R + "\"}";
LOG(ERROR) << R;
return DRet;
}
std::string Launcher::Login(const std::string& fields) {
if (fields == "LO") {
LoginAuth = false;
UpdateKey("");
return "";
}
LOG(INFO) << "Attempting to authenticate...";
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
Json d = Json::parse(Buffer, nullptr, false);
if (fields == "LO") {
LoginAuth = false;
UpdateKey("");
return "";
}
LOG(INFO) << "Attempting to authenticate...";
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
Json d = Json::parse(Buffer, nullptr, false);
if (Buffer == "-1") {
return GetFail("Failed to communicate with the auth system!");
}
if (Buffer == "-1") {
return GetFail("Failed to communicate with the auth system!");
}
if (Buffer.at(0) != '{' || d.is_discarded()) {
LOG(ERROR) << Buffer;
return GetFail("Invalid answer from authentication servers, please try again later!");
}
if (Buffer.at(0) != '{' || d.is_discarded()) {
LOG(ERROR) << Buffer;
return GetFail(
"Invalid answer from authentication servers, please try again "
"later!");
}
if (!d["success"].is_null() && d["success"].get<bool>()) {
LoginAuth = true;
if (!d["private_key"].is_null()) {
UpdateKey(d["private_key"].get<std::string>());
}
if (!d["public_key"].is_null()) {
PublicKey = d["public_key"].get<std::string>();
}
LOG(INFO) << "Authentication successful!";
} else
LOG(WARNING) << "Authentication failed!";
if (!d["success"].is_null() && d["success"].get<bool>()) {
LoginAuth = true;
if (!d["private_key"].is_null()) {
UpdateKey(d["private_key"].get<std::string>());
}
if (!d["public_key"].is_null()) {
PublicKey = d["public_key"].get<std::string>();
}
LOG(INFO) << "Authentication successful!";
} else LOG(WARNING) << "Authentication failed!";
if (!d["message"].is_null()) {
d.erase("private_key");
d.erase("public_key");
return d.dump();
}
return GetFail("Invalid message parsing!");
if (!d["message"].is_null()) {
d.erase("private_key");
d.erase("public_key");
return d.dump();
}
return GetFail("Invalid message parsing!");
}
void Launcher::CheckKey() {
if (fs::exists("key") && fs::file_size("key") < 100) {
std::ifstream Key("key");
if (Key.is_open()) {
auto Size = fs::file_size("key");
std::string Buffer(Size, 0);
Key.read(&Buffer[0], std::streamsize(Size));
Key.close();
if (fs::exists("key") && fs::file_size("key") < 100) {
std::ifstream Key("key");
if (Key.is_open()) {
auto Size = fs::file_size("key");
std::string Buffer(Size, 0);
Key.read(&Buffer[0], std::streamsize(Size));
Key.close();
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
Buffer = HTTP::Post("https://auth.beammp.com/userlogin",
R"({"pk":")" + Buffer + "\"}");
Json d = Json::parse(Buffer, nullptr, false);
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
LOG(DEBUG) << Buffer;
LOG(FATAL) << "Invalid answer from authentication servers, please try again later!";
throw ShutdownException("Fatal Error");
}
if (d["success"].get<bool>()) {
LoginAuth = true;
UpdateKey(d["private_key"].get<std::string>());
PublicKey = d["public_key"].get<std::string>();
UserRole = d["role"].get<std::string>();
LOG(INFO) << "Auto-Authentication was successful";
} else {
LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!";
UpdateKey("");
}
} else {
LOG(WARNING) << "Could not open saved key!";
Json d = Json::parse(Buffer, nullptr, false);
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
LOG(DEBUG) << Buffer;
LOG(FATAL)
<< "Invalid answer from authentication servers, please try "
"again later!";
throw ShutdownException("Fatal Error");
}
if (d["success"].get<bool>()) {
LoginAuth = true;
UpdateKey(d["private_key"].get<std::string>());
PublicKey = d["public_key"].get<std::string>();
UserRole = d["role"].get<std::string>();
LOG(INFO) << "Auto-Authentication was successful";
} else {
LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!";
UpdateKey("");
}
} else
UpdateKey("");
}
} else {
LOG(WARNING) << "Could not open saved key!";
UpdateKey("");
}
} else UpdateKey("");
}

View File

@@ -3,9 +3,7 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
///
#include "Launcher.h"
#include "Logger.h"
#include "Server.h"
#include <ws2tcpip.h>
#include <atomic>
#include <cstring>
#include <filesystem>
@@ -14,319 +12,318 @@
#include <string>
#include <thread>
#include <vector>
#include <ws2tcpip.h>
#include "Launcher.h"
#include "Logger.h"
#include "Server.h"
namespace fs = std::filesystem;
std::vector<std::string> Split(const std::string& String, const std::string& delimiter) {
std::vector<std::string> Val;
size_t pos;
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);
s.erase(0, pos + delimiter.length());
}
if (!s.empty())
Val.push_back(s);
return Val;
std::vector<std::string> Split(const std::string& String,
const std::string& delimiter) {
std::vector<std::string> Val;
size_t pos;
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);
s.erase(0, pos + delimiter.length());
}
if (!s.empty()) Val.push_back(s);
return Val;
}
void CheckForDir() {
if (!fs::exists("Resources")) {
_wmkdir(L"Resources");
}
if (!fs::exists("Resources")) {
_wmkdir(L"Resources");
}
}
void Server::WaitForConfirm() {
while (!Terminate && !ModLoaded) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
ModLoaded = false;
while (!Terminate && !ModLoaded) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
ModLoaded = false;
}
void Server::Abort() {
Terminate = true;
LOG(INFO) << "Terminated!";
Terminate = true;
LOG(INFO) << "Terminated!";
}
std::string Server::Auth() {
TCPSend("VC" + LauncherInstance->getVersion());
TCPSend("VC" + LauncherInstance->getVersion());
auto Res = TCPRcv();
auto Res = TCPRcv();
if (Res.empty() || Res[0] == 'E') {
Abort();
return "";
}
if (Res.empty() || Res[0] == 'E') {
Abort();
return "";
}
TCPSend(LauncherInstance->getPublicKey());
if (Terminate)
return "";
TCPSend(LauncherInstance->getPublicKey());
if (Terminate) return "";
Res = TCPRcv();
if (Res.empty() || Res[0] != 'P') {
Abort();
return "";
}
Res = TCPRcv();
if (Res.empty() || Res[0] != 'P') {
Abort();
return "";
}
Res = Res.substr(1);
if (std::all_of(Res.begin(), Res.end(), isdigit)) {
ClientID = std::stoi(Res);
} else {
Abort();
UUl("Authentication failed!");
return "";
}
TCPSend("SR");
if (Terminate)
return "";
Res = Res.substr(1);
if (std::all_of(Res.begin(), Res.end(), isdigit)) {
ClientID = std::stoi(Res);
} else {
Abort();
UUl("Authentication failed!");
return "";
}
TCPSend("SR");
if (Terminate) return "";
Res = TCPRcv();
Res = TCPRcv();
if (Res[0] == 'E') {
Abort();
return "";
}
if (Res[0] == 'E') {
Abort();
return "";
}
if (Res.empty() || Res == "-") {
LOG(INFO) << "Didn't Receive any mods...";
ModList = "-";
TCPSend("Done");
LOG(INFO) << "Done!";
return "";
}
return Res;
if (Res.empty() || Res == "-") {
LOG(INFO) << "Didn't Receive any mods...";
ModList = "-";
TCPSend("Done");
LOG(INFO) << "Done!";
return "";
}
return Res;
}
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) {
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);
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);
}
char* Server::TCPRcvRaw(uint64_t Sock, uint64_t& GRcv, uint64_t Size) {
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;
int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
if (Temp < 1) {
UUl("Socket Closed Code 1");
KillSocket(Sock);
Terminate = true;
delete[] File;
return nullptr;
}
Rcv += Temp;
GRcv += Temp;
} while (Rcv < Size && !Terminate);
return File;
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;
int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
if (Temp < 1) {
UUl("Socket Closed Code 1");
KillSocket(Sock);
Terminate = true;
delete[] File;
return nullptr;
}
Rcv += Temp;
GRcv += Temp;
} while (Rcv < Size && !Terminate);
return File;
}
void Server::MultiKill(uint64_t Sock) {
KillSocket(TCPSocket);
KillSocket(Sock);
Terminate = true;
KillSocket(TCPSocket);
KillSocket(Sock);
Terminate = true;
}
uint64_t Server::InitDSock() {
SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN ServerAddr;
if (DSock < 1) {
KillSocket(DSock);
Terminate = true;
return 0;
}
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) {
KillSocket(DSock);
Terminate = true;
return 0;
}
char Code[2] = { 'D', char(ClientID) };
if (send(DSock, Code, 2, 0) != 2) {
KillSocket(DSock);
Terminate = true;
return 0;
}
return DSock;
SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN ServerAddr;
if (DSock < 1) {
KillSocket(DSock);
Terminate = true;
return 0;
}
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) {
KillSocket(DSock);
Terminate = true;
return 0;
}
char Code[2] = {'D', char(ClientID)};
if (send(DSock, Code, 2, 0) != 2) {
KillSocket(DSock);
Terminate = true;
return 0;
}
return DSock;
}
std::string Server::MultiDownload(uint64_t DSock, uint64_t Size, const std::string& Name) {
std::string Server::MultiDownload(uint64_t DSock, uint64_t Size,
const std::string& Name) {
uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize;
uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize;
std::thread Au(&Server::AsyncUpdate, this, std::ref(GRcv), Size, Name);
std::thread Au(&Server::AsyncUpdate, this, std::ref(GRcv), Size, Name);
std::packaged_task<char*()> task(
[&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); });
std::future<char*> f1 = task.get_future();
std::thread Dt(std::move(task));
Dt.detach();
std::packaged_task<char*()> task([&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); });
std::future<char*> 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) {
MultiKill(DSock);
return "";
}
if (!DData) {
MultiKill(DSock);
return "";
}
f1.wait();
char* MData = f1.get();
f1.wait();
char* MData = f1.get();
if (!MData) {
MultiKill(DSock);
return "";
}
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;
return Ret;
}
void Server::InvalidResource(const std::string& File) {
UUl("Invalid mod \"" + File + "\"");
LOG(WARNING) << "The server tried to sync \"" << File << "\" that is not a .zip file!";
Terminate = true;
UUl("Invalid mod \"" + File + "\"");
LOG(WARNING) << "The server tried to sync \"" << File
<< "\" that is not a .zip file!";
Terminate = true;
}
void Server::SyncResources() {
std::string Ret = Auth();
if (Ret.empty())
return;
LOG(INFO) << "Checking Resources...";
CheckForDir();
std::string Ret = Auth();
if (Ret.empty()) return;
LOG(INFO) << "Checking Resources...";
CheckForDir();
std::vector<std::string> list = Split(Ret, ";");
std::vector<std::string> FNames(list.begin(), list.begin() + (list.size() / 2));
std::vector<std::string> FSizes(list.begin() + (list.size() / 2), list.end());
list.clear();
Ret.clear();
std::vector<std::string> list = Split(Ret, ";");
std::vector<std::string> FNames(list.begin(),
list.begin() + (list.size() / 2));
std::vector<std::string> FSizes(list.begin() + (list.size() / 2),
list.end());
list.clear();
Ret.clear();
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;
t.clear();
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)
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;
t.clear();
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;
Amount++;
}
if (!FNames.empty()) LOG(INFO) << "Syncing...";
SOCKET DSock = InitDSock();
for (auto FN = FNames.begin(), FS = FSizes.begin();
FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/');
if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos);
} else continue;
Pos++;
if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit)) continue;
if (fs::file_size(a) == std::stoull(*FS)) {
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) +
": " + a.substr(a.find_last_of('/')));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
try {
if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath());
}
fs::copy_file(a,
LauncherInstance->getMPUserPath() +
a.substr(a.find_last_of('/')),
fs::copy_options::overwrite_existing);
} catch (std::exception& e) {
LOG(ERROR) << "Failed copy to the mods folder! " << e.what();
Terminate = true;
continue;
}
WaitForConfirm();
continue;
Amount++;
}
if (!FNames.empty())
LOG(INFO) << "Syncing...";
SOCKET DSock = InitDSock();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/');
if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos);
} else
continue;
Pos++;
if (fs::exists(a)) {
if (!std::all_of(FS->begin(), FS->end(), isdigit))
continue;
if (fs::file_size(a) == std::stoull(*FS)) {
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/')));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
try {
if (!fs::exists(LauncherInstance->getMPUserPath())) {
fs::create_directories(LauncherInstance->getMPUserPath());
}
fs::copy_file(a, LauncherInstance->getMPUserPath() + a.substr(a.find_last_of('/')),
fs::copy_options::overwrite_existing);
} catch (std::exception& e) {
LOG(ERROR) << "Failed copy to the mods folder! " << e.what();
Terminate = true;
continue;
}
WaitForConfirm();
continue;
} else
remove(a.c_str());
}
CheckForDir();
std::string FName = a.substr(a.find_last_of('/'));
do {
TCPSend("f" + *FN);
} else remove(a.c_str());
}
CheckForDir();
std::string FName = a.substr(a.find_last_of('/'));
do {
TCPSend("f" + *FN);
std::string Data = TCPRcv();
if (Data == "CO" || Terminate) {
Terminate = true;
UUl("Server cannot find " + FName);
break;
}
std::string Data = TCPRcv();
if (Data == "CO" || Terminate) {
Terminate = true;
UUl("Server cannot find " + FName);
break;
}
std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
std::string Name =
std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
Data = MultiDownload(DSock, std::stoull(*FS), Name);
Data = MultiDownload(DSock, std::stoull(*FS), Name);
if (Terminate)
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()) {
LFS.write(&Data[0], std::streamsize(Data.size()));
LFS.close();
}
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()) {
LFS.write(&Data[0], std::streamsize(Data.size()));
LFS.close();
}
} 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);
}
WaitForConfirm();
}
KillSocket(DSock);
if (!Terminate) {
TCPSend("Done");
LOG(INFO) << "Done!";
} else {
UStatus = "start";
LOG(INFO) << "Connection Terminated!";
}
} 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);
}
WaitForConfirm();
}
KillSocket(DSock);
if (!Terminate) {
TCPSend("Done");
LOG(INFO) << "Done!";
} else {
UStatus = "start";
LOG(INFO) << "Connection Terminated!";
}
}

View File

@@ -6,364 +6,345 @@
#define WIN32_LEAN_AND_MEAN
#include "Server.h"
#include "Compressor.h"
#include "Launcher.h"
#include "Logger.h"
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include "Compressor.h"
#include "Launcher.h"
#include "Logger.h"
Server::Server(Launcher* Instance)
: LauncherInstance(Instance) {
WSADATA wsaData;
int iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes != 0) {
LOG(ERROR) << "WSAStartup failed with error: " << iRes;
}
UDPSockAddress = std::make_unique<sockaddr_in>();
Server::Server(Launcher* Instance) : LauncherInstance(Instance) {
WSADATA wsaData;
int iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes != 0) {
LOG(ERROR) << "WSAStartup failed with error: " << iRes;
}
UDPSockAddress = std::make_unique<sockaddr_in>();
}
Server::~Server() {
Close();
WSACleanup();
Close();
WSACleanup();
}
void Server::TCPClientMain() {
SOCKADDR_IN ServerAddr;
TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPSocket == -1) {
LOG(ERROR) << "Socket failed! Error code: " << GetSocketApiError();
return;
}
const char optval = 0;
int status = ::setsockopt(TCPSocket, SOL_SOCKET, SO_DONTLINGER, &optval, sizeof(optval));
if (status < 0) {
LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError();
}
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));
if (status != 0) {
UStatus = "Connection Failed!";
LOG(ERROR) << "Connect failed! Error code: " << GetSocketApiError();
Terminate.store(true);
return;
}
SOCKADDR_IN ServerAddr;
TCPSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPSocket == -1) {
LOG(ERROR) << "Socket failed! Error code: " << GetSocketApiError();
return;
}
const char optval = 0;
int status = ::setsockopt(TCPSocket, SOL_SOCKET, SO_DONTLINGER, &optval,
sizeof(optval));
if (status < 0) {
LOG(INFO) << "Failed to set DONTLINGER: " << GetSocketApiError();
}
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));
if (status != 0) {
UStatus = "Connection Failed!";
LOG(ERROR) << "Connect failed! Error code: " << GetSocketApiError();
Terminate.store(true);
return;
}
char Code = 'C';
if (send(TCPSocket, &Code, 1, 0) != 1) {
Terminate.store(true);
return;
}
LOG(INFO) << "Connected!";
SyncResources();
while (!Terminate.load()) {
ServerParser(TCPRcv());
}
LauncherInstance->SendIPC("T", false);
KillSocket(TCPSocket);
char Code = 'C';
if (send(TCPSocket, &Code, 1, 0) != 1) {
Terminate.store(true);
return;
}
LOG(INFO) << "Connected!";
SyncResources();
while (!Terminate.load()) {
ServerParser(TCPRcv());
}
LauncherInstance->SendIPC("T", false);
KillSocket(TCPSocket);
}
void Server::StartUDP() {
if (TCPConnection.joinable() && !UDPConnection.joinable()) {
LOG(INFO) << "Connecting UDP";
UDPConnection = std::thread(&Server::UDPMain, this);
}
if (TCPConnection.joinable() && !UDPConnection.joinable()) {
LOG(INFO) << "Connecting UDP";
UDPConnection = std::thread(&Server::UDPMain, this);
}
}
void Server::UDPSend(std::string Data) {
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();
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();
}
void Server::UDPParser(std::string Packet) {
if (Packet.substr(0, 4) == "ABG:") {
Packet = Zlib::DeComp(Packet.substr(4));
}
ServerParser(Packet);
if (Packet.substr(0, 4) == "ABG:") {
Packet = Zlib::DeComp(Packet.substr(4));
}
ServerParser(Packet);
}
void Server::UDPRcv() {
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;
UDPParser(Ret.substr(0, Rcv));
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;
UDPParser(Ret.substr(0, Rcv));
}
void Server::UDPClient() {
UDPSockAddress->sin_family = AF_INET;
UDPSockAddress->sin_port = htons(Port);
inet_pton(AF_INET, IP.c_str(), &UDPSockAddress->sin_addr);
UDPSocket = socket(AF_INET, SOCK_DGRAM, 0);
LauncherInstance->SendIPC("P" + std::to_string(ClientID), false);
TCPSend("H");
UDPSend("p");
while (!Terminate)
UDPRcv();
KillSocket(UDPSocket);
UDPSockAddress->sin_family = AF_INET;
UDPSockAddress->sin_port = htons(Port);
inet_pton(AF_INET, IP.c_str(), &UDPSockAddress->sin_addr);
UDPSocket = socket(AF_INET, SOCK_DGRAM, 0);
LauncherInstance->SendIPC("P" + std::to_string(ClientID), false);
TCPSend("H");
UDPSend("p");
while (!Terminate) UDPRcv();
KillSocket(UDPSocket);
}
void Server::UDPMain() {
AutoPing = std::thread(&Server::PingLoop, this);
UDPClient();
Terminate = true;
LOG(INFO) << "Connection terminated";
AutoPing = std::thread(&Server::PingLoop, this);
UDPClient();
Terminate = true;
LOG(INFO) << "Connection terminated";
}
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)";
ModList = "-";
Terminate.store(true);
return;
}
Port = std::stoi(port);
LauncherInstance->CheckKey();
UStatus = "Loading...";
Ping = -1;
TCPConnection = std::thread(&Server::TCPClientMain, this);
LOG(INFO) << "Connecting to server";
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)";
ModList = "-";
Terminate.store(true);
return;
}
Port = std::stoi(port);
LauncherInstance->CheckKey();
UStatus = "Loading...";
Ping = -1;
TCPConnection = std::thread(&Server::TCPClientMain, this);
LOG(INFO) << "Connecting to server";
}
void Server::SendLarge(std::string Data) {
if (Data.length() > 400) {
std::string CMP(Zlib::Comp(Data));
Data = "ABG:" + CMP;
}
TCPSend(Data);
if (Data.length() > 400) {
std::string CMP(Zlib::Comp(Data));
Data = "ABG:" + CMP;
}
TCPSend(Data);
}
std::string Server::GetSocketApiError() {
// This will provide us with the error code and an error message, all in one.
// The resulting format is "<CODE> - <MESSAGE>"
int err;
char msgbuf[256];
msgbuf[0] = '\0';
// This will provide us with the error code and an error message, all in one.
// The resulting format is "<CODE> - <MESSAGE>"
int err;
char msgbuf[256];
msgbuf[0] = '\0';
err = WSAGetLastError();
err = WSAGetLastError();
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf,
sizeof(msgbuf),
nullptr);
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf, sizeof(msgbuf), nullptr);
if (*msgbuf) {
return std::to_string(WSAGetLastError()) + " - " + std::string(msgbuf);
} else {
return std::to_string(WSAGetLastError());
}
if (*msgbuf) {
return std::to_string(WSAGetLastError()) + " - " + std::string(msgbuf);
} else {
return std::to_string(WSAGetLastError());
}
}
void Server::ServerSend(std::string Data, bool Rel) {
if (Terminate || Data.empty())
return;
char C = 0;
int DLen = int(Data.length());
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 (Ack || Rel) {
if (Ack || DLen > 1000)
SendLarge(Data);
else
TCPSend(Data);
} else
UDPSend(Data);
if (Terminate || Data.empty()) return;
char C = 0;
int DLen = int(Data.length());
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 (Ack || Rel) {
if (Ack || DLen > 1000) SendLarge(Data);
else TCPSend(Data);
} else UDPSend(Data);
}
void Server::PingLoop() {
while (!Terminate) {
ServerSend("p", false);
PingStart = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
while (!Terminate) {
ServerSend("p", false);
PingStart = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Server::Close() {
Terminate.store(true);
KillSocket(TCPSocket);
KillSocket(UDPSocket);
Ping = -1;
if (TCPConnection.joinable()) {
TCPConnection.join();
}
if (UDPConnection.joinable()) {
UDPConnection.join();
}
if (AutoPing.joinable()) {
AutoPing.join();
}
Terminate.store(true);
KillSocket(TCPSocket);
KillSocket(UDPSocket);
Ping = -1;
if (TCPConnection.joinable()) {
TCPConnection.join();
}
if (UDPConnection.joinable()) {
UDPConnection.join();
}
if (AutoPing.joinable()) {
AutoPing.join();
}
}
const std::string& Server::getMap() {
return MStatus;
return MStatus;
}
bool Server::Terminated() {
return Terminate;
return Terminate;
}
const std::string& Server::getModList() {
return ModList;
return ModList;
}
int Server::getPing() const {
return Ping;
return Ping;
}
const std::string& Server::getUIStatus() {
return UStatus;
return UStatus;
}
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));
return Ret;
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));
return Ret;
}
int Server::KillSocket(uint64_t Dead) {
if (Dead == (SOCKET)-1)
return 0;
shutdown(Dead, SD_BOTH);
return closesocket(Dead);
if (Dead == (SOCKET)-1) return 0;
shutdown(Dead, SD_BOTH);
return closesocket(Dead);
}
void Server::setModLoaded() {
ModLoaded.store(true);
ModLoaded.store(true);
}
void Server::UUl(const std::string& R) {
UStatus = "Disconnected: " + R;
UStatus = "Disconnected: " + R;
}
bool Server::CheckBytes(int32_t Bytes) {
if (Bytes == 0) {
// debug("(TCP) Connection closing... CheckBytes(16)");
Terminate = true;
return false;
} else if (Bytes < 0) {
// debug("(TCP CB) recv failed with error: " + GetSocketApiError();
KillSocket(TCPSocket);
Terminate = true;
return false;
}
return true;
if (Bytes == 0) {
// debug("(TCP) Connection closing... CheckBytes(16)");
Terminate = true;
return false;
} else if (Bytes < 0) {
// debug("(TCP CB) recv failed with error: " + GetSocketApiError();
KillSocket(TCPSocket);
Terminate = true;
return false;
}
return true;
}
void Server::TCPSend(const std::string& Data) {
if (TCPSocket == -1) {
Terminate = true;
UUl("Invalid Socket");
return;
}
if (TCPSocket == -1) {
Terminate = true;
UUl("Invalid Socket");
return;
}
int32_t Size, Sent, Temp;
std::string Send(4, 0);
Size = int32_t(Data.size());
memcpy(&Send[0], &Size, sizeof(Size));
Send += Data;
// Do not use Size before this point for anything but the header
Sent = 0;
Size += 4;
do {
if (size_t(Sent) >= Send.size()) {
LOG(ERROR) << "string OOB in " << std::string(__func__);
UUl("TCP Send OOB");
Terminate = true;
return;
}
Temp = send(TCPSocket, &Send[Sent], Size - Sent, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 2");
Terminate = true;
return;
}
Sent += Temp;
} while (Sent < Size);
int32_t Size, Sent, Temp;
std::string Send(4, 0);
Size = int32_t(Data.size());
memcpy(&Send[0], &Size, sizeof(Size));
Send += Data;
// Do not use Size before this point for anything but the header
Sent = 0;
Size += 4;
do {
if (size_t(Sent) >= Send.size()) {
LOG(ERROR) << "string OOB in " << std::string(__func__);
UUl("TCP Send OOB");
Terminate = true;
return;
}
Temp = send(TCPSocket, &Send[Sent], Size - Sent, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 2");
Terminate = true;
return;
}
Sent += Temp;
} while (Sent < Size);
}
std::string Server::TCPRcv() {
if (TCPSocket == -1) {
Terminate = true;
UUl("Invalid Socket");
return "";
}
int32_t Header, BytesRcv = 0, Temp;
std::vector<char> Data(sizeof(Header));
do {
Temp = recv(TCPSocket, &Data[BytesRcv], 4 - BytesRcv, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 3");
Terminate = true;
return "";
}
BytesRcv += Temp;
} while (BytesRcv < 4);
memcpy(&Header, &Data[0], sizeof(Header));
if (TCPSocket == -1) {
Terminate = true;
UUl("Invalid Socket");
return "";
}
int32_t Header, BytesRcv = 0, Temp;
std::vector<char> Data(sizeof(Header));
do {
Temp = recv(TCPSocket, &Data[BytesRcv], 4 - BytesRcv, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 3");
Terminate = true;
return "";
}
BytesRcv += Temp;
} while (BytesRcv < 4);
memcpy(&Header, &Data[0], sizeof(Header));
if (!CheckBytes(BytesRcv)) {
UUl("Socket Closed Code 4");
Terminate = true;
return "";
}
Data.resize(Header);
BytesRcv = 0;
do {
Temp = recv(TCPSocket, &Data[BytesRcv], Header - BytesRcv, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 5");
Terminate = true;
return "";
}
BytesRcv += Temp;
} while (BytesRcv < Header);
if (!CheckBytes(BytesRcv)) {
UUl("Socket Closed Code 4");
Terminate = true;
return "";
}
Data.resize(Header);
BytesRcv = 0;
do {
Temp = recv(TCPSocket, &Data[BytesRcv], Header - BytesRcv, 0);
if (!CheckBytes(Temp)) {
UUl("Socket Closed Code 5");
Terminate = true;
return "";
}
BytesRcv += Temp;
} while (BytesRcv < Header);
std::string Ret(Data.data(), Header);
std::string Ret(Data.data(), Header);
if (Ret.substr(0, 4) == "ABG:") {
Ret = Zlib::DeComp(Ret.substr(4));
}
if (Ret.substr(0, 4) == "ABG:") {
Ret = Zlib::DeComp(Ret.substr(4));
}
if (Ret[0] == 'E')
UUl(Ret.substr(1));
return Ret;
if (Ret[0] == 'E') UUl(Ret.substr(1));
return Ret;
}

View File

@@ -9,137 +9,132 @@
#include "Logger.h"
VersionParser::VersionParser(const std::string& from_string) {
std::string token;
std::istringstream tokenStream(from_string);
while (std::getline(tokenStream, token, '.')) {
data.emplace_back(std::stol(token));
split.emplace_back(token);
}
std::string token;
std::istringstream tokenStream(from_string);
while (std::getline(tokenStream, token, '.')) {
data.emplace_back(std::stol(token));
split.emplace_back(token);
}
}
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;
}
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;
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;
}
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 {
return std::is_eq(*this <=> rhs);
return std::is_eq(*this <=> rhs);
}
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) {
HTTP = HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true");
fallback = true;
if (HTTP.find_first_of("0123456789") == std::string::npos) {
LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!";
throw ShutdownException("Fatal Error");
}
}
if (fallback) {
link = "https://backup1.beammp.com/builds/launcher?download=true";
} else
link = "https://beammp.com/builds/launcher?download=true";
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) {
HTTP =
HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true");
fallback = true;
if (HTTP.find_first_of("0123456789") == std::string::npos) {
LOG(FATAL) << "Primary Servers Offline! sorry for the inconvenience!";
throw ShutdownException("Fatal Error");
}
}
if (fallback) {
link = "https://backup1.beammp.com/builds/launcher?download=true";
} else 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());
std::string RemoteVer;
for (char& c : HTTP) {
if (std::isdigit(c) || c == '.') {
RemoteVer += c;
}
}
if (fs::exists(Back)) remove(Back.c_str());
std::string RemoteVer;
for (char& c : HTTP) {
if (std::isdigit(c) || c == '.') {
RemoteVer += c;
}
}
if (VersionParser(RemoteVer) > VersionParser(FullVersion)) {
system("cls");
LOG(INFO) << "Update found! Downloading...";
if (std::rename(EP.c_str(), Back.c_str())) {
LOG(ERROR) << "Failed to create a backup!";
}
if (VersionParser(RemoteVer) > VersionParser(FullVersion)) {
system("cls");
LOG(INFO) << "Update found! Downloading...";
if (std::rename(EP.c_str(), Back.c_str())) {
LOG(ERROR) << "Failed to create a backup!";
}
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)) {
LOG(ERROR) << "Launcher Update failed! trying again...";
std::this_thread::sleep_for(std::chrono::seconds(2));
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";
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";
}
size_t DirCount(const std::filesystem::path& path) {
return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {});
return (size_t)std::distance(std::filesystem::directory_iterator{path},
std::filesystem::directory_iterator{});
}
void Launcher::ResetMods() {
if (!fs::exists(MPUserPath)) {
fs::create_directories(MPUserPath);
return;
}
if (DirCount(fs::path(MPUserPath)) > 3) {
LOG(WARNING) << "mods/multiplayer will be cleared in 15 seconds, close to abort";
std::this_thread::sleep_for(std::chrono::seconds(15));
}
fs::remove_all(MPUserPath);
fs::create_directories(MPUserPath);
if (!fs::exists(MPUserPath)) {
fs::create_directories(MPUserPath);
return;
}
if (DirCount(fs::path(MPUserPath)) > 3) {
LOG(WARNING)
<< "mods/multiplayer will be cleared in 15 seconds, close to abort";
std::this_thread::sleep_for(std::chrono::seconds(15));
}
fs::remove_all(MPUserPath);
fs::create_directories(MPUserPath);
}
void Launcher::EnableMP() {
std::string File(BeamUserPath + "mods\\db.json");
if (!fs::exists(File))
return;
auto Size = fs::file_size(File);
if (Size < 2)
return;
std::ifstream db(File);
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()) {
d["mods"]["multiplayerbeammp"]["active"] = true;
std::ofstream ofs(File);
if (ofs.is_open()) {
ofs << std::setw(4) << d;
ofs.close();
} else {
LOG(ERROR) << "Failed to write " << File;
}
}
}
std::string File(BeamUserPath + "mods\\db.json");
if (!fs::exists(File)) return;
auto Size = fs::file_size(File);
if (Size < 2) return;
std::ifstream db(File);
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()) {
d["mods"]["multiplayerbeammp"]["active"] = true;
std::ofstream ofs(File);
if (ofs.is_open()) {
ofs << std::setw(4) << d;
ofs.close();
} else {
LOG(ERROR) << "Failed to write " << File;
}
}
}
}
void Launcher::SetupMOD() {
ResetMods();
EnableMP();
LOG(INFO) << "Downloading mod please wait";
HTTP::Download("https://backend.beammp.com/builds/client?download=true"
"&pk="
+ PublicKey + "&branch=" + TargetBuild,
MPUserPath + "\\BeamMP.zip");
ResetMods();
EnableMP();
LOG(INFO) << "Downloading mod please wait";
HTTP::Download(
"https://backend.beammp.com/builds/client?download=true"
"&pk=" +
PublicKey + "&branch=" + TargetBuild,
MPUserPath + "\\BeamMP.zip");
}