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

View File

@@ -7,46 +7,46 @@
#include <zlib.h>
#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<Bytef *>(C);
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;
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;
}

View File

@@ -3,22 +3,22 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
///
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <cpp-httplib/httplib.h>
#include "Launcher.h"
#include "HttpAPI.h"
#include <iostream>
#include "Launcher.h"
#include "Logger.h"
#include <fstream>
#include <mutex>
#include <cmath>
#include <cpp-httplib/httplib.h>
#include <fstream>
#include <iostream>
#include <mutex>
bool HTTP::isDownload = false;
std::atomic<httplib::Client*> CliRef = nullptr;
std::string HTTP::Get(const std::string &IP) {
std::string HTTP::Get(const std::string& IP) {
static std::mutex Lock;
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!";

View File

@@ -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<bool>()){
if (!d["success"].is_null() && d["success"].get<bool>()) {
LoginAuth = true;
if(!d["private_key"].is_null()){
if (!d["private_key"].is_null()) {
UpdateKey(d["private_key"].get<std::string>());
}
if(!d["public_key"].is_null()){
if (!d["public_key"].is_null()) {
PublicKey = d["public_key"].get<std::string>();
}
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<bool>()){
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{
} else {
LOG(WARNING) << "Auto-Authentication unsuccessful please re-login!";
UpdateKey("");
}
}else{
} else {
LOG(WARNING) << "Could not open saved key!";
UpdateKey("");
}
}else UpdateKey("");
} else
UpdateKey("");
}

View File

@@ -3,42 +3,43 @@
/// Copyright (c) 2021-present Anonymous275 read the LICENSE file for more info.
///
#include <ws2tcpip.h>
#include <filesystem>
#include "Launcher.h"
#include "Server.h"
#include "Logger.h"
#include "Server.h"
#include <atomic>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <future>
#include <string>
#include <thread>
#include <atomic>
#include <vector>
#include <future>
#include <ws2tcpip.h>
namespace fs = std::filesystem;
std::vector<std::string> Split(const std::string& String, const std::string& delimiter){
std::vector<std::string> Split(const std::string& String, const std::string& delimiter) {
std::vector<std::string> Val;
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<char*()> task([&] { return TCPRcvRaw(TCPSocket,GRcv,MSize); });
std::packaged_task<char*()> task([&] { return TCPRcvRaw(TCPSocket, GRcv, MSize); });
std::future<char*> f1 = task.get_future();
std::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!";
}

View File

@@ -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 <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#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;
}

View File

@@ -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");
}