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
#include <string>
std::string HttpRequest(const std::string& IP,int port);
std::string PostHTTP(const std::string& IP,const std::string& Fields);
std::string HttpRequest(const std::string& IP, int port);
std::string PostHTTP(const std::string& IP, const std::string& Fields);

View File

@ -2,10 +2,10 @@
/// Created by Anonymous275 on 4/2/2020.
///
#pragma once
#include "Security/Xor.h"
#include <iostream>
#include <mutex>
#include <string>
#include "Security/Xor.h"
void InitLog();
#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

View File

@ -6,14 +6,14 @@
#include <string>
void TCPServerMain();
void UpdatePlayers();
void OnConnect(Client*c);
void InitClient(Client*c);
void SyncResources(Client*c);
void OnConnect(Client* c);
void InitClient(Client* c);
void SyncResources(Client* c);
[[noreturn]] void UDPServerMain();
void OnDisconnect(Client*c,bool kicked);
void UDPSend(Client*c,std::string Data);
void TCPSend(Client*c,const std::string& Data);
void SendLarge(Client*c,std::string Data);
void GParser(Client*c, const std::string&Packet);
void Respond(Client*c, const std::string& MSG, bool Rel);
void SendToAll(Client*c, const std::string& Data, bool Self, bool Rel);
void OnDisconnect(Client* c, bool kicked);
void UDPSend(Client* c, std::string Data);
void TCPSend(Client* c, const std::string& Data);
void SendLarge(Client* c, std::string Data);
void GParser(Client* c, const std::string& Packet);
void Respond(Client* c, const std::string& MSG, 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.
// locks the mutex for writing. Construction may be blocking. Destruction is guaranteed to release the lock.
using WriteLock = std::unique_lock<RWMutex>;

View File

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

View File

@ -2,107 +2,108 @@
/// Created by Anonymous275 on 8/11/2020
///
#pragma once
#include <string>
#include <array>
#include <cstdarg>
#include <cstdio>
#include <string>
#define BEGIN_NAMESPACE(x) namespace x {
#define END_NAMESPACE }
BEGIN_NAMESPACE(XorCompileTime)
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 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;
// 1988, Stephen Park and Keith Miller
// "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:
// with 32-bit math and without division
template <int N>
struct RandomGenerator{
private:
static constexpr unsigned a = 16807; // 7^5
static constexpr unsigned m = 2147483647; // 2^31 - 1
template <int N>
struct RandomGenerator {
private:
static constexpr unsigned a = 16807; // 7^5
static constexpr unsigned m = 2147483647; // 2^31 - 1
static constexpr unsigned s = RandomGenerator< N - 1 >::value;
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 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 lo3 = lo2 + hi;
static constexpr unsigned s = RandomGenerator<N - 1>::value;
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 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 lo3 = lo2 + hi;
public:
static constexpr unsigned max = m;
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};
public:
static constexpr unsigned max = m;
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};
template <>
struct RandomGenerator< 0 >{
static constexpr unsigned value = seed;
};
template <>
struct RandomGenerator<0> {
static constexpr unsigned value = seed;
};
template <int N, int M>
struct RandomInt{
static constexpr auto value = RandomGenerator< N + 1 >::value % M;
};
template <int N, int M>
struct RandomInt {
static constexpr auto value = RandomGenerator<N + 1>::value % M;
};
template <int N>
struct RandomChar{
static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
};
template <int N>
struct RandomChar {
static const char value = static_cast<char>(1 + RandomInt<N, 0x7F - 1>::value);
};
template <size_t N, int K, typename Char>
struct XorString{
private:
const char _key;
std::array< Char, N + 1 > _encrypted;
template <size_t N, int K, typename Char>
struct XorString {
private:
const char _key;
std::array<Char, N + 1> _encrypted;
constexpr Char enc(Char c) const{
return c ^ _key;
constexpr Char enc(Char c) const {
return c ^ _key;
}
Char dec(Char c) const {
return c ^ _key;
}
public:
template <size_t... Is>
constexpr inline XorString(const Char* str, std::index_sequence<Is...>)
: _key(RandomChar<K>::value)
, _encrypted { enc(str[Is])... } { }
inline decltype(auto) decrypt() {
for (size_t i = 0; i < N; ++i) {
_encrypted[i] = dec(_encrypted[i]);
}
_encrypted[N] = '\0';
return _encrypted.data();
}
};
Char dec(Char c) const{
return c ^ _key;
}
static auto w_printf = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
};
public:
template <size_t... Is>
constexpr inline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
{}
static auto w_printf_s = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
};
inline decltype(auto) decrypt(){
for (size_t i = 0; i < N; ++i) {
_encrypted[i] = dec(_encrypted[i]);
}
_encrypted[N] = '\0';
return _encrypted.data();
}
};
static auto w_printf = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
};
static auto w_printf_s = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, 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_start(args, fmt);
vsprintf(buf, fmt, 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;
va_list args;
va_start(args, fmt);
@ -111,21 +112,21 @@ BEGIN_NAMESPACE(XorCompileTime)
return ret;
};*/
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vsnprintf(buf, buf_size, fmt, args);
va_end(args);
};
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vsnprintf(buf, buf_size, fmt, args);
va_end(args);
};
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
int ret;
va_list args;
va_start(args, fmt);
ret = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
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 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()
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
int ret;
va_list args;
va_start(args, fmt);
ret = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
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 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

