This commit is contained in:
Lion Kortlepel 2024-06-17 22:01:15 +02:00
parent 3488136ca4
commit a82b9fb36f
No known key found for this signature in database
GPG Key ID: 4322FF2B4C71259B
21 changed files with 1085 additions and 1017 deletions

View File

@ -6,14 +6,15 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string>
#include "Logger.h" #include "Logger.h"
#include <string>
class HTTP { class HTTP {
public: public:
static bool Download(const std::string& IP, const std::string& Path); static bool Download(const std::string& IP, const std::string& Path);
static std::string Post(const std::string& IP, const std::string& Fields); static std::string Post(const std::string& IP, const std::string& Fields);
static std::string Get(const std::string& IP); static std::string Get(const std::string& IP);
static bool ProgressBar(size_t c, size_t t); static bool ProgressBar(size_t c, size_t t);
public: public:
static bool isDownload; static bool isDownload;
}; };

View File

@ -6,8 +6,8 @@
/// Created by Anonymous275 on 4/2/2020. /// Created by Anonymous275 on 4/2/2020.
/// ///
#pragma once #pragma once
#include <string>
#include <iostream> #include <iostream>
#include <string>
void InitLog(); void InitLog();
void except(const std::string& toPrint); void except(const std::string& toPrint);
void fatal(const std::string& toPrint); void fatal(const std::string& toPrint);

View File

@ -6,19 +6,16 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string> #include <string>
#ifdef __linux__ #ifdef __linux__
#include <cstdint>
#include "linuxfixes.h" #include "linuxfixes.h"
#include <bits/types/siginfo_t.h> #include <bits/types/siginfo_t.h>
#include <cstdint>
#include <sys/ucontext.h> #include <sys/ucontext.h>
#endif #endif
void NetReset(); void NetReset();
extern bool Dev; extern bool Dev;
extern int ping; extern int ping;
@ -55,4 +52,3 @@ void TCPSend(const std::string&Data,uint64_t Sock);
void TCPClientMain(const std::string& IP, int Port); void TCPClientMain(const std::string& IP, int Port);
void UDPClientMain(const std::string& IP, int Port); void UDPClientMain(const std::string& IP, int Port);
void TCPGameServer(const std::string& IP, int Port); void TCPGameServer(const std::string& IP, int Port);

View File

@ -6,8 +6,8 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string>
#include <compare> #include <compare>
#include <string>
#include <vector> #include <vector>
void InitLauncher(int argc, char* argv[]); void InitLauncher(int argc, char* argv[]);

View File

@ -2,12 +2,12 @@
/// Created by Anonymous275 on 2/23/2021 /// Created by Anonymous275 on 2/23/2021
/// ///
#include <nlohmann/json.hpp>
#include "Network/network.hpp"
#include <filesystem>
#include "Logger.h" #include "Logger.h"
#include <fstream> #include "Network/network.hpp"
#include <cstdint> #include <cstdint>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string Branch; std::string Branch;
@ -23,7 +23,8 @@ void ParseConfig(const nlohmann::json& d){
if (d["Build"].is_string()) { if (d["Build"].is_string()) {
Branch = d["Build"].get<std::string>(); Branch = d["Build"].get<std::string>();
for(char& c : Branch)c = char(tolower(c)); for (char& c : Branch)
c = char(tolower(c));
} }
} }
@ -40,7 +41,8 @@ void ConfigInit(){
fatal("Config failed to parse make sure it's valid JSON!"); fatal("Config failed to parse make sure it's valid JSON!");
} }
ParseConfig(d); ParseConfig(d);
}else fatal("Failed to open Launcher.cfg!"); } else
fatal("Failed to open Launcher.cfg!");
} else { } else {
std::ofstream cfg("Launcher.cfg"); std::ofstream cfg("Launcher.cfg");
if (cfg.is_open()) { if (cfg.is_open()) {
@ -55,4 +57,3 @@ void ConfigInit(){
} }
} }
} }

View File

