mirror of
https://github.com/BeamMP/BeamMP-Launcher.git
synced 2026-04-05 15:26:11 +00:00
remove all files
This commit is contained in:
@@ -1,54 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/15/2020
|
||||
///
|
||||
|
||||
#include <iostream>
|
||||
#include <zlib.h>
|
||||
|
||||
#define Biggest 30000
|
||||
std::string 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);
|
||||
int TO = defstream.total_out;
|
||||
std::string Ret(TO,0);
|
||||
memcpy_s(&Ret[0],TO,C,TO);
|
||||
delete [] C;
|
||||
return Ret;
|
||||
}
|
||||
std::string 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);
|
||||
int TO = infstream.total_out;
|
||||
std::string Ret(TO,0);
|
||||
memcpy_s(&Ret[0],TO,C,TO);
|
||||
delete [] C;
|
||||
return Ret;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 2/23/2021
|
||||
///
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "Network/network.h"
|
||||
#include <filesystem>
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <cstdint>
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
std::string Branch;
|
||||
void ParseConfig(const nlohmann::json& d){
|
||||
if(d["Port"].is_number()){
|
||||
DEFAULT_PORT = d["Port"].get<int>();
|
||||
}
|
||||
//Default -1
|
||||
//Release 1
|
||||
//EA 2
|
||||
//Dev 3
|
||||
//Custom 3
|
||||
|
||||
if(d["Build"].is_string()){
|
||||
Branch = d["Build"].get<std::string>();
|
||||
for(char& c : Branch)c = char(tolower(c));
|
||||
}
|
||||
}
|
||||
|
||||
void ConfigInit(){
|
||||
if(fs::exists("Launcher.cfg")){
|
||||
std::ifstream cfg("Launcher.cfg");
|
||||
if(cfg.is_open()){
|
||||
auto Size = fs::file_size("Launcher.cfg");
|
||||
std::string Buffer(Size, 0);
|
||||
cfg.read(&Buffer[0], Size);
|
||||
cfg.close();
|
||||
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
|
||||
if(d.is_discarded()){
|
||||
fatal("Config failed to parse make sure it's valid JSON!");
|
||||
}
|
||||
ParseConfig(d);
|
||||
}else fatal("Failed to open Launcher.cfg!");
|
||||
}else{
|
||||
std::ofstream cfg("Launcher.cfg");
|
||||
if(cfg.is_open()){
|
||||
cfg <<
|
||||
R"({
|
||||
"Port": 4444,
|
||||
"Build": "Default"
|
||||
})";
|
||||
cfg.close();
|
||||
}else{
|
||||
fatal("Failed to write config on disk!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
111
src/Discord.cpp
111
src/Discord.cpp
@@ -1,111 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Discord/discord_rpc.h"
|
||||
#include "Logger.h"
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
#include <ctime>
|
||||
|
||||
struct DInfo{
|
||||
std::string Name;
|
||||
std::string Tag;
|
||||
std::string DID;
|
||||
};
|
||||
DInfo* DiscordInfo = nullptr;
|
||||
int64_t StartTime;
|
||||
void updateDiscordPresence(){
|
||||
//if (SendPresence) {
|
||||
//char buffer[256];
|
||||
DiscordRichPresence discordPresence;
|
||||
memset(&discordPresence, 0, sizeof(discordPresence));
|
||||
std::string P = "Playing with friends!"; ///to be revisited
|
||||
discordPresence.state = P.c_str();
|
||||
//sprintf(buffer, "Frustration level: %d", FrustrationLevel);
|
||||
//discordPresence.details = buffer;
|
||||
discordPresence.startTimestamp = StartTime;
|
||||
//discordPresence.endTimestamp = time(0) + 5 * 60;
|
||||
|
||||
discordPresence.largeImageKey = "mainlogo";
|
||||
//discordPresence.smallImageKey = "logo";
|
||||
//discordPresence.partyId = "party1234";
|
||||
//discordPresence.partySize = 1;
|
||||
//discordPresence.partyMax = 6;
|
||||
//discordPresence.matchSecret = "xyzzy";
|
||||
//discordPresence.joinSecret = "join";
|
||||
//discordPresence.spectateSecret = "look";
|
||||
//discordPresence.instance = 0;
|
||||
Discord_UpdatePresence(&discordPresence);
|
||||
//}
|
||||
//else {
|
||||
// Discord_ClearPresence();
|
||||
//}
|
||||
}
|
||||
void handleDiscordReady(const DiscordUser* User){
|
||||
DiscordInfo = new DInfo{
|
||||
User->username,
|
||||
User->discriminator,
|
||||
User->userId
|
||||
};
|
||||
}
|
||||
void discordInit(){
|
||||
DiscordEventHandlers handlers;
|
||||
memset(&handlers, 0, sizeof(handlers));
|
||||
handlers.ready = handleDiscordReady;
|
||||
/*handlers.disconnected = handleDiscordDisconnected;
|
||||
handlers.errored = handleDiscordError;
|
||||
handlers.joinGame = handleDiscordJoin;
|
||||
handlers.spectateGame = handleDiscordSpectate;
|
||||
handlers.joinRequest = handleDiscordJoinRequest;*/
|
||||
Discord_Initialize("629743237988352010", &handlers, 1,nullptr);
|
||||
}
|
||||
[[noreturn]] void Loop(){
|
||||
StartTime = time(nullptr);
|
||||
while (true) {
|
||||
updateDiscordPresence();
|
||||
#ifdef DISCORD_DISABLE_IO_THREAD
|
||||
Discord_UpdateConnection();
|
||||
#endif
|
||||
Discord_RunCallbacks();
|
||||
if(DiscordInfo == nullptr){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(250));
|
||||
}else std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
|
||||
void DMain(){
|
||||
discordInit();
|
||||
Loop();
|
||||
}
|
||||
std::string GetDName(){
|
||||
return DiscordInfo->Name;
|
||||
}
|
||||
std::string GetDTag(){
|
||||
return DiscordInfo->Tag;
|
||||
}
|
||||
std::string GetDID(){
|
||||
return DiscordInfo->DID;
|
||||
}
|
||||
void DAboard(){
|
||||
DiscordInfo = nullptr;
|
||||
}
|
||||
void ErrorAboard(){
|
||||
error("Discord timeout! please start the discord app and try again after 30 secs");
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(6);
|
||||
}
|
||||
void Discord_Main(){
|
||||
/*std::thread t1(DMain);
|
||||
t1.detach();*/
|
||||
/*info("Connecting to discord client...");
|
||||
int C = 0;
|
||||
while(DiscordInfo == nullptr && C < 80){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
C++;
|
||||
}
|
||||
if(DiscordInfo == nullptr)ErrorAboard();*/
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/19/2020
|
||||
///
|
||||
|
||||
#include <Security/Init.h>
|
||||
#include <windows.h>
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <thread>
|
||||
|
||||
unsigned long GamePID = 0;
|
||||
std::string QueryKey(HKEY hKey,int ID);
|
||||
std::string GetGamePath(){
|
||||
static std::string Path;
|
||||
if(!Path.empty())return Path;
|
||||
|
||||
HKEY hKey;
|
||||
LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive";
|
||||
LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
|
||||
if (openRes != ERROR_SUCCESS){
|
||||
fatal("Please launch the game at least once!");
|
||||
}
|
||||
Path = QueryKey(hKey,4);
|
||||
|
||||
if(Path.empty()){
|
||||
sk = R"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)";
|
||||
openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
|
||||
if (openRes != ERROR_SUCCESS){
|
||||
fatal("Cannot get Local Appdata directory!");
|
||||
}
|
||||
Path = QueryKey(hKey,5);
|
||||
Path += "\\BeamNG.drive\\";
|
||||
}
|
||||
std::string Ver = CheckVer(GetGameDir());
|
||||
Ver = Ver.substr(0,Ver.find('.',Ver.find('.')+1));
|
||||
Path += Ver + "\\";
|
||||
return Path;
|
||||
}
|
||||
|
||||
void StartGame(std::string Dir){
|
||||
BOOL bSuccess = FALSE;
|
||||
PROCESS_INFORMATION pi;
|
||||
STARTUPINFO si = {0};
|
||||
si.cb = sizeof(si);
|
||||
std::string BaseDir = Dir; //+"\\Bin64";
|
||||
//Dir += R"(\Bin64\BeamNG.drive.x64.exe)";
|
||||
Dir += "\\BeamNG.drive.exe";
|
||||
bSuccess = CreateProcessA(Dir.c_str(), nullptr, nullptr, nullptr, TRUE, 0, nullptr, BaseDir.c_str(), &si, &pi);
|
||||
if (bSuccess){
|
||||
info("Game Launched!");
|
||||
GamePID = pi.dwProcessId;
|
||||
WaitForSingleObject(pi.hProcess, INFINITE);
|
||||
error("Game Closed! launcher closing soon");
|
||||
}else{
|
||||
error("Failed to Launch the game! launcher closing soon");
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(2);
|
||||
}
|
||||
|
||||
void InitGame(const std::string& Dir){
|
||||
if(!Dev){
|
||||
std::thread Game(StartGame, Dir);
|
||||
Game.detach();
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/17/2020
|
||||
///
|
||||
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
std::string getDate() {
|
||||
time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
|
||||
tm local_tm = *localtime(&tt);
|
||||
std::stringstream date;
|
||||
int S = local_tm.tm_sec;
|
||||
int M = local_tm.tm_min;
|
||||
int H = local_tm.tm_hour;
|
||||
std::string Secs = (S > 9 ? std::to_string(S) : "0" + std::to_string(S));
|
||||
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
|
||||
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
|
||||
date
|
||||
<< "["
|
||||
<< local_tm.tm_mday << "/"
|
||||
<< local_tm.tm_mon + 1 << "/"
|
||||
<< local_tm.tm_year + 1900 << " "
|
||||
<< Hour << ":"
|
||||
<< Min << ":"
|
||||
<< Secs
|
||||
<< "] ";
|
||||
return date.str();
|
||||
}
|
||||
void InitLog(){
|
||||
std::ofstream LFS;
|
||||
LFS.open(GetEP() + "Launcher.log");
|
||||
if(!LFS.is_open()){
|
||||
error("logger file init failed!");
|
||||
}else LFS.close();
|
||||
}
|
||||
void addToLog(const std::string& Line){
|
||||
std::ofstream LFS;
|
||||
LFS.open(GetEP() + "Launcher.log", std::ios_base::app);
|
||||
LFS << Line.c_str();
|
||||
LFS.close();
|
||||
}
|
||||
void info(const std::string& toPrint) {
|
||||
std::string Print = getDate() + "[INFO] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void debug(const std::string& toPrint) {
|
||||
if(!Dev)return;
|
||||
std::string Print = getDate() + "[DEBUG] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void warn(const std::string& toPrint){
|
||||
std::string Print = getDate() + "[WARN] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void error(const std::string& toPrint) {
|
||||
std::string Print = getDate() + "[ERROR] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void fatal(const std::string& toPrint) {
|
||||
std::string Print = getDate() + "[FATAL] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
}
|
||||
void except(const std::string& toPrint) {
|
||||
std::string Print = getDate() + "[EXCEP] " + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
@@ -1,272 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/20/2020
|
||||
///
|
||||
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include <regex>
|
||||
#include "Http.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <charconv>
|
||||
#include <thread>
|
||||
#include <set>
|
||||
|
||||
extern int TraceBack;
|
||||
std::set<std::string>* ConfList = nullptr;
|
||||
bool TCPTerminate = false;
|
||||
int DEFAULT_PORT = 4444;
|
||||
bool Terminate = false;
|
||||
bool LoginAuth = false;
|
||||
std::string UlStatus;
|
||||
std::string MStatus;
|
||||
bool ModLoaded;
|
||||
int ping = -1;
|
||||
|
||||
void StartSync(const std::string &Data){
|
||||
std::string IP = GetAddr(Data.substr(1,Data.find(':')-1));
|
||||
if(IP.find('.') == -1){
|
||||
if(IP == "DNS")UlStatus ="UlConnection Failed! (DNS Lookup Failed)";
|
||||
else UlStatus = "UlConnection Failed! (WSA failed to start)";
|
||||
ListOfMods = "-";
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
CheckLocalKey();
|
||||
UlStatus = "UlLoading...";
|
||||
TCPTerminate = false;
|
||||
Terminate = false;
|
||||
ConfList->clear();
|
||||
ping = -1;
|
||||
std::thread GS(TCPGameServer,IP,std::stoi(Data.substr(Data.find(':')+1)));
|
||||
GS.detach();
|
||||
info("Connecting to server");
|
||||
}
|
||||
|
||||
bool IsAllowedLink(const std::string& Link) {
|
||||
std::regex link_pattern(R"(https:\/\/(?:\w+)?(?:\.)?(?:beammp\.com|discord\.gg))");
|
||||
std::smatch link_match;
|
||||
return std::regex_search(Link,link_match, link_pattern) && link_match.position() == 0;
|
||||
}
|
||||
|
||||
void Parse(std::string Data,SOCKET CSocket){
|
||||
char Code = Data.at(0), SubCode = 0;
|
||||
if(Data.length() > 1)SubCode = Data.at(1);
|
||||
switch (Code){
|
||||
case 'A':
|
||||
Data = Data.substr(0,1);
|
||||
break;
|
||||
case 'B':
|
||||
NetReset();
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
Data = Code + HTTP::Get("https://backend.beammp.com/servers-info");
|
||||
break;
|
||||
case 'C':
|
||||
ListOfMods.clear();
|
||||
StartSync(Data);
|
||||
while(ListOfMods.empty() && !Terminate){
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
if(ListOfMods == "-")Data = "L";
|
||||
else Data = "L"+ListOfMods;
|
||||
break;
|
||||
case 'O': //open default browser with URL
|
||||
if(IsAllowedLink(Data.substr(1))) {
|
||||
ShellExecuteA(nullptr, "open", Data.substr(1).c_str(), nullptr, nullptr,SW_SHOW); ///TODO: Look at when working on linux port
|
||||
info("Opening Link \"" + Data.substr(1) + "\"");
|
||||
}
|
||||
Data.clear();
|
||||
break;
|
||||
case 'P':
|
||||
Data = Code + std::to_string(ProxyPort);
|
||||
break;
|
||||
case 'U':
|
||||
if(SubCode == 'l')Data = UlStatus;
|
||||
if(SubCode == 'p'){
|
||||
if(ping > 800){
|
||||
Data = "Up-2";
|
||||
}else Data = "Up" + std::to_string(ping);
|
||||
}
|
||||
if(!SubCode){
|
||||
std::string Ping;
|
||||
if(ping > 800)Ping = "-2";
|
||||
else Ping = std::to_string(ping);
|
||||
Data = std::string(UlStatus) + "\n" + "Up" + Ping;
|
||||
}
|
||||
break;
|
||||
case 'M':
|
||||
Data = MStatus;
|
||||
break;
|
||||
case 'Q':
|
||||
if(SubCode == 'S'){
|
||||
NetReset();
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
ping = -1;
|
||||
}
|
||||
if(SubCode == 'G')exit(2);
|
||||
Data.clear();
|
||||
break;
|
||||
case 'R': //will send mod name
|
||||
if(ConfList->find(Data) == ConfList->end()){
|
||||
ConfList->insert(Data);
|
||||
ModLoaded = true;
|
||||
}
|
||||
Data.clear();
|
||||
break;
|
||||
case 'Z':
|
||||
Data = "Z" + GetVer();
|
||||
break;
|
||||
case 'N':
|
||||
if (SubCode == 'c'){
|
||||
Data = "N{\"Auth\":"+std::to_string(LoginAuth)+"}";
|
||||
}else{
|
||||
Data = "N" + Login(Data.substr(Data.find(':') + 1));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
Data.clear();
|
||||
break;
|
||||
}
|
||||
if(!Data.empty() && CSocket != -1){
|
||||
int res = send(CSocket, (Data+"\n").c_str(), int(Data.size())+1, 0);
|
||||
if(res < 0){
|
||||
debug("(Core) send failed with error: " + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
}
|
||||
}
|
||||
void GameHandler(SOCKET Client){
|
||||
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
do{
|
||||
Rcv = 0;
|
||||
do{
|
||||
Temp = recv(Client,&Header[Rcv],1,0);
|
||||
if(Temp < 1)break;
|
||||
if(!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
|
||||
error("(Core) Invalid lua communication");
|
||||
KillSocket(Client);
|
||||
return;
|
||||
}
|
||||
}while(Header[Rcv++] != '>');
|
||||
if(Temp < 1)break;
|
||||
if(std::from_chars(Header,&Header[Rcv],Size).ptr[0] != '>'){
|
||||
debug("(Core) Invalid lua Header -> " + std::string(Header,Rcv));
|
||||
break;
|
||||
}
|
||||
std::string Ret(Size,0);
|
||||
Rcv = 0;
|
||||
|
||||
do{
|
||||
Temp = recv(Client,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size);
|
||||
if(Temp < 1)break;
|
||||
|
||||
std::thread Respond(Parse, Ret, Client);
|
||||
Respond.detach();
|
||||
}while(Temp > 0);
|
||||
if (Temp == 0) {
|
||||
debug("(Core) Connection closing");
|
||||
} else {
|
||||
debug("(Core) recv failed with error: " + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
NetReset();
|
||||
KillSocket(Client);
|
||||
}
|
||||
void localRes(){
|
||||
MStatus = " ";
|
||||
UlStatus = "Ulstart";
|
||||
if(ConfList != nullptr){
|
||||
ConfList->clear();
|
||||
delete ConfList;
|
||||
ConfList = nullptr;
|
||||
}
|
||||
ConfList = new std::set<std::string>;
|
||||
}
|
||||
void CoreMain() {
|
||||
debug("Core Network on start!");
|
||||
WSADATA wsaData;
|
||||
SOCKET LSocket,CSocket;
|
||||
struct addrinfo *res = nullptr;
|
||||
struct addrinfo hints{};
|
||||
int iRes = WSAStartup(514, &wsaData); //2.2
|
||||
if (iRes)debug("WSAStartup failed with error: " + std::to_string(iRes));
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
iRes = getaddrinfo(nullptr, std::to_string(DEFAULT_PORT).c_str(), &hints, &res);
|
||||
if (iRes){
|
||||
debug("(Core) addr info failed with error: " + std::to_string(iRes));
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
LSocket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (LSocket == -1){
|
||||
debug("(Core) socket failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
iRes = bind(LSocket, res->ai_addr, int(res->ai_addrlen));
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error("(Core) bind failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
iRes = listen(LSocket, SOMAXCONN);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
debug("(Core) listen failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
do{
|
||||
CSocket = accept(LSocket, nullptr, nullptr);
|
||||
if (CSocket == -1) {
|
||||
error("(Core) accept failed with error: " + std::to_string(WSAGetLastError()));
|
||||
continue;
|
||||
}
|
||||
localRes();
|
||||
info("Game Connected!");
|
||||
GameHandler(CSocket);
|
||||
warn("Game Reconnecting...");
|
||||
}while(CSocket);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
}
|
||||
int Handle(EXCEPTION_POINTERS *ep){
|
||||
char* hex = new char[100];
|
||||
sprintf_s(hex,100, "%lX", ep->ExceptionRecord->ExceptionCode);
|
||||
except("(Core) Code : " + std::string(hex));
|
||||
delete [] hex;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
[[noreturn]] void CoreNetwork(){
|
||||
while(true) {
|
||||
#ifndef __MINGW32__
|
||||
__try{
|
||||
#endif
|
||||
CoreMain();
|
||||
#ifndef __MINGW32__
|
||||
}__except(Handle(GetExceptionInformation())){}
|
||||
#endif
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 9/25/2020
|
||||
///
|
||||
|
||||
#include <string>
|
||||
#include <winsock2.h>
|
||||
#include "Logger.h"
|
||||
|
||||
std::string GetAddr(const std::string&IP){
|
||||
if(IP.find_first_not_of("0123456789.") == -1)return IP;
|
||||
WSADATA wsaData;
|
||||
hostent *host;
|
||||
if(WSAStartup(514, &wsaData) != 0){
|
||||
error("WSA Startup Failed!");
|
||||
WSACleanup();
|
||||
return "";
|
||||
}
|
||||
host = gethostbyname(IP.c_str());
|
||||
if(!host){
|
||||
error("DNS lookup failed! on " + IP);
|
||||
WSACleanup();
|
||||
return "DNS";
|
||||
}
|
||||
std::string Ret = inet_ntoa(*((struct in_addr *)host->h_addr));
|
||||
WSACleanup();
|
||||
return Ret;
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/25/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include "Logger.h"
|
||||
#include <charconv>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> PingStart,PingEnd;
|
||||
bool GConnected = false;
|
||||
bool CServer = true;
|
||||
SOCKET CSocket = -1;
|
||||
SOCKET GSocket = -1;
|
||||
|
||||
int KillSocket(uint64_t Dead){
|
||||
if(Dead == (SOCKET)-1){
|
||||
debug("Kill socket got -1 returning...");
|
||||
return 0;
|
||||
}
|
||||
shutdown(Dead,SD_BOTH);
|
||||
int a = closesocket(Dead);
|
||||
if(a != 0){
|
||||
warn("Failed to close socket!");
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
bool CheckBytes(uint32_t Bytes){
|
||||
if(Bytes == 0){
|
||||
debug("(Proxy) Connection closing");
|
||||
return false;
|
||||
}else if(Bytes < 0){
|
||||
debug("(Proxy) send failed with error: " + std::to_string(WSAGetLastError()));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void GameSend(std::string Data){
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
if(TCPTerminate || !GConnected || CSocket == -1)return;
|
||||
int32_t Size,Temp,Sent;
|
||||
Data += '\n';
|
||||
Size = int32_t(Data.size());
|
||||
Sent = 0;
|
||||
#ifdef DEBUG
|
||||
if(Size > 1000){
|
||||
debug("Launcher -> game (" +std::to_string(Size)+")");
|
||||
}
|
||||
#endif
|
||||
do{
|
||||
if(Sent > -1){
|
||||
Temp = send(CSocket, &Data[Sent], Size - Sent, 0);
|
||||
}
|
||||
if(!CheckBytes(Temp))return;
|
||||
Sent += Temp;
|
||||
}while(Sent < Size);
|
||||
}
|
||||
void ServerSend(std::string Data, bool Rel){
|
||||
if(Terminate || Data.empty())return;
|
||||
if(Data.find("Zp") != std::string::npos && Data.size() > 500){
|
||||
abort();
|
||||
}
|
||||
char C = 0;
|
||||
bool Ack = false;
|
||||
int DLen = int(Data.length());
|
||||
if(DLen > 3)C = Data.at(0);
|
||||
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 || DLen > 1000)SendLarge(Data);
|
||||
else TCPSend(Data,TCPSock);
|
||||
}else UDPSend(Data);
|
||||
|
||||
if (DLen > 1000) {
|
||||
debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : "
|
||||
+ Data.substr(0, 10)
|
||||
+ Data.substr(Data.length() - 10));
|
||||
}else if(C == 'Z'){
|
||||
//debug("(Game->Launcher) : " + Data);
|
||||
}
|
||||
}
|
||||
|
||||
void NetReset(){
|
||||
TCPTerminate = false;
|
||||
GConnected = false;
|
||||
Terminate = false;
|
||||
UlStatus = "Ulstart";
|
||||
MStatus = " ";
|
||||
if(UDPSock != (SOCKET)(-1)){
|
||||
debug("Terminating UDP Socket : " + std::to_string(TCPSock));
|
||||
KillSocket(UDPSock);
|
||||
}
|
||||
UDPSock = -1;
|
||||
if(TCPSock != (SOCKET)(-1)){
|
||||
debug("Terminating TCP Socket : " + std::to_string(TCPSock));
|
||||
KillSocket(TCPSock);
|
||||
}
|
||||
TCPSock = -1;
|
||||
if(GSocket != (SOCKET)(-1)){
|
||||
debug("Terminating GTCP Socket : " + std::to_string(GSocket));
|
||||
KillSocket(GSocket);
|
||||
}
|
||||
GSocket = -1;
|
||||
}
|
||||
|
||||
SOCKET SetupListener(){
|
||||
if(GSocket != -1)return GSocket;
|
||||
struct addrinfo *result = nullptr;
|
||||
struct addrinfo hints{};
|
||||
WSADATA wsaData;
|
||||
int iRes = WSAStartup(514, &wsaData); //2.2
|
||||
if (iRes != 0) {
|
||||
error("(Proxy) WSAStartup failed with error: " + std::to_string(iRes));
|
||||
return -1;
|
||||
}
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
iRes = getaddrinfo(nullptr, std::to_string(DEFAULT_PORT+1).c_str(), &hints, &result);
|
||||
if (iRes != 0) {
|
||||
error("(Proxy) info failed with error: " + std::to_string(iRes));
|
||||
WSACleanup();
|
||||
}
|
||||
GSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
|
||||
if (GSocket == -1) {
|
||||
error("(Proxy) socket failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(result);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
iRes = bind(GSocket, result->ai_addr, (int) result->ai_addrlen);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error("(Proxy) bind failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(result);
|
||||
KillSocket(GSocket);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
freeaddrinfo(result);
|
||||
iRes = listen(GSocket, SOMAXCONN);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error("(Proxy) listen failed with error: " + std::to_string(WSAGetLastError()));
|
||||
KillSocket(GSocket);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
return GSocket;
|
||||
}
|
||||
void AutoPing(){
|
||||
while(!Terminate){
|
||||
ServerSend("p",false);
|
||||
PingStart = std::chrono::high_resolution_clock::now();
|
||||
std::this_thread::sleep_for(std::chrono::seconds (1));
|
||||
}
|
||||
}
|
||||
int ClientID = -1;
|
||||
void ParserAsync(const std::string& Data){
|
||||
if(Data.empty())return;
|
||||
char Code = Data.at(0),SubCode = 0;
|
||||
if(Data.length() > 1)SubCode = Data.at(1);
|
||||
switch (Code) {
|
||||
case 'p':
|
||||
PingEnd = std::chrono::high_resolution_clock::now();
|
||||
if(PingStart > PingEnd)ping = 0;
|
||||
else ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd-PingStart).count());
|
||||
return;
|
||||
case 'M':
|
||||
MStatus = Data;
|
||||
UlStatus = "Uldone";
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
GameSend(Data);
|
||||
}
|
||||
void ServerParser(const std::string& Data){
|
||||
ParserAsync(Data);
|
||||
}
|
||||
void NetMain(const std::string& IP, int Port){
|
||||
std::thread Ping(AutoPing);
|
||||
Ping.detach();
|
||||
UDPClientMain(IP,Port);
|
||||
CServer = true;
|
||||
Terminate = true;
|
||||
info("Connection Terminated!");
|
||||
}
|
||||
void TCPGameServer(const std::string& IP, int Port){
|
||||
GSocket = SetupListener();
|
||||
while (!TCPTerminate && GSocket != -1){
|
||||
debug("MAIN LOOP OF GAME SERVER");
|
||||
GConnected = false;
|
||||
if(!CServer){
|
||||
warn("Connection still alive terminating");
|
||||
NetReset();
|
||||
TCPTerminate = true;
|
||||
Terminate = true;
|
||||
break;
|
||||
}
|
||||
if(CServer) {
|
||||
std::thread Client(TCPClientMain, IP, Port);
|
||||
Client.detach();
|
||||
}
|
||||
CSocket = accept(GSocket, nullptr, nullptr);
|
||||
if (CSocket == -1) {
|
||||
debug("(Proxy) accept failed with error: " + std::to_string(WSAGetLastError()));
|
||||
break;
|
||||
}
|
||||
debug("(Proxy) Game Connected!");
|
||||
GConnected = true;
|
||||
if(CServer){
|
||||
std::thread t1(NetMain, IP, Port);
|
||||
t1.detach();
|
||||
CServer = false;
|
||||
}
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
|
||||
//Read byte by byte until '>' is rcved then get the size and read based on it
|
||||
do{
|
||||
Rcv = 0;
|
||||
|
||||
do{
|
||||
Temp = recv(CSocket,&Header[Rcv],1,0);
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
}while(Header[Rcv++] != '>');
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
if(std::from_chars(Header,&Header[Rcv],Size).ptr[0] != '>'){
|
||||
debug("(Game) Invalid lua Header -> " + std::string(Header,Rcv));
|
||||
break;
|
||||
}
|
||||
std::string Ret(Size,0);
|
||||
Rcv = 0;
|
||||
do{
|
||||
Temp = recv(CSocket,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size && !TCPTerminate);
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
|
||||
ServerSend(Ret,false);
|
||||
|
||||
}while(Temp > 0 && !TCPTerminate);
|
||||
if(Temp == 0)debug("(Proxy) Connection closing");
|
||||
else debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
TCPTerminate = true;
|
||||
GConnected = false;
|
||||
Terminate = true;
|
||||
if(CSocket != SOCKET_ERROR)KillSocket(CSocket);
|
||||
debug("END OF GAME SERVER");
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT
|
||||
|
||||
#include <iostream>
|
||||
#include <Logger.h>
|
||||
#include <fstream>
|
||||
#include "Http.h"
|
||||
#include <mutex>
|
||||
#include <cmath>
|
||||
#include <httplib.h>
|
||||
|
||||
bool HTTP::isDownload = false;
|
||||
std::string HTTP::Get(const std::string &IP) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
auto pos = IP.find('/',10);
|
||||
|
||||
httplib::Client cli(IP.substr(0, pos).c_str());
|
||||
cli.set_connection_timeout(std::chrono::seconds(10));
|
||||
cli.set_follow_location(true);
|
||||
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
|
||||
std::string Ret;
|
||||
|
||||
if(res){
|
||||
if(res->status == 200){
|
||||
Ret = res->body;
|
||||
}else error(res->reason);
|
||||
|
||||
}else{
|
||||
if(isDownload) {
|
||||
std::cout << "\n";
|
||||
}
|
||||
error("HTTP Get failed on " + to_string(res.error()));
|
||||
}
|
||||
|
||||
return Ret;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
httplib::Client cli(IP.substr(0, pos).c_str());
|
||||
cli.set_connection_timeout(std::chrono::seconds(10));
|
||||
std::string Ret;
|
||||
|
||||
if(!Fields.empty()) {
|
||||
httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json");
|
||||
|
||||
if(res) {
|
||||
if (res->status != 200) {
|
||||
error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
}else{
|
||||
error("HTTP Post failed on " + to_string(res.error()));
|
||||
}
|
||||
}else{
|
||||
httplib::Result res = cli.Post(IP.substr(pos).c_str());
|
||||
if(res) {
|
||||
if (res->status != 200) {
|
||||
error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
}else{
|
||||
error("HTTP Post failed on " + to_string(res.error()));
|
||||
}
|
||||
}
|
||||
|
||||
if(Ret.empty())return "-1";
|
||||
else return Ret;
|
||||
}
|
||||
|
||||
bool HTTP::ProgressBar(size_t c, size_t t){
|
||||
if(isDownload) {
|
||||
static double last_progress, progress_bar_adv;
|
||||
progress_bar_adv = round(c / double(t) * 25);
|
||||
std::cout << "\r";
|
||||
std::cout << "Progress : [ ";
|
||||
std::cout << round(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 << "]";
|
||||
last_progress = round(c / double(t) * 100);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HTTP::Download(const std::string &IP, const std::string &Path) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
isDownload = true;
|
||||
std::string Ret = Get(IP);
|
||||
isDownload = false;
|
||||
|
||||
if(Ret.empty())return false;
|
||||
|
||||
std::ofstream File(Path, std::ios::binary);
|
||||
if(File.is_open()) {
|
||||
File << Ret;
|
||||
File.close();
|
||||
std::cout << "\n";
|
||||
info("Download Complete!");
|
||||
}else{
|
||||
error("Failed to open file directory: " + Path);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,325 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 4/11/2020
|
||||
///
|
||||
|
||||
#include "Network/network.h"
|
||||
#include <ws2tcpip.h>
|
||||
#include <filesystem>
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
#include <future>
|
||||
#include <cmath>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
std::string ListOfMods;
|
||||
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");
|
||||
}
|
||||
}
|
||||
void WaitForConfirm(){
|
||||
while(!Terminate && !ModLoaded){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
ModLoaded = false;
|
||||
}
|
||||
|
||||
|
||||
void Abord(){
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
info("Terminated!");
|
||||
}
|
||||
|
||||
std::string Auth(SOCKET Sock){
|
||||
TCPSend("VC" + GetVer(),Sock);
|
||||
|
||||
auto Res = TCPRcv(Sock);
|
||||
|
||||
if(Res.empty() || Res[0] == 'E' || Res[0] == 'K'){
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
TCPSend(PublicKey,Sock);
|
||||
if(Terminate)return "";
|
||||
|
||||
Res = TCPRcv(Sock);
|
||||
if(Res.empty() || Res[0] != 'P'){
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
Res = Res.substr(1);
|
||||
if(Res.find_first_not_of("0123456789") == std::string::npos){
|
||||
ClientID = std::stoi(Res);
|
||||
}else{
|
||||
Abord();
|
||||
UUl("Authentication failed!");
|
||||
return "";
|
||||
}
|
||||
TCPSend("SR",Sock);
|
||||
if(Terminate)return "";
|
||||
|
||||
Res = TCPRcv(Sock);
|
||||
|
||||
if(Res[0] == 'E' || Res[0] == 'K'){
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
if(Res.empty() || Res == "-"){
|
||||
info("Didn't Receive any mods...");
|
||||
ListOfMods = "-";
|
||||
TCPSend("Done",Sock);
|
||||
info("Done!");
|
||||
return "";
|
||||
}
|
||||
return Res;
|
||||
}
|
||||
|
||||
void UpdateUl(bool D,const std::string& msg){
|
||||
if(D)UlStatus = "UlDownloading Resource " + msg;
|
||||
else UlStatus = "UlLoading Resource " + msg;
|
||||
}
|
||||
|
||||
void 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* TCPRcvRaw(SOCKET 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){
|
||||
info(std::to_string(Temp));
|
||||
UUl("Socket Closed Code 1");
|
||||
KillSocket(Sock);
|
||||
Terminate = true;
|
||||
delete[] File;
|
||||
return nullptr;
|
||||
}
|
||||
Rcv += Temp;
|
||||
GRcv += Temp;
|
||||
}while(Rcv < Size && !Terminate);
|
||||
return File;
|
||||
}
|
||||
void MultiKill(SOCKET Sock,SOCKET Sock1){
|
||||
KillSocket(Sock1);
|
||||
KillSocket(Sock);
|
||||
Terminate = true;
|
||||
}
|
||||
SOCKET 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(LastPort);
|
||||
inet_pton(AF_INET, LastIP.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 MultiDownload(SOCKET MSock,SOCKET DSock, uint64_t Size, const std::string& Name){
|
||||
|
||||
uint64_t GRcv = 0, MSize = Size/2, DSize = Size - MSize;
|
||||
|
||||
std::thread Au(AsyncUpdate,std::ref(GRcv), Size, Name);
|
||||
|
||||
std::packaged_task<char*()> task([&] { return TCPRcvRaw(MSock,GRcv,MSize); });
|
||||
std::future<char*> f1 = task.get_future();
|
||||
std::thread Dt(std::move(task));
|
||||
Dt.detach();
|
||||
|
||||
char* DData = TCPRcvRaw(DSock,GRcv,DSize);
|
||||
|
||||
if(!DData){
|
||||
MultiKill(MSock,DSock);
|
||||
return "";
|
||||
}
|
||||
|
||||
f1.wait();
|
||||
char* MData = f1.get();
|
||||
|
||||
if(!MData){
|
||||
MultiKill(MSock,DSock);
|
||||
return "";
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
memcpy_s(&Ret[MSize],DSize,DData,DSize);
|
||||
delete[]DData;
|
||||
|
||||
return Ret;
|
||||
}
|
||||
|
||||
void InvalidResource(const std::string& File){
|
||||
UUl("Invalid mod \"" + File + "\"");
|
||||
warn("The server tried to sync \"" + File + "\" that is not a .zip file!");
|
||||
Terminate = true;
|
||||
}
|
||||
|
||||
void SyncResources(SOCKET Sock){
|
||||
std::string Ret = Auth(Sock);
|
||||
if(Ret.empty())return;
|
||||
|
||||
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();
|
||||
|
||||
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())ListOfMods = "-";
|
||||
else ListOfMods = 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())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 (FS->find_first_not_of("0123456789") != std::string::npos)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(GetGamePath() + "mods/multiplayer")){
|
||||
fs::create_directories(GetGamePath() + "mods/multiplayer");
|
||||
}
|
||||
auto name = GetGamePath() + "mods/multiplayer" + a.substr(a.find_last_of('/'));
|
||||
auto tmp_name = name + ".tmp";
|
||||
fs::copy_file(a,tmp_name,fs::copy_options::overwrite_existing);
|
||||
fs::rename(tmp_name, name);
|
||||
} catch (std::exception& e) {
|
||||
error("Failed copy to the mods folder! " + std::string(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,Sock);
|
||||
|
||||
std::string Data = TCPRcv(Sock);
|
||||
if (Data == "CO" || Terminate){
|
||||
Terminate = true;
|
||||
UUl("Server cannot find " + FName);
|
||||
break;
|
||||
}
|
||||
|
||||
std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
|
||||
|
||||
Data = MultiDownload(Sock,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], Data.size());
|
||||
LFS.close();
|
||||
}
|
||||
|
||||
}while(fs::file_size(a) != std::stoull(*FS) && !Terminate);
|
||||
if(!Terminate){
|
||||
if(!fs::exists(GetGamePath() + "mods/multiplayer")){
|
||||
fs::create_directories(GetGamePath() + "mods/multiplayer");
|
||||
}
|
||||
fs::copy_file(a,GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
WaitForConfirm();
|
||||
}
|
||||
KillSocket(DSock);
|
||||
if(!Terminate){
|
||||
TCPSend("Done",Sock);
|
||||
info("Done!");
|
||||
}else{
|
||||
UlStatus = "Ulstart";
|
||||
info("Connection Terminated!");
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
#include "Zlib/Compressor.h"
|
||||
#include "Network/network.h"
|
||||
|
||||
#include <ws2tcpip.h>
|
||||
#include "Logger.h"
|
||||
#include <string>
|
||||
#include <set>
|
||||
|
||||
SOCKET UDPSock = -1;
|
||||
sockaddr_in* ToServer = nullptr;
|
||||
|
||||
void UDPSend(std::string Data){
|
||||
if(ClientID == -1 || UDPSock == -1)return;
|
||||
if(Data.length() > 400){
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
std::string Packet = char(ClientID+1) + std::string(":") + Data;
|
||||
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()));
|
||||
}
|
||||
|
||||
|
||||
void SendLarge(std::string Data){
|
||||
if(Data.length() > 400){
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
TCPSend(Data,TCPSock);
|
||||
}
|
||||
|
||||
void UDPParser(std::string Packet){
|
||||
if(Packet.substr(0,4) == "ABG:"){
|
||||
Packet = DeComp(Packet.substr(4));
|
||||
}
|
||||
ServerParser(Packet);
|
||||
}
|
||||
void UDPRcv(){
|
||||
sockaddr_in FromServer{};
|
||||
int clientLength = sizeof(FromServer);
|
||||
ZeroMemory(&FromServer, clientLength);
|
||||
std::string Ret(10240,0);
|
||||
if(UDPSock == -1)return;
|
||||
int32_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength);
|
||||
if (Rcv == SOCKET_ERROR)return;
|
||||
UDPParser(Ret.substr(0,Rcv));
|
||||
}
|
||||
void UDPClientMain(const std::string& IP,int Port){
|
||||
WSADATA data;
|
||||
if (WSAStartup(514, &data)){
|
||||
error("Can't start Winsock!");
|
||||
return;
|
||||
}
|
||||
delete ToServer;
|
||||
ToServer = new sockaddr_in;
|
||||
ToServer->sin_family = AF_INET;
|
||||
ToServer->sin_port = htons(Port);
|
||||
inet_pton(AF_INET, IP.c_str(), &ToServer->sin_addr);
|
||||
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
GameSend("P"+std::to_string(ClientID));
|
||||
TCPSend("H",TCPSock);
|
||||
UDPSend("p");
|
||||
while(!Terminate)UDPRcv();
|
||||
KillSocket(UDPSock);
|
||||
WSACleanup();
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <ws2tcpip.h>
|
||||
#include <Zlib/Compressor.h>
|
||||
|
||||
#include "Network/network.h"
|
||||
|
||||
|
||||
int LastPort;
|
||||
std::string LastIP;
|
||||
SOCKET TCPSock = -1;
|
||||
|
||||
bool 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: " + std::to_string(WSAGetLastError()));
|
||||
KillSocket(TCPSock);
|
||||
Terminate = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void UUl(const std::string& R){
|
||||
UlStatus = "UlDisconnected: " + R;
|
||||
}
|
||||
|
||||
void TCPSend(const std::string&Data,uint64_t Sock){
|
||||
if(Sock == -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()) {
|
||||
error("string OOB in " + std::string(__func__));
|
||||
UUl("TCP Send OOB");
|
||||
return;
|
||||
}
|
||||
Temp = send(Sock, &Send[Sent], Size - Sent, 0);
|
||||
if(!CheckBytes(Temp)){
|
||||
UUl("Socket Closed Code 2");
|
||||
return;
|
||||
}
|
||||
Sent += Temp;
|
||||
}while(Sent < Size);
|
||||
}
|
||||
|
||||
std::string TCPRcv(SOCKET Sock){
|
||||
if(Sock == -1){
|
||||
Terminate = true;
|
||||
UUl("Invalid Socket");
|
||||
return "";
|
||||
}
|
||||
int32_t Header,BytesRcv = 0,Temp;
|
||||
std::vector<char> Data(sizeof(Header));
|
||||
do{
|
||||
Temp = recv(Sock,&Data[BytesRcv],4-BytesRcv,0);
|
||||
if(!CheckBytes(Temp)){
|
||||
UUl("Socket Closed Code 3");
|
||||
return "";
|
||||
}
|
||||
BytesRcv += Temp;
|
||||
}while(BytesRcv < 4);
|
||||
memcpy(&Header,&Data[0],sizeof(Header));
|
||||
|
||||
if(!CheckBytes(BytesRcv)){
|
||||
UUl("Socket Closed Code 4");
|
||||
return "";
|
||||
}
|
||||
Data.resize(Header);
|
||||
BytesRcv = 0;
|
||||
do{
|
||||
Temp = recv(Sock,&Data[BytesRcv],Header-BytesRcv,0);
|
||||
if(!CheckBytes(Temp)){
|
||||
UUl("Socket Closed Code 5");
|
||||
return "";
|
||||
}
|
||||
BytesRcv += Temp;
|
||||
}while(BytesRcv < Header);
|
||||
|
||||
std::string Ret(Data.data(),Header);
|
||||
|
||||
if (Ret.substr(0, 4) == "ABG:") {
|
||||
Ret = DeComp(Ret.substr(4));
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
//debug("Parsing from server -> " + std::to_string(Ret.size()));
|
||||
#endif
|
||||
if(Ret[0] == 'E' || Ret[0] == 'K')UUl(Ret.substr(1));
|
||||
return Ret;
|
||||
}
|
||||
|
||||
void TCPClientMain(const std::string& IP,int Port){
|
||||
LastIP = IP;
|
||||
LastPort = Port;
|
||||
WSADATA wsaData;
|
||||
SOCKADDR_IN ServerAddr;
|
||||
int RetCode;
|
||||
WSAStartup(514, &wsaData); //2.2
|
||||
TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
|
||||
if(TCPSock == -1){
|
||||
printf("Client: socket failed! Error code: %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
ServerAddr.sin_family = AF_INET;
|
||||
ServerAddr.sin_port = htons(Port);
|
||||
inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr);
|
||||
RetCode = connect(TCPSock, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr));
|
||||
if(RetCode != 0){
|
||||
UlStatus = "UlConnection Failed!";
|
||||
error("Client: connect failed! Error code: " + std::to_string(WSAGetLastError()));
|
||||
KillSocket(TCPSock);
|
||||
WSACleanup();
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
info("Connected!");
|
||||
|
||||
char Code = 'C';
|
||||
send(TCPSock, &Code, 1, 0);
|
||||
SyncResources(TCPSock);
|
||||
while(!Terminate){
|
||||
ServerParser(TCPRcv(TCPSock));
|
||||
}
|
||||
GameSend("T");
|
||||
////Game Send Terminate
|
||||
if(KillSocket(TCPSock) != 0)
|
||||
debug("(TCP) Cannot close socket. Error code: " + std::to_string(WSAGetLastError()));
|
||||
|
||||
if(WSACleanup() != 0)
|
||||
debug("(TCP) Client: WSACleanup() failed!...");
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
|
||||
#include <filesystem>
|
||||
#include <windows.h>
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#define MAX_KEY_LENGTH 255
|
||||
#define MAX_VALUE_NAME 16383
|
||||
|
||||
int TraceBack = 0;
|
||||
std::string GameDir;
|
||||
|
||||
void lowExit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
"Failed to find the game please launch it. Report this if the issue persists code ";
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(2);
|
||||
}
|
||||
/*void Exit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
"Sorry. We do not support cracked copies report this if you believe this is a mistake code ";
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(3);
|
||||
}
|
||||
void SteamExit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
"Illegal steam modifications detected report this if you believe this is a mistake code ";
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(4);
|
||||
}*/
|
||||
std::string GetGameDir(){
|
||||
//if(TraceBack != 4)Exit(0);
|
||||
return GameDir.substr(0,GameDir.find_last_of('\\'));
|
||||
}
|
||||
LONG OpenKey(HKEY root,const char* path,PHKEY hKey){
|
||||
return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey);
|
||||
}
|
||||
std::string QueryKey(HKEY hKey,int ID){
|
||||
TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name
|
||||
DWORD cbName; // size of name string
|
||||
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
|
||||
DWORD cchClassName = MAX_PATH; // size of class string
|
||||
DWORD cSubKeys=0; // number of subkeys
|
||||
DWORD cbMaxSubKey; // longest subkey size
|
||||
DWORD cchMaxClass; // longest class string
|
||||
DWORD cValues; // number of values for key
|
||||
DWORD cchMaxValue; // longest value name
|
||||
DWORD cbMaxValueData; // longest value data
|
||||
DWORD cbSecurityDescriptor; // size of security descriptor
|
||||
FILETIME ftLastWriteTime; // last write time
|
||||
|
||||
DWORD i, retCode;
|
||||
|
||||
TCHAR achValue[MAX_VALUE_NAME];
|
||||
DWORD cchValue = MAX_VALUE_NAME;
|
||||
|
||||
retCode = RegQueryInfoKey(
|
||||
hKey, // key handle
|
||||
achClass, // buffer for class name
|
||||
&cchClassName, // size of class string
|
||||
nullptr, // reserved
|
||||
&cSubKeys, // number of subkeys
|
||||
&cbMaxSubKey, // longest subkey size
|
||||
&cchMaxClass, // longest class string
|
||||
&cValues, // number of values for this key
|
||||
&cchMaxValue, // longest value name
|
||||
&cbMaxValueData, // longest value data
|
||||
&cbSecurityDescriptor, // security descriptor
|
||||
&ftLastWriteTime); // last write time
|
||||
|
||||
BYTE* buffer = new BYTE[cbMaxValueData];
|
||||
ZeroMemory(buffer, cbMaxValueData);
|
||||
if (cSubKeys){
|
||||
for (i=0; i<cSubKeys; i++){
|
||||
cbName = MAX_KEY_LENGTH;
|
||||
retCode = RegEnumKeyEx(hKey, i,achKey,&cbName,nullptr,nullptr,nullptr,&ftLastWriteTime);
|
||||
if (retCode == ERROR_SUCCESS){
|
||||
if(strcmp(achKey,"Steam App 284160") == 0){
|
||||
return achKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cValues){
|
||||
for (i=0, retCode = ERROR_SUCCESS; i<cValues; i++){
|
||||
cchValue = MAX_VALUE_NAME;
|
||||
achValue[0] = '\0';
|
||||
retCode = RegEnumValue(hKey, i,achValue,&cchValue,nullptr,nullptr,nullptr,nullptr);
|
||||
if (retCode == ERROR_SUCCESS ){
|
||||
DWORD lpData = cbMaxValueData;
|
||||
buffer[0] = '\0';
|
||||
LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData);
|
||||
std::string data = (char *)(buffer);
|
||||
std::string key = achValue;
|
||||
|
||||
switch (ID){
|
||||
case 1: if(key == "SteamExe"){
|
||||
auto p = data.find_last_of("/\\");
|
||||
if(p != std::string::npos){
|
||||
return data.substr(0,p);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 2: if(key == "Name" && data == "BeamNG.drive")return data;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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete [] buffer;
|
||||
return "";
|
||||
}
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
bool NameValid(const std::string& N){
|
||||
if(N == "config" || N == "librarycache"){
|
||||
return true;
|
||||
}
|
||||
if(N.find_first_not_of("0123456789") == std::string::npos){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void FileList(std::vector<std::string>&a,const std::string& Path){
|
||||
for (const auto &entry : fs::directory_iterator(Path)) {
|
||||
const auto& DPath = entry.path();
|
||||
if (!entry.is_directory()) {
|
||||
a.emplace_back(DPath.string());
|
||||
}else if(NameValid(DPath.filename().string())){
|
||||
FileList(a, DPath.string());
|
||||
}
|
||||
}
|
||||
}
|
||||
bool Find(const std::string& FName,const std::string& Path){
|
||||
std::vector<std::string> FS;
|
||||
FileList(FS,Path+"\\userdata");
|
||||
for(std::string&a : FS){
|
||||
if(a.find(FName) != std::string::npos){
|
||||
FS.clear();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
FS.clear();
|
||||
return false;
|
||||
}
|
||||
bool FindHack(const std::string& Path){
|
||||
bool s = true;
|
||||
for (const auto &entry : fs::directory_iterator(Path)) {
|
||||
std::string Name = entry.path().filename().string();
|
||||
for(char&c : Name)c = char(tolower(c));
|
||||
if(Name == "steam.exe")s = false;
|
||||
if(Name.find("greenluma") != -1){
|
||||
error("Found malicious file/folder \"" + Name+"\"");
|
||||
return true;
|
||||
}
|
||||
Name.clear();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
std::vector<std::string> GetID(const std::string& log){
|
||||
std::string vec,t,r;
|
||||
std::vector<std::string> Ret;
|
||||
std::ifstream f(log.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
vec.resize(size_t(fileSize) + 1);
|
||||
f.seekg(0, std::ios_base::beg);
|
||||
f.read(&vec[0], fileSize);
|
||||
f.close();
|
||||
std::stringstream ss(vec);
|
||||
bool S = false;
|
||||
while (std::getline(ss, t, '{')) {
|
||||
if(!S)S = true;
|
||||
else{
|
||||
for(char& c : t){
|
||||
if(isdigit(c))r += c;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ret.emplace_back(r);
|
||||
r.clear();
|
||||
S = false;
|
||||
bool L = true;
|
||||
while (std::getline(ss, t, '}')) {
|
||||
if(L){
|
||||
L = false;
|
||||
continue;
|
||||
}
|
||||
for(char& c : t){
|
||||
if(c == '"'){
|
||||
if(!S)S = true;
|
||||
else{
|
||||
if(r.length() > 10) {
|
||||
Ret.emplace_back(r);
|
||||
}
|
||||
r.clear();
|
||||
S = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(isdigit(c))r += c;
|
||||
}
|
||||
}
|
||||
vec.clear();
|
||||
return Ret;
|
||||
}
|
||||
std::string GetManifest(const std::string& Man){
|
||||
std::string vec;
|
||||
std::ifstream f(Man.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
vec.resize(size_t(fileSize) + 1);
|
||||
f.seekg(0, std::ios_base::beg);
|
||||
f.read(&vec[0], fileSize);
|
||||
f.close();
|
||||
std::string ToFind = "\"LastOwner\"\t\t\"";
|
||||
int pos = int(vec.find(ToFind));
|
||||
if(pos != -1){
|
||||
pos += int(ToFind.length());
|
||||
vec = vec.substr(pos);
|
||||
return vec.substr(0,vec.find('\"'));
|
||||
}else return "";
|
||||
}
|
||||
bool IDCheck(std::string Man, std::string steam){
|
||||
bool a = false,b = true;
|
||||
int pos = int(Man.rfind("steamapps"));
|
||||
// if(pos == -1)Exit(5);
|
||||
Man = Man.substr(0,pos+9) + "\\appmanifest_284160.acf";
|
||||
steam += "\\config\\loginusers.vdf";
|
||||
if(fs::exists(Man) && fs::exists(steam)){
|
||||
for(const std::string&ID : GetID(steam)){
|
||||
if(ID == GetManifest(Man))b = false;
|
||||
}
|
||||
//if(b)Exit(6);
|
||||
}else a = true;
|
||||
return a;
|
||||
}
|
||||
void LegitimacyCheck(){
|
||||
|
||||
//std::string K1 = R"(Software\Valve\Steam)";
|
||||
//std::string K2 = R"(Software\Valve\Steam\Apps\284160)";
|
||||
|
||||
/*LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K1.c_str(), &hKey);
|
||||
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 1);
|
||||
if(Result.empty())Exit(1);
|
||||
|
||||
if(fs::exists(Result)){
|
||||
if(!Find("284160.json",Result))Exit(2);
|
||||
if(FindHack(Result))SteamExit(1);
|
||||
}else Exit(3);
|
||||
|
||||
T = Result;
|
||||
Result.clear();
|
||||
TraceBack++;
|
||||
}else Exit(4);
|
||||
|
||||
K1.clear();
|
||||
RegCloseKey(hKey);
|
||||
dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K2.c_str(), &hKey);
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 2);
|
||||
if(Result.empty())lowExit(1);
|
||||
TraceBack++;
|
||||
}else lowExit(2);
|
||||
K2.clear();
|
||||
RegCloseKey(hKey);*/
|
||||
std::string Result;
|
||||
std::string K3 = R"(Software\BeamNG\BeamNG.drive)";
|
||||
HKEY hKey;
|
||||
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 3);
|
||||
if(Result.empty())lowExit(3);
|
||||
//if(IDCheck(Result,T))lowExit(5);
|
||||
GameDir = Result;
|
||||
//TraceBack++;
|
||||
}else lowExit(4);
|
||||
K3.clear();
|
||||
Result.clear();
|
||||
RegCloseKey(hKey);
|
||||
//if(TraceBack < 3)exit(-1);
|
||||
}
|
||||
std::string CheckVer(const std::string &dir){
|
||||
std::string temp,Path = dir + "\\integrity.json";
|
||||
std::ifstream f(Path.c_str(), std::ios::binary);
|
||||
int Size = int(std::filesystem::file_size(Path));
|
||||
std::string vec(Size,0);
|
||||
f.read(&vec[0], Size);
|
||||
f.close();
|
||||
|
||||
vec = vec.substr(vec.find_last_of("version"),vec.find_last_of('"'));
|
||||
for(const char &a : vec){
|
||||
if(isdigit(a) || a == '.')temp+=a;
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 11/26/2020
|
||||
///
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "Http.h"
|
||||
#include <filesystem>
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
std::string PublicKey;
|
||||
std::string PrivateKey;
|
||||
extern bool LoginAuth;
|
||||
std::string Role;
|
||||
|
||||
void UpdateKey(const char* newKey){
|
||||
if(newKey && std::isalnum(newKey[0])){
|
||||
PrivateKey = newKey;
|
||||
std::ofstream Key("key");
|
||||
if(Key.is_open()){
|
||||
Key << newKey;
|
||||
Key.close();
|
||||
}else fatal("Cannot write to disk!");
|
||||
}else if(fs::exists("key")){
|
||||
remove("key");
|
||||
}
|
||||
}
|
||||
|
||||
/// "username":"value","password":"value"
|
||||
/// "Guest":"Name"
|
||||
/// "pk":"private_key"
|
||||
|
||||
std::string GetFail(const std::string& R){
|
||||
std::string DRet = R"({"success":false,"message":)";
|
||||
DRet += "\""+R+"\"}";
|
||||
error(R);
|
||||
return DRet;
|
||||
}
|
||||
|
||||
std::string Login(const std::string& fields){
|
||||
if(fields == "LO"){
|
||||
LoginAuth = false;
|
||||
UpdateKey(nullptr);
|
||||
return "";
|
||||
}
|
||||
info("Attempting to authenticate...");
|
||||
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
|
||||
|
||||
if(Buffer == "-1"){
|
||||
return GetFail("Failed to communicate with the auth system!");
|
||||
}
|
||||
|
||||
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
|
||||
|
||||
if (Buffer.at(0) != '{' || d.is_discarded()) {
|
||||
error(Buffer);
|
||||
return GetFail("Invalid answer from authentication servers, please try again later!");
|
||||
}
|
||||
if(d.contains("success") && d["success"].get<bool>()){
|
||||
LoginAuth = true;
|
||||
if(!d.contains("private_key")) {
|
||||
UpdateKey(d["private_key"].get<std::string>().c_str());
|
||||
}
|
||||
if(!d.contains("public_key")){
|
||||
PublicKey = d["public_key"].get<std::string>();
|
||||
}
|
||||
info("Authentication successful!");
|
||||
}else info("Authentication failed!");
|
||||
if(!d.contains("message")){
|
||||
d.erase("private_key");
|
||||
d.erase("public_key");
|
||||
return d.dump();
|
||||
}
|
||||
return GetFail("Invalid message parsing!");
|
||||
}
|
||||
|
||||
void CheckLocalKey(){
|
||||
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], Size);
|
||||
Key.close();
|
||||
|
||||
for (char& c : Buffer) {
|
||||
if (!std::isalnum(c) && c != '-') {
|
||||
UpdateKey(nullptr);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
|
||||
|
||||
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
|
||||
|
||||
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
|
||||
error(Buffer);
|
||||
info("Invalid answer from authentication servers.");
|
||||
UpdateKey(nullptr);
|
||||
}
|
||||
if(d["success"].get<bool>()){
|
||||
LoginAuth = true;
|
||||
UpdateKey(d["private_key"].get<std::string>().c_str());
|
||||
PublicKey = d["public_key"].get<std::string>();
|
||||
Role = d["role"].get<std::string>();
|
||||
//info(Role);
|
||||
}else{
|
||||
info("Auto-Authentication unsuccessful please re-login!");
|
||||
UpdateKey(nullptr);
|
||||
}
|
||||
}else{
|
||||
warn("Could not open saved key!");
|
||||
UpdateKey(nullptr);
|
||||
}
|
||||
}else UpdateKey(nullptr);
|
||||
}
|
||||
326
src/Startup.cpp
326
src/Startup.cpp
@@ -1,326 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <httplib.h>
|
||||
#include "zip_file.h"
|
||||
#include <windows.h>
|
||||
#include "Discord/discord_info.h"
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include <filesystem>
|
||||
#include "Startup.h"
|
||||
#include "hashpp.h"
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <thread>
|
||||
#include "Http.h"
|
||||
|
||||
|
||||
extern int TraceBack;
|
||||
bool Dev = false;
|
||||
int ProxyPort = 0;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
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::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);
|
||||
}
|
||||
|
||||
|
||||
std::string GetEN(){
|
||||
return "BeamMP-Launcher.exe";
|
||||
}
|
||||
std::string GetVer(){
|
||||
return "2.0";
|
||||
}
|
||||
std::string GetPatch(){
|
||||
return ".84";
|
||||
}
|
||||
|
||||
std::string GetEP(char*P){
|
||||
static std::string Ret = [&](){
|
||||
std::string path(P);
|
||||
return path.substr(0, path.find_last_of("\\/") + 1);
|
||||
} ();
|
||||
return Ret;
|
||||
}
|
||||
void ReLaunch(int argc,char*args[]){
|
||||
std::string Arg;
|
||||
for(int c = 2; c <= argc; c++){
|
||||
Arg += " ";
|
||||
Arg += args[c-1];
|
||||
}
|
||||
system("cls");
|
||||
ShellExecute(nullptr,"runas",(GetEP() + GetEN()).c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(),0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void URelaunch(int argc,char* args[]){
|
||||
std::string Arg;
|
||||
for(int c = 2; c <= argc; c++){
|
||||
Arg += " ";
|
||||
Arg += args[c-1];
|
||||
}
|
||||
ShellExecute(nullptr,"open",(GetEP() + GetEN()).c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(),0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void CheckName(int argc,char* args[]){
|
||||
std::string DN = GetEN(),CDir = args[0],FN = CDir.substr(CDir.find_last_of('\\')+1);
|
||||
if(FN != DN){
|
||||
if(fs::exists(DN))remove(DN.c_str());
|
||||
if(fs::exists(DN))ReLaunch(argc,args);
|
||||
std::rename(FN.c_str(), DN.c_str());
|
||||
URelaunch(argc,args);
|
||||
}
|
||||
}
|
||||
|
||||
void CheckForUpdates(int argc, char* args[], const std::string& CV) {
|
||||
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/launcher?branch=" + Branch + "&pk=" + PublicKey);
|
||||
std::string LatestVersion = HTTP::Get(
|
||||
"https://backend.beammp.com/version/launcher?branch=" + Branch + "&pk=" + PublicKey);
|
||||
|
||||
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
|
||||
std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back");
|
||||
|
||||
std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, EP);
|
||||
|
||||
if (FileHash != LatestHash && VersionParser(LatestVersion) > VersionParser(GetVer()+GetPatch())) {
|
||||
info("Launcher update found!");
|
||||
fs::remove(Back);
|
||||
fs::rename(EP, Back);
|
||||
info("Downloading Launcher update " + LatestHash);
|
||||
HTTP::Download(
|
||||
"https://backend.beammp.com/builds/launcher?download=true"
|
||||
"&pk=" +
|
||||
PublicKey + "&branch=" + Branch,
|
||||
EP);
|
||||
URelaunch(argc, args);
|
||||
} else info("Launcher version is up to date");
|
||||
TraceBack++;
|
||||
}
|
||||
|
||||
void CustomPort(int argc, char* argv[]){
|
||||
if(argc > 1){
|
||||
std::string Port = argv[1];
|
||||
if(Port.find_first_not_of("0123456789") == std::string::npos){
|
||||
if(std::stoi(Port) > 1000){
|
||||
DEFAULT_PORT = std::stoi(Port);
|
||||
warn("Running on custom port : " + std::to_string(DEFAULT_PORT));
|
||||
}
|
||||
}
|
||||
if(argc > 2)Dev = true;
|
||||
}
|
||||
}
|
||||
|
||||
void LinuxPatch(){
|
||||
HKEY hKey = nullptr;
|
||||
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey);
|
||||
if (result != ERROR_SUCCESS || getenv("USER") == nullptr)return;
|
||||
RegCloseKey(hKey);
|
||||
info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit");
|
||||
info("Applying patches...");
|
||||
|
||||
result = RegCreateKey(HKEY_CURRENT_USER, R"(Software\Valve\Steam\Apps\284160)", &hKey);
|
||||
|
||||
if (result != ERROR_SUCCESS){
|
||||
fatal(R"(failed to create HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)");
|
||||
return;
|
||||
}
|
||||
|
||||
result = RegSetValueEx(hKey, "Name", 0, REG_SZ, (BYTE*)"BeamNG.drive", 12);
|
||||
|
||||
if (result != ERROR_SUCCESS){
|
||||
fatal(R"(failed to create the value "Name" under HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)");
|
||||
return;
|
||||
}
|
||||
RegCloseKey(hKey);
|
||||
|
||||
info("Patched!");
|
||||
}
|
||||
|
||||
void InitLauncher(int argc, char* argv[]) {
|
||||
system("cls");
|
||||
SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str());
|
||||
InitLog();
|
||||
CheckName(argc, argv);
|
||||
LinuxPatch();
|
||||
CheckLocalKey();
|
||||
ConfigInit();
|
||||
CustomPort(argc, argv);
|
||||
Discord_Main();
|
||||
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
|
||||
}
|
||||
|
||||
size_t DirCount(const std::filesystem::path& path){
|
||||
return (size_t)std::distance(std::filesystem::directory_iterator{path}, std::filesystem::directory_iterator{});
|
||||
}
|
||||
|
||||
void CheckMP(const std::string& Path) {
|
||||
if (!fs::exists(Path))return;
|
||||
size_t c = DirCount(fs::path(Path));
|
||||
try {
|
||||
for (auto& p : fs::directory_iterator(Path)){
|
||||
if(p.exists() && !p.is_directory()){
|
||||
std::string Name = p.path().filename().string();
|
||||
for(char&Ch : Name)Ch = char(tolower(Ch));
|
||||
if(Name != "beammp.zip")fs::remove(p.path());
|
||||
}
|
||||
}
|
||||
} 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?");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void EnableMP(){
|
||||
std::string File(GetGamePath() + "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], Size);
|
||||
db.close();
|
||||
nlohmann::json d = nlohmann::json::parse(Data, nullptr, false);
|
||||
if(Data.at(0) != '{' || d.is_discarded()) {
|
||||
//error("Failed to parse " + File); //TODO illegal formatting
|
||||
return;
|
||||
}
|
||||
if(d.contains("mods") && d["mods"].contains("multiplayerbeammp")){
|
||||
d["mods"]["multiplayerbeammp"]["active"] = true;
|
||||
std::ofstream ofs(File);
|
||||
if(ofs.is_open()){
|
||||
ofs << d.dump();
|
||||
ofs.close();
|
||||
}else{
|
||||
error("Failed to write " + File);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PreGame(const std::string& GamePath){
|
||||
std::string GameVer = CheckVer(GamePath);
|
||||
info("Game Version : " + GameVer);
|
||||
|
||||
CheckMP(GetGamePath() + "mods/multiplayer");
|
||||
|
||||
if(!Dev) {
|
||||
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey);
|
||||
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
|
||||
LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
|
||||
[](auto const& c ) -> bool { return !std::isalnum(c); } ), LatestHash.end());
|
||||
|
||||
try {
|
||||
if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
|
||||
fs::create_directories(GetGamePath() + "mods/multiplayer");
|
||||
}
|
||||
EnableMP();
|
||||
}catch(std::exception&e){
|
||||
fatal(e.what());
|
||||
}
|
||||
|
||||
std::string ZipPath(GetGamePath() + R"(mods\multiplayer\BeamMP.zip)");
|
||||
|
||||
std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, ZipPath);
|
||||
|
||||
if (FileHash != LatestHash) {
|
||||
info("Downloading BeamMP Update " + LatestHash);
|
||||
HTTP::Download("https://backend.beammp.com/builds/client?download=true"
|
||||
"&pk=" + PublicKey + "&branch=" + Branch, ZipPath);
|
||||
}
|
||||
|
||||
std::string Target(GetGamePath() + "mods/unpacked/beammp");
|
||||
|
||||
if(fs::is_directory(Target)) {
|
||||
fs::remove_all(Target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void set_headers(httplib::Response& res) {
|
||||
res.set_header("Access-Control-Allow-Origin", "*");
|
||||
res.set_header("Access-Control-Request-Method", "POST, OPTIONS, GET");
|
||||
res.set_header("Access-Control-Request-Headers", "X-API-Version");
|
||||
}
|
||||
|
||||
void StartProxy() {
|
||||
std::thread proxy([&](){
|
||||
httplib::Server HTTPProxy;
|
||||
httplib::Headers headers = {
|
||||
{"User-Agent", "BeamMP-Launcher/" + GetVer() + GetPatch()},
|
||||
{"Accept", "*/*"}
|
||||
};
|
||||
std::string pattern = "/:any1";
|
||||
for (int i = 2; i <= 4; i++) {
|
||||
HTTPProxy.Get(pattern, [&](const httplib::Request &req, httplib::Response &res) {
|
||||
httplib::Client cli("https://backend.beammp.com");
|
||||
set_headers(res);
|
||||
if (req.has_header("X-BMP-Authentication")) {
|
||||
headers.emplace("X-BMP-Authentication", PrivateKey);
|
||||
}
|
||||
if (req.has_header("X-API-Version")) {
|
||||
headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
|
||||
}
|
||||
if (auto cli_res = cli.Get(req.path, headers); cli_res) {
|
||||
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
|
||||
} else {
|
||||
res.set_content(to_string(cli_res.error()), "text/plain");
|
||||
}
|
||||
});
|
||||
|
||||
HTTPProxy.Post(pattern, [&](const httplib::Request &req, httplib::Response &res) {
|
||||
httplib::Client cli("https://backend.beammp.com");
|
||||
set_headers(res);
|
||||
if (req.has_header("X-BMP-Authentication")) {
|
||||
headers.emplace("X-BMP-Authentication", PrivateKey);
|
||||
}
|
||||
if (req.has_header("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,
|
||||
req.get_header_value("Content-Type")); cli_res) {
|
||||
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
|
||||
} else {
|
||||
res.set_content(to_string(cli_res.error()), "text/plain");
|
||||
}
|
||||
});
|
||||
pattern += "/:any" + std::to_string(i);
|
||||
}
|
||||
ProxyPort = HTTPProxy.bind_to_any_port("0.0.0.0");
|
||||
HTTPProxy.listen_after_bind();
|
||||
});
|
||||
proxy.detach();
|
||||
}
|
||||
44
src/main.cpp
44
src/main.cpp
@@ -1,44 +0,0 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher code is not in the public domain and is not free software.
|
||||
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
|
||||
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include "Startup.h"
|
||||
#include <iostream>
|
||||
#include "Logger.h"
|
||||
#include <thread>
|
||||
#include "Http.h"
|
||||
|
||||
[[noreturn]] void flush(){
|
||||
while(true){
|
||||
std::cout.flush();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
#ifdef DEBUG
|
||||
std::thread th(flush);
|
||||
th.detach();
|
||||
#endif
|
||||
GetEP(argv[0]);
|
||||
|
||||
InitLauncher(argc, argv);
|
||||
|
||||
try {
|
||||
LegitimacyCheck();
|
||||
} catch (std::exception &e) {
|
||||
fatal("Main 1 : " + std::string(e.what()));
|
||||
}
|
||||
|
||||
StartProxy();
|
||||
PreGame(GetGameDir());
|
||||
InitGame(GetGameDir());
|
||||
CoreNetwork();
|
||||
|
||||
///TODO: make sure to use argv[0] for everything that should be in the same dir (mod down ect...)
|
||||
}
|
||||
Reference in New Issue
Block a user