View File

@ -8,8 +8,8 @@
#include "CustomAssert.h"
#include <cstring>
#include <unistd.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
inline void ZeroMemory(void* dst, size_t len) {
@ -26,7 +26,7 @@ inline void closesocket(int socket) {
#endif
#ifndef __except
#define __except(x) /**/
#define __except (x) /**/
#endif
#endif // WIN32

View File

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

View File

@ -140,8 +140,8 @@ static void ProcessCompositeInput() {
#else // unix
if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 65 }.data(), 2) == 0) {
#endif // WIN32
// UP ARROW
// info(std::to_string(ConsoleHistoryReadIndex));
// UP ARROW
// info(std::to_string(ConsoleHistoryReadIndex));
if (!ConsoleHistory.empty()) {
if (ConsoleHistoryReadIndex != 0) {
ConsoleHistoryReadIndex -= 1;
@ -153,7 +153,7 @@ static void ProcessCompositeInput() {
#else // unix
} else if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 66 }.data(), 2) == 0) {
#endif // WIN32
// DOWN ARROW
// DOWN ARROW
if (!ConsoleHistory.empty()) {
if (ConsoleHistoryReadIndex != ConsoleHistory.size() - 1) {
ConsoleHistoryReadIndex += 1;
@ -214,7 +214,7 @@ static void ProcessCompositeInput() {
#else // unix
} else if (In == 27) {
#endif // WIN32
// escape char, assume stuff follows
// escape char, assume stuff follows
CompositeInputExpected = true;
CompositeInput.clear();
} else if (!isprint(In)) {

View File

@ -2,30 +2,31 @@
/// Created by Anonymous275 on 7/28/2020
///
#include "Security/Enc.h"
#include "Settings.h"
#include "CustomAssert.h"
#include "Settings.h"
//#include <windows.h>
#include "Logger.h"
#include <random>
#include <sstream>
#include <thread>
#include <random>
int Rand(){
int Rand() {
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, 5000);
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;
for (; p; p >>= 1u){
if (p & 1u)result = int((1LL * result * n) % mod);
for (; p; p >>= 1u) {
if (p & 1u)
result = int((1LL * result * n) % mod);
n = int((1LL * n * n) % mod);
}
return result;
}
bool rabin_miller(int n){
bool rabin_miller(int n) {
bool ok = true;
for (int i = 1; i <= 5 && ok; i++) {
int a = Rand() + 1;
@ -34,13 +35,14 @@ bool rabin_miller(int n){
}
return ok;
}
int generate_prime(){
int generate_prime() {
int generated = Rand();
while (!rabin_miller(generated))generated = Rand();
while (!rabin_miller(generated))
generated = Rand();
return generated;
}
int gcd(int a, int b){
while (b){
int gcd(int a, int b) {
while (b) {
int r = a % b;
a = b;
b = r;
@ -48,79 +50,83 @@ int gcd(int a, int b){
return a;
}
int generate_coprime(int n){
int generate_coprime(int n) {
int generated = Rand();
while (gcd(n, generated) != 1)generated = Rand();
while (gcd(n, generated) != 1)
generated = Rand();
return generated;
}
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);
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;
while(inverse < 0)inverse += mod;
while (inverse < 0)
inverse += mod;
return inverse;
}
RSA* GenKey(){
RSA* GenKey() {
int p, q;
p = generate_prime();
q = generate_prime();
int n = p * q;
int phi = (p -1) * (q - 1);
int phi = (p - 1) * (q - 1);
int e = generate_coprime(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);
}
int Dec(int value,int d,int n){
int Dec(int value, int d, int n) {
return log_power(value, d, n);
}
#ifdef WIN32
int Handle(EXCEPTION_POINTERS *ep,char* Origin){
int Handle(EXCEPTION_POINTERS* ep, char* Origin) {
//Assert(false);
std::stringstream R;
R << Sec("Code : ") << std::hex
<< ep->ExceptionRecord->ExceptionCode
<< std::dec << Sec(" Origin : ") << Origin;
<< ep->ExceptionRecord->ExceptionCode
<< std::dec << Sec(" Origin : ") << Origin;
except(R.str());
return 1;
}
#else
// stub
int Handle(EXCEPTION_POINTERS *, char*) { return 1; }
int Handle(EXCEPTION_POINTERS*, char*) { return 1; }
#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;
for(const char&c : Data){
stream << std::hex << Enc(uint8_t(c),k->e,k->n) << "g";
for (const char& c : Data) {
stream << std::hex << Enc(uint8_t(c), k->e, k->n) << "g";
}
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;
for(const char&c : Data){
stream << std::hex << Enc(uint8_t(c),e,n) << "g";
for (const char& c : Data) {
stream << std::hex << Enc(uint8_t(c), e, n) << "g";
}
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::string token,ret;
std::string token, ret;
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);
ret += char(Dec(c,k->d,k->n));
ret += char(Dec(c, k->d, k->n));
}
return ret;
}

View File

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

View File

@ -1,82 +1,85 @@
///
/// Created by Anonymous275 on 7/28/2020
///
#include "Security/Enc.h"
#include "Curl/Http.h"
#include "Client.hpp"
#include "Settings.h"
#include "Curl/Http.h"
#include "Logger.h"
#include <sstream>
#include <thread>
#include "Security/Enc.h"
#include "Settings.h"
#include <chrono>
#include <future>
#include <sstream>
#include <thread>
void WebsocketInit();
std::string GetPlayers(){
std::string GetPlayers() {
std::string Return;
for(auto& c : CI->Clients){
if(c != nullptr){
for (auto& c : CI->Clients) {
if (c != nullptr) {
Return += c->GetName() + ";";
}
}
return Return;
}
std::string GenerateCall(){
std::string GenerateCall() {
std::stringstream Ret;
Ret << "uuid=" << Key << "&players=" << CI->Size()
<< "&maxplayers=" << MaxPlayers << "&port=" << Port
<< "&map=" << MapName << "&private=" << (Private ? "true" : "false")
<< "&version=" << GetSVer() << "&clientversion=" << GetCVer()
<< "&name=" << ServerName << "&pps=" << StatReport
<< "&modlist=" << FileList << "&modstotalsize=" << MaxModSize
<< "&modstotal=" << ModsLoaded << "&playerslist=" << GetPlayers()
<< "&desc=" << ServerDesc;
<< "&maxplayers=" << MaxPlayers << "&port=" << Port
<< "&map=" << MapName << "&private=" << (Private ? "true" : "false")
<< "&version=" << GetSVer() << "&clientversion=" << GetCVer()
<< "&name=" << ServerName << "&pps=" << StatReport
<< "&modlist=" << FileList << "&modstotalsize=" << MaxModSize
<< "&modstotal=" << ModsLoaded << "&playerslist=" << GetPlayers()
<< "&desc=" << ServerDesc;
return Ret.str();
}
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::thread t(std::move(task));
t.detach();
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"));
std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0);
}
void Heartbeat(){
void Heartbeat() {
DebugPrintTID();
std::string R,T;
std::string R, T;
bool isAuth = false;
while(true){
while (true) {
R = GenerateCall();
if(!CustomIP.empty())R+="&ip="+CustomIP;
if (!CustomIP.empty())
R += "&ip=" + CustomIP;
std::string link = Sec("https://beammp.com/heartbeatv2");
T = RunPromise(link,R);
if(T.find_first_not_of(Sec("20")) != std::string::npos){
T = RunPromise(link, R);
if (T.find_first_not_of(Sec("20")) != std::string::npos) {
//Backend system refused server startup!
std::this_thread::sleep_for(std::chrono::seconds(10));
std::string Backup = Sec("https://backup1.beammp.com/heartbeatv2");
T = RunPromise(Backup,R);
if(T.find_first_not_of(Sec("20")) != std::string::npos) {
T = RunPromise(Backup, R);
if (T.find_first_not_of(Sec("20")) != std::string::npos) {
error(Sec("Backend system refused server! Check your AuthKey"));
std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(-1);
}
}
//Server Authenticated
if(T.length() == 4)info(Sec("Server authenticated"));
if (T.length() == 4)
info(Sec("Server authenticated"));
R.clear();
T.clear();
if(!isAuth){
if (!isAuth) {
WebsocketInit();
isAuth = true;
}
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}
void HBInit(){
void HBInit() {
std::thread HB(Heartbeat);
HB.detach();
}

View File

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

View File

@ -1,35 +1,36 @@
///
/// Created by Anonymous275 on 7/28/2020
///
#include "Security/Enc.h"
#include "Client.hpp"
#include "Logger.h"
#include <string>
#include "Security/Enc.h"
#include <algorithm>
#include <string>
std::string CustomIP;
std::string GetSVer(){
std::string GetSVer() {
static std::string r = Sec("1.0");
return r;
}
std::string GetCVer(){
std::string GetCVer() {
static std::string r = Sec("1.70");
return r;
}
void Args(int argc, char* argv[]){
void Args(int argc, char* argv[]) {
info(Sec("BeamMP Server Running version ") + GetSVer());
if(argc > 1){
if (argc > 1) {
CustomIP = argv[1];
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
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();
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();
Args(argc,argv);
Args(argc, argv);
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) {
DebugPrintTID();
while (true) {
if(!PluginEngine.empty()) {
for (auto &Script : PluginEngine) {
struct stat Info{};
if (!PluginEngine.empty()) {
for (auto& Script : PluginEngine) {
struct stat Info { };
if (stat(Script->GetFileName().c_str(), &Info) != 0) {
Script->SetStopThread(true);
PluginEngine.erase(Script);

View File

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

View File

@ -1,21 +1,20 @@
///
/// Created by Anonymous275 on 7/31/2020
///
#include "Security/Enc.h"
#include "Curl/Http.h"
#include "Settings.h"
#include "Network.h"
#include "Logger.h"
#include <sstream>
#include <thread>
#include <cstring>
#include <algorithm>
#include <string>
#include <atomic>
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.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
int BytesSent;
int len = static_cast<int>(Data.size());
@ -35,13 +34,13 @@ bool Send(SOCKET TCPSock,std::string Data){
}
return true;
}
std::string Rcv(SOCKET TCPSock){
std::string Rcv(SOCKET TCPSock) {
uint32_t RealSize;
#ifdef WIN32
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<char*>(&RealSize), sizeof(RealSize), 0);
#else
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<void*>(&RealSize), sizeof(RealSize), 0);
#endif
#ifdef WIN32
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<char*>(&RealSize), sizeof(RealSize), 0);
#else
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<void*>(&RealSize), sizeof(RealSize), 0);
#endif
if (BytesRcv != sizeof(RealSize)) {
error(std::string(Sec("invalid packet: expected 4, got ")) + std::to_string(BytesRcv));
return "";
@ -63,21 +62,23 @@ std::string Rcv(SOCKET TCPSock){
return "";
return std::string(buf);
}
std::string GetRole(const std::string &DID){
if(!DID.empty()){
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);
if(!a.empty() || !b.empty()){
if(a != b)a = b;
std::string GetRole(const std::string& DID) {
if (!DID.empty()) {
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);
if (!a.empty() || !b.empty()) {
if (a != b)
a = b;
auto pos = a.find('"');
if(pos != std::string::npos){
return a.substr(pos+1,a.find('"',pos+1)-2);
}else if(a == "[]")return Sec("Member");
if (pos != std::string::npos) {
return a.substr(pos + 1, a.find('"', pos + 1) - 2);
} else if (a == "[]")
return Sec("Member");
}
}
return "";
}
void Check(SOCKET TCPSock, std::reference_wrapper<std::atomic_bool> ok){
void Check(SOCKET TCPSock, std::reference_wrapper<std::atomic_bool> ok) {
DebugPrintTID();
size_t accum = 0;
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;
for(auto& c : CI->Clients){
if(c != nullptr){
if(c->GetRole() == Sec("MDEV"))M++;
for (auto& c : CI->Clients) {
if (c != nullptr) {
if (c->GetRole() == Sec("MDEV"))
M++;
}
}
return M;
}
void CreateClient(SOCKET TCPSock,const std::string &Name, const std::string &DID,const std::string &Role) {
auto *c = new Client;
void CreateClient(SOCKET TCPSock, const std::string& Name, const std::string& DID, const std::string& Role) {
auto* c = new Client;
c->SetTCPSock(TCPSock);
c->SetName(Name);
c->SetRole(Role);
@ -109,41 +111,43 @@ void CreateClient(SOCKET TCPSock,const std::string &Name, const std::string &DID
CI->AddClient(std::move(c));
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::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')) {
if(t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return a;
if(a.first == 0){
if (t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)
return a;
if (a.first == 0) {
a.first = std::stoi(t, nullptr, 16);
}else if(a.second == 0){
} else if (a.second == 0) {
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;
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();
}
void Identification(SOCKET TCPSock, RSA*Skey){
void Identification(SOCKET TCPSock, RSA* Skey) {
DebugPrintTID();
Assert(Skey);
std::atomic_bool ok { false };
std::thread Timeout(Check, TCPSock, std::ref<std::atomic_bool>(ok));
Timeout.detach();
std::string Name,DID,Role;
if(!Send(TCPSock,GenerateM(Skey))) {
std::string Name, DID, Role;
if (!Send(TCPSock, GenerateM(Skey))) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
std::string msg = Rcv(TCPSock);
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__));
closesocket(TCPSock);
return;
@ -152,43 +156,43 @@ void Identification(SOCKET TCPSock, RSA*Skey){
std::string Res = Rcv(TCPSock);
std::string Ver = Rcv(TCPSock);
ok = true;
Ver = RSA_D(Ver,Skey);
if(Ver.size() > 3 && Ver.substr(0,2) == Sec("VC")){
Ver = RSA_D(Ver, Skey);
if (Ver.size() > 3 && Ver.substr(0, 2) == Sec("VC")) {
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__));
closesocket(TCPSock);
return;
}
}else{
} else {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
Res = RSA_D(Res,Skey);
if(Res.size() < 3 || Res.substr(0,2) != Sec("NR")) {
Res = RSA_D(Res, Skey);
if (Res.size() < 3 || Res.substr(0, 2) != Sec("NR")) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
if(Res.find(':') == std::string::npos){
if (Res.find(':') == std::string::npos) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
Name = Res.substr(2,Res.find(':')-2);
DID = Res.substr(Res.find(':')+1);
Name = Res.substr(2, Res.find(':') - 2);
DID = Res.substr(Res.find(':') + 1);
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__));
closesocket(TCPSock);
return;
}
// DebugPrintTIDInternal(std::string("Client(") + Name + ")");
debug(Sec("Name -> ") + Name + Sec(", Role -> ") + Role + Sec(", ID -> ") + DID);
for(auto& c : CI->Clients){
if(c != nullptr){
if(c->GetDID() == DID){
debug(Sec("Name -> ") + Name + Sec(", Role -> ") + Role + Sec(", ID -> ") + DID);
for (auto& c : CI->Clients) {
if (c != nullptr) {
if (c->GetDID() == DID) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(c->GetTCPSock());
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");
CreateClient(TCPSock,Name,DID,Role);
CreateClient(TCPSock, Name, DID, Role);
} else {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
}
}
void Identify(SOCKET TCPSock){
RSA*Skey = GenKey();
void Identify(SOCKET TCPSock) {
RSA* Skey = GenKey();
// this disgusting ifdef stuff is needed because for some
// 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
// the macros
/*#ifdef WIN32
/*#ifdef WIN32
__try{
#endif // WIN32*/
Identification(TCPSock, Skey);
/*#ifdef WIN32
Identification(TCPSock, Skey);
/*#ifdef WIN32
}__except(1){
if(TCPSock != -1){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
@ -226,87 +230,87 @@ void Identify(SOCKET TCPSock){
delete Skey;
}
void TCPServerMain(){
void TCPServerMain() {
DebugPrintTID();
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(514, &wsaData)){
if (WSAStartup(514, &wsaData)) {
error(Sec("Can't start Winsock!"));
return;
}
SOCKET client, Listener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
sockaddr_in addr{};
SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in addr {};
addr.sin_addr.S_un.S_addr = ADDR_ANY;
addr.sin_family = AF_INET;
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()));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
}
if(Listener == -1){
if (Listener == -1) {
error(Sec("Invalid listening socket"));
return;
}
if(listen(Listener,SOMAXCONN)){
error(Sec("listener failed ")+ std::to_string(GetLastError()));
if (listen(Listener, SOMAXCONN)) {
error(Sec("listener failed ") + std::to_string(GetLastError()));
return;
}
info(Sec("Vehicle event network online"));
do{
do {
try {
client = accept(Listener, nullptr, nullptr);
if(client == -1){
warn(Sec("Got an invalid client socket on connect! Skipping..."));
continue;
}
std::thread ID(Identify,client);
ID.detach();
client = accept(Listener, nullptr, nullptr);
if (client == -1) {
warn(Sec("Got an invalid client socket on connect! Skipping..."));
continue;
}
std::thread ID(Identify, client);
ID.detach();
} catch (const std::exception& e) {
error(Sec("fatal: ") + std::string(e.what()));
}
}while(client);
} while (client);
closesocket(client);
WSACleanup();
#else // unix
// wondering why we need slightly different implementations of this?
// 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;
setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
// TODO: check optval or return value idk
sockaddr_in addr{};
sockaddr_in addr {};
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
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)));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
}
if(Listener == -1){
if (Listener == -1) {
error(Sec("Invalid listening socket"));
return;
}
if(listen(Listener,SOMAXCONN)){
error(Sec("listener failed ")+ std::string(strerror(errno)));
if (listen(Listener, SOMAXCONN)) {
error(Sec("listener failed ") + std::string(strerror(errno)));
return;
}
info(Sec("Vehicle event network online"));
do{
do {
try {
client = accept(Listener, nullptr, nullptr);
if(client == -1){
if (client == -1) {
warn(Sec("Got an invalid client socket on connect! Skipping..."));
continue;
}
std::thread ID(Identify,client);
std::thread ID(Identify, client);
ID.detach();
} catch (const std::exception& e) {
error(Sec("fatal: ") + std::string(e.what()));
}
}while(client);
} while (client);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(client);

View File

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

View File

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

View File

@ -2,38 +2,39 @@
/// Created by Anonymous275 on 4/9/2020
///
#include <curl/curl.h>
#include "CustomAssert.h"
#include <curl/curl.h>
#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);
return size * nmemb;
}
std::string HttpRequest(const std::string& IP,int port){
CURL *curl;
std::string HttpRequest(const std::string& IP, int port) {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
Assert(curl);
if(curl) {
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_PORT, port);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res != CURLE_OK)return "-1";
if (res != CURLE_OK)
return "-1";
}
return readBuffer;
}
std::string PostHTTP(const std::string& IP,const std::string& Fields){
CURL *curl;
std::string PostHTTP(const std::string& IP, const std::string& Fields) {
CURL* curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
Assert(curl);
if(curl) {
if (curl) {
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_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);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res != CURLE_OK)return "-1";
if (res != CURLE_OK)
return "-1";
}
return readBuffer;
}

View File

@ -1,26 +1,26 @@
///
/// Created by Anonymous275 on 8/1/2020
///
#include "Lua/LuaSystem.hpp"
#include "Security/Enc.h"
#include "Client.hpp"
#include "Settings.h"
#include "Network.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;
bool found;
do {
found = true;
for (auto& c : CI->Clients){
if(c != nullptr){
if(c->GetID() == ID){
for (auto& c : CI->Clients) {
if (c != nullptr) {
if (c->GetID() == ID) {
found = false;
ID++;
}
}
}
}
}while (!found);
} while (!found);
return ID;
}
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);
}
}
void SendToAll(Client*c, const std::string& Data, bool Self, bool Rel){
if (!Self)Assert(c);
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel) {
if (!Self)
Assert(c);
char C = Data.at(0);
for(auto& client : CI->Clients){
if(client != nullptr) {
for (auto& client : CI->Clients) {
if (client != nullptr) {
if (Self || client.get() != c) {
if (client->isSynced) {
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
if (C == 'O' || C == 'T' ||
Data.length() > 1000)SendLarge(client.get(), Data);
else TCPSend(client.get(), Data);
} else UDPSend(client.get(), Data);
if (C == 'O' || C == 'T' || Data.length() > 1000)
SendLarge(client.get(), Data);
else
TCPSend(client.get(), Data);
} else
UDPSend(client.get(), Data);
}
}
}
}
}
void UpdatePlayers(){
std::string Packet = Sec("Ss") + std::to_string(CI->Size())+"/"+std::to_string(MaxPlayers) + ":";
void UpdatePlayers() {
std::string Packet = Sec("Ss") + std::to_string(CI->Size()) + "/" + std::to_string(MaxPlayers) + ":";
for (auto& c : CI->Clients) {
if(c != nullptr)Packet += c->GetName() + ",";
if (c != nullptr)
Packet += c->GetName() + ",";
}
Packet = Packet.substr(0,Packet.length()-1);
SendToAll(nullptr, Packet,true,true);
Packet = Packet.substr(0, Packet.length() - 1);
SendToAll(nullptr, Packet, true, true);
}
void OnDisconnect(Client*c,bool kicked){
void OnDisconnect(Client* c, bool kicked) {
Assert(c);
info(c->GetName() + Sec(" Connection Terminated"));
if(c == nullptr)return;
if (c == nullptr)
return;
std::string Packet;
for(auto& v : c->GetAllCars()){
if(v != nullptr) {
for (auto& v : c->GetAllCars()) {
if (v != nullptr) {
Packet = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(v->ID);
SendToAll(c, Packet, false, true);
}
}
if(kicked)Packet = Sec("L")+c->GetName()+Sec(" was kicked!");
Packet = Sec("L")+c->GetName()+Sec(" Left the server!");
SendToAll(c, Packet,false,true);
if (kicked)
Packet = Sec("L") + c->GetName() + Sec(" was kicked!");
Packet = Sec("L") + c->GetName() + Sec(" Left the server!");
SendToAll(c, Packet, false, true);
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
}
void OnConnect(Client*c){
void OnConnect(Client* c) {
Assert(c);
info(Sec("Client connected"));
c->SetID(OpenID());
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);
if(c->GetStatus() < 0)return;
Respond(c,"M"+MapName,true); //Send the Map on connect
if (c->GetStatus() < 0)
return;
Respond(c, "M" + MapName, true); //Send the Map on connect
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 <thread>
#include <memory>
#include <thread>
std::unique_ptr<ClientInterface> CI;
void NetMain(){
void NetMain() {
std::thread TCP(TCPServerMain);
TCP.detach();
UDPServerMain();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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