@ -6,22 +6,21 @@
/// Created by Anonymous275 on 7/19/2020 /// Created by Anonymous275 on 7/19/2020
/// ///
#if defined(_WIN32) #if defined(_WIN32)
#include <windows.h> #include <windows.h>
#elif defined(__linux__) #elif defined(__linux__)
#include "vdf_parser.hpp" #include "vdf_parser.hpp"
#include <pwd.h> #include <pwd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <spawn.h> #include <spawn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif #endif
#include "Logger.h"
#include "Startup.h"
#include <Security/Init.h> #include <Security/Init.h>
#include <filesystem> #include <filesystem>
#include "Startup.h"
#include "Logger.h"
#include <thread> #include <thread>
unsigned long GamePID = 0; unsigned long GamePID = 0;
@ -29,7 +28,8 @@ unsigned long GamePID = 0;
std::string QueryKey(HKEY hKey, int ID); std::string QueryKey(HKEY hKey, int ID);
std::string GetGamePath() { std::string GetGamePath() {
static std::string Path; static std::string Path;
if(!Path.empty())return Path; if (!Path.empty())
return Path;
HKEY hKey; HKEY hKey;
LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive"; LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive";
@ -108,25 +108,6 @@ void StartGame(std::string Dir) {
exit(2); exit(2);
} }
#endif #endif
void StartGame(std::string Dir) {
int status;
std::string filename = (Dir + "/BinLinux/BeamNG.drive.x64");
char *argv[] = {filename.data(), NULL};
pid_t pid;
int result = posix_spawn(&pid, filename.c_str(), NULL, NULL, argv, environ);
if (result != 0) {
error("Failed to Launch the game! launcher closing soon");
return;
} else {
waitpid(pid, &status, 0);
error("Game Closed! launcher closing soon");
}
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(2);
}
#endif
void InitGame(const std::string& Dir) { void InitGame(const std::string& Dir) {
if (!Dev) { if (!Dev) {

View File

@ -6,11 +6,11 @@
/// Created by Anonymous275 on 7/17/2020 /// Created by Anonymous275 on 7/17/2020
/// ///
#include "Startup.h"
#include "Logger.h" #include "Logger.h"
#include "Startup.h"
#include <chrono>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <chrono>
#include <thread> #include <thread>
std::string getDate() { std::string getDate() {
@ -39,7 +39,8 @@ void InitLog(){
LFS.open(GetEP() + "Launcher.log"); LFS.open(GetEP() + "Launcher.log");
if (!LFS.is_open()) { if (!LFS.is_open()) {
error("logger file init failed!"); error("logger file init failed!");
}else LFS.close(); } else
LFS.close();
} }
void addToLog(const std::string& Line) { void addToLog(const std::string& Line) {
std::ofstream LFS; std::ofstream LFS;
@ -53,7 +54,8 @@ void info(const std::string& toPrint) {
addToLog(Print); addToLog(Print);
} }
void debug(const std::string& toPrint) { void debug(const std::string& toPrint) {
if(!Dev)return; if (!Dev)
return;
std::string Print = getDate() + "[DEBUG] " + toPrint + "\n"; std::string Print = getDate() + "[DEBUG] " + toPrint + "\n";
std::cout << Print; std::cout << Print;
addToLog(Print); addToLog(Print);

View File

@ -5,28 +5,28 @@
/// ///
/// Created by Anonymous275 on 7/20/2020 /// Created by Anonymous275 on 7/20/2020
/// ///
#include "Http.h"
#include "Network/network.hpp" #include "Network/network.hpp"
#include "Security/Init.h" #include "Security/Init.h"
#include <regex> #include <regex>
#include "Http.h"
#if defined(_WIN32) #if defined(_WIN32)
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #elif defined(__linux__)
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <cstring> #include <cstring>
#include <errno.h> #include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif #endif
#include "Startup.h"
#include "Logger.h" #include "Logger.h"
#include <nlohmann/json.hpp> #include "Startup.h"
#include <charconv> #include <charconv>
#include <thread> #include <nlohmann/json.hpp>
#include <set> #include <set>
#include <thread>
extern int TraceBack; extern int TraceBack;
std::set<std::string>* ConfList = nullptr; std::set<std::string>* ConfList = nullptr;
@ -44,8 +44,10 @@ int ping = -1;
void StartSync(const std::string& Data) { void StartSync(const std::string& Data) {
std::string IP = GetAddr(Data.substr(1, Data.find(':') - 1)); std::string IP = GetAddr(Data.substr(1, Data.find(':') - 1));
if (IP.find('.') == -1) { if (IP.find('.') == -1) {
if(IP == "DNS")UlStatus ="UlConnection Failed! (DNS Lookup Failed)"; if (IP == "DNS")
else UlStatus = "UlConnection Failed! (WSA failed to start)"; UlStatus = "UlConnection Failed! (DNS Lookup Failed)";
else
UlStatus = "UlConnection Failed! (WSA failed to start)";
ListOfMods = "-"; ListOfMods = "-";
Terminate = true; Terminate = true;
return; return;
@ -69,7 +71,8 @@ bool IsAllowedLink(const std::string& Link) {
void Parse(std::string Data, SOCKET CSocket) { void Parse(std::string Data, SOCKET CSocket) {
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':
Data = Data.substr(0, 1); Data = Data.substr(0, 1);
@ -86,8 +89,10 @@ void Parse(std::string Data,SOCKET CSocket){
while (ListOfMods.empty() && !Terminate) { while (ListOfMods.empty() && !Terminate) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if(ListOfMods == "-")Data = "L"; if (ListOfMods == "-")
else Data = "L"+ListOfMods; Data = "L";
else
Data = "L" + ListOfMods;
break; break;
case 'O': // open default browser with URL case 'O': // open default browser with URL
if (IsAllowedLink(Data.substr(1))) { if (IsAllowedLink(Data.substr(1))) {
@ -100,16 +105,20 @@ void Parse(std::string Data,SOCKET CSocket){
Data = Code + std::to_string(ProxyPort); Data = Code + std::to_string(ProxyPort);
break; break;
case 'U': case 'U':
if(SubCode == 'l')Data = UlStatus; if (SubCode == 'l')
Data = UlStatus;
if (SubCode == 'p') { if (SubCode == 'p') {
if (ping > 800) { if (ping > 800) {
Data = "Up-2"; Data = "Up-2";
}else Data = "Up" + std::to_string(ping); } else
Data = "Up" + std::to_string(ping);
} }
if (!SubCode) { if (!SubCode) {
std::string Ping; std::string Ping;
if(ping > 800)Ping = "-2"; if (ping > 800)
else Ping = std::to_string(ping); Ping = "-2";
else
Ping = std::to_string(ping);
Data = std::string(UlStatus) + "\n" + "Up" + Ping; Data = std::string(UlStatus) + "\n" + "Up" + Ping;
} }
break; break;
@ -123,7 +132,8 @@ void Parse(std::string Data,SOCKET CSocket){
TCPTerminate = true; TCPTerminate = true;
ping = -1; ping = -1;
} }
if(SubCode == 'G')exit(2); if (SubCode == 'G')
exit(2);
Data.clear(); Data.clear();
break; break;
case 'R': // will send mod name case 'R': // will send mod name
@ -171,14 +181,16 @@ void GameHandler(SOCKET Client){
Rcv = 0; Rcv = 0;
do { do {
Temp = recv(Client, &Header[Rcv], 1, 0); Temp = recv(Client, &Header[Rcv], 1, 0);
if(Temp < 1)break; if (Temp < 1)
break;
if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') { if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
error("(Core) Invalid lua communication"); error("(Core) Invalid lua communication");
KillSocket(Client); KillSocket(Client);
return; return;
} }
} while (Header[Rcv++] != '>'); } while (Header[Rcv++] != '>');
if(Temp < 1)break; if (Temp < 1)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') { if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
debug("(Core) Invalid lua Header -> " + std::string(Header, Rcv)); debug("(Core) Invalid lua Header -> " + std::string(Header, Rcv));
break; break;
@ -188,10 +200,12 @@ void GameHandler(SOCKET Client){
do { do {
Temp = recv(Client, &Ret[Rcv], Size - Rcv, 0); Temp = recv(Client, &Ret[Rcv], Size - Rcv, 0);
if(Temp < 1)break; if (Temp < 1)
break;
Rcv += Temp; Rcv += Temp;
} while (Rcv < Size); } while (Rcv < Size);
if(Temp < 1)break; if (Temp < 1)
break;
std::thread Respond(Parse, Ret, Client); std::thread Respond(Parse, Ret, Client);
Respond.detach(); Respond.detach();
@ -223,7 +237,8 @@ void CoreMain() {
#ifdef _WIN32 #ifdef _WIN32
WSADATA wsaData; WSADATA wsaData;
iRes = WSAStartup(514, &wsaData); // 2.2 iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes)debug("WSAStartup failed with error: " + std::to_string(iRes)); if (iRes)
debug("WSAStartup failed with error: " + std::to_string(iRes));
#endif #endif
ZeroMemory(&hints, sizeof(hints)); ZeroMemory(&hints, sizeof(hints));
@ -297,7 +312,8 @@ int Handle(EXCEPTION_POINTERS *ep){
#if not defined(__MINGW32__) and not defined(__linux__) #if not defined(__MINGW32__) and not defined(__linux__)
} __except (Handle(GetExceptionInformation())) { } } __except (Handle(GetExceptionInformation())) { }
#elif not defined(__MINGW32__) and defined(__linux__) #elif not defined(__MINGW32__) and defined(__linux__)
} catch(...){ }
catch (...) {
except("(Core) Code : " + std::string(strerror(errno))); except("(Core) Code : " + std::string(strerror(errno)));
} }
#endif #endif

View File

@ -12,14 +12,15 @@
#include <winsock2.h> #include <winsock2.h>
#elif defined(__linux__) #elif defined(__linux__)
#include "linuxfixes.h" #include "linuxfixes.h"
#include <netdb.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <netdb.h>
#endif #endif
#include "Logger.h" #include "Logger.h"
std::string GetAddr(const std::string& IP) { std::string GetAddr(const std::string& IP) {
if(IP.find_first_not_of("0123456789.") == -1)return IP; if (IP.find_first_not_of("0123456789.") == -1)
return IP;
hostent* host; hostent* host;
#ifdef _WIN32 #ifdef _WIN32
WSADATA wsaData; WSADATA wsaData;

View File

@ -11,19 +11,19 @@
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #elif defined(__linux__)
#include "linuxfixes.h" #include "linuxfixes.h"
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <cstring>
#endif #endif
#include "Logger.h" #include "Logger.h"
#include <charconv> #include <charconv>
#include <mutex>
#include <string> #include <string>
#include <thread> #include <thread>
#include <mutex>
std::chrono::time_point<std::chrono::high_resolution_clock> PingStart, PingEnd; std::chrono::time_point<std::chrono::high_resolution_clock> PingStart, PingEnd;
bool GConnected = false; bool GConnected = false;
@ -58,7 +58,8 @@ bool CheckBytes(uint32_t Bytes){
void GameSend(std::string Data) { void GameSend(std::string Data) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
if(TCPTerminate || !GConnected || CSocket == -1)return; if (TCPTerminate || !GConnected || CSocket == -1)
return;
int32_t Size, Temp, Sent; int32_t Size, Temp, Sent;
Data += '\n'; Data += '\n';
Size = int32_t(Data.size()); Size = int32_t(Data.size());
@ -72,25 +73,33 @@ void GameSend(std::string Data){
if (Sent > -1) { if (Sent > -1) {
Temp = send(CSocket, &Data[Sent], Size - Sent, 0); Temp = send(CSocket, &Data[Sent], Size - Sent, 0);
} }
if(!CheckBytes(Temp))return; if (!CheckBytes(Temp))
return;
Sent += Temp; Sent += Temp;
} while (Sent < Size); } while (Sent < Size);
} }
void ServerSend(std::string Data, bool Rel) { void ServerSend(std::string Data, bool Rel) {
if(Terminate || Data.empty())return; if (Terminate || Data.empty())
return;
if (Data.find("Zp") != std::string::npos && Data.size() > 500) { if (Data.find("Zp") != std::string::npos && Data.size() > 500) {
abort(); abort();
} }
char C = 0; char C = 0;
bool Ack = false; bool Ack = false;
int DLen = int(Data.length()); int DLen = int(Data.length());
if(DLen > 3)C = Data.at(0); if (DLen > 3)
if (C == 'O' || C == 'T')Ack = true; C = Data.at(0);
if(C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')Rel = true; if (C == 'O' || C == 'T')
Ack = 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,TCPSock); SendLarge(Data);
}else UDPSend(Data); else
TCPSend(Data, TCPSock);
} else
UDPSend(Data);
if (DLen > 1000) { if (DLen > 1000) {
debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : " debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : "
@ -125,7 +134,8 @@ void NetReset(){
} }
SOCKET SetupListener() { SOCKET SetupListener() {
if(GSocket != -1)return GSocket; if (GSocket != -1)
return GSocket;
struct addrinfo* result = nullptr; struct addrinfo* result = nullptr;
struct addrinfo hints { }; struct addrinfo hints { };
int iRes; int iRes;
@ -182,14 +192,18 @@ void AutoPing(){
} }
int ClientID = -1; int ClientID = -1;
void ParserAsync(const std::string& Data) { void ParserAsync(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;
@ -248,9 +262,11 @@ void TCPGameServer(const std::string& IP, int Port){
do { do {
Temp = recv(CSocket, &Header[Rcv], 1, 0); Temp = recv(CSocket, &Header[Rcv], 1, 0);
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
} while (Header[Rcv++] != '>'); } while (Header[Rcv++] != '>');
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') { if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
debug("(Game) Invalid lua Header -> " + std::string(Header, Rcv)); debug("(Game) Invalid lua Header -> " + std::string(Header, Rcv));
break; break;
@ -259,20 +275,25 @@ void TCPGameServer(const std::string& IP, int Port){
Rcv = 0; Rcv = 0;
do { do {
Temp = recv(CSocket, &Ret[Rcv], Size - Rcv, 0); Temp = recv(CSocket, &Ret[Rcv], Size - Rcv, 0);
if(Temp < 1)break; if (Temp < 1)
break;
Rcv += Temp; Rcv += Temp;
} while (Rcv < Size && !TCPTerminate); } while (Rcv < Size && !TCPTerminate);
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
ServerSend(Ret, false); ServerSend(Ret, false);
} while (Temp > 0 && !TCPTerminate); } while (Temp > 0 && !TCPTerminate);
if(Temp == 0)debug("(Proxy) Connection closing"); if (Temp == 0)
else debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError())); debug("(Proxy) Connection closing");
else
debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError()));
} }
TCPTerminate = true; TCPTerminate = true;
GConnected = false; GConnected = false;
Terminate = true; Terminate = true;
if(CSocket != SOCKET_ERROR)KillSocket(CSocket); if (CSocket != SOCKET_ERROR)
KillSocket(CSocket);
debug("END OF GAME SERVER"); debug("END OF GAME SERVER");
} }

View File

@ -7,14 +7,14 @@
/// ///
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
#include <iostream>
#include <Logger.h>
#include <fstream>
#include "Http.h" #include "Http.h"
#include <mutex> #include <Logger.h>
#include <cmath> #include <cmath>
#include <filesystem> #include <filesystem>
#include <fstream>
#include <httplib.h> #include <httplib.h>
#include <iostream>
#include <mutex>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try { void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try {
@ -40,8 +40,7 @@ void WriteHttpDebug(const httplib::Client& client, const std::string& method, co
{ "port", client.port() }, { "port", client.port() },
{ "socket_open", client.is_socket_open() }, { "socket_open", client.is_socket_open() },
{ "valid", client.is_valid() }, { "valid", client.is_valid() },
} } },
},
}; };
if (result) { if (result) {
auto value = result.value(); auto value = result.value();
@ -54,8 +53,7 @@ void WriteHttpDebug(const httplib::Client& client, const std::string& method, co
js["result"]["reason"] = value.reason; js["result"]["reason"] = value.reason;
} }
of << js.dump(); of << js.dump();
} } catch (const std::exception& e) {
catch (const std::exception& e) {
error(e.what()); error(e.what());
} }
@ -75,20 +73,16 @@ std::string HTTP::Get(const std::string& IP) {
if (res) { if (res) {
if (res->status == 200) { if (res->status == 200) {
Ret = res->body; Ret = res->body;
} } else {
else {
WriteHttpDebug(cli, "GET", IP, res); WriteHttpDebug(cli, "GET", IP, res);
error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} } else {
else {
if (isDownload) { if (isDownload) {
std::cout << "\n"; std::cout << "\n";
} }
WriteHttpDebug(cli, "GET", IP, res); WriteHttpDebug(cli, "GET", IP, res);
error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
return Ret; return Ret;
@ -112,30 +106,27 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
error(res->reason); error(res->reason);
} }
Ret = res->body; Ret = res->body;
} } else {
else {
WriteHttpDebug(cli, "POST", IP, res); WriteHttpDebug(cli, "POST", IP, res);
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} } else {
else {
httplib::Result res = cli.Post(IP.substr(pos).c_str()); httplib::Result res = cli.Post(IP.substr(pos).c_str());
if (res) { if (res) {
if (res->status != 200) { if (res->status != 200) {
error(res->reason); error(res->reason);
} }
Ret = res->body; Ret = res->body;
} } else {
else {
WriteHttpDebug(cli, "POST", IP, res); WriteHttpDebug(cli, "POST", IP, res);
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} }
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) {
@ -147,8 +138,10 @@ bool HTTP::ProgressBar(size_t c, size_t t) {
std::cout << round(c / double(t) * 100); std::cout << round(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 << "]";
last_progress = round(c / double(t) * 100); last_progress = round(c / double(t) * 100);
} }
@ -163,7 +156,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::ofstream File(Path, std::ios::binary); std::ofstream File(Path, std::ios::binary);
if (File.is_open()) { if (File.is_open()) {
@ -171,8 +165,7 @@ bool HTTP::Download(const std::string& IP, const std::string& Path) {
File.close(); File.close();
std::cout << "\n"; std::cout << "\n";
info("Download Complete!"); info("Download Complete!");
} } else {
else {
error("Failed to open file directory: " + Path); error("Failed to open file directory: " + Path);
return false; return false;
} }

View File

@ -11,26 +11,26 @@
#if defined(_WIN32) #if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #elif defined(__linux__)
#include <sys/socket.h> #include <arpa/inet.h>
#include <sys/types.h>
#include <cstring> #include <cstring>
#include <errno.h> #include <errno.h>
#include <netdb.h> #include <netdb.h>
#include <arpa/inet.h> #include <sys/socket.h>
#include <sys/types.h>
#endif #endif
#include <filesystem>
#include "Startup.h"
#include "Logger.h" #include "Logger.h"
#include <iostream> #include "Startup.h"
#include <atomic>
#include <cmath>
#include <cstring> #include <cstring>
#include <filesystem>
#include <fstream> #include <fstream>
#include <future>
#include <iostream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <atomic>
#include <vector> #include <vector>
#include <future>
#include <cmath>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string ListOfMods; std::string ListOfMods;
@ -40,10 +40,12 @@ std::vector<std::string> Split(const std::string& String,const std::string& deli
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;
} }
@ -64,7 +66,6 @@ void WaitForConfirm(){
ModLoaded = false; ModLoaded = false;
} }
void Abord() { void Abord() {
Terminate = true; Terminate = true;
TCPTerminate = true; TCPTerminate = true;
@ -82,7 +83,8 @@ std::string Auth(SOCKET Sock){
} }
TCPSend(PublicKey, Sock); TCPSend(PublicKey, Sock);
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
if (Res.empty() || Res[0] != 'P') { if (Res.empty() || Res[0] != 'P') {
@ -99,7 +101,8 @@ std::string Auth(SOCKET Sock){
return ""; return "";
} }
TCPSend("SR", Sock); TCPSend("SR", Sock);
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
@ -119,8 +122,10 @@ std::string Auth(SOCKET Sock){
} }
void UpdateUl(bool D, const std::string& msg) { void UpdateUl(bool D, const std::string& msg) {
if(D)UlStatus = "UlDownloading Resource " + msg; if (D)
else UlStatus = "UlLoading Resource " + msg; UlStatus = "UlDownloading Resource " + msg;
else
UlStatus = "UlLoading Resource " + msg;
} }
void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name) { void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name) {
@ -142,7 +147,8 @@ char* TCPRcvRaw(SOCKET 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) {
info(std::to_string(Temp)); info(std::to_string(Temp));
@ -213,8 +219,8 @@ std::string MultiDownload(SOCKET MSock,SOCKET DSock, uint64_t Size, const std::s
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);
@ -235,7 +241,8 @@ void InvalidResource(const std::string& File){
void SyncResources(SOCKET Sock) { void SyncResources(SOCKET Sock) {
std::string Ret = Auth(Sock); std::string Ret = Auth(Sock);
if(Ret.empty())return; if (Ret.empty())
return;
info("Checking Resources..."); info("Checking Resources...");
CheckForDir(); CheckForDir();
@ -253,8 +260,10 @@ void SyncResources(SOCKET Sock){
t += name.substr(name.find_last_of('/') + 1) + ";"; t += name.substr(name.find_last_of('/') + 1) + ";";
} }
} }
if(t.empty())ListOfMods = "-"; if (t.empty())
else ListOfMods = t; ListOfMods = "-";
else
ListOfMods = 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('/');
@ -263,19 +272,23 @@ void SyncResources(SOCKET Sock){
InvalidResource(*FN); InvalidResource(*FN);
return; return;
} }
if (pos == std::string::npos)continue; if (pos == std::string::npos)
continue;
Amount++; Amount++;
} }
if(!FNames.empty())info("Syncing..."); if (!FNames.empty())
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 (FS->find_first_not_of("0123456789") != std::string::npos)continue; if (FS->find_first_not_of("0123456789") != std::string::npos)
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));
@ -293,12 +306,6 @@ void SyncResources(SOCKET Sock){
auto tmp_name = name + ".tmp"; auto tmp_name = name + ".tmp";
fs::copy_file(a, tmp_name, fs::copy_options::overwrite_existing); fs::copy_file(a, tmp_name, fs::copy_options::overwrite_existing);
fs::rename(tmp_name, name); fs::rename(tmp_name, name);
for(char &c : FName){
c = ::tolower(c);
}
#endif
fs::copy_file(a, GetGamePath() + "mods/multiplayer" + FName,
} catch (std::exception& e) { } catch (std::exception& e) {
error("Failed copy to the mods folder! " + std::string(e.what())); error("Failed copy to the mods folder! " + std::string(e.what()));
Terminate = true; Terminate = true;
@ -306,7 +313,8 @@ void SyncResources(SOCKET Sock){
} }
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('/'));
@ -324,7 +332,8 @@ void SyncResources(SOCKET Sock){
Data = MultiDownload(Sock, DSock, std::stoull(*FS), Name); Data = MultiDownload(Sock, 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);

View File

@ -5,40 +5,41 @@
/// ///
/// Created by Anonymous275 on 5/8/2020 /// Created by Anonymous275 on 5/8/2020
/// ///
#include "Zlib/Compressor.h"
#include "Network/network.hpp" #include "Network/network.hpp"
#include "Zlib/Compressor.h"
#if defined(_WIN32) #if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #elif defined(__linux__)
#include <sys/socket.h> #include "linuxfixes.h"
#include <sys/types.h> #include <arpa/inet.h>
#include <cstring> #include <cstring>
#include <errno.h> #include <errno.h>
#include <netdb.h> #include <netdb.h>
#include <arpa/inet.h> #include <sys/socket.h>
#include "linuxfixes.h" #include <sys/types.h>
#endif #endif
#include "Logger.h" #include "Logger.h"
#include <string>
#include <set> #include <set>
#include <string>
SOCKET UDPSock = -1; SOCKET UDPSock = -1;
sockaddr_in* ToServer = nullptr; sockaddr_in* ToServer = nullptr;
void UDPSend(std::string Data) { void UDPSend(std::string Data) {
if(ClientID == -1 || UDPSock == -1)return; if (ClientID == -1 || UDPSock == -1)
return;
if (Data.length() > 400) { if (Data.length() > 400) {
std::string CMP(Comp(Data)); std::string CMP(Comp(Data));
Data = "ABG:" + CMP; Data = "ABG:" + CMP;
} }
std::string Packet = char(ClientID + 1) + std::string(":") + Data; std::string Packet = char(ClientID + 1) + std::string(":") + Data;
int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer)); int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer));
if (sendOk == SOCKET_ERROR)error("Error Code : " + std::to_string(WSAGetLastError())); if (sendOk == SOCKET_ERROR)
error("Error Code : " + std::to_string(WSAGetLastError()));
} }
void SendLarge(std::string Data) { void SendLarge(std::string Data) {
if (Data.length() > 400) { if (Data.length() > 400) {
std::string CMP(Comp(Data)); std::string CMP(Comp(Data));
@ -62,9 +63,11 @@ void UDPRcv(){
#endif #endif
ZeroMemory(&FromServer, clientLength); ZeroMemory(&FromServer, clientLength);
std::string Ret(10240, 0); std::string Ret(10240, 0);
if(UDPSock == -1)return; if (UDPSock == -1)
return;
int32_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength); int32_t Rcv = recvfrom(UDPSock, &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));
} }
void UDPClientMain(const std::string& IP, int Port) { void UDPClientMain(const std::string& IP, int Port) {
@ -85,7 +88,8 @@ void UDPClientMain(const std::string& IP,int Port){
GameSend("P" + std::to_string(ClientID)); GameSend("P" + std::to_string(ClientID));
TCPSend("H", TCPSock); TCPSend("H", TCPSock);
UDPSend("p"); UDPSend("p");
while(!Terminate)UDPRcv(); while (!Terminate)
UDPRcv();
KillSocket(UDPSock); KillSocket(UDPSock);
WSACleanup(); WSACleanup();
} }

View File

@ -6,21 +6,21 @@
/// Created by Anonymous275 on 5/8/2020 /// Created by Anonymous275 on 5/8/2020
/// ///
#include <chrono>
#include <vector>
#include "Logger.h" #include "Logger.h"
#include <iostream>
#include <Zlib/Compressor.h> #include <Zlib/Compressor.h>
#include <chrono>
#include <iostream>
#include <vector>
#if defined(_WIN32) #if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #elif defined(__linux__)
#include <sys/socket.h> #include <arpa/inet.h>
#include <sys/types.h>
#include <cstring> #include <cstring>
#include <errno.h> #include <errno.h>
#include <netdb.h> #include <netdb.h>
#include <arpa/inet.h> #include <sys/socket.h>
#include <sys/types.h>
#endif #endif
#include "Network/network.hpp" #include "Network/network.hpp"
@ -118,7 +118,8 @@ std::string TCPRcv(SOCKET Sock){
#ifdef DEBUG #ifdef DEBUG
// debug("Parsing from server -> " + std::to_string(Ret.size())); // debug("Parsing from server -> " + std::to_string(Ret.size()));
#endif #endif
if(Ret[0] == 'E' || Ret[0] == 'K')UUl(Ret.substr(1)); if (Ret[0] == 'E' || Ret[0] == 'K')
UUl(Ret.substr(1));
return Ret; return Ret;
} }
@ -168,5 +169,4 @@ void TCPClientMain(const std::string& IP,int Port){
if (WSACleanup() != 0) if (WSACleanup() != 0)
debug("(TCP) Client: WSACleanup() failed!..."); debug("(TCP) Client: WSACleanup() failed!...");
#endif #endif
} }

View File

@ -11,9 +11,9 @@
#include <windows.h> #include <windows.h>
#elif defined(__linux__) #elif defined(__linux__)
#include "vdf_parser.hpp" #include "vdf_parser.hpp"
#include <vector>
#include <pwd.h> #include <pwd.h>
#include <unistd.h> #include <unistd.h>
#include <vector>
#endif #endif
#include "Logger.h" #include "Logger.h"
#include <fstream> #include <fstream>
@ -29,8 +29,7 @@ std::string GameDir;
void lowExit(int code) { void lowExit(int code) {
TraceBack = 0; TraceBack = 0;
std::string msg = std::string msg = "Failed to find the game please launch it. Report this if the issue persists code ";
"Failed to find the game please launch it. Report this if the issue persists code ";
error(msg + std::to_string(code)); error(msg + std::to_string(code));
std::this_thread::sleep_for(std::chrono::seconds(10)); std::this_thread::sleep_for(std::chrono::seconds(10));
exit(2); exit(2);
@ -122,18 +121,30 @@ std::string QueryKey(HKEY hKey,int ID){
std::string key = achValue; std::string key = achValue;
switch (ID) { switch (ID) {
case 1: if(key == "SteamExe"){ case 1:
if (key == "SteamExe") {
auto p = data.find_last_of("/\\"); auto p = data.find_last_of("/\\");
if (p != std::string::npos) { if (p != std::string::npos) {
return data.substr(0, p); return data.substr(0, p);
} }
} }
break; break;
case 2: if(key == "Name" && data == "BeamNG.drive")return data;break; case 2:
case 3: if(key == "rootpath")return data;break; if (key == "Name" && data == "BeamNG.drive")
case 4: if(key == "userpath_override")return data; return data;
case 5: if(key == "Local AppData")return data; break;
default: break; case 3:
if (key == "rootpath")
return data;
break;
case 4:
if (key == "userpath_override")
return data;
case 5:
if (key == "Local AppData")
return data;
default:
break;
} }
} }
} }
@ -180,8 +191,10 @@ bool FindHack(const std::string& Path){
bool s = true; bool s = true;
for (const auto& entry : fs::directory_iterator(Path)) { for (const auto& entry : fs::directory_iterator(Path)) {
std::string Name = entry.path().filename().string(); std::string Name = entry.path().filename().string();
for(char&c : Name)c = char(tolower(c)); for (char& c : Name)
if(Name == "steam.exe")s = false; c = char(tolower(c));
if (Name == "steam.exe")
s = false;
if (Name.find("greenluma") != -1) { if (Name.find("greenluma") != -1) {
error("Found malicious file/folder \"" + Name + "\""); error("Found malicious file/folder \"" + Name + "\"");
return true; return true;
@ -203,10 +216,12 @@ std::vector<std::string> GetID(const std::string& log){
std::stringstream ss(vec); std::stringstream ss(vec);
bool S = false; bool S = false;
while (std::getline(ss, t, '{')) { while (std::getline(ss, t, '{')) {
if(!S)S = true; if (!S)
S = true;
else { else {
for (char& c : t) { for (char& c : t) {
if(isdigit(c))r += c; if (isdigit(c))
r += c;
} }
break; break;
} }
@ -222,7 +237,8 @@ std::vector<std::string> GetID(const std::string& log){
} }
for (char& c : t) { for (char& c : t) {
if (c == '"') { if (c == '"') {
if(!S)S = true; if (!S)
S = true;
else { else {
if (r.length() > 10) { if (r.length() > 10) {
Ret.emplace_back(r); Ret.emplace_back(r);
@ -232,7 +248,8 @@ std::vector<std::string> GetID(const std::string& log){
continue; continue;
} }
} }
if(isdigit(c))r += c; if (isdigit(c))
r += c;
} }
} }
vec.clear(); vec.clear();
@ -253,7 +270,8 @@ std::string GetManifest(const std::string& Man){
pos += int(ToFind.length()); pos += int(ToFind.length());
vec = vec.substr(pos); vec = vec.substr(pos);
return vec.substr(0, vec.find('\"')); return vec.substr(0, vec.find('\"'));
}else return ""; } else
return "";
} }
bool IDCheck(std::string Man, std::string steam) { bool IDCheck(std::string Man, std::string steam) {
bool a = false, b = true; bool a = false, b = true;
@ -263,10 +281,12 @@ bool IDCheck(std::string Man, std::string steam){
steam += "\\config\\loginusers.vdf"; steam += "\\config\\loginusers.vdf";
if (fs::exists(Man) && fs::exists(steam)) { if (fs::exists(Man) && fs::exists(steam)) {
for (const std::string& ID : GetID(steam)) { for (const std::string& ID : GetID(steam)) {
if(ID == GetManifest(Man))b = false; if (ID == GetManifest(Man))
b = false;
} }
// if(b)Exit(6); // if(b)Exit(6);
}else a = true; } else
a = true;
return a; return a;
} }
void LegitimacyCheck() { void LegitimacyCheck() {
@ -307,11 +327,13 @@ void LegitimacyCheck(){
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey); LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
if (dwRegOPenKey == ERROR_SUCCESS) { if (dwRegOPenKey == ERROR_SUCCESS) {
Result = QueryKey(hKey, 3); Result = QueryKey(hKey, 3);
if(Result.empty())lowExit(3); if (Result.empty())
lowExit(3);
// if(IDCheck(Result,T))lowExit(5); // if(IDCheck(Result,T))lowExit(5);
GameDir = Result; GameDir = Result;
// TraceBack++; // TraceBack++;
}else lowExit(4); } else
lowExit(4);
K3.clear(); K3.clear();
Result.clear(); Result.clear();
RegCloseKey(hKey); RegCloseKey(hKey);
@ -345,7 +367,8 @@ std::string CheckVer(const std::string &dir){
vec = vec.substr(vec.find_last_of("version"), vec.find_last_of('"')); vec = vec.substr(vec.find_last_of("version"), vec.find_last_of('"'));
for (const char& a : vec) { for (const char& a : vec) {
if(isdigit(a) || a == '.')temp+=a; if (isdigit(a) || a == '.')
temp += a;
} }
return temp; return temp;
} }

View File

@ -6,12 +6,11 @@
/// Created by Anonymous275 on 11/26/2020 /// Created by Anonymous275 on 11/26/2020
/// ///
#include <nlohmann/json.hpp>
#include "Http.h" #include "Http.h"
#include <filesystem>
#include "Logger.h" #include "Logger.h"
#include <filesystem>
#include <fstream> #include <fstream>
#include <nlohmann/json.hpp>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string PublicKey; std::string PublicKey;
@ -27,7 +26,8 @@ void UpdateKey(const char* newKey){
if (Key.is_open()) { if (Key.is_open()) {
Key << newKey; Key << newKey;
Key.close(); Key.close();
}else fatal("Cannot write to disk!"); } else
fatal("Cannot write to disk!");
} else if (fs::exists("key")) { } else if (fs::exists("key")) {
remove("key"); remove("key");
} }
@ -81,7 +81,8 @@ std::string Login(const std::string& fields){
PublicKey = d["public_key"].get<std::string>(); PublicKey = d["public_key"].get<std::string>();
} }
info("Authentication successful!"); info("Authentication successful!");
}else info("Authentication failed!"); } else
info("Authentication failed!");
if (d.contains("message")) { if (d.contains("message")) {
d.erase("private_key"); d.erase("private_key");
d.erase("public_key"); d.erase("public_key");
@ -137,5 +138,6 @@ void CheckLocalKey(){
warn("Could not open saved key!"); warn("Could not open saved key!");
UpdateKey(nullptr); UpdateKey(nullptr);
} }
}else UpdateKey(nullptr); } else
UpdateKey(nullptr);
} }

View File

@ -6,25 +6,24 @@
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include <nlohmann/json.hpp>
#include <httplib.h>
#include "zip_file.h" #include "zip_file.h"
#include <httplib.h>
#include <nlohmann/json.hpp>
#include <string> #include <string>
#if defined(_WIN32) #if defined(_WIN32)
#include <windows.h> #include <windows.h>
#elif defined(__linux__) #elif defined(__linux__)
#include <unistd.h> #include <unistd.h>
#endif #endif
#include "Http.h"
#include "Logger.h"
#include "Network/network.hpp" #include "Network/network.hpp"
#include "Security/Init.h" #include "Security/Init.h"
#include <filesystem>
#include "Startup.h" #include "Startup.h"
#include "hashpp.h" #include "hashpp.h"
#include "Logger.h" #include <filesystem>
#include <fstream> #include <fstream>
#include <thread> #include <thread>
#include "Http.h"
extern int TraceBack; extern int TraceBack;
bool Dev = false; bool Dev = false;
@ -45,13 +44,19 @@ std::strong_ordering VersionParser::operator<=>(
const VersionParser& rhs) const noexcept { 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 {
@ -135,8 +140,10 @@ void CheckName(int argc,char* args[]){
std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('/') + 1); std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('/') + 1);
#endif #endif
if (FN != DN) { if (FN != DN) {
if(fs::exists(DN))remove(DN.c_str()); if (fs::exists(DN))
if(fs::exists(DN))ReLaunch(argc,args); remove(DN.c_str());
if (fs::exists(DN))
ReLaunch(argc, args);
std::rename(FN.c_str(), DN.c_str()); std::rename(FN.c_str(), DN.c_str());
URelaunch(argc, args); URelaunch(argc, args);
} }
@ -163,11 +170,12 @@ void CheckForUpdates(int argc, char* args[], const std::string& CV) {
info("Downloading Launcher update " + LatestHash); info("Downloading Launcher update " + LatestHash);
HTTP::Download( HTTP::Download(
"https://backend.beammp.com/builds/launcher?download=true" "https://backend.beammp.com/builds/launcher?download=true"
"&pk=" + "&pk="
PublicKey + "&branch=" + Branch, + PublicKey + "&branch=" + Branch,
EP); EP);
URelaunch(argc, args); URelaunch(argc, args);
} else info("Launcher version is up to date"); } else
info("Launcher version is up to date");
TraceBack++; TraceBack++;
} }
@ -180,7 +188,8 @@ void CustomPort(int argc, char* argv[]){
warn("Running on custom port : " + std::to_string(DEFAULT_PORT)); warn("Running on custom port : " + std::to_string(DEFAULT_PORT));
} }
} }
if(argc > 2)Dev = true; if (argc > 2)
Dev = true;
} }
} }
@ -188,7 +197,8 @@ void CustomPort(int argc, char* argv[]){
void LinuxPatch() { void LinuxPatch() {
HKEY hKey = nullptr; HKEY hKey = nullptr;
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey); LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS || getenv("USER") == nullptr)return; if (result != ERROR_SUCCESS || getenv("USER") == nullptr)
return;
RegCloseKey(hKey); RegCloseKey(hKey);
info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit"); info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit");
info("Applying patches..."); info("Applying patches...");
@ -241,27 +251,31 @@ size_t DirCount(const std::filesystem::path& path){
} }
void CheckMP(const std::string& Path) { void CheckMP(const std::string& Path) {
if (!fs::exists(Path))return; if (!fs::exists(Path))
return;
size_t c = DirCount(fs::path(Path)); size_t c = DirCount(fs::path(Path));
try { try {
for (auto& p : fs::directory_iterator(Path)) { for (auto& p : fs::directory_iterator(Path)) {
if (p.exists() && !p.is_directory()) { if (p.exists() && !p.is_directory()) {
std::string Name = p.path().filename().string(); std::string Name = p.path().filename().string();
for(char&Ch : Name)Ch = char(tolower(Ch)); for (char& Ch : Name)
if(Name != "beammp.zip")fs::remove(p.path()); Ch = char(tolower(Ch));
if (Name != "beammp.zip")
fs::remove(p.path());
} }
} }
} catch (...) { } catch (...) {
fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?"); fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?");
} }
} }
void EnableMP() { void EnableMP() {
std::string File(GetGamePath() + "mods/db.json"); std::string File(GetGamePath() + "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);
@ -295,7 +309,8 @@ void PreGame(const std::string& GamePath){
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey); std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey);
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower); transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(), LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
[](auto const& c ) -> bool { return !std::isalnum(c); } ), LatestHash.end()); [](auto const& c) -> bool { return !std::isalnum(c); }),
LatestHash.end());
try { try {
if (!fs::exists(GetGamePath() + "mods/multiplayer")) { if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
@ -317,7 +332,9 @@ void PreGame(const std::string& GamePath){
if (FileHash != LatestHash) { if (FileHash != LatestHash) {
info("Downloading BeamMP Update " + LatestHash); info("Downloading BeamMP Update " + LatestHash);
HTTP::Download("https://backend.beammp.com/builds/client?download=true" HTTP::Download("https://backend.beammp.com/builds/client?download=true"
"&pk=" + PublicKey + "&branch=" + Branch, ZipPath); "&pk="
+ PublicKey + "&branch=" + Branch,
ZipPath);
} }
std::string Target(GetGamePath() + "mods/unpacked/beammp"); std::string Target(GetGamePath() + "mods/unpacked/beammp");
@ -369,7 +386,8 @@ void StartProxy() {
headers.emplace("X-API-Version", req.get_header_value("X-API-Version")); headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
} }
if (auto cli_res = cli.Post(req.path, headers, req.body, if (auto cli_res = cli.Post(req.path, headers, req.body,
req.get_header_value("Content-Type")); cli_res) { req.get_header_value("Content-Type"));
cli_res) {
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type")); res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
} else { } else {
res.set_content(to_string(cli_res.error()), "text/plain"); res.set_content(to_string(cli_res.error()), "text/plain");

View File

@ -5,13 +5,13 @@
/// ///
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include "Http.h"
#include "Logger.h"
#include "Network/network.hpp" #include "Network/network.hpp"
#include "Security/Init.h" #include "Security/Init.h"
#include "Startup.h" #include "Startup.h"
#include <iostream> #include <iostream>
#include "Logger.h"
#include <thread> #include <thread>
#include "Http.h"
[[noreturn]] void flush() { [[noreturn]] void flush() {
while (true) { while (true) {