mirror of
https://github.com/BeamMP/BeamMP-Launcher.git
synced 2026-04-13 19:26:20 +00:00
reformat
This commit is contained in:
@@ -5,28 +5,28 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/20/2020
|
||||
///
|
||||
#include "Http.h"
|
||||
#include "Network/network.hpp"
|
||||
#include "Security/Init.h"
|
||||
#include <regex>
|
||||
#include "Http.h"
|
||||
#if defined(_WIN32)
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
#elif defined(__linux__)
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netdb.h>
|
||||
#include <cstring>
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "Startup.h"
|
||||
#include <charconv>
|
||||
#include <thread>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
extern int TraceBack;
|
||||
std::set<std::string>* ConfList = nullptr;
|
||||
@@ -41,11 +41,13 @@ 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)";
|
||||
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;
|
||||
@@ -56,7 +58,7 @@ void StartSync(const std::string &Data){
|
||||
Terminate = false;
|
||||
ConfList->clear();
|
||||
ping = -1;
|
||||
std::thread GS(TCPGameServer,IP,std::stoi(Data.substr(Data.find(':')+1)));
|
||||
std::thread GS(TCPGameServer, IP, std::stoi(Data.substr(Data.find(':') + 1)));
|
||||
GS.detach();
|
||||
info("Connecting to server");
|
||||
}
|
||||
@@ -64,138 +66,150 @@ void StartSync(const std::string &Data){
|
||||
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;
|
||||
return std::regex_search(Link, link_match, link_pattern) && link_match.position() == 0;
|
||||
}
|
||||
|
||||
void Parse(std::string Data,SOCKET CSocket){
|
||||
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':
|
||||
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;
|
||||
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));
|
||||
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') {
|
||||
nlohmann::json Auth = {
|
||||
{ "Auth", LoginAuth ? 1 : 0 },
|
||||
};
|
||||
if (!Username.empty()) {
|
||||
Auth["username"] = Username;
|
||||
}
|
||||
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) + "\"");
|
||||
if (!UserRole.empty()) {
|
||||
Auth["role"] = UserRole;
|
||||
}
|
||||
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'){
|
||||
nlohmann::json Auth = {
|
||||
{"Auth", LoginAuth ? 1 : 0 },
|
||||
};
|
||||
if (!Username.empty()) {
|
||||
Auth["username"] = Username;
|
||||
}
|
||||
if (!UserRole.empty()) {
|
||||
Auth["role"] = UserRole;
|
||||
}
|
||||
Data = Auth.dump();
|
||||
}else{
|
||||
Data = "N" + Login(Data.substr(Data.find(':') + 1));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
Data.clear();
|
||||
break;
|
||||
Data = Auth.dump();
|
||||
} 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){
|
||||
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){
|
||||
void GameHandler(SOCKET Client) {
|
||||
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
do{
|
||||
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] != '>') {
|
||||
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));
|
||||
} 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);
|
||||
std::string Ret(Size, 0);
|
||||
Rcv = 0;
|
||||
|
||||
do{
|
||||
Temp = recv(Client,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
do {
|
||||
Temp = recv(Client, &Ret[Rcv], Size - Rcv, 0);
|
||||
if (Temp < 1)
|
||||
break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size);
|
||||
if(Temp < 1)break;
|
||||
} while (Rcv < Size);
|
||||
if (Temp < 1)
|
||||
break;
|
||||
|
||||
std::thread Respond(Parse, Ret, Client);
|
||||
Respond.detach();
|
||||
}while(Temp > 0);
|
||||
} while (Temp > 0);
|
||||
if (Temp == 0) {
|
||||
debug("(Core) Connection closing");
|
||||
} else {
|
||||
@@ -204,10 +218,10 @@ void GameHandler(SOCKET Client){
|
||||
NetReset();
|
||||
KillSocket(Client);
|
||||
}
|
||||
void localRes(){
|
||||
void localRes() {
|
||||
MStatus = " ";
|
||||
UlStatus = "Ulstart";
|
||||
if(ConfList != nullptr){
|
||||
if (ConfList != nullptr) {
|
||||
ConfList->clear();
|
||||
delete ConfList;
|
||||
ConfList = nullptr;
|
||||
@@ -216,16 +230,17 @@ void localRes(){
|
||||
}
|
||||
void CoreMain() {
|
||||
debug("Core Network on start!");
|
||||
SOCKET LSocket,CSocket;
|
||||
struct addrinfo *res = nullptr;
|
||||
struct addrinfo hints{};
|
||||
SOCKET LSocket, CSocket;
|
||||
struct addrinfo* res = nullptr;
|
||||
struct addrinfo hints { };
|
||||
int iRes;
|
||||
#ifdef _WIN32
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
iRes = WSAStartup(514, &wsaData); //2.2
|
||||
if (iRes)debug("WSAStartup failed with error: " + std::to_string(iRes));
|
||||
#endif
|
||||
|
||||
iRes = WSAStartup(514, &wsaData); // 2.2
|
||||
if (iRes)
|
||||
debug("WSAStartup failed with error: " + std::to_string(iRes));
|
||||
#endif
|
||||
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
|
||||
hints.ai_family = AF_INET;
|
||||
@@ -233,13 +248,13 @@ void CoreMain() {
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
iRes = getaddrinfo(nullptr, std::to_string(DEFAULT_PORT).c_str(), &hints, &res);
|
||||
if (iRes){
|
||||
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){
|
||||
if (LSocket == -1) {
|
||||
debug("(Core) socket failed with error: " + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
WSACleanup();
|
||||
@@ -261,7 +276,7 @@ void CoreMain() {
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
do{
|
||||
do {
|
||||
CSocket = accept(LSocket, nullptr, nullptr);
|
||||
if (CSocket == -1) {
|
||||
error("(Core) accept failed with error: " + std::to_string(WSAGetLastError()));
|
||||
@@ -271,36 +286,37 @@ void CoreMain() {
|
||||
info("Game Connected!");
|
||||
GameHandler(CSocket);
|
||||
warn("Game Reconnecting...");
|
||||
}while(CSocket);
|
||||
} while (CSocket);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
int Handle(EXCEPTION_POINTERS *ep){
|
||||
int Handle(EXCEPTION_POINTERS* ep) {
|
||||
char* hex = new char[100];
|
||||
sprintf_s(hex,100, "%lX", ep->ExceptionRecord->ExceptionCode);
|
||||
sprintf_s(hex, 100, "%lX", ep->ExceptionRecord->ExceptionCode);
|
||||
except("(Core) Code : " + std::string(hex));
|
||||
delete [] hex;
|
||||
delete[] hex;
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
[[noreturn]] void CoreNetwork(){
|
||||
while(true) {
|
||||
#if not defined(__MINGW32__)
|
||||
__try{
|
||||
#endif
|
||||
|
||||
CoreMain();
|
||||
[[noreturn]] void CoreNetwork() {
|
||||
while (true) {
|
||||
#if not defined(__MINGW32__)
|
||||
__try {
|
||||
#endif
|
||||
|
||||
#if not defined(__MINGW32__) and not defined(__linux__)
|
||||
}__except(Handle(GetExceptionInformation())){}
|
||||
#elif not defined(__MINGW32__) and defined(__linux__)
|
||||
} catch(...){
|
||||
except("(Core) Code : " + std::string(strerror(errno)));
|
||||
}
|
||||
#endif
|
||||
CoreMain();
|
||||
|
||||
#if not defined(__MINGW32__) and not defined(__linux__)
|
||||
} __except (Handle(GetExceptionInformation())) { }
|
||||
#elif not defined(__MINGW32__) and defined(__linux__)
|
||||
}
|
||||
catch (...) {
|
||||
except("(Core) Code : " + std::string(strerror(errno)));
|
||||
}
|
||||
#endif
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
|
||||
@@ -12,31 +12,32 @@
|
||||
#include <winsock2.h>
|
||||
#elif defined(__linux__)
|
||||
#include "linuxfixes.h"
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#endif
|
||||
|
||||
#include "Logger.h"
|
||||
|
||||
std::string GetAddr(const std::string&IP){
|
||||
if(IP.find_first_not_of("0123456789.") == -1)return IP;
|
||||
hostent *host;
|
||||
#ifdef _WIN32
|
||||
std::string GetAddr(const std::string& IP) {
|
||||
if (IP.find_first_not_of("0123456789.") == -1)
|
||||
return IP;
|
||||
hostent* host;
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
if(WSAStartup(514, &wsaData) != 0){
|
||||
if (WSAStartup(514, &wsaData) != 0) {
|
||||
error("WSA Startup Failed!");
|
||||
WSACleanup();
|
||||
return "";
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
host = gethostbyname(IP.c_str());
|
||||
if(!host){
|
||||
if (!host) {
|
||||
error("DNS lookup failed! on " + IP);
|
||||
WSACleanup();
|
||||
return "DNS";
|
||||
}
|
||||
std::string Ret = inet_ntoa(*((struct in_addr *)host->h_addr));
|
||||
std::string Ret = inet_ntoa(*((struct in_addr*)host->h_addr));
|
||||
WSACleanup();
|
||||
return Ret;
|
||||
}
|
||||
@@ -11,139 +11,149 @@
|
||||
#include <ws2tcpip.h>
|
||||
#elif defined(__linux__)
|
||||
#include "linuxfixes.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#endif
|
||||
|
||||
#include "Logger.h"
|
||||
#include <charconv>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#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 CServer = true;
|
||||
SOCKET CSocket = -1;
|
||||
SOCKET GSocket = -1;
|
||||
|
||||
int KillSocket(uint64_t Dead){
|
||||
if(Dead == (SOCKET)-1){
|
||||
int KillSocket(uint64_t Dead) {
|
||||
if (Dead == (SOCKET)-1) {
|
||||
debug("Kill socket got -1 returning...");
|
||||
return 0;
|
||||
}
|
||||
shutdown(Dead,SD_BOTH);
|
||||
shutdown(Dead, SD_BOTH);
|
||||
int a = closesocket(Dead);
|
||||
if(a != 0){
|
||||
if (a != 0) {
|
||||
warn("Failed to close socket!");
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
bool CheckBytes(uint32_t Bytes){
|
||||
if(Bytes == 0){
|
||||
bool CheckBytes(uint32_t Bytes) {
|
||||
if (Bytes == 0) {
|
||||
debug("(Proxy) Connection closing");
|
||||
return false;
|
||||
}else if(Bytes < 0){
|
||||
} else if (Bytes < 0) {
|
||||
debug("(Proxy) send failed with error: " + std::to_string(WSAGetLastError()));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void GameSend(std::string Data){
|
||||
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;
|
||||
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){
|
||||
#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;
|
||||
}
|
||||
if (!CheckBytes(Temp))
|
||||
return;
|
||||
Sent += Temp;
|
||||
}while(Sent < Size);
|
||||
} 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){
|
||||
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 > 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);
|
||||
+ Data.substr(0, 10)
|
||||
+ Data.substr(Data.length() - 10));
|
||||
} else if (C == 'Z') {
|
||||
// debug("(Game->Launcher) : " + Data);
|
||||
}
|
||||
}
|
||||
|
||||
void NetReset(){
|
||||
void NetReset() {
|
||||
TCPTerminate = false;
|
||||
GConnected = false;
|
||||
Terminate = false;
|
||||
UlStatus = "Ulstart";
|
||||
MStatus = " ";
|
||||
if(UDPSock != (SOCKET)(-1)){
|
||||
if (UDPSock != (SOCKET)(-1)) {
|
||||
debug("Terminating UDP Socket : " + std::to_string(TCPSock));
|
||||
KillSocket(UDPSock);
|
||||
}
|
||||
UDPSock = -1;
|
||||
if(TCPSock != (SOCKET)(-1)){
|
||||
if (TCPSock != (SOCKET)(-1)) {
|
||||
debug("Terminating TCP Socket : " + std::to_string(TCPSock));
|
||||
KillSocket(TCPSock);
|
||||
}
|
||||
TCPSock = -1;
|
||||
if(GSocket != (SOCKET)(-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{};
|
||||
SOCKET SetupListener() {
|
||||
if (GSocket != -1)
|
||||
return GSocket;
|
||||
struct addrinfo* result = nullptr;
|
||||
struct addrinfo hints { };
|
||||
int iRes;
|
||||
#ifdef _WIN32
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
iRes = WSAStartup(514, &wsaData); //2.2
|
||||
iRes = WSAStartup(514, &wsaData); // 2.2
|
||||
if (iRes != 0) {
|
||||
error("(Proxy) WSAStartup failed with error: " + std::to_string(iRes));
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
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);
|
||||
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();
|
||||
@@ -155,7 +165,7 @@ SOCKET SetupListener(){
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
iRes = bind(GSocket, result->ai_addr, (int) result->ai_addrlen);
|
||||
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);
|
||||
@@ -173,57 +183,61 @@ SOCKET SetupListener(){
|
||||
}
|
||||
return GSocket;
|
||||
}
|
||||
void AutoPing(){
|
||||
while(!Terminate){
|
||||
ServerSend("p",false);
|
||||
void AutoPing() {
|
||||
while (!Terminate) {
|
||||
ServerSend("p", false);
|
||||
PingStart = std::chrono::high_resolution_clock::now();
|
||||
std::this_thread::sleep_for(std::chrono::seconds (1));
|
||||
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);
|
||||
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;
|
||||
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){
|
||||
void ServerParser(const std::string& Data) {
|
||||
ParserAsync(Data);
|
||||
}
|
||||
void NetMain(const std::string& IP, int Port){
|
||||
void NetMain(const std::string& IP, int Port) {
|
||||
std::thread Ping(AutoPing);
|
||||
Ping.detach();
|
||||
UDPClientMain(IP,Port);
|
||||
UDPClientMain(IP, Port);
|
||||
CServer = true;
|
||||
Terminate = true;
|
||||
info("Connection Terminated!");
|
||||
}
|
||||
void TCPGameServer(const std::string& IP, int Port){
|
||||
void TCPGameServer(const std::string& IP, int Port) {
|
||||
GSocket = SetupListener();
|
||||
while (!TCPTerminate && GSocket != -1){
|
||||
while (!TCPTerminate && GSocket != -1) {
|
||||
debug("MAIN LOOP OF GAME SERVER");
|
||||
GConnected = false;
|
||||
if(!CServer){
|
||||
if (!CServer) {
|
||||
warn("Connection still alive terminating");
|
||||
NetReset();
|
||||
TCPTerminate = true;
|
||||
Terminate = true;
|
||||
break;
|
||||
}
|
||||
if(CServer) {
|
||||
if (CServer) {
|
||||
std::thread Client(TCPClientMain, IP, Port);
|
||||
Client.detach();
|
||||
}
|
||||
@@ -234,45 +248,52 @@ void TCPGameServer(const std::string& IP, int Port){
|
||||
}
|
||||
debug("(Proxy) Game Connected!");
|
||||
GConnected = true;
|
||||
if(CServer){
|
||||
if (CServer) {
|
||||
std::thread t1(NetMain, IP, Port);
|
||||
t1.detach();
|
||||
CServer = false;
|
||||
}
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
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{
|
||||
// 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));
|
||||
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);
|
||||
std::string Ret(Size, 0);
|
||||
Rcv = 0;
|
||||
do{
|
||||
Temp = recv(CSocket,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
do {
|
||||
Temp = recv(CSocket, &Ret[Rcv], Size - Rcv, 0);
|
||||
if (Temp < 1)
|
||||
break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size && !TCPTerminate);
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
} while (Rcv < Size && !TCPTerminate);
|
||||
if (Temp < 1 || TCPTerminate)
|
||||
break;
|
||||
|
||||
ServerSend(Ret,false);
|
||||
ServerSend(Ret, false);
|
||||
|
||||
}while(Temp > 0 && !TCPTerminate);
|
||||
if(Temp == 0)debug("(Proxy) Connection closing");
|
||||
else debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError()));
|
||||
} 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);
|
||||
if (CSocket != SOCKET_ERROR)
|
||||
KillSocket(CSocket);
|
||||
debug("END OF GAME SERVER");
|
||||
}
|
||||
@@ -7,175 +7,168 @@
|
||||
///
|
||||
#define CPPHTTPLIB_OPENSSL_SUPPORT
|
||||
|
||||
#include <iostream>
|
||||
#include <Logger.h>
|
||||
#include <fstream>
|
||||
#include "Http.h"
|
||||
#include <mutex>
|
||||
#include <Logger.h>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <httplib.h>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try {
|
||||
const std::filesystem::path folder = ".https_debug";
|
||||
std::filesystem::create_directories(folder);
|
||||
if (!std::filesystem::exists(folder / "WHAT IS THIS FOLDER.txt")) {
|
||||
std::ofstream ignore { folder / "WHAT IS THIS FOLDER.txt" };
|
||||
ignore << "This folder exists to help debug current issues with the backend. Do not share this folder with anyone but BeamMP staff. It contains detailed logs of any failed http requests." << std::endl;
|
||||
}
|
||||
const auto file = folder / (method + ".json");
|
||||
// 1 MB limit
|
||||
if (std::filesystem::exists(file) && std::filesystem::file_size(file) > 1'000'000) {
|
||||
std::filesystem::rename(file, file.generic_string() + ".bak");
|
||||
}
|
||||
const std::filesystem::path folder = ".https_debug";
|
||||
std::filesystem::create_directories(folder);
|
||||
if (!std::filesystem::exists(folder / "WHAT IS THIS FOLDER.txt")) {
|
||||
std::ofstream ignore { folder / "WHAT IS THIS FOLDER.txt" };
|
||||
ignore << "This folder exists to help debug current issues with the backend. Do not share this folder with anyone but BeamMP staff. It contains detailed logs of any failed http requests." << std::endl;
|
||||
}
|
||||
const auto file = folder / (method + ".json");
|
||||
// 1 MB limit
|
||||
if (std::filesystem::exists(file) && std::filesystem::file_size(file) > 1'000'000) {
|
||||
std::filesystem::rename(file, file.generic_string() + ".bak");
|
||||
}
|
||||
|
||||
std::ofstream of { file, std::ios::app };
|
||||
nlohmann::json js {
|
||||
{ "utc", std::chrono::system_clock::now().time_since_epoch().count() },
|
||||
{ "target", target },
|
||||
{ "client_info", {
|
||||
{ "openssl_verify_result", client.get_openssl_verify_result() },
|
||||
{ "host", client.host()},
|
||||
{ "port", client.port()},
|
||||
{ "socket_open", client.is_socket_open()},
|
||||
{"valid", client.is_valid()},
|
||||
}
|
||||
},
|
||||
};
|
||||
if (result) {
|
||||
auto value = result.value();
|
||||
js["result"] = {};
|
||||
js["result"]["body"] = value.body;
|
||||
js["result"]["status"] = value.status;
|
||||
js["result"]["headers"] = value.headers;
|
||||
js["result"]["version"] = value.version;
|
||||
js["result"]["location"] = value.location;
|
||||
js["result"]["reason"] = value.reason;
|
||||
}
|
||||
of << js.dump();
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
error(e.what());
|
||||
std::ofstream of { file, std::ios::app };
|
||||
nlohmann::json js {
|
||||
{ "utc", std::chrono::system_clock::now().time_since_epoch().count() },
|
||||
{ "target", target },
|
||||
{ "client_info", {
|
||||
{ "openssl_verify_result", client.get_openssl_verify_result() },
|
||||
{ "host", client.host() },
|
||||
{ "port", client.port() },
|
||||
{ "socket_open", client.is_socket_open() },
|
||||
{ "valid", client.is_valid() },
|
||||
} },
|
||||
};
|
||||
if (result) {
|
||||
auto value = result.value();
|
||||
js["result"] = {};
|
||||
js["result"]["body"] = value.body;
|
||||
js["result"]["status"] = value.status;
|
||||
js["result"]["headers"] = value.headers;
|
||||
js["result"]["version"] = value.version;
|
||||
js["result"]["location"] = value.location;
|
||||
js["result"]["reason"] = value.reason;
|
||||
}
|
||||
of << js.dump();
|
||||
} catch (const std::exception& e) {
|
||||
error(e.what());
|
||||
}
|
||||
|
||||
bool HTTP::isDownload = false;
|
||||
std::string HTTP::Get(const std::string& IP) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
auto pos = IP.find('/', 10);
|
||||
auto pos = IP.find('/', 10);
|
||||
|
||||
httplib::Client cli(IP.substr(0, pos).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;
|
||||
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 {
|
||||
WriteHttpDebug(cli, "GET", IP, res);
|
||||
error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (isDownload) {
|
||||
std::cout << "\n";
|
||||
}
|
||||
WriteHttpDebug(cli, "GET", IP, res);
|
||||
error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
|
||||
}
|
||||
if (res) {
|
||||
if (res->status == 200) {
|
||||
Ret = res->body;
|
||||
} else {
|
||||
WriteHttpDebug(cli, "GET", IP, res);
|
||||
error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
}
|
||||
} else {
|
||||
if (isDownload) {
|
||||
std::cout << "\n";
|
||||
}
|
||||
WriteHttpDebug(cli, "GET", IP, res);
|
||||
error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
}
|
||||
|
||||
return Ret;
|
||||
return Ret;
|
||||
}
|
||||
|
||||
std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
auto pos = IP.find('/', 10);
|
||||
auto pos = IP.find('/', 10);
|
||||
|
||||
httplib::Client cli(IP.substr(0, pos).c_str());
|
||||
cli.set_connection_timeout(std::chrono::seconds(10));
|
||||
std::string Ret;
|
||||
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 (!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 {
|
||||
WriteHttpDebug(cli, "POST", IP, res);
|
||||
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
httplib::Result res = cli.Post(IP.substr(pos).c_str());
|
||||
if (res) {
|
||||
if (res->status != 200) {
|
||||
error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
}
|
||||
else {
|
||||
WriteHttpDebug(cli, "POST", IP, res);
|
||||
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
|
||||
}
|
||||
}
|
||||
if (res) {
|
||||
if (res->status != 200) {
|
||||
error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
} else {
|
||||
WriteHttpDebug(cli, "POST", IP, res);
|
||||
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
}
|
||||
} else {
|
||||
httplib::Result res = cli.Post(IP.substr(pos).c_str());
|
||||
if (res) {
|
||||
if (res->status != 200) {
|
||||
error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
} else {
|
||||
WriteHttpDebug(cli, "POST", IP, res);
|
||||
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
|
||||
}
|
||||
}
|
||||
|
||||
if (Ret.empty())return "-1";
|
||||
else return Ret;
|
||||
if (Ret.empty())
|
||||
return "-1";
|
||||
else
|
||||
return Ret;
|
||||
}
|
||||
|
||||
bool HTTP::ProgressBar(size_t c, size_t t) {
|
||||
if (isDownload) {
|
||||
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;
|
||||
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);
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
isDownload = true;
|
||||
std::string Ret = Get(IP);
|
||||
isDownload = false;
|
||||
isDownload = true;
|
||||
std::string Ret = Get(IP);
|
||||
isDownload = false;
|
||||
|
||||
if (Ret.empty())return false;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -11,140 +11,146 @@
|
||||
#if defined(_WIN32)
|
||||
#include <ws2tcpip.h>
|
||||
#elif defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#include <filesystem>
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include "Startup.h"
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#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> Split(const std::string& String, const std::string& delimiter) {
|
||||
std::vector<std::string> Val;
|
||||
size_t pos;
|
||||
std::string token,s = String;
|
||||
std::string token, s = String;
|
||||
while ((pos = s.find(delimiter)) != std::string::npos) {
|
||||
token = s.substr(0, pos);
|
||||
if(!token.empty())Val.push_back(token);
|
||||
if (!token.empty())
|
||||
Val.push_back(token);
|
||||
s.erase(0, pos + delimiter.length());
|
||||
}
|
||||
if(!s.empty())Val.push_back(s);
|
||||
if (!s.empty())
|
||||
Val.push_back(s);
|
||||
return Val;
|
||||
}
|
||||
|
||||
void CheckForDir(){
|
||||
if(!fs::exists("Resources")){
|
||||
// Could we just use fs::create_directory instead?
|
||||
#if defined(_WIN32)
|
||||
void CheckForDir() {
|
||||
if (!fs::exists("Resources")) {
|
||||
// Could we just use fs::create_directory instead?
|
||||
#if defined(_WIN32)
|
||||
_wmkdir(L"Resources");
|
||||
#elif defined(__linux__)
|
||||
#elif defined(__linux__)
|
||||
fs::create_directory(L"Resources");
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
}
|
||||
void WaitForConfirm(){
|
||||
while(!Terminate && !ModLoaded){
|
||||
void WaitForConfirm() {
|
||||
while (!Terminate && !ModLoaded) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
ModLoaded = false;
|
||||
}
|
||||
|
||||
|
||||
void Abord(){
|
||||
void Abord() {
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
info("Terminated!");
|
||||
}
|
||||
|
||||
std::string Auth(SOCKET Sock){
|
||||
TCPSend("VC" + GetVer(),Sock);
|
||||
std::string Auth(SOCKET Sock) {
|
||||
TCPSend("VC" + GetVer(), Sock);
|
||||
|
||||
auto Res = TCPRcv(Sock);
|
||||
|
||||
if(Res.empty() || Res[0] == 'E' || Res[0] == 'K'){
|
||||
if (Res.empty() || Res[0] == 'E' || Res[0] == 'K') {
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
TCPSend(PublicKey,Sock);
|
||||
if(Terminate)return "";
|
||||
TCPSend(PublicKey, Sock);
|
||||
if (Terminate)
|
||||
return "";
|
||||
|
||||
Res = TCPRcv(Sock);
|
||||
if(Res.empty() || Res[0] != 'P'){
|
||||
if (Res.empty() || Res[0] != 'P') {
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
Res = Res.substr(1);
|
||||
if(Res.find_first_not_of("0123456789") == std::string::npos){
|
||||
if (Res.find_first_not_of("0123456789") == std::string::npos) {
|
||||
ClientID = std::stoi(Res);
|
||||
}else{
|
||||
} else {
|
||||
Abord();
|
||||
UUl("Authentication failed!");
|
||||
return "";
|
||||
}
|
||||
TCPSend("SR",Sock);
|
||||
if(Terminate)return "";
|
||||
TCPSend("SR", Sock);
|
||||
if (Terminate)
|
||||
return "";
|
||||
|
||||
Res = TCPRcv(Sock);
|
||||
|
||||
if(Res[0] == 'E' || Res[0] == 'K'){
|
||||
if (Res[0] == 'E' || Res[0] == 'K') {
|
||||
Abord();
|
||||
return "";
|
||||
}
|
||||
|
||||
if(Res.empty() || Res == "-"){
|
||||
if (Res.empty() || Res == "-") {
|
||||
info("Didn't Receive any mods...");
|
||||
ListOfMods = "-";
|
||||
TCPSend("Done",Sock);
|
||||
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 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){
|
||||
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);
|
||||
} while (!Terminate && Rcv < Size);
|
||||
}
|
||||
|
||||
char* TCPRcvRaw(SOCKET Sock,uint64_t& GRcv, uint64_t Size){
|
||||
if(Sock == -1){
|
||||
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;
|
||||
do {
|
||||
int Len = int(Size - Rcv);
|
||||
if (Len > 1000000)
|
||||
Len = 1000000;
|
||||
int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
|
||||
if(Temp < 1){
|
||||
if (Temp < 1) {
|
||||
info(std::to_string(Temp));
|
||||
UUl("Socket Closed Code 1");
|
||||
KillSocket(Sock);
|
||||
@@ -154,18 +160,18 @@ char* TCPRcvRaw(SOCKET Sock,uint64_t& GRcv, uint64_t Size){
|
||||
}
|
||||
Rcv += Temp;
|
||||
GRcv += Temp;
|
||||
}while(Rcv < Size && !Terminate);
|
||||
} while (Rcv < Size && !Terminate);
|
||||
return File;
|
||||
}
|
||||
void MultiKill(SOCKET Sock,SOCKET Sock1){
|
||||
void MultiKill(SOCKET Sock, SOCKET Sock1) {
|
||||
KillSocket(Sock1);
|
||||
KillSocket(Sock);
|
||||
Terminate = true;
|
||||
}
|
||||
SOCKET InitDSock(){
|
||||
SOCKET InitDSock() {
|
||||
SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
SOCKADDR_IN ServerAddr;
|
||||
if(DSock < 1){
|
||||
if (DSock < 1) {
|
||||
KillSocket(DSock);
|
||||
Terminate = true;
|
||||
return 0;
|
||||
@@ -173,13 +179,13 @@ SOCKET InitDSock(){
|
||||
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){
|
||||
if (connect(DSock, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)) != 0) {
|
||||
KillSocket(DSock);
|
||||
Terminate = true;
|
||||
return 0;
|
||||
}
|
||||
char Code[2] = {'D',char(ClientID)};
|
||||
if(send(DSock,Code,2,0) != 2){
|
||||
char Code[2] = { 'D', char(ClientID) };
|
||||
if (send(DSock, Code, 2, 0) != 2) {
|
||||
KillSocket(DSock);
|
||||
Terminate = true;
|
||||
return 0;
|
||||
@@ -187,55 +193,56 @@ SOCKET InitDSock(){
|
||||
return DSock;
|
||||
}
|
||||
|
||||
std::string MultiDownload(SOCKET MSock,SOCKET DSock, uint64_t Size, const std::string& Name){
|
||||
std::string MultiDownload(SOCKET MSock, SOCKET DSock, uint64_t Size, const std::string& Name) {
|
||||
|
||||
uint64_t GRcv = 0, MSize = Size/2, DSize = Size - MSize;
|
||||
uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize;
|
||||
|
||||
std::thread Au(AsyncUpdate,std::ref(GRcv), Size, Name);
|
||||
std::thread Au(AsyncUpdate, std::ref(GRcv), Size, Name);
|
||||
|
||||
std::packaged_task<char*()> task([&] { return TCPRcvRaw(MSock,GRcv,MSize); });
|
||||
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);
|
||||
char* DData = TCPRcvRaw(DSock, GRcv, DSize);
|
||||
|
||||
if(!DData){
|
||||
MultiKill(MSock,DSock);
|
||||
if (!DData) {
|
||||
MultiKill(MSock, DSock);
|
||||
return "";
|
||||
}
|
||||
|
||||
f1.wait();
|
||||
char* MData = f1.get();
|
||||
|
||||
if(!MData){
|
||||
MultiKill(MSock,DSock);
|
||||
if (!MData) {
|
||||
MultiKill(MSock, DSock);
|
||||
return "";
|
||||
}
|
||||
|
||||
if(Au.joinable())Au.join();
|
||||
if (Au.joinable())
|
||||
Au.join();
|
||||
|
||||
/// omg yes very ugly my god but i was in a rush will revisit
|
||||
std::string Ret(Size, 0);
|
||||
memcpy(&Ret[0], MData, MSize);
|
||||
delete[] MData;
|
||||
|
||||
///omg yes very ugly my god but i was in a rush will revisit
|
||||
std::string Ret(Size,0);
|
||||
memcpy(&Ret[0],MData,MSize);
|
||||
delete[]MData;
|
||||
|
||||
memcpy(&Ret[MSize],DData,DSize);
|
||||
delete[]DData;
|
||||
memcpy(&Ret[MSize], DData, DSize);
|
||||
delete[] DData;
|
||||
|
||||
return Ret;
|
||||
}
|
||||
|
||||
void InvalidResource(const std::string& File){
|
||||
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){
|
||||
void SyncResources(SOCKET Sock) {
|
||||
std::string Ret = Auth(Sock);
|
||||
if(Ret.empty())return;
|
||||
if (Ret.empty())
|
||||
return;
|
||||
|
||||
info("Checking Resources...");
|
||||
CheckForDir();
|
||||
@@ -246,59 +253,59 @@ void SyncResources(SOCKET Sock){
|
||||
list.clear();
|
||||
Ret.clear();
|
||||
|
||||
int Amount = 0,Pos = 0;
|
||||
std::string a,t;
|
||||
for(const std::string&name : FNames){
|
||||
if(!name.empty()){
|
||||
int Amount = 0, Pos = 0;
|
||||
std::string a, t;
|
||||
for (const std::string& name : FNames) {
|
||||
if (!name.empty()) {
|
||||
t += name.substr(name.find_last_of('/') + 1) + ";";
|
||||
}
|
||||
}
|
||||
if(t.empty())ListOfMods = "-";
|
||||
else ListOfMods = t;
|
||||
if (t.empty())
|
||||
ListOfMods = "-";
|
||||
else
|
||||
ListOfMods = t;
|
||||
t.clear();
|
||||
for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
|
||||
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
|
||||
auto pos = FN->find_last_of('/');
|
||||
auto ZIP = FN->find(".zip");
|
||||
if (ZIP == std::string::npos || FN->length() - ZIP != 4) {
|
||||
InvalidResource(*FN);
|
||||
return;
|
||||
}
|
||||
if (pos == std::string::npos)continue;
|
||||
if (pos == std::string::npos)
|
||||
continue;
|
||||
Amount++;
|
||||
}
|
||||
if(!FNames.empty())info("Syncing...");
|
||||
if (!FNames.empty())
|
||||
info("Syncing...");
|
||||
SOCKET DSock = InitDSock();
|
||||
for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
|
||||
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
|
||||
auto pos = FN->find_last_of('/');
|
||||
if (pos != std::string::npos) {
|
||||
a = "Resources" + FN->substr(pos);
|
||||
} else continue;
|
||||
} else
|
||||
continue;
|
||||
Pos++;
|
||||
if (fs::exists(a)) {
|
||||
if (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('/')));
|
||||
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")){
|
||||
if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
|
||||
fs::create_directories(GetGamePath() + "mods/multiplayer");
|
||||
}
|
||||
auto name = GetGamePath() + "mods/multiplayer" + a.substr(a.find_last_of('/'));
|
||||
#if defined(__linux__)
|
||||
#if defined(__linux__)
|
||||
// Linux version of the game doesnt support uppercase letters in mod names
|
||||
for(char &c : name){
|
||||
for (char& c : name) {
|
||||
c = ::tolower(c);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
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);
|
||||
for(char &c : FName){
|
||||
c = ::tolower(c);
|
||||
}
|
||||
#endif
|
||||
|
||||
fs::copy_file(a, GetGamePath() + "mods/multiplayer" + FName,
|
||||
} catch (std::exception& e) {
|
||||
error("Failed copy to the mods folder! " + std::string(e.what()));
|
||||
Terminate = true;
|
||||
@@ -306,15 +313,16 @@ void SyncResources(SOCKET Sock){
|
||||
}
|
||||
WaitForConfirm();
|
||||
continue;
|
||||
}else remove(a.c_str());
|
||||
} else
|
||||
remove(a.c_str());
|
||||
}
|
||||
CheckForDir();
|
||||
std::string FName = a.substr(a.find_last_of('/'));
|
||||
do {
|
||||
TCPSend("f" + *FN,Sock);
|
||||
TCPSend("f" + *FN, Sock);
|
||||
|
||||
std::string Data = TCPRcv(Sock);
|
||||
if (Data == "CO" || Terminate){
|
||||
if (Data == "CO" || Terminate) {
|
||||
Terminate = true;
|
||||
UUl("Server cannot find " + FName);
|
||||
break;
|
||||
@@ -322,10 +330,11 @@ void SyncResources(SOCKET Sock){
|
||||
|
||||
std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
|
||||
|
||||
Data = MultiDownload(Sock,DSock,std::stoull(*FS), Name);
|
||||
Data = MultiDownload(Sock, DSock, std::stoull(*FS), Name);
|
||||
|
||||
if(Terminate)break;
|
||||
UpdateUl(false,std::to_string(Pos)+"/"+std::to_string(Amount)+": "+FName);
|
||||
if (Terminate)
|
||||
break;
|
||||
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName);
|
||||
std::ofstream LFS;
|
||||
LFS.open(a.c_str(), std::ios_base::app | std::ios::binary);
|
||||
if (LFS.is_open()) {
|
||||
@@ -333,29 +342,29 @@ void SyncResources(SOCKET Sock){
|
||||
LFS.close();
|
||||
}
|
||||
|
||||
}while(fs::file_size(a) != std::stoull(*FS) && !Terminate);
|
||||
if(!Terminate){
|
||||
if(!fs::exists(GetGamePath() + "mods/multiplayer")){
|
||||
} while (fs::file_size(a) != std::stoull(*FS) && !Terminate);
|
||||
if (!Terminate) {
|
||||
if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
|
||||
fs::create_directories(GetGamePath() + "mods/multiplayer");
|
||||
}
|
||||
|
||||
// Linux version of the game doesnt support uppercase letters in mod names
|
||||
#if defined(__linux__)
|
||||
for(char &c : FName){
|
||||
// Linux version of the game doesnt support uppercase letters in mod names
|
||||
#if defined(__linux__)
|
||||
for (char& c : FName) {
|
||||
c = ::tolower(c);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
fs::copy_file(a,GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
|
||||
fs::copy_file(a, GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
|
||||
}
|
||||
WaitForConfirm();
|
||||
}
|
||||
KillSocket(DSock);
|
||||
if(!Terminate){
|
||||
TCPSend("Done",Sock);
|
||||
if (!Terminate) {
|
||||
TCPSend("Done", Sock);
|
||||
info("Done!");
|
||||
}else{
|
||||
} else {
|
||||
UlStatus = "Ulstart";
|
||||
info("Connection Terminated!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,87 +5,91 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
#include "Zlib/Compressor.h"
|
||||
#include "Network/network.hpp"
|
||||
#include "Zlib/Compressor.h"
|
||||
|
||||
#if defined(_WIN32)
|
||||
#include <ws2tcpip.h>
|
||||
#elif defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include "linuxfixes.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
#include "linuxfixes.h"
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#include "Logger.h"
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
SOCKET UDPSock = -1;
|
||||
sockaddr_in* ToServer = nullptr;
|
||||
|
||||
void UDPSend(std::string Data){
|
||||
if(ClientID == -1 || UDPSock == -1)return;
|
||||
if(Data.length() > 400){
|
||||
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;
|
||||
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()));
|
||||
if (sendOk == SOCKET_ERROR)
|
||||
error("Error Code : " + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
|
||||
|
||||
void SendLarge(std::string Data){
|
||||
if(Data.length() > 400){
|
||||
void SendLarge(std::string Data) {
|
||||
if (Data.length() > 400) {
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
TCPSend(Data,TCPSock);
|
||||
TCPSend(Data, TCPSock);
|
||||
}
|
||||
|
||||
void UDPParser(std::string Packet){
|
||||
if(Packet.substr(0,4) == "ABG:"){
|
||||
void UDPParser(std::string Packet) {
|
||||
if (Packet.substr(0, 4) == "ABG:") {
|
||||
Packet = DeComp(Packet.substr(4));
|
||||
}
|
||||
ServerParser(Packet);
|
||||
}
|
||||
void UDPRcv(){
|
||||
sockaddr_in FromServer{};
|
||||
#if defined(_WIN32)
|
||||
void UDPRcv() {
|
||||
sockaddr_in FromServer {};
|
||||
#if defined(_WIN32)
|
||||
int clientLength = sizeof(FromServer);
|
||||
#elif defined(__linux__)
|
||||
#elif defined(__linux__)
|
||||
socklen_t clientLength = sizeof(FromServer);
|
||||
#endif
|
||||
#endif
|
||||
ZeroMemory(&FromServer, clientLength);
|
||||
std::string Ret(10240,0);
|
||||
if(UDPSock == -1)return;
|
||||
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));
|
||||
if (Rcv == SOCKET_ERROR)
|
||||
return;
|
||||
UDPParser(Ret.substr(0, Rcv));
|
||||
}
|
||||
void UDPClientMain(const std::string& IP,int Port){
|
||||
#ifdef _WIN32
|
||||
void UDPClientMain(const std::string& IP, int Port) {
|
||||
#ifdef _WIN32
|
||||
WSADATA data;
|
||||
if (WSAStartup(514, &data)){
|
||||
if (WSAStartup(514, &data)) {
|
||||
error("Can't start Winsock!");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
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);
|
||||
GameSend("P" + std::to_string(ClientID));
|
||||
TCPSend("H", TCPSock);
|
||||
UDPSend("p");
|
||||
while(!Terminate)UDPRcv();
|
||||
while (!Terminate)
|
||||
UDPRcv();
|
||||
KillSocket(UDPSock);
|
||||
WSACleanup();
|
||||
}
|
||||
@@ -6,21 +6,21 @@
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <Zlib/Compressor.h>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#include <ws2tcpip.h>
|
||||
#elif defined(__linux__)
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <cstring>
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#include "Network/network.hpp"
|
||||
@@ -29,12 +29,12 @@ int LastPort;
|
||||
std::string LastIP;
|
||||
SOCKET TCPSock = -1;
|
||||
|
||||
bool CheckBytes(int32_t Bytes){
|
||||
if (Bytes == 0){
|
||||
bool CheckBytes(int32_t Bytes) {
|
||||
if (Bytes == 0) {
|
||||
debug("(TCP) Connection closing... CheckBytes(16)");
|
||||
Terminate = true;
|
||||
return false;
|
||||
}else if (Bytes < 0) {
|
||||
} else if (Bytes < 0) {
|
||||
debug("(TCP CB) recv failed with error: " + std::to_string(WSAGetLastError()));
|
||||
KillSocket(TCPSock);
|
||||
Terminate = true;
|
||||
@@ -42,98 +42,99 @@ bool CheckBytes(int32_t Bytes){
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void UUl(const std::string& R){
|
||||
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;
|
||||
}
|
||||
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);
|
||||
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){
|
||||
std::string TCPRcv(SOCKET Sock) {
|
||||
if (Sock == -1) {
|
||||
Terminate = true;
|
||||
UUl("Invalid Socket");
|
||||
return "";
|
||||
}
|
||||
int32_t Header,BytesRcv = 0,Temp;
|
||||
int32_t Header, BytesRcv = 0, Temp;
|
||||
std::vector<char> Data(sizeof(Header));
|
||||
do{
|
||||
Temp = recv(Sock,&Data[BytesRcv],4-BytesRcv,0);
|
||||
if(!CheckBytes(Temp)){
|
||||
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));
|
||||
} while (BytesRcv < 4);
|
||||
memcpy(&Header, &Data[0], sizeof(Header));
|
||||
|
||||
if(!CheckBytes(BytesRcv)){
|
||||
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)){
|
||||
do {
|
||||
Temp = recv(Sock, &Data[BytesRcv], Header - BytesRcv, 0);
|
||||
if (!CheckBytes(Temp)) {
|
||||
UUl("Socket Closed Code 5");
|
||||
return "";
|
||||
}
|
||||
BytesRcv += Temp;
|
||||
}while(BytesRcv < Header);
|
||||
} while (BytesRcv < Header);
|
||||
|
||||
std::string Ret(Data.data(),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()));
|
||||
// debug("Parsing from server -> " + std::to_string(Ret.size()));
|
||||
#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;
|
||||
}
|
||||
|
||||
void TCPClientMain(const std::string& IP,int Port){
|
||||
void TCPClientMain(const std::string& IP, int Port) {
|
||||
LastIP = IP;
|
||||
LastPort = Port;
|
||||
SOCKADDR_IN ServerAddr;
|
||||
int RetCode;
|
||||
#ifdef _WIN32
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
WSAStartup(514, &wsaData); //2.2
|
||||
#endif
|
||||
WSAStartup(514, &wsaData); // 2.2
|
||||
#endif
|
||||
TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
|
||||
if(TCPSock == -1){
|
||||
if (TCPSock == -1) {
|
||||
printf("Client: socket failed! Error code: %d\n", WSAGetLastError());
|
||||
WSACleanup();
|
||||
return;
|
||||
@@ -142,8 +143,8 @@ void TCPClientMain(const std::string& IP,int Port){
|
||||
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){
|
||||
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);
|
||||
@@ -156,17 +157,16 @@ void TCPClientMain(const std::string& IP,int Port){
|
||||
char Code = 'C';
|
||||
send(TCPSock, &Code, 1, 0);
|
||||
SyncResources(TCPSock);
|
||||
while(!Terminate){
|
||||
while (!Terminate) {
|
||||
ServerParser(TCPRcv(TCPSock));
|
||||
}
|
||||
GameSend("T");
|
||||
////Game Send Terminate
|
||||
if(KillSocket(TCPSock) != 0)
|
||||
if (KillSocket(TCPSock) != 0)
|
||||
debug("(TCP) Cannot close socket. Error code: " + std::to_string(WSAGetLastError()));
|
||||
|
||||
#ifdef _WIN32
|
||||
if(WSACleanup() != 0)
|
||||
#ifdef _WIN32
|
||||
if (WSACleanup() != 0)
|
||||
debug("(TCP) Client: WSACleanup() failed!...");
|
||||
#endif
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user