clang-format everything

This commit is contained in:
Lion Kortlepel 2020-11-12 17:09:14 +01:00
parent c9f5ee9729
commit 58e65cf43f
29 changed files with 716 additions and 677 deletions

View File

@ -3,5 +3,5 @@
/// ///
#pragma once #pragma once
#include <string> #include <string>
std::string HttpRequest(const std::string& IP,int port); std::string HttpRequest(const std::string& IP, int port);
std::string PostHTTP(const std::string& IP,const std::string& Fields); std::string PostHTTP(const std::string& IP, const std::string& Fields);

View File

@ -2,10 +2,10 @@
/// Created by Anonymous275 on 4/2/2020. /// Created by Anonymous275 on 4/2/2020.
/// ///
#pragma once #pragma once
#include "Security/Xor.h"
#include <iostream> #include <iostream>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include "Security/Xor.h"
void InitLog(); void InitLog();
#define DebugPrintTID() DebugPrintTIDInternal(__func__, false) #define DebugPrintTID() DebugPrintTIDInternal(__func__, false)
void DebugPrintTIDInternal(const std::string& func, bool overwrite = true); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier void DebugPrintTIDInternal(const std::string& func, bool overwrite = true); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier

View File

@ -6,14 +6,14 @@
#include <string> #include <string>
void TCPServerMain(); void TCPServerMain();
void UpdatePlayers(); void UpdatePlayers();
void OnConnect(Client*c); void OnConnect(Client* c);
void InitClient(Client*c); void InitClient(Client* c);
void SyncResources(Client*c); void SyncResources(Client* c);
[[noreturn]] void UDPServerMain(); [[noreturn]] void UDPServerMain();
void OnDisconnect(Client*c,bool kicked); void OnDisconnect(Client* c, bool kicked);
void UDPSend(Client*c,std::string Data); void UDPSend(Client* c, std::string Data);
void TCPSend(Client*c,const std::string& Data); void TCPSend(Client* c, const std::string& Data);
void SendLarge(Client*c,std::string Data); void SendLarge(Client* c, std::string Data);
void GParser(Client*c, const std::string&Packet); void GParser(Client* c, const std::string& Packet);
void Respond(Client*c, const std::string& MSG, bool Rel); void Respond(Client* c, const std::string& MSG, bool Rel);
void SendToAll(Client*c, const std::string& Data, bool Self, bool Rel); void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel);

View File

@ -17,4 +17,3 @@ using ReadLock = std::shared_lock<RWMutex>;
// Construct with an RWMutex as a non-const reference. // Construct with an RWMutex as a non-const reference.
// locks the mutex for writing. Construction may be blocking. Destruction is guaranteed to release the lock. // locks the mutex for writing. Construction may be blocking. Destruction is guaranteed to release the lock.
using WriteLock = std::unique_lock<RWMutex>; using WriteLock = std::unique_lock<RWMutex>;

View File

@ -7,15 +7,15 @@
#else #else
#include <WS2tcpip.h> #include <WS2tcpip.h>
#endif #endif
#include <string>
#include "Xor.h" #include "Xor.h"
struct RSA{ #include <string>
struct RSA {
int n = 0; int n = 0;
int e = 0; int e = 0;
int d = 0; int d = 0;
}; };
std::string RSA_E(const std::string& Data,int e, int n); std::string RSA_E(const std::string& Data, int e, int n);
std::string RSA_E(const std::string& Data, RSA*k); std::string RSA_E(const std::string& Data, RSA* k);
std::string RSA_D(const std::string& Data, RSA*k); std::string RSA_D(const std::string& Data, RSA* k);
int Handle(EXCEPTION_POINTERS *ep,char* Origin); int Handle(EXCEPTION_POINTERS* ep, char* Origin);
RSA* GenKey(); RSA* GenKey();

View File

@ -2,107 +2,108 @@
/// Created by Anonymous275 on 8/11/2020 /// Created by Anonymous275 on 8/11/2020
/// ///
#pragma once #pragma once
#include <string>
#include <array> #include <array>
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <string>
#define BEGIN_NAMESPACE(x) namespace x { #define BEGIN_NAMESPACE(x) namespace x {
#define END_NAMESPACE } #define END_NAMESPACE }
BEGIN_NAMESPACE(XorCompileTime) BEGIN_NAMESPACE(XorCompileTime)
constexpr auto time = __TIME__; constexpr auto time = __TIME__;
constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000; constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast<int>(time[1]) * 3600 + static_cast<int>(time[0]) * 36000;
// 1988, Stephen Park and Keith Miller // 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard" // "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation: // Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division // with 32-bit math and without division
template <int N> template <int N>
struct RandomGenerator{ struct RandomGenerator {
private: private:
static constexpr unsigned a = 16807; // 7^5 static constexpr unsigned a = 16807; // 7^5
static constexpr unsigned m = 2147483647; // 2^31 - 1 static constexpr unsigned m = 2147483647; // 2^31 - 1
static constexpr unsigned s = RandomGenerator< N - 1 >::value; static constexpr unsigned s = RandomGenerator<N - 1>::value;
static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807 static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807
static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807 static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807
static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits
static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi
static constexpr unsigned lo3 = lo2 + hi; static constexpr unsigned lo3 = lo2 + hi;
public: public:
static constexpr unsigned max = m; static constexpr unsigned max = m;
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3; static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
}; };
template <> template <>
struct RandomGenerator< 0 >{ struct RandomGenerator<0> {
static constexpr unsigned value = seed; static constexpr unsigned value = seed;
}; };
template <int N, int M> template <int N, int M>
struct RandomInt{ struct RandomInt {
static constexpr auto value = RandomGenerator< N + 1 >::value % M; static constexpr auto value = RandomGenerator<N + 1>::value % M;
}; };
template <int N> template <int N>
struct RandomChar{ struct RandomChar {
static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value); static const char value = static_cast<char>(1 + RandomInt<N, 0x7F - 1>::value);
}; };
template <size_t N, int K, typename Char> template <size_t N, int K, typename Char>
struct XorString{ struct XorString {
private: private:
const char _key; const char _key;
std::array< Char, N + 1 > _encrypted; std::array<Char, N + 1> _encrypted;
constexpr Char enc(Char c) const{ constexpr Char enc(Char c) const {
return c ^ _key; return c ^ _key;
} }
Char dec(Char c) const{ Char dec(Char c) const {
return c ^ _key; return c ^ _key;
} }
public: public:
template <size_t... Is> template <size_t... Is>
constexpr inline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... } constexpr inline XorString(const Char* str, std::index_sequence<Is...>)
{} : _key(RandomChar<K>::value)
, _encrypted { enc(str[Is])... } { }
inline decltype(auto) decrypt(){ inline decltype(auto) decrypt() {
for (size_t i = 0; i < N; ++i) { for (size_t i = 0; i < N; ++i) {
_encrypted[i] = dec(_encrypted[i]); _encrypted[i] = dec(_encrypted[i]);
} }
_encrypted[N] = '\0'; _encrypted[N] = '\0';
return _encrypted.data(); return _encrypted.data();
} }
}; };
static auto w_printf = [](const char* fmt, ...) { static auto w_printf = [](const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
vprintf(fmt, args); vprintf(fmt, args);
va_end(args); va_end(args);
}; };
static auto w_printf_s = [](const char* fmt, ...) { static auto w_printf_s = [](const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
vprintf(fmt, args); vprintf(fmt, args);
va_end(args); va_end(args);
}; };
/*static auto w_sprintf = [](char* buf, const char* fmt, ...) { /*static auto w_sprintf = [](char* buf, const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
vsprintf(buf, fmt, args); vsprintf(buf, fmt, args);
va_end(args); va_end(args);
};*/ };*/
/*static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) { /*static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
int ret; int ret;
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
@ -111,21 +112,21 @@ BEGIN_NAMESPACE(XorCompileTime)
return ret; return ret;
};*/ };*/
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) { static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
vsnprintf(buf, buf_size, fmt, args); vsnprintf(buf, buf_size, fmt, args);
va_end(args); va_end(args);
}; };
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) { static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
int ret; int ret;
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
ret = vsnprintf(buf, buf_size, fmt, args); ret = vsnprintf(buf, buf_size, fmt, args);
va_end(args); va_end(args);
return ret; return ret;
}; };
#define Sec( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt() #define Sec(s) [] { constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
#define SecW( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt() #define SecW(s) [] { constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
END_NAMESPACE END_NAMESPACE

View File

@ -8,8 +8,8 @@
#include "CustomAssert.h" #include "CustomAssert.h"
#include <cstring> #include <cstring>
#include <unistd.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h>
// ZeroMemory is just a {0} or a memset(addr, 0, len), and it's a macro on MSVC // ZeroMemory is just a {0} or a memset(addr, 0, len), and it's a macro on MSVC
inline void ZeroMemory(void* dst, size_t len) { inline void ZeroMemory(void* dst, size_t len) {
@ -26,7 +26,7 @@ inline void closesocket(int socket) {
#endif #endif
#ifndef __except #ifndef __except
#define __except(x) /**/ #define __except (x) /**/
#endif #endif
#endif // WIN32 #endif // WIN32

View File

@ -2,14 +2,14 @@
/// Created by Anonymous275 on 7/15/2020 /// Created by Anonymous275 on 7/15/2020
/// ///
#include <iostream>
#include <algorithm> #include <algorithm>
#include <zlib.h>
#include <array> #include <array>
#include <iostream>
#include <zlib.h>
#define Biggest 30000 #define Biggest 30000
std::string Comp(std::string Data){ std::string Comp(std::string Data) {
std::array<char, Biggest> C{}; std::array<char, Biggest> C {};
// obsolete // obsolete
C.fill(0); C.fill(0);
z_stream defstream; z_stream defstream;
@ -17,20 +17,20 @@ std::string Comp(std::string Data){
defstream.zfree = Z_NULL; defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL; defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)Data.length(); defstream.avail_in = (uInt)Data.length();
defstream.next_in = (Bytef *)&Data[0]; defstream.next_in = (Bytef*)&Data[0];
defstream.avail_out = Biggest; defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef *>(C.data()); defstream.next_out = reinterpret_cast<Bytef*>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION); deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH); deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH); deflate(&defstream, Z_FINISH);
deflateEnd(&defstream); deflateEnd(&defstream);
size_t TO = defstream.total_out; size_t TO = defstream.total_out;
std::string Ret(TO,0); std::string Ret(TO, 0);
std::copy_n(C.begin(), TO, Ret.begin()); std::copy_n(C.begin(), TO, Ret.begin());
return Ret; return Ret;
} }
std::string DeComp(std::string Compressed){ std::string DeComp(std::string Compressed) {
std::array<char, Biggest> C{}; std::array<char, Biggest> C {};
// not needed // not needed
C.fill(0); C.fill(0);
z_stream infstream; z_stream infstream;
@ -38,15 +38,15 @@ std::string DeComp(std::string Compressed){
infstream.zfree = Z_NULL; infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL; infstream.opaque = Z_NULL;
infstream.avail_in = Biggest; infstream.avail_in = Biggest;
infstream.next_in = (Bytef *)(&Compressed[0]); infstream.next_in = (Bytef*)(&Compressed[0]);
infstream.avail_out = Biggest; infstream.avail_out = Biggest;
infstream.next_out = (Bytef *)(C.data()); infstream.next_out = (Bytef*)(C.data());
inflateInit(&infstream); inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH); inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH); inflate(&infstream, Z_FINISH);
inflateEnd(&infstream); inflateEnd(&infstream);
size_t TO = infstream.total_out; size_t TO = infstream.total_out;
std::string Ret(TO,0); std::string Ret(TO, 0);
std::copy_n(C.begin(), TO, Ret.begin()); std::copy_n(C.begin(), TO, Ret.begin());
return Ret; return Ret;
} }

View File

@ -2,30 +2,31 @@
/// Created by Anonymous275 on 7/28/2020 /// Created by Anonymous275 on 7/28/2020
/// ///
#include "Security/Enc.h" #include "Security/Enc.h"
#include "Settings.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Settings.h"
//#include <windows.h> //#include <windows.h>
#include "Logger.h" #include "Logger.h"
#include <random>
#include <sstream> #include <sstream>
#include <thread> #include <thread>
#include <random>
int Rand(){ int Rand() {
std::random_device r; std::random_device r;
std::default_random_engine e1(r()); std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 5000); std::uniform_int_distribution<int> uniform_dist(1, 5000);
return uniform_dist(e1); return uniform_dist(e1);
} }
int log_power(int n,unsigned int p, int mod){ int log_power(int n, unsigned int p, int mod) {
int result = 1; int result = 1;
for (; p; p >>= 1u){ for (; p; p >>= 1u) {
if (p & 1u)result = int((1LL * result * n) % mod); if (p & 1u)
result = int((1LL * result * n) % mod);
n = int((1LL * n * n) % mod); n = int((1LL * n * n) % mod);
} }
return result; return result;
} }
bool rabin_miller(int n){ bool rabin_miller(int n) {
bool ok = true; bool ok = true;
for (int i = 1; i <= 5 && ok; i++) { for (int i = 1; i <= 5 && ok; i++) {
int a = Rand() + 1; int a = Rand() + 1;
@ -34,13 +35,14 @@ bool rabin_miller(int n){
} }
return ok; return ok;
} }
int generate_prime(){ int generate_prime() {
int generated = Rand(); int generated = Rand();
while (!rabin_miller(generated))generated = Rand(); while (!rabin_miller(generated))
generated = Rand();
return generated; return generated;
} }
int gcd(int a, int b){ int gcd(int a, int b) {
while (b){ while (b) {
int r = a % b; int r = a % b;
a = b; a = b;
b = r; b = r;
@ -48,45 +50,48 @@ int gcd(int a, int b){
return a; return a;
} }
int generate_coprime(int n){ int generate_coprime(int n) {
int generated = Rand(); int generated = Rand();
while (gcd(n, generated) != 1)generated = Rand(); while (gcd(n, generated) != 1)
generated = Rand();
return generated; return generated;
} }
std::pair<int, int> euclid_extended(int a, int b) { std::pair<int, int> euclid_extended(int a, int b) {
if(!b)return {1, 0}; if (!b)
return { 1, 0 };
auto result = euclid_extended(b, a % b); auto result = euclid_extended(b, a % b);
return {result.second, result.first - (a / b) * result.second}; return { result.second, result.first - (a / b) * result.second };
} }
int modular_inverse(int n, int mod){ int modular_inverse(int n, int mod) {
int inverse = euclid_extended(n, mod).first; int inverse = euclid_extended(n, mod).first;
while(inverse < 0)inverse += mod; while (inverse < 0)
inverse += mod;
return inverse; return inverse;
} }
RSA* GenKey(){ RSA* GenKey() {
int p, q; int p, q;
p = generate_prime(); p = generate_prime();
q = generate_prime(); q = generate_prime();
int n = p * q; int n = p * q;
int phi = (p -1) * (q - 1); int phi = (p - 1) * (q - 1);
int e = generate_coprime(phi); int e = generate_coprime(phi);
int d = modular_inverse(e, phi); int d = modular_inverse(e, phi);
return new RSA{n,e,d}; return new RSA { n, e, d };
} }
int Enc(int value,int e,int n){ int Enc(int value, int e, int n) {
return log_power(value, e, n); return log_power(value, e, n);
} }
int Dec(int value,int d,int n){ int Dec(int value, int d, int n) {
return log_power(value, d, n); return log_power(value, d, n);
} }
#ifdef WIN32 #ifdef WIN32
int Handle(EXCEPTION_POINTERS *ep,char* Origin){ int Handle(EXCEPTION_POINTERS* ep, char* Origin) {
//Assert(false); //Assert(false);
std::stringstream R; std::stringstream R;
R << Sec("Code : ") << std::hex R << Sec("Code : ") << std::hex
@ -97,30 +102,31 @@ int Handle(EXCEPTION_POINTERS *ep,char* Origin){
} }
#else #else
// stub // stub
int Handle(EXCEPTION_POINTERS *, char*) { return 1; } int Handle(EXCEPTION_POINTERS*, char*) { return 1; }
#endif // WIN32 #endif // WIN32
std::string RSA_E(const std::string& Data, RSA*k){ std::string RSA_E(const std::string& Data, RSA* k) {
std::stringstream stream; std::stringstream stream;
for(const char&c : Data){ for (const char& c : Data) {
stream << std::hex << Enc(uint8_t(c),k->e,k->n) << "g"; stream << std::hex << Enc(uint8_t(c), k->e, k->n) << "g";
} }
return stream.str(); return stream.str();
} }
std::string RSA_E(const std::string& Data,int e, int n){ std::string RSA_E(const std::string& Data, int e, int n) {
std::stringstream stream; std::stringstream stream;
for(const char&c : Data){ for (const char& c : Data) {
stream << std::hex << Enc(uint8_t(c),e,n) << "g"; stream << std::hex << Enc(uint8_t(c), e, n) << "g";
} }
return stream.str(); return stream.str();
} }
std::string RSA_D(const std::string& Data, RSA*k){ std::string RSA_D(const std::string& Data, RSA* k) {
std::stringstream ss(Data); std::stringstream ss(Data);
std::string token,ret; std::string token, ret;
while (std::getline(ss, token, 'g')) { while (std::getline(ss, token, 'g')) {
if(token.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return ""; if (token.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)
return "";
int c = std::stoi(token, nullptr, 16); int c = std::stoi(token, nullptr, 16);
ret += char(Dec(c,k->d,k->n)); ret += char(Dec(c, k->d, k->n));
} }
return ret; return ret;
} }

View File

@ -1,9 +1,9 @@
/// ///
/// Created by Anonymous275 on 7/28/2020 /// Created by Anonymous275 on 7/28/2020
/// ///
#include "Security/Enc.h"
#include "Logger.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Logger.h"
#include "Security/Enc.h"
#include <fstream> #include <fstream>
#include <string> #include <string>
#include <thread> #include <thread>
@ -22,69 +22,75 @@ void SetValues(const std::string& Line, int Index) {
int state = 0; int state = 0;
std::string Data; std::string Data;
bool Switch = false; bool Switch = false;
if (Index > 5)Switch = true; if (Index > 5)
Switch = true;
for (char c : Line) { for (char c : Line) {
if (Switch){ if (Switch) {
if (c == '\"')state++; if (c == '\"')
if (state > 0 && state < 2)Data += c; state++;
}else{ if (state > 0 && state < 2)
if (c == ' ')state++; Data += c;
if (state > 1)Data += c; } else {
if (c == ' ')
state++;
if (state > 1)
Data += c;
} }
} }
Data = Data.substr(1); Data = Data.substr(1);
std::string::size_type sz; std::string::size_type sz;
bool FoundTrue = std::string(Data).find("true") != std::string::npos;//searches for "true" bool FoundTrue = std::string(Data).find("true") != std::string::npos; //searches for "true"
switch (Index) { switch (Index) {
case 1 : case 1:
Debug = FoundTrue;//checks and sets the Debug Value Debug = FoundTrue; //checks and sets the Debug Value
break; break;
case 2 : case 2:
Private = FoundTrue;//checks and sets the Private Value Private = FoundTrue; //checks and sets the Private Value
break; break;
case 3 : case 3:
Port = std::stoi(Data, &sz);//sets the Port Port = std::stoi(Data, &sz); //sets the Port
break; break;
case 4 : case 4:
MaxCars = std::stoi(Data, &sz);//sets the Max Car amount MaxCars = std::stoi(Data, &sz); //sets the Max Car amount
break; break;
case 5 : case 5:
MaxPlayers = std::stoi(Data, &sz); //sets the Max Amount of player MaxPlayers = std::stoi(Data, &sz); //sets the Max Amount of player
break; break;
case 6 : case 6:
MapName = Data; //Map MapName = Data; //Map
break; break;
case 7 : case 7:
ServerName = Data; //Name ServerName = Data; //Name
break; break;
case 8 : case 8:
ServerDesc = Data; //desc ServerDesc = Data; //desc
break; break;
case 9 : case 9:
Resource = Data; //File name Resource = Data; //File name
break; break;
case 10 : case 10:
Key = Data; //File name Key = Data; //File name
default: default:
break; break;
} }
} }
std::string RemoveComments(const std::string& Line){ std::string RemoveComments(const std::string& Line) {
std::string Return; std::string Return;
for(char c : Line) { for (char c : Line) {
if(c == '#')break; if (c == '#')
break;
Return += c; Return += c;
} }
return Return; return Return;
} }
void LoadConfig(std::ifstream& IFS){ void LoadConfig(std::ifstream& IFS) {
Assert(IFS.is_open()); Assert(IFS.is_open());
std::string line; std::string line;
int index = 1; int index = 1;
while (getline(IFS, line)) { while (getline(IFS, line)) {
index++; index++;
} }
if(index-1 < 11){ if (index - 1 < 11) {
error(Sec("Outdated/Incorrect config please remove it server will close in 5 secs")); error(Sec("Outdated/Incorrect config please remove it server will close in 5 secs"));
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0); _Exit(0);
@ -94,16 +100,16 @@ void LoadConfig(std::ifstream& IFS){
info(Sec("Config found updating values")); info(Sec("Config found updating values"));
index = 1; index = 1;
while (getline(IFS, line)) { while (getline(IFS, line)) {
if(line.rfind('#', 0) != 0 && line.rfind(' ', 0) != 0){ //Checks if it starts as Comment if (line.rfind('#', 0) != 0 && line.rfind(' ', 0) != 0) { //Checks if it starts as Comment
std::string CleanLine = RemoveComments(line); //Cleans it from the Comments std::string CleanLine = RemoveComments(line); //Cleans it from the Comments
SetValues(CleanLine,index); //sets the values SetValues(CleanLine, index); //sets the values
index++; index++;
} }
} }
} }
void GenerateConfig(){ void GenerateConfig() {
std::ofstream FileStream; std::ofstream FileStream;
FileStream.open (Sec("Server.cfg")); FileStream.open(Sec("Server.cfg"));
FileStream << Sec("# This is the BeamMP Server Configuration File v0.60\n" FileStream << Sec("# This is the BeamMP Server Configuration File v0.60\n"
"Debug = false # true or false to enable debug console output\n" "Debug = false # true or false to enable debug console output\n"
"Private = false # Private?\n" "Private = false # Private?\n"
@ -117,16 +123,16 @@ void GenerateConfig(){
"AuthKey = \"\" # Auth Key"); "AuthKey = \"\" # Auth Key");
FileStream.close(); FileStream.close();
} }
void Default(){ void Default() {
info(Sec("Config not found generating default")); info(Sec("Config not found generating default"));
GenerateConfig(); GenerateConfig();
warn(Sec("You are required to input the AuthKey")); warn(Sec("You are required to input the AuthKey"));
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0); _Exit(0);
} }
void DebugData(){ void DebugData() {
debug(std::string(Sec("Debug : ")) + (Debug?"true":"false")); debug(std::string(Sec("Debug : ")) + (Debug ? "true" : "false"));
debug(std::string(Sec("Private : ")) + (Private?"true":"false")); debug(std::string(Sec("Private : ")) + (Private ? "true" : "false"));
debug(Sec("Port : ") + std::to_string(Port)); debug(Sec("Port : ") + std::to_string(Port));
debug(Sec("Max Cars : ") + std::to_string(MaxCars)); debug(Sec("Max Cars : ") + std::to_string(MaxCars));
debug(Sec("MaxPlayers : ") + std::to_string(MaxPlayers)); debug(Sec("MaxPlayers : ") + std::to_string(MaxPlayers));
@ -136,16 +142,20 @@ void DebugData(){
debug(Sec("File : ") + Resource); debug(Sec("File : ") + Resource);
debug(Sec("Key length: ") + std::to_string(Key.length())); debug(Sec("Key length: ") + std::to_string(Key.length()));
} }
void InitConfig(){ void InitConfig() {
std::ifstream IFS; std::ifstream IFS;
IFS.open(Sec("Server.cfg")); IFS.open(Sec("Server.cfg"));
if(IFS.good())LoadConfig(IFS); if (IFS.good())
else Default(); LoadConfig(IFS);
if(IFS.is_open())IFS.close(); else
if(Key.empty()){ Default();
if (IFS.is_open())
IFS.close();
if (Key.empty()) {
error(Sec("No AuthKey was found")); error(Sec("No AuthKey was found"));
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0); _Exit(0);
} }
if(Debug)DebugData(); if (Debug)
DebugData();
} }

View File

@ -1,27 +1,27 @@
/// ///
/// Created by Anonymous275 on 7/28/2020 /// Created by Anonymous275 on 7/28/2020
/// ///
#include "Security/Enc.h"
#include "Curl/Http.h"
#include "Client.hpp" #include "Client.hpp"
#include "Settings.h" #include "Curl/Http.h"
#include "Logger.h" #include "Logger.h"
#include <sstream> #include "Security/Enc.h"
#include <thread> #include "Settings.h"
#include <chrono> #include <chrono>
#include <future> #include <future>
#include <sstream>
#include <thread>
void WebsocketInit(); void WebsocketInit();
std::string GetPlayers(){ std::string GetPlayers() {
std::string Return; std::string Return;
for(auto& c : CI->Clients){ for (auto& c : CI->Clients) {
if(c != nullptr){ if (c != nullptr) {
Return += c->GetName() + ";"; Return += c->GetName() + ";";
} }
} }
return Return; return Return;
} }
std::string GenerateCall(){ std::string GenerateCall() {
std::stringstream Ret; std::stringstream Ret;
Ret << "uuid=" << Key << "&players=" << CI->Size() Ret << "uuid=" << Key << "&players=" << CI->Size()
<< "&maxplayers=" << MaxPlayers << "&port=" << Port << "&maxplayers=" << MaxPlayers << "&port=" << Port
@ -34,49 +34,52 @@ std::string GenerateCall(){
return Ret.str(); return Ret.str();
} }
std::string RunPromise(const std::string& IP, const std::string& R) { std::string RunPromise(const std::string& IP, const std::string& R) {
std::packaged_task<std::string()> task([&]() { return PostHTTP(IP,R); }); std::packaged_task<std::string()> task([&]() { return PostHTTP(IP, R); });
std::future<std::string> f1 = task.get_future(); std::future<std::string> f1 = task.get_future();
std::thread t(std::move(task)); std::thread t(std::move(task));
t.detach(); t.detach();
auto status = f1.wait_for(std::chrono::seconds(10)); auto status = f1.wait_for(std::chrono::seconds(10));
if (status != std::future_status::timeout)return f1.get(); if (status != std::future_status::timeout)
return f1.get();
error(Sec("Backend system Timeout please try again later")); error(Sec("Backend system Timeout please try again later"));
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0); _Exit(0);
} }
void Heartbeat(){ void Heartbeat() {
DebugPrintTID(); DebugPrintTID();
std::string R,T; std::string R, T;
bool isAuth = false; bool isAuth = false;
while(true){ while (true) {
R = GenerateCall(); R = GenerateCall();
if(!CustomIP.empty())R+="&ip="+CustomIP; if (!CustomIP.empty())
R += "&ip=" + CustomIP;
std::string link = Sec("https://beammp.com/heartbeatv2"); std::string link = Sec("https://beammp.com/heartbeatv2");
T = RunPromise(link,R); T = RunPromise(link, R);
if(T.find_first_not_of(Sec("20")) != std::string::npos){ if (T.find_first_not_of(Sec("20")) != std::string::npos) {
//Backend system refused server startup! //Backend system refused server startup!
std::this_thread::sleep_for(std::chrono::seconds(10)); std::this_thread::sleep_for(std::chrono::seconds(10));
std::string Backup = Sec("https://backup1.beammp.com/heartbeatv2"); std::string Backup = Sec("https://backup1.beammp.com/heartbeatv2");
T = RunPromise(Backup,R); T = RunPromise(Backup, R);
if(T.find_first_not_of(Sec("20")) != std::string::npos) { if (T.find_first_not_of(Sec("20")) != std::string::npos) {
error(Sec("Backend system refused server! Check your AuthKey")); error(Sec("Backend system refused server! Check your AuthKey"));
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(-1); _Exit(-1);
} }
} }
//Server Authenticated //Server Authenticated
if(T.length() == 4)info(Sec("Server authenticated")); if (T.length() == 4)
info(Sec("Server authenticated"));
R.clear(); R.clear();
T.clear(); T.clear();
if(!isAuth){ if (!isAuth) {
WebsocketInit(); WebsocketInit();
isAuth = true; isAuth = true;
} }
std::this_thread::sleep_for(std::chrono::seconds(3)); std::this_thread::sleep_for(std::chrono::seconds(3));
} }
} }
void HBInit(){ void HBInit() {
std::thread HB(Heartbeat); std::thread HB(Heartbeat);
HB.detach(); HB.detach();
} }

View File

@ -1,11 +1,11 @@
/// ///
/// Created by Anonymous275 on 7/28/2020 /// Created by Anonymous275 on 7/28/2020
/// ///
#include "Logger.h"
#include "Security/Enc.h" #include "Security/Enc.h"
#include <filesystem>
#include "Settings.h" #include "Settings.h"
#include <algorithm> #include <algorithm>
#include "Logger.h" #include <filesystem>
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -14,22 +14,23 @@ std::string FileSizes;
std::string FileList; std::string FileList;
int ModsLoaded = 0; int ModsLoaded = 0;
void InitRes(){ void InitRes() {
std::string Path = Resource + Sec("/Client"); std::string Path = Resource + Sec("/Client");
if(!fs::exists(Path))fs::create_directory(Path); if (!fs::exists(Path))
for (const auto & entry : fs::directory_iterator(Path)){ fs::create_directory(Path);
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().string().find(Sec(".zip")); auto pos = entry.path().string().find(Sec(".zip"));
if(pos != std::string::npos){ if (pos != std::string::npos) {
if(entry.path().string().length() - pos == 4){ if (entry.path().string().length() - pos == 4) {
FileList += entry.path().string() + ";"; FileList += entry.path().string() + ";";
FileSizes += std::to_string(fs::file_size(entry.path()))+";"; FileSizes += std::to_string(fs::file_size(entry.path())) + ";";
MaxModSize += fs::file_size(entry.path()); MaxModSize += fs::file_size(entry.path());
ModsLoaded++; ModsLoaded++;
} }
} }
} }
std::replace(FileList.begin(),FileList.end(),'\\','/'); std::replace(FileList.begin(), FileList.end(), '\\', '/');
if(ModsLoaded){ if (ModsLoaded) {
info(Sec("Loaded ")+std::to_string(ModsLoaded)+Sec(" Mods")); info(Sec("Loaded ") + std::to_string(ModsLoaded) + Sec(" Mods"));
} }
} }

View File

@ -1,35 +1,36 @@
/// ///
/// Created by Anonymous275 on 7/28/2020 /// Created by Anonymous275 on 7/28/2020
/// ///
#include "Security/Enc.h"
#include "Client.hpp" #include "Client.hpp"
#include "Logger.h" #include "Logger.h"
#include <string> #include "Security/Enc.h"
#include <algorithm> #include <algorithm>
#include <string>
std::string CustomIP; std::string CustomIP;
std::string GetSVer(){ std::string GetSVer() {
static std::string r = Sec("1.0"); static std::string r = Sec("1.0");
return r; return r;
} }
std::string GetCVer(){ std::string GetCVer() {
static std::string r = Sec("1.70"); static std::string r = Sec("1.70");
return r; return r;
} }
void Args(int argc, char* argv[]){ void Args(int argc, char* argv[]) {
info(Sec("BeamMP Server Running version ") + GetSVer()); info(Sec("BeamMP Server Running version ") + GetSVer());
if(argc > 1){ if (argc > 1) {
CustomIP = argv[1]; CustomIP = argv[1];
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.'); size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
auto p = CustomIP.find_first_not_of(Sec(".0123456789")); auto p = CustomIP.find_first_not_of(Sec(".0123456789"));
if(p != std::string::npos || n != 3 || CustomIP.substr(0,3) == Sec("127")){ if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == Sec("127")) {
CustomIP.clear(); CustomIP.clear();
warn(Sec("IP Specified is invalid! Ignoring")); warn(Sec("IP Specified is invalid! Ignoring"));
}else info(Sec("Server started with custom IP")); } else
info(Sec("Server started with custom IP"));
} }
} }
void InitServer(int argc, char* argv[]){ void InitServer(int argc, char* argv[]) {
InitLog(); InitLog();
Args(argc,argv); Args(argc, argv);
CI = std::make_unique<ClientInterface>(); CI = std::make_unique<ClientInterface>();
} }

View File

@ -50,9 +50,9 @@ void FolderList(const std::string& Path, bool HotSwap) {
[[noreturn]] void HotSwaps(const std::string& path) { [[noreturn]] void HotSwaps(const std::string& path) {
DebugPrintTID(); DebugPrintTID();
while (true) { while (true) {
if(!PluginEngine.empty()) { if (!PluginEngine.empty()) {
for (auto &Script : PluginEngine) { for (auto& Script : PluginEngine) {
struct stat Info{}; struct stat Info { };
if (stat(Script->GetFileName().c_str(), &Info) != 0) { if (stat(Script->GetFileName().c_str(), &Info) != 0) {
Script->SetStopThread(true); Script->SetStopThread(true);
PluginEngine.erase(Script); PluginEngine.erase(Script);

View File

@ -11,8 +11,8 @@
#include "UnixCompat.h" #include "UnixCompat.h"
#include <future> #include <future>
#include <iostream> #include <iostream>
#include <utility>
#include <optional> #include <optional>
#include <utility>
std::unique_ptr<LuaArg> CreateArg(lua_State* L, int T, int S) { std::unique_ptr<LuaArg> CreateArg(lua_State* L, int T, int S) {
if (S > T) if (S > T)

View File

@ -1,21 +1,20 @@
/// ///
/// Created by Anonymous275 on 7/31/2020 /// Created by Anonymous275 on 7/31/2020
/// ///
#include "Security/Enc.h"
#include "Curl/Http.h" #include "Curl/Http.h"
#include "Settings.h"
#include "Network.h"
#include "Logger.h" #include "Logger.h"
#include <sstream> #include "Network.h"
#include <thread> #include "Security/Enc.h"
#include <cstring> #include "Settings.h"
#include <algorithm>
#include <string>
#include <atomic>
#include "UnixCompat.h" #include "UnixCompat.h"
#include <algorithm>
#include <atomic>
#include <cstring>
#include <sstream>
#include <string>
#include <thread>
bool Send(SOCKET TCPSock, std::string Data) {
bool Send(SOCKET TCPSock,std::string Data){
#ifdef WIN32 #ifdef WIN32
int BytesSent; int BytesSent;
int len = static_cast<int>(Data.size()); int len = static_cast<int>(Data.size());
@ -35,13 +34,13 @@ bool Send(SOCKET TCPSock,std::string Data){
} }
return true; return true;
} }
std::string Rcv(SOCKET TCPSock){ std::string Rcv(SOCKET TCPSock) {
uint32_t RealSize; uint32_t RealSize;
#ifdef WIN32 #ifdef WIN32
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<char*>(&RealSize), sizeof(RealSize), 0); int64_t BytesRcv = recv(TCPSock, reinterpret_cast<char*>(&RealSize), sizeof(RealSize), 0);
#else #else
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<void*>(&RealSize), sizeof(RealSize), 0); int64_t BytesRcv = recv(TCPSock, reinterpret_cast<void*>(&RealSize), sizeof(RealSize), 0);
#endif #endif
if (BytesRcv != sizeof(RealSize)) { if (BytesRcv != sizeof(RealSize)) {
error(std::string(Sec("invalid packet: expected 4, got ")) + std::to_string(BytesRcv)); error(std::string(Sec("invalid packet: expected 4, got ")) + std::to_string(BytesRcv));
return ""; return "";
@ -63,21 +62,23 @@ std::string Rcv(SOCKET TCPSock){
return ""; return "";
return std::string(buf); return std::string(buf);
} }
std::string GetRole(const std::string &DID){ std::string GetRole(const std::string& DID) {
if(!DID.empty()){ if (!DID.empty()) {
std::string a = HttpRequest(Sec("https://beammp.com/entitlement?did=")+DID,443); std::string a = HttpRequest(Sec("https://beammp.com/entitlement?did=") + DID, 443);
std::string b = HttpRequest(Sec("https://backup1.beammp.com/entitlement?did=")+DID,443); std::string b = HttpRequest(Sec("https://backup1.beammp.com/entitlement?did=") + DID, 443);
if(!a.empty() || !b.empty()){ if (!a.empty() || !b.empty()) {
if(a != b)a = b; if (a != b)
a = b;
auto pos = a.find('"'); auto pos = a.find('"');
if(pos != std::string::npos){ if (pos != std::string::npos) {
return a.substr(pos+1,a.find('"',pos+1)-2); return a.substr(pos + 1, a.find('"', pos + 1) - 2);
}else if(a == "[]")return Sec("Member"); } else if (a == "[]")
return Sec("Member");
} }
} }
return ""; return "";
} }
void Check(SOCKET TCPSock, std::reference_wrapper<std::atomic_bool> ok){ void Check(SOCKET TCPSock, std::reference_wrapper<std::atomic_bool> ok) {
DebugPrintTID(); DebugPrintTID();
size_t accum = 0; size_t accum = 0;
while (!ok.get()) { while (!ok.get()) {
@ -90,17 +91,18 @@ void Check(SOCKET TCPSock, std::reference_wrapper<std::atomic_bool> ok){
} }
} }
} }
int Max(){ int Max() {
int M = MaxPlayers; int M = MaxPlayers;
for(auto& c : CI->Clients){ for (auto& c : CI->Clients) {
if(c != nullptr){ if (c != nullptr) {
if(c->GetRole() == Sec("MDEV"))M++; if (c->GetRole() == Sec("MDEV"))
M++;
} }
} }
return M; return M;
} }
void CreateClient(SOCKET TCPSock,const std::string &Name, const std::string &DID,const std::string &Role) { void CreateClient(SOCKET TCPSock, const std::string& Name, const std::string& DID, const std::string& Role) {
auto *c = new Client; auto* c = new Client;
c->SetTCPSock(TCPSock); c->SetTCPSock(TCPSock);
c->SetName(Name); c->SetName(Name);
c->SetRole(Role); c->SetRole(Role);
@ -109,41 +111,43 @@ void CreateClient(SOCKET TCPSock,const std::string &Name, const std::string &DID
CI->AddClient(std::move(c)); CI->AddClient(std::move(c));
InitClient(&Client); InitClient(&Client);
} }
std::pair<int,int> Parse(const std::string& msg){ std::pair<int, int> Parse(const std::string& msg) {
std::stringstream ss(msg); std::stringstream ss(msg);
std::string t; std::string t;
std::pair<int,int> a = {0,0}; //N then E std::pair<int, int> a = { 0, 0 }; //N then E
while (std::getline(ss, t, 'g')) { while (std::getline(ss, t, 'g')) {
if(t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return a; if (t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)
if(a.first == 0){ return a;
if (a.first == 0) {
a.first = std::stoi(t, nullptr, 16); a.first = std::stoi(t, nullptr, 16);
}else if(a.second == 0){ } else if (a.second == 0) {
a.second = std::stoi(t, nullptr, 16); a.second = std::stoi(t, nullptr, 16);
}else return a; } else
return a;
} }
return {0,0}; return { 0, 0 };
} }
std::string GenerateM(RSA*key){ std::string GenerateM(RSA* key) {
std::stringstream stream; std::stringstream stream;
stream << std::hex << key->n << "g" << key->e << "g" << RSA_E(Sec("IDC"),key); stream << std::hex << key->n << "g" << key->e << "g" << RSA_E(Sec("IDC"), key);
return stream.str(); return stream.str();
} }
void Identification(SOCKET TCPSock, RSA*Skey){ void Identification(SOCKET TCPSock, RSA* Skey) {
DebugPrintTID(); DebugPrintTID();
Assert(Skey); Assert(Skey);
std::atomic_bool ok { false }; std::atomic_bool ok { false };
std::thread Timeout(Check, TCPSock, std::ref<std::atomic_bool>(ok)); std::thread Timeout(Check, TCPSock, std::ref<std::atomic_bool>(ok));
Timeout.detach(); Timeout.detach();
std::string Name,DID,Role; std::string Name, DID, Role;
if(!Send(TCPSock,GenerateM(Skey))) { if (!Send(TCPSock, GenerateM(Skey))) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
std::string msg = Rcv(TCPSock); std::string msg = Rcv(TCPSock);
auto Keys = Parse(msg); auto Keys = Parse(msg);
if(!Send(TCPSock,RSA_E("HC",Keys.second,Keys.first))){ if (!Send(TCPSock, RSA_E("HC", Keys.second, Keys.first))) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
@ -152,43 +156,43 @@ void Identification(SOCKET TCPSock, RSA*Skey){
std::string Res = Rcv(TCPSock); std::string Res = Rcv(TCPSock);
std::string Ver = Rcv(TCPSock); std::string Ver = Rcv(TCPSock);
ok = true; ok = true;
Ver = RSA_D(Ver,Skey); Ver = RSA_D(Ver, Skey);
if(Ver.size() > 3 && Ver.substr(0,2) == Sec("VC")){ if (Ver.size() > 3 && Ver.substr(0, 2) == Sec("VC")) {
Ver = Ver.substr(2); Ver = Ver.substr(2);
if(Ver.length() > 4 || Ver != GetCVer()){ if (Ver.length() > 4 || Ver != GetCVer()) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
}else{ } else {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
Res = RSA_D(Res,Skey); Res = RSA_D(Res, Skey);
if(Res.size() < 3 || Res.substr(0,2) != Sec("NR")) { if (Res.size() < 3 || Res.substr(0, 2) != Sec("NR")) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
if(Res.find(':') == std::string::npos){ if (Res.find(':') == std::string::npos) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
Name = Res.substr(2,Res.find(':')-2); Name = Res.substr(2, Res.find(':') - 2);
DID = Res.substr(Res.find(':')+1); DID = Res.substr(Res.find(':') + 1);
Role = GetRole(DID); Role = GetRole(DID);
if(Role.empty() || Role.find(Sec("Error")) != std::string::npos){ if (Role.empty() || Role.find(Sec("Error")) != std::string::npos) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
return; return;
} }
// DebugPrintTIDInternal(std::string("Client(") + Name + ")"); // DebugPrintTIDInternal(std::string("Client(") + Name + ")");
debug(Sec("Name -> ") + Name + Sec(", Role -> ") + Role + Sec(", ID -> ") + DID); debug(Sec("Name -> ") + Name + Sec(", Role -> ") + Role + Sec(", ID -> ") + DID);
for(auto& c : CI->Clients){ for (auto& c : CI->Clients) {
if(c != nullptr){ if (c != nullptr) {
if(c->GetDID() == DID){ if (c->GetDID() == DID) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(c->GetTCPSock()); closesocket(c->GetTCPSock());
c->SetStatus(-2); c->SetStatus(-2);
@ -196,25 +200,25 @@ void Identification(SOCKET TCPSock, RSA*Skey){
} }
} }
} }
if(Role == Sec("MDEV") || CI->Size() < Max()){ if (Role == Sec("MDEV") || CI->Size() < Max()) {
debug("Identification success"); debug("Identification success");
CreateClient(TCPSock,Name,DID,Role); CreateClient(TCPSock, Name, DID, Role);
} else { } else {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock); closesocket(TCPSock);
} }
} }
void Identify(SOCKET TCPSock){ void Identify(SOCKET TCPSock) {
RSA*Skey = GenKey(); RSA* Skey = GenKey();
// this disgusting ifdef stuff is needed because for some // this disgusting ifdef stuff is needed because for some
// reason MSVC defines __try and __except and libg++ defines // reason MSVC defines __try and __except and libg++ defines
// __try and __catch so its all a big mess if we leave this in or undefine // __try and __catch so its all a big mess if we leave this in or undefine
// the macros // the macros
/*#ifdef WIN32 /*#ifdef WIN32
__try{ __try{
#endif // WIN32*/ #endif // WIN32*/
Identification(TCPSock, Skey); Identification(TCPSock, Skey);
/*#ifdef WIN32 /*#ifdef WIN32
}__except(1){ }__except(1){
if(TCPSock != -1){ if(TCPSock != -1){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__)); error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
@ -226,87 +230,87 @@ void Identify(SOCKET TCPSock){
delete Skey; delete Skey;
} }
void TCPServerMain(){ void TCPServerMain() {
DebugPrintTID(); DebugPrintTID();
#ifdef WIN32 #ifdef WIN32
WSADATA wsaData; WSADATA wsaData;
if (WSAStartup(514, &wsaData)){ if (WSAStartup(514, &wsaData)) {
error(Sec("Can't start Winsock!")); error(Sec("Can't start Winsock!"));
return; return;
} }
SOCKET client, Listener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in addr{}; sockaddr_in addr {};
addr.sin_addr.S_un.S_addr = ADDR_ANY; addr.sin_addr.S_un.S_addr = ADDR_ANY;
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_port = htons(Port); addr.sin_port = htons(Port);
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR){ if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
error(Sec("Can't bind socket! ") + std::to_string(WSAGetLastError())); error(Sec("Can't bind socket! ") + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1); _Exit(-1);
} }
if(Listener == -1){ if (Listener == -1) {
error(Sec("Invalid listening socket")); error(Sec("Invalid listening socket"));
return; return;
} }
if(listen(Listener,SOMAXCONN)){ if (listen(Listener, SOMAXCONN)) {
error(Sec("listener failed ")+ std::to_string(GetLastError())); error(Sec("listener failed ") + std::to_string(GetLastError()));
return; return;
} }
info(Sec("Vehicle event network online")); info(Sec("Vehicle event network online"));
do{ do {
try { try {
client = accept(Listener, nullptr, nullptr); client = accept(Listener, nullptr, nullptr);
if(client == -1){ if (client == -1) {
warn(Sec("Got an invalid client socket on connect! Skipping...")); warn(Sec("Got an invalid client socket on connect! Skipping..."));
continue; continue;
} }
std::thread ID(Identify,client); std::thread ID(Identify, client);
ID.detach(); ID.detach();
} catch (const std::exception& e) { } catch (const std::exception& e) {
error(Sec("fatal: ") + std::string(e.what())); error(Sec("fatal: ") + std::string(e.what()));
} }
}while(client); } while (client);
closesocket(client); closesocket(client);
WSACleanup(); WSACleanup();
#else // unix #else // unix
// wondering why we need slightly different implementations of this? // wondering why we need slightly different implementations of this?
// ask ms. // ask ms.
SOCKET client = -1, Listener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); SOCKET client = -1, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int optval = 1; int optval = 1;
setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
// TODO: check optval or return value idk // TODO: check optval or return value idk
sockaddr_in addr{}; sockaddr_in addr {};
addr.sin_addr.s_addr = INADDR_ANY; addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_port = htons(uint16_t(Port)); addr.sin_port = htons(uint16_t(Port));
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0){ if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
error(Sec("Can't bind socket! ") + std::string(strerror(errno))); error(Sec("Can't bind socket! ") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1); _Exit(-1);
} }
if(Listener == -1){ if (Listener == -1) {
error(Sec("Invalid listening socket")); error(Sec("Invalid listening socket"));
return; return;
} }
if(listen(Listener,SOMAXCONN)){ if (listen(Listener, SOMAXCONN)) {
error(Sec("listener failed ")+ std::string(strerror(errno))); error(Sec("listener failed ") + std::string(strerror(errno)));
return; return;
} }
info(Sec("Vehicle event network online")); info(Sec("Vehicle event network online"));
do{ do {
try { try {
client = accept(Listener, nullptr, nullptr); client = accept(Listener, nullptr, nullptr);
if(client == -1){ if (client == -1) {
warn(Sec("Got an invalid client socket on connect! Skipping...")); warn(Sec("Got an invalid client socket on connect! Skipping..."));
continue; continue;
} }
std::thread ID(Identify,client); std::thread ID(Identify, client);
ID.detach(); ID.detach();
} catch (const std::exception& e) { } catch (const std::exception& e) {
error(Sec("fatal: ") + std::string(e.what())); error(Sec("fatal: ") + std::string(e.what()));
} }
}while(client); } while (client);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__)); debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(client); closesocket(client);

View File

@ -3,104 +3,103 @@
/// ///
#include "Client.hpp" #include "Client.hpp"
std::string Client::GetName(){ std::string Client::GetName() {
return Name; return Name;
} }
void Client::SetName(const std::string& name){ void Client::SetName(const std::string& name) {
Name = name; Name = name;
} }
void Client::SetDID(const std::string& did){ void Client::SetDID(const std::string& did) {
DID = did; DID = did;
} }
std::string Client::GetDID(){ std::string Client::GetDID() {
return DID; return DID;
} }
void Client::SetRole(const std::string& role){ void Client::SetRole(const std::string& role) {
Role = role; Role = role;
} }
std::string Client::GetRole(){ std::string Client::GetRole() {
return Role; return Role;
} }
int Client::GetID(){ int Client::GetID() {
return ID; return ID;
} }
void Client::SetID(int id){ void Client::SetID(int id) {
ID = id; ID = id;
} }
void Client::SetStatus(int state){ void Client::SetStatus(int state) {
Status = state; Status = state;
} }
int Client::GetStatus(){ int Client::GetStatus() {
return Status; return Status;
} }
void Client::SetUDPAddr(sockaddr_in Addr){ void Client::SetUDPAddr(sockaddr_in Addr) {
UDPADDR = Addr; UDPADDR = Addr;
} }
sockaddr_in Client::GetUDPAddr(){ sockaddr_in Client::GetUDPAddr() {
return UDPADDR; return UDPADDR;
} }
void Client::SetTCPSock(SOCKET CSock) { void Client::SetTCPSock(SOCKET CSock) {
TCPSOCK = CSock; TCPSOCK = CSock;
} }
SOCKET Client::GetTCPSock(){ SOCKET Client::GetTCPSock() {
return TCPSOCK; return TCPSOCK;
} }
void Client::DeleteCar(int ident){ void Client::DeleteCar(int ident) {
for(auto& v : VehicleData){ for (auto& v : VehicleData) {
if(v != nullptr && v->ID == ident){ if (v != nullptr && v->ID == ident) {
VehicleData.erase(v); VehicleData.erase(v);
break; break;
} }
} }
} }
void Client::ClearCars(){ void Client::ClearCars() {
VehicleData.clear(); VehicleData.clear();
} }
int Client::GetOpenCarID(){ int Client::GetOpenCarID() {
int OpenID = 0; int OpenID = 0;
bool found; bool found;
do { do {
found = true; found = true;
for (auto& v : VehicleData) { for (auto& v : VehicleData) {
if (v != nullptr && v->ID == OpenID){ if (v != nullptr && v->ID == OpenID) {
OpenID++; OpenID++;
found = false; found = false;
} }
} }
}while (!found); } while (!found);
return OpenID; return OpenID;
} }
void Client::AddNewCar(int ident,const std::string& Data){ void Client::AddNewCar(int ident, const std::string& Data) {
VehicleData.insert(std::unique_ptr<VData>(new VData{ident,Data})); VehicleData.insert(std::unique_ptr<VData>(new VData { ident, Data }));
} }
std::set<std::unique_ptr<VData>>& Client::GetAllCars(){ std::set<std::unique_ptr<VData>>& Client::GetAllCars() {
return VehicleData; return VehicleData;
} }
const std::set<std::unique_ptr<VData>> &Client::GetAllCars() const { const std::set<std::unique_ptr<VData>>& Client::GetAllCars() const {
return VehicleData; return VehicleData;
} }
std::string Client::GetCarData(int ident){ std::string Client::GetCarData(int ident) {
for(auto& v : VehicleData){ for (auto& v : VehicleData) {
if(v != nullptr && v->ID == ident){ if (v != nullptr && v->ID == ident) {
return v->Data; return v->Data;
} }
} }
DeleteCar(ident); DeleteCar(ident);
return ""; return "";
} }
void Client::SetCarData(int ident,const std::string&Data){ void Client::SetCarData(int ident, const std::string& Data) {
for(auto& v : VehicleData){ for (auto& v : VehicleData) {
if(v != nullptr && v->ID == ident){ if (v != nullptr && v->ID == ident) {
v->Data = Data; v->Data = Data;
return; return;
} }
} }
DeleteCar(ident); DeleteCar(ident);
} }
int Client::GetCarCount(){ int Client::GetCarCount() {
return int(VehicleData.size()); return int(VehicleData.size());
} }

View File

@ -1,65 +1,62 @@
/// ///
/// Created by Anonymous275 on 8/1/2020 /// Created by Anonymous275 on 8/1/2020
/// ///
#include "Lua/LuaSystem.hpp"
#include "Security/Enc.h"
#include "Client.hpp" #include "Client.hpp"
#include "Settings.h"
#include "Network.h"
#include "Logger.h" #include "Logger.h"
#include "Lua/LuaSystem.hpp"
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h" #include "UnixCompat.h"
#include <memory> #include <memory>
#include <sstream> #include <sstream>
int FC(const std::string& s, const std::string& p, int n) {
int FC(const std::string& s,const std::string& p,int n) {
auto i = s.find(p); auto i = s.find(p);
int j; int j;
for (j = 1; j < n && i != std::string::npos; ++j){ for (j = 1; j < n && i != std::string::npos; ++j) {
i = s.find(p, i+1); i = s.find(p, i + 1);
} }
if (j == n)return int(i); if (j == n)
else return -1; return int(i);
else
return -1;
} }
void Apply(Client*c,int VID,const std::string& pckt){ void Apply(Client* c, int VID, const std::string& pckt) {
Assert(c); Assert(c);
std::string Packet = pckt; std::string Packet = pckt;
std::string VD = c->GetCarData(VID); std::string VD = c->GetCarData(VID);
Packet = Packet.substr(FC(Packet, ",", 2) + 1); Packet = Packet.substr(FC(Packet, ",", 2) + 1);
Packet = VD.substr(0, FC(VD, ",", 2) + 1) + Packet = VD.substr(0, FC(VD, ",", 2) + 1) + Packet.substr(0, Packet.find_last_of('"') + 1) + VD.substr(FC(VD, ",\"", 7));
Packet.substr(0, Packet.find_last_of('"') + 1) +
VD.substr(FC(VD, ",\"", 7));
c->SetCarData(VID, Packet); c->SetCarData(VID, Packet);
} }
void VehicleParser(Client*c,const std::string& Pckt){ void VehicleParser(Client* c, const std::string& Pckt) {
Assert(c); Assert(c);
if(c == nullptr || Pckt.length() < 4)return; if (c == nullptr || Pckt.length() < 4)
return;
std::string Packet = Pckt; std::string Packet = Pckt;
char Code = Packet.at(1); char Code = Packet.at(1);
int PID = -1; int PID = -1;
int VID = -1; int VID = -1;
std::string Data = Packet.substr(3),pid,vid; std::string Data = Packet.substr(3), pid, vid;
switch(Code){ //Spawned Destroyed Switched/Moved NotFound Reset switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
case 's': case 's':
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'Os' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'Os' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
if(Data.at(0) == '0'){ if (Data.at(0) == '0') {
int CarID = c->GetOpenCarID(); int CarID = c->GetOpenCarID();
debug(c->GetName() + Sec(" created a car with ID ") + std::to_string(CarID)); debug(c->GetName() + Sec(" created a car with ID ") + std::to_string(CarID));
Packet = "Os:"+c->GetRole()+":"+c->GetName()+":"+std::to_string(c->GetID())+"-"+std::to_string(CarID)+Packet.substr(4); Packet = "Os:" + c->GetRole() + ":" + c->GetName() + ":" + std::to_string(c->GetID()) + "-" + std::to_string(CarID) + Packet.substr(4);
if(c->GetCarCount() >= MaxCars || if (c->GetCarCount() >= MaxCars || TriggerLuaEvent(Sec("onVehicleSpawn"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), CarID, Packet.substr(3) } }), true)) {
TriggerLuaEvent(Sec("onVehicleSpawn"),false,nullptr, Respond(c, Packet, true);
std::make_unique<LuaArg>(LuaArg{{c->GetID(),CarID,Packet.substr(3)}}), std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(CarID);
true)){ Respond(c, Destroy, true);
Respond(c,Packet,true);
std::string Destroy = "Od:" + std::to_string(c->GetID())+"-"+std::to_string(CarID);
Respond(c,Destroy,true);
debug(c->GetName() + Sec(" (force : car limit/lua) removed ID ") + std::to_string(CarID)); debug(c->GetName() + Sec(" (force : car limit/lua) removed ID ") + std::to_string(CarID));
}else{ } else {
c->AddNewCar(CarID,Packet); c->AddNewCar(CarID, Packet);
SendToAll(nullptr, Packet,true,true); SendToAll(nullptr, Packet, true, true);
} }
} }
return; return;
@ -67,21 +64,21 @@ void VehicleParser(Client*c,const std::string& Pckt){
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'Oc' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'Oc' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
pid = Data.substr(0,Data.find('-')); pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-')+1,Data.find(':',1)-Data.find('-')-1); vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
if(pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos){ if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid); PID = stoi(pid);
VID = stoi(vid); VID = stoi(vid);
} }
if(PID != -1 && VID != -1 && PID == c->GetID()){ if (PID != -1 && VID != -1 && PID == c->GetID()) {
if(!TriggerLuaEvent(Sec("onVehicleEdited"),false,nullptr, if (!TriggerLuaEvent(Sec("onVehicleEdited"), false, nullptr,
std::unique_ptr<LuaArg>(new LuaArg{{c->GetID(),VID,Packet.substr(3)}}), std::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), VID, Packet.substr(3) } }),
true)) { true)) {
SendToAll(c, Packet, false, true); SendToAll(c, Packet, false, true);
Apply(c,VID,Packet); Apply(c, VID, Packet);
}else{ } else {
std::string Destroy = "Od:" + std::to_string(c->GetID())+"-"+std::to_string(VID); std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(VID);
Respond(c,Destroy,true); Respond(c, Destroy, true);
c->DeleteCar(VID); c->DeleteCar(VID);
} }
} }
@ -90,16 +87,16 @@ void VehicleParser(Client*c,const std::string& Pckt){
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'Od' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'Od' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
pid = Data.substr(0,Data.find('-')); pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-')+1); vid = Data.substr(Data.find('-') + 1);
if(pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos){ if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid); PID = stoi(pid);
VID = stoi(vid); VID = stoi(vid);
} }
if(PID != -1 && VID != -1 && PID == c->GetID()){ if (PID != -1 && VID != -1 && PID == c->GetID()) {
SendToAll(nullptr,Packet,true,true); SendToAll(nullptr, Packet, true, true);
TriggerLuaEvent(Sec("onVehicleDeleted"),false,nullptr, TriggerLuaEvent(Sec("onVehicleDeleted"), false, nullptr,
std::unique_ptr<LuaArg>(new LuaArg{{c->GetID(),VID}}),false); std::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), VID } }), false);
c->DeleteCar(VID); c->DeleteCar(VID);
debug(c->GetName() + Sec(" deleted car with ID ") + std::to_string(VID)); debug(c->GetName() + Sec(" deleted car with ID ") + std::to_string(VID));
} }
@ -108,7 +105,7 @@ void VehicleParser(Client*c,const std::string& Pckt){
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'Or' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'Or' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
SendToAll(c,Packet,false,true); SendToAll(c, Packet, false, true);
return; return;
default: default:
#ifdef DEBUG #ifdef DEBUG
@ -117,19 +114,20 @@ void VehicleParser(Client*c,const std::string& Pckt){
return; return;
} }
} }
void SyncClient(Client*c){ void SyncClient(Client* c) {
Assert(c); Assert(c);
if(c->isSynced)return; if (c->isSynced)
return;
c->isSynced = true; c->isSynced = true;
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
Respond(c,Sec("Sn")+c->GetName(),true); Respond(c, Sec("Sn") + c->GetName(), true);
SendToAll(c,Sec("JWelcome ")+c->GetName()+"!",false,true); SendToAll(c, Sec("JWelcome ") + c->GetName() + "!", false, true);
TriggerLuaEvent(Sec("onPlayerJoin"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false); TriggerLuaEvent(Sec("onPlayerJoin"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
for (auto& client : CI->Clients) { for (auto& client : CI->Clients) {
if(client != nullptr){ if (client != nullptr) {
if (client.get() != c) { if (client.get() != c) {
for (auto& v : client->GetAllCars()) { for (auto& v : client->GetAllCars()) {
if(v != nullptr){ if (v != nullptr) {
Respond(c, v->Data, true); Respond(c, v->Data, true);
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(2));
} }
@ -139,49 +137,51 @@ void SyncClient(Client*c){
} }
info(c->GetName() + Sec(" is now synced!")); info(c->GetName() + Sec(" is now synced!"));
} }
void ParseVeh(Client*c, const std::string& Packet){ void ParseVeh(Client* c, const std::string& Packet) {
Assert(c); Assert(c);
#ifdef WIN32 #ifdef WIN32
__try{ __try {
VehicleParser(c,Packet); VehicleParser(c, Packet);
}__except(Handle(GetExceptionInformation(),Sec("Vehicle Handler"))){} } __except (Handle(GetExceptionInformation(), Sec("Vehicle Handler"))) { }
#else // unix #else // unix
VehicleParser(c,Packet); VehicleParser(c, Packet);
#endif // WIN32 #endif // WIN32
} }
void HandleEvent(Client*c ,const std::string&Data){ void HandleEvent(Client* c, const std::string& Data) {
Assert(c); Assert(c);
std::stringstream ss(Data); std::stringstream ss(Data);
std::string t,Name; std::string t, Name;
int a = 0; int a = 0;
while (std::getline(ss, t, ':')) { while (std::getline(ss, t, ':')) {
switch(a){ switch (a) {
case 1: case 1:
Name = t; Name = t;
break; break;
case 2: case 2:
TriggerLuaEvent(Name, false, nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID(),t}}),false); TriggerLuaEvent(Name, false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), t } }), false);
break; break;
default: default:
break; break;
} }
if(a == 2)break; if (a == 2)
break;
a++; a++;
} }
} }
void GlobalParser(Client*c, const std::string& Pack){ void GlobalParser(Client* c, const std::string& Pack) {
Assert(c); Assert(c);
if(Pack.empty() || c == nullptr)return; if (Pack.empty() || c == nullptr)
std::string Packet = Pack.substr(0,strlen(Pack.c_str())); return;
std::string Packet = Pack.substr(0, strlen(Pack.c_str()));
std::string pct; std::string pct;
char Code = Packet.at(0); char Code = Packet.at(0);
//V to Z //V to Z
if(Code <= 90 && Code >= 86){ if (Code <= 90 && Code >= 86) {
PPS++; PPS++;
SendToAll(c,Packet,false,false); SendToAll(c, Packet, false, false);
return; return;
} }
switch (Code) { switch (Code) {
@ -189,56 +189,58 @@ void GlobalParser(Client*c, const std::string& Pack){
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'P' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'P' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
Respond(c, Sec("P") + std::to_string(c->GetID()),true); Respond(c, Sec("P") + std::to_string(c->GetID()), true);
SyncClient(c); SyncClient(c);
return; return;
case 'p': case 'p':
Respond(c,Sec("p"),false); Respond(c, Sec("p"), false);
UpdatePlayers(); UpdatePlayers();
return; return;
case 'O': case 'O':
if(Packet.length() > 1000) { if (Packet.length() > 1000) {
debug(Sec("Received data from: ") + c->GetName() + Sec(" Size: ") + std::to_string(Packet.length())); debug(Sec("Received data from: ") + c->GetName() + Sec(" Size: ") + std::to_string(Packet.length()));
} }
ParseVeh(c,Packet); ParseVeh(c, Packet);
return; return;
case 'J': case 'J':
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'J' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'J' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
SendToAll(c,Packet,false,true); SendToAll(c, Packet, false, true);
return; return;
case 'C': case 'C':
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'C' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'C' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
if(Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)break; if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break;
if (TriggerLuaEvent(Sec("onChatMessage"), false, nullptr, if (TriggerLuaEvent(Sec("onChatMessage"), false, nullptr,
std::unique_ptr<LuaArg>(new LuaArg{ std::unique_ptr<LuaArg>(new LuaArg {
{c->GetID(), c->GetName(), Packet.substr(Packet.find(':', 3) + 1)} { c->GetID(), c->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }),
}),true))break; true))
break;
SendToAll(nullptr, Packet, true, true); SendToAll(nullptr, Packet, true, true);
return; return;
case 'E': case 'E':
#ifdef DEBUG #ifdef DEBUG
debug(std::string(Sec("got 'E' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")")); debug(std::string(Sec("got 'E' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
#endif #endif
HandleEvent(c,Packet); HandleEvent(c, Packet);
return; return;
default: default:
return; return;
} }
} }
void GParser(Client*c, const std::string& Packet){ void GParser(Client* c, const std::string& Packet) {
Assert(c); Assert(c);
if(Packet.find("Zp") != std::string::npos && Packet.size() > 500){ if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
abort(); abort();
} }
#ifdef WIN32 #ifdef WIN32
__try{ __try {
GlobalParser(c, Packet); GlobalParser(c, Packet);
}__except(Handle(GetExceptionInformation(),Sec("Global Handler"))){} } __except (Handle(GetExceptionInformation(), Sec("Global Handler"))) { }
#else #else
GlobalParser(c, Packet); GlobalParser(c, Packet);
#endif // WIN32 #endif // WIN32

View File

@ -2,38 +2,39 @@
/// Created by Anonymous275 on 4/9/2020 /// Created by Anonymous275 on 4/9/2020
/// ///
#include <curl/curl.h>
#include "CustomAssert.h" #include "CustomAssert.h"
#include <curl/curl.h>
#include <iostream> #include <iostream>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp){ static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb); ((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb; return size * nmemb;
} }
std::string HttpRequest(const std::string& IP,int port){ std::string HttpRequest(const std::string& IP, int port) {
CURL *curl; CURL* curl;
CURLcode res; CURLcode res;
std::string readBuffer; std::string readBuffer;
curl = curl_easy_init(); curl = curl_easy_init();
Assert(curl); Assert(curl);
if(curl) { if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str()); curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_PORT, port); curl_easy_setopt(curl, CURLOPT_PORT, port);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl); res = curl_easy_perform(curl);
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
if(res != CURLE_OK)return "-1"; if (res != CURLE_OK)
return "-1";
} }
return readBuffer; return readBuffer;
} }
std::string PostHTTP(const std::string& IP,const std::string& Fields){ std::string PostHTTP(const std::string& IP, const std::string& Fields) {
CURL *curl; CURL* curl;
CURLcode res; CURLcode res;
std::string readBuffer; std::string readBuffer;
curl = curl_easy_init(); curl = curl_easy_init();
Assert(curl); Assert(curl);
if(curl) { if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str()); curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
/*curl_easy_setopt(curl, CURLOPT_URL, "https://95.216.35.232/heartbeatv2"); /*curl_easy_setopt(curl, CURLOPT_URL, "https://95.216.35.232/heartbeatv2");
curl_easy_setopt(curl, CURLOPT_PORT, 3600);*/ curl_easy_setopt(curl, CURLOPT_PORT, 3600);*/
@ -44,7 +45,8 @@ std::string PostHTTP(const std::string& IP,const std::string& Fields){
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
res = curl_easy_perform(curl); res = curl_easy_perform(curl);
curl_easy_cleanup(curl); curl_easy_cleanup(curl);
if(res != CURLE_OK)return "-1"; if (res != CURLE_OK)
return "-1";
} }
return readBuffer; return readBuffer;
} }

View File

@ -1,26 +1,26 @@
/// ///
/// Created by Anonymous275 on 8/1/2020 /// Created by Anonymous275 on 8/1/2020
/// ///
#include "Lua/LuaSystem.hpp"
#include "Security/Enc.h"
#include "Client.hpp" #include "Client.hpp"
#include "Settings.h"
#include "Network.h"
#include "Logger.h" #include "Logger.h"
int OpenID(){ #include "Lua/LuaSystem.hpp"
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
int OpenID() {
int ID = 0; int ID = 0;
bool found; bool found;
do { do {
found = true; found = true;
for (auto& c : CI->Clients){ for (auto& c : CI->Clients) {
if(c != nullptr){ if (c != nullptr) {
if(c->GetID() == ID){ if (c->GetID() == ID) {
found = false; found = false;
ID++; ID++;
} }
} }
} }
}while (!found); } while (!found);
return ID; return ID;
} }
void Respond(Client* c, const std::string& MSG, bool Rel) { void Respond(Client* c, const std::string& MSG, bool Rel) {
@ -36,59 +36,66 @@ void Respond(Client* c, const std::string& MSG, bool Rel) {
UDPSend(c, MSG); UDPSend(c, MSG);
} }
} }
void SendToAll(Client*c, const std::string& Data, bool Self, bool Rel){ void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel) {
if (!Self)Assert(c); if (!Self)
Assert(c);
char C = Data.at(0); char C = Data.at(0);
for(auto& client : CI->Clients){ for (auto& client : CI->Clients) {
if(client != nullptr) { if (client != nullptr) {
if (Self || client.get() != c) { if (Self || client.get() != c) {
if (client->isSynced) { if (client->isSynced) {
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') { if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
if (C == 'O' || C == 'T' || if (C == 'O' || C == 'T' || Data.length() > 1000)
Data.length() > 1000)SendLarge(client.get(), Data); SendLarge(client.get(), Data);
else TCPSend(client.get(), Data); else
} else UDPSend(client.get(), Data); TCPSend(client.get(), Data);
} else
UDPSend(client.get(), Data);
} }
} }
} }
} }
} }
void UpdatePlayers(){ void UpdatePlayers() {
std::string Packet = Sec("Ss") + std::to_string(CI->Size())+"/"+std::to_string(MaxPlayers) + ":"; std::string Packet = Sec("Ss") + std::to_string(CI->Size()) + "/" + std::to_string(MaxPlayers) + ":";
for (auto& c : CI->Clients) { for (auto& c : CI->Clients) {
if(c != nullptr)Packet += c->GetName() + ","; if (c != nullptr)
Packet += c->GetName() + ",";
} }
Packet = Packet.substr(0,Packet.length()-1); Packet = Packet.substr(0, Packet.length() - 1);
SendToAll(nullptr, Packet,true,true); SendToAll(nullptr, Packet, true, true);
} }
void OnDisconnect(Client*c,bool kicked){ void OnDisconnect(Client* c, bool kicked) {
Assert(c); Assert(c);
info(c->GetName() + Sec(" Connection Terminated")); info(c->GetName() + Sec(" Connection Terminated"));
if(c == nullptr)return; if (c == nullptr)
return;
std::string Packet; std::string Packet;
for(auto& v : c->GetAllCars()){ for (auto& v : c->GetAllCars()) {
if(v != nullptr) { if (v != nullptr) {
Packet = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(v->ID); Packet = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(v->ID);
SendToAll(c, Packet, false, true); SendToAll(c, Packet, false, true);
} }
} }
if(kicked)Packet = Sec("L")+c->GetName()+Sec(" was kicked!"); if (kicked)
Packet = Sec("L")+c->GetName()+Sec(" Left the server!"); Packet = Sec("L") + c->GetName() + Sec(" was kicked!");
SendToAll(c, Packet,false,true); Packet = Sec("L") + c->GetName() + Sec(" Left the server!");
SendToAll(c, Packet, false, true);
Packet.clear(); Packet.clear();
TriggerLuaEvent(Sec("onPlayerDisconnect"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false); TriggerLuaEvent(Sec("onPlayerDisconnect"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
CI->RemoveClient(c); ///Removes the Client from existence CI->RemoveClient(c); ///Removes the Client from existence
} }
void OnConnect(Client*c){ void OnConnect(Client* c) {
Assert(c); Assert(c);
info(Sec("Client connected")); info(Sec("Client connected"));
c->SetID(OpenID()); c->SetID(OpenID());
info(Sec("Assigned ID ") + std::to_string(c->GetID()) + Sec(" to ") + c->GetName()); info(Sec("Assigned ID ") + std::to_string(c->GetID()) + Sec(" to ") + c->GetName());
TriggerLuaEvent(Sec("onPlayerConnecting"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false); TriggerLuaEvent(Sec("onPlayerConnecting"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
SyncResources(c); SyncResources(c);
if(c->GetStatus() < 0)return; if (c->GetStatus() < 0)
Respond(c,"M"+MapName,true); //Send the Map on connect return;
Respond(c, "M" + MapName, true); //Send the Map on connect
info(c->GetName() + Sec(" : Connected")); info(c->GetName() + Sec(" : Connected"));
TriggerLuaEvent(Sec("onPlayerJoining"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false); TriggerLuaEvent(Sec("onPlayerJoining"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
} }

View File

@ -1,8 +1,8 @@
#include "Network.h" #include "Network.h"
#include <thread>
#include <memory> #include <memory>
#include <thread>
std::unique_ptr<ClientInterface> CI; std::unique_ptr<ClientInterface> CI;
void NetMain(){ void NetMain() {
std::thread TCP(TCPServerMain); std::thread TCP(TCPServerMain);
TCP.detach(); TCP.detach();
UDPServerMain(); UDPServerMain();

View File

@ -1,8 +1,8 @@
/// ///
/// Created by Anonymous275 on 6/18/2020 /// Created by Anonymous275 on 6/18/2020
/// ///
#include "Security/Enc.h"
#include "Client.hpp" #include "Client.hpp"
#include "Security/Enc.h"
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <thread> #include <thread>
@ -10,7 +10,7 @@ std::string StatReport;
int PPS = 0; int PPS = 0;
void Monitor() { void Monitor() {
int R, C = 0, V = 0; int R, C = 0, V = 0;
if (CI->Clients.empty()){ if (CI->Clients.empty()) {
StatReport = "-"; StatReport = "-";
return; return;
} }
@ -29,15 +29,15 @@ void Monitor() {
PPS = 0; PPS = 0;
} }
[[noreturn]]void Stat(){ [[noreturn]] void Stat() {
DebugPrintTID(); DebugPrintTID();
while(true){ while (true) {
Monitor(); Monitor();
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
} }
void StatInit(){ void StatInit() {
StatReport = "-"; StatReport = "-";
std::thread Init(Stat); std::thread Init(Stat);
Init.detach(); Init.detach();

View File

@ -39,7 +39,7 @@ void STCPSend(Client* c, std::string Data) {
void SendFile(Client* c, const std::string& Name) { void SendFile(Client* c, const std::string& Name) {
Assert(c); Assert(c);
info(c->GetName() + Sec(" requesting : ") + Name.substr(Name.find_last_of('/'))); info(c->GetName() + Sec(" requesting : ") + Name.substr(Name.find_last_of('/')));
struct stat Info {}; struct stat Info { };
if (stat(Name.c_str(), &Info) != 0) { if (stat(Name.c_str(), &Info) != 0) {
STCPSend(c, Sec("Cannot Open")); STCPSend(c, Sec("Cannot Open"));
return; return;
@ -99,11 +99,11 @@ bool STCPRecv(Client* c) {
Assert(c); Assert(c);
if (c == nullptr) if (c == nullptr)
return false; return false;
#define len 200 #define len 200
char buf[len]; char buf[len];
ZeroMemory(buf, len); ZeroMemory(buf, len);
int64_t BytesRcv = recv(c->GetTCPSock(), buf, len, 0); int64_t BytesRcv = recv(c->GetTCPSock(), buf, len, 0);
#undef len #undef len
if (BytesRcv == 0) { if (BytesRcv == 0) {
if (c->GetStatus() > -1) if (c->GetStatus() > -1)
c->SetStatus(-1); c->SetStatus(-1);

View File

@ -1,55 +1,59 @@
/// ///
/// Created by Anonymous275 on 8/1/2020 /// Created by Anonymous275 on 8/1/2020
/// ///
#include "Compressor.h"
#include "Logger.h"
#include "Network.h"
#include "Security/Enc.h" #include "Security/Enc.h"
#include "UnixCompat.h" #include "UnixCompat.h"
#include "Compressor.h"
#include "Network.h"
#include "Logger.h"
#include <thread> #include <thread>
void TCPSend(Client* c, const std::string& Data) {
void TCPSend(Client*c,const std::string&Data){
Assert(c); Assert(c);
if(c == nullptr)return; if (c == nullptr)
return;
// Size is BIG ENDIAN now, use only for header! // Size is BIG ENDIAN now, use only for header!
//auto Size = htonl(int32_t(Data.size())); //auto Size = htonl(int32_t(Data.size()));
///TODO : BIG ENDIAN for other OS ///TODO : BIG ENDIAN for other OS
int32_t Size, Sent, Temp; int32_t Size, Sent, Temp;
std::string Send(4,0); std::string Send(4, 0);
Size = int32_t(Data.size()); Size = int32_t(Data.size());
memcpy(&Send[0],&Size,sizeof(Size)); memcpy(&Send[0], &Size, sizeof(Size));
Send += Data; Send += Data;
Sent = 0; Sent = 0;
Size += 4; Size += 4;
do { do {
Temp = send(c->GetTCPSock(), &Send[Sent], Size - Sent, 0); Temp = send(c->GetTCPSock(), &Send[Sent], Size - Sent, 0);
if (Temp == 0) { if (Temp == 0) {
if (c->GetStatus() > -1)c->SetStatus(-1); if (c->GetStatus() > -1)
c->SetStatus(-1);
return; return;
} else if (Temp < 0) { } else if (Temp < 0) {
if (c->GetStatus() > -1)c->SetStatus(-1); if (c->GetStatus() > -1)
c->SetStatus(-1);
info(Sec("Closing socket, Temp < 0")); info(Sec("Closing socket, Temp < 0"));
closesocket(c->GetTCPSock()); closesocket(c->GetTCPSock());
return; return;
} }
Sent += Temp; Sent += Temp;
}while(Sent < Size); } while (Sent < Size);
} }
bool CheckBytes(Client*c,int32_t BytesRcv){ bool CheckBytes(Client* c, int32_t BytesRcv) {
Assert(c); Assert(c);
if (BytesRcv == 0){ if (BytesRcv == 0) {
debug(Sec("(TCP) Connection closing...")); debug(Sec("(TCP) Connection closing..."));
if(c->GetStatus() > -1)c->SetStatus(-1); if (c->GetStatus() > -1)
c->SetStatus(-1);
return false; return false;
}else if (BytesRcv < 0) { } else if (BytesRcv < 0) {
#ifdef WIN32 #ifdef WIN32
debug(Sec("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError())); debug(Sec("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
#else // unix #else // unix
debug(Sec("(TCP) recv failed with error: ") + std::string(strerror(errno))); debug(Sec("(TCP) recv failed with error: ") + std::string(strerror(errno)));
#endif // WIN32 #endif // WIN32
if(c->GetStatus() > -1)c->SetStatus(-1); if (c->GetStatus() > -1)
c->SetStatus(-1);
info(Sec("Closing socket in CheckBytes, BytesRcv < 0")); info(Sec("Closing socket in CheckBytes, BytesRcv < 0"));
closesocket(c->GetTCPSock()); closesocket(c->GetTCPSock());
return false; return false;
@ -57,28 +61,29 @@ bool CheckBytes(Client*c,int32_t BytesRcv){
return true; return true;
} }
void TCPRcv(Client*c){ void TCPRcv(Client* c) {
Assert(c); Assert(c);
int32_t Header,BytesRcv = 0,Temp; int32_t Header, BytesRcv = 0, Temp;
if(c == nullptr || c->GetStatus() < 0)return; if (c == nullptr || c->GetStatus() < 0)
return;
std::vector<char> Data(sizeof(Header)); std::vector<char> Data(sizeof(Header));
do { do {
Temp = recv(c->GetTCPSock(), &Data[BytesRcv], 4-BytesRcv, 0); Temp = recv(c->GetTCPSock(), &Data[BytesRcv], 4 - BytesRcv, 0);
if(!CheckBytes(c,Temp)){ if (!CheckBytes(c, Temp)) {
#ifdef DEBUG #ifdef DEBUG
error(std::string(__func__) + Sec(": failed on CheckBytes in while(BytesRcv < 4)")); error(std::string(__func__) + Sec(": failed on CheckBytes in while(BytesRcv < 4)"));
#endif // DEBUG #endif // DEBUG
return; return;
} }
BytesRcv += Temp; BytesRcv += Temp;
}while(size_t(BytesRcv) < sizeof(Header)); } while (size_t(BytesRcv) < sizeof(Header));
memcpy(&Header,&Data[0],sizeof(Header)); memcpy(&Header, &Data[0], sizeof(Header));
#ifdef DEBUG #ifdef DEBUG
//debug(std::string(__func__) + Sec(": expecting ") + std::to_string(Header) + Sec(" bytes.")); //debug(std::string(__func__) + Sec(": expecting ") + std::to_string(Header) + Sec(" bytes."));
#endif // DEBUG #endif // DEBUG
if(!CheckBytes(c,BytesRcv)) { if (!CheckBytes(c, BytesRcv)) {
#ifdef DEBUG #ifdef DEBUG
error(std::string(__func__) + Sec(": failed on CheckBytes")); error(std::string(__func__) + Sec(": failed on CheckBytes"));
#endif // DEBUG #endif // DEBUG
@ -86,9 +91,9 @@ void TCPRcv(Client*c){
} }
Data.resize(Header); Data.resize(Header);
BytesRcv = 0; BytesRcv = 0;
do{ do {
Temp = recv(c->GetTCPSock(), &Data[BytesRcv], Header-BytesRcv,0); Temp = recv(c->GetTCPSock(), &Data[BytesRcv], Header - BytesRcv, 0);
if(!CheckBytes(c,Temp)){ if (!CheckBytes(c, Temp)) {
#ifdef DEBUG #ifdef DEBUG
error(std::string(__func__) + Sec(": failed on CheckBytes in while(BytesRcv < Header)")); error(std::string(__func__) + Sec(": failed on CheckBytes in while(BytesRcv < Header)"));
#endif // DEBUG #endif // DEBUG
@ -99,11 +104,11 @@ void TCPRcv(Client*c){
//debug(std::string(__func__) + Sec(": Temp: ") + std::to_string(Temp) + Sec(", BytesRcv: ") + std::to_string(BytesRcv)); //debug(std::string(__func__) + Sec(": Temp: ") + std::to_string(Temp) + Sec(", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG #endif // DEBUG
BytesRcv += Temp; BytesRcv += Temp;
}while(BytesRcv < Header); } while (BytesRcv < Header);
#ifdef DEBUG #ifdef DEBUG
//debug(std::string(__func__) + Sec(": finished recv with Temp: ") + std::to_string(Temp) + Sec(", BytesRcv: ") + std::to_string(BytesRcv)); //debug(std::string(__func__) + Sec(": finished recv with Temp: ") + std::to_string(Temp) + Sec(", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG #endif // DEBUG
std::string Ret(Data.data(),Header); std::string Ret(Data.data(), Header);
if (Ret.substr(0, 4) == "ABG:") { if (Ret.substr(0, 4) == "ABG:") {
Ret = DeComp(Ret.substr(4)); Ret = DeComp(Ret.substr(4));
@ -111,21 +116,22 @@ void TCPRcv(Client*c){
#ifdef DEBUG #ifdef DEBUG
//debug("Parsing from " + c->GetName() + " -> " +std::to_string(Ret.size())); //debug("Parsing from " + c->GetName() + " -> " +std::to_string(Ret.size()));
#endif #endif
GParser(c,Ret); GParser(c, Ret);
} }
void TCPClient(Client*c){ void TCPClient(Client* c) {
DebugPrintTIDInternal(Sec("Client(") + c->GetName() + Sec(")"), true); DebugPrintTIDInternal(Sec("Client(") + c->GetName() + Sec(")"), true);
Assert(c); Assert(c);
if(c->GetTCPSock() == -1){ if (c->GetTCPSock() == -1) {
CI->RemoveClient(c); CI->RemoveClient(c);
return; return;
} }
OnConnect(c); OnConnect(c);
while (c->GetStatus() > -1)TCPRcv(c); while (c->GetStatus() > -1)
TCPRcv(c);
OnDisconnect(c, c->GetStatus() == -2); OnDisconnect(c, c->GetStatus() == -2);
} }
void InitClient(Client*c){ void InitClient(Client* c) {
std::thread NewClient(TCPClient,c); std::thread NewClient(TCPClient, c);
NewClient.detach(); NewClient.detach();
} }

View File

@ -103,7 +103,7 @@ void SendLarge(Client* c, std::string Data) {
std::string CMP(Comp(Data)); std::string CMP(Comp(Data));
Data = "ABG:" + CMP; Data = "ABG:" + CMP;
} }
TCPSend(c,Data); TCPSend(c, Data);
} }
struct HandledC { struct HandledC {
size_t Pos = 0; size_t Pos = 0;
@ -172,7 +172,7 @@ std::string UDPRcvFromClient(sockaddr_in& client) {
#endif // WIN32 #endif // WIN32
return ""; return "";
} }
return Ret.substr(0,Rcv); return Ret.substr(0, Rcv);
} }
SplitData* GetSplit(int SplitID) { SplitData* GetSplit(int SplitID) {
@ -221,7 +221,7 @@ void HandleChunk(Client* c, const std::string& Data) {
} }
} }
void UDPParser(Client* c, std::string Packet) { void UDPParser(Client* c, std::string Packet) {
if(Packet.find("Zp") != std::string::npos && Packet.size() > 500){ if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
abort(); abort();
} }
Assert(c); Assert(c);
@ -253,8 +253,8 @@ void UDPParser(Client* c, std::string Packet) {
void LOOP() { void LOOP() {
DebugPrintTID(); DebugPrintTID();
while (UDPSock != -1) { while (UDPSock != -1) {
if(!DataAcks.empty()) { if (!DataAcks.empty()) {
for (PacketData *p : DataAcks) { for (PacketData* p : DataAcks) {
if (p != nullptr) { if (p != nullptr) {
if (p->Client == nullptr || p->Client->GetTCPSock() == -1) { if (p->Client == nullptr || p->Client->GetTCPSock() == -1) {
DataAcks.erase(p); DataAcks.erase(p);

View File

@ -2,14 +2,14 @@
/// Created by Anonymous275 on 11/6/2020 /// Created by Anonymous275 on 11/6/2020
/// ///
/*#include <boost/beast/core.hpp> /*#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp> #include "Logger.h"
#include "Security/Enc.h"
#include <boost/asio/connect.hpp> #include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>*/ #include <boost/asio/ip/tcp.hpp>*/
#include "Security/Enc.h" #include <boost/beast/websocket.hpp>
#include <iostream> #include <iostream>
#include "Logger.h"
#include <thread>
#include <string> #include <string>
#include <thread>
/*namespace beast = boost::beast; /*namespace beast = boost::beast;
namespace http = beast::http; namespace http = beast::http;
@ -21,7 +21,7 @@ std::string GetRes(const beast::flat_buffer& buff) {
return (char*)buff.data().data(); return (char*)buff.data().data();
}*/ }*/
void SyncData(){ void SyncData() {
/*DebugPrintTID(); /*DebugPrintTID();
try { try {
std::string const host = Sec("95.216.35.232"); std::string const host = Sec("95.216.35.232");
@ -50,9 +50,7 @@ void SyncData(){
}*/ }*/
} }
void WebsocketInit() {
void WebsocketInit(){
/*std::thread t1(SyncData); /*std::thread t1(SyncData);
t1.detach();*/ t1.detach();*/
} }

View File

@ -2,6 +2,7 @@
/// Created by Anonymous275 on 7/17/2020 /// Created by Anonymous275 on 7/17/2020
/// ///
#include "Logger.h" #include "Logger.h"
#include "RWMutex.h"
#include "Security/Enc.h" #include "Security/Enc.h"
#include "Settings.h" #include "Settings.h"
#include <chrono> #include <chrono>
@ -10,7 +11,6 @@
#include <sstream> #include <sstream>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
#include "RWMutex.h"
static RWMutex ThreadNameMapMutex; static RWMutex ThreadNameMapMutex;
static std::unordered_map<std::thread::id, std::string> ThreadNameMap; static std::unordered_map<std::thread::id, std::string> ThreadNameMap;

View File

@ -1,9 +1,9 @@
#include "CustomAssert.h" #include "CustomAssert.h"
#include <curl/curl.h> #include "Security/Xor.h"
#include "Startup.h" #include "Startup.h"
#include <curl/curl.h>
#include <iostream> #include <iostream>
#include <thread> #include <thread>
#include "Security/Xor.h"
#ifndef WIN32 #ifndef WIN32
#include <signal.h> #include <signal.h>
void UnixSignalHandler(int sig) { void UnixSignalHandler(int sig) {
@ -18,9 +18,9 @@ void UnixSignalHandler(int sig) {
} }
#endif // WIN32 #endif // WIN32
[[noreturn]] void loop(){ [[noreturn]] void loop() {
DebugPrintTID(); DebugPrintTID();
while(true){ while (true) {
std::cout.flush(); std::cout.flush();
std::this_thread::sleep_for(std::chrono::milliseconds(600)); std::this_thread::sleep_for(std::chrono::milliseconds(600));
} }
@ -36,12 +36,12 @@ int main(int argc, char* argv[]) {
DebugPrintTID(); DebugPrintTID();
// curl needs to be initialized to properly deallocate its resources later // curl needs to be initialized to properly deallocate its resources later
Assert(curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK); Assert(curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK);
#ifdef DEBUG #ifdef DEBUG
std::thread t1(loop); std::thread t1(loop);
t1.detach(); t1.detach();
#endif #endif
ConsoleInit(); ConsoleInit();
InitServer(argc,argv); InitServer(argc, argv);
InitConfig(); InitConfig();
InitLua(); InitLua();
InitRes(); InitRes();