Merge pull request #4 from Starystars67/cross-platform

Cross platform
This commit is contained in:
Lion Kortlepel 2020-11-06 14:30:11 +01:00 committed by GitHub
commit b49abe02eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 1336 additions and 732 deletions

5
.clang-format Normal file
View File

@ -0,0 +1,5 @@
---
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
...

1
.gitignore vendored
View File

@ -459,3 +459,4 @@ out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-540e487569703b71
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T17-35-38-0764.json
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-6a61e390ef8eaf17e9f8.json
out/build/x86-Debug/Server.cfg
*Server.cfg*

View File

@ -1,9 +1,28 @@
cmake_minimum_required(VERSION 3.10)
project(Server)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
if (UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Og -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -s")
elseif (WIN32)
# This might cause issues with old windows headers, but it's worth the trouble to keep the code
# completely cross platform. For fixes to common issues arising from /permissive- visit:
# https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /permissive-")
endif ()
find_package(Boost 1.71.0 REQUIRED COMPONENTS system thread)
file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "include/*.h" "include/*/*.h" "include/*.hpp" "include/*/*.hpp")
add_executable(${PROJECT_NAME} ${source_files})
target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "BeamMP-Server")
target_link_libraries(${PROJECT_NAME} libcurl_a urlmon ws2_32 lua53 zlibstatic)
add_executable(BeamMP-Server ${source_files})
target_include_directories(BeamMP-Server PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> ${Boost_INCLUDE_DIRS})
if (UNIX)
target_link_libraries(BeamMP-Server curl lua5.3 krb5 z pthread stdc++fs ${Boost_LINK_DIRS})
elseif (WIN32)
target_link_libraries(BeamMP-Server libcurl_a urlmon ws2_32 lua53 zlibstatic ${Boost_LINK_DIRS})
endif ()

View File

@ -3,12 +3,13 @@
///
#pragma once
#include <mutex>
#include "CustomAssert.h"
class Client;
void GParser(Client*c, const std::string&Packet);
class Buffer{
public:
void Handle(Client*c,const std::string& Data){
if(c == nullptr)return;
Assert(c);
Buf += Data;
Manage(c);
}
@ -18,11 +19,12 @@ public:
private:
std::string Buf;
void Manage(Client*c){
Assert(c);
if(!Buf.empty()){
std::string::size_type p;
if (Buf.at(0) == '\n'){
p = Buf.find('\n',1);
if(p != -1){
if(p != std::string::npos){
std::string R = Buf.substr(1,p-1);
std::string_view B(R.c_str(),R.find(char(0)));
GParser(c, B.data());
@ -31,7 +33,7 @@ private:
}
}else{
p = Buf.find('\n');
if(p == -1)Buf.clear();
if(p == std::string::npos)Buf.clear();
else{
Buf = Buf.substr(p);
Manage(c);

View File

@ -3,8 +3,14 @@
///
#pragma once
#ifdef WIN32
#include <WS2tcpip.h>
#else
#include <arpa/inet.h>
#define SOCKET int
#endif
#include "Buffer.h"
#include "CustomAssert.h"
#include <string>
#include <vector>
#include <chrono>
@ -60,6 +66,7 @@ struct ClientInterface{
c = nullptr;
}
void AddClient(Client *c){
Assert(c);
Clients.insert(c);
}
int Size(){
@ -67,4 +74,4 @@ struct ClientInterface{
}
};
extern ClientInterface* CI;
extern ClientInterface* CI;

View File

@ -38,7 +38,7 @@
* Define WIN32 when build target is Win32 API
*/
#if (defined(_WIN32) || defined(__WIN32__)) && \
#if (defined(_WIN32) || defined(WIN32__)) && \
!defined(WIN32) && !defined(__SYMBIAN32__)
#define WIN32
#endif

67
include/CustomAssert.h Normal file
View File

@ -0,0 +1,67 @@
// Author: lionkor
/*
* Asserts are to be used anywhere where assumptions about state are made
* implicitly. AssertNotReachable is used where code should never go, like in
* default switch cases which shouldn't trigger. They make it explicit
* that a place cannot normally be reached and make it an error if they do.
*/
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <thread>
#include "Logger.h"
static const char* const ANSI_RESET = "\u001b[0m";
static const char* const ANSI_BLACK = "\u001b[30m";
static const char* const ANSI_RED = "\u001b[31m";
static const char* const ANSI_GREEN = "\u001b[32m";
static const char* const ANSI_YELLOW = "\u001b[33m";
static const char* const ANSI_BLUE = "\u001b[34m";
static const char* const ANSI_MAGENTA = "\u001b[35m";
static const char* const ANSI_CYAN = "\u001b[36m";
static const char* const ANSI_WHITE = "\u001b[37m";
static const char* const ANSI_BLACK_BOLD = "\u001b[30;1m";
static const char* const ANSI_RED_BOLD = "\u001b[31;1m";
static const char* const ANSI_GREEN_BOLD = "\u001b[32;1m";
static const char* const ANSI_YELLOW_BOLD = "\u001b[33;1m";
static const char* const ANSI_BLUE_BOLD = "\u001b[34;1m";
static const char* const ANSI_MAGENTA_BOLD = "\u001b[35;1m";
static const char* const ANSI_CYAN_BOLD = "\u001b[36;1m";
static const char* const ANSI_WHITE_BOLD = "\u001b[37;1m";
static const char* const ANSI_BOLD = "\u001b[1m";
static const char* const ANSI_UNDERLINE = "\u001b[4m";
#if DEBUG
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
if (!result) {
std::cout << std::flush << "(debug build) TID "
<< std::this_thread::get_id() << ": ASSERTION FAILED: at "
<< file << ":" << line << " \n\t-> in "
<< function << ", Line " << line << ": \n\t\t-> "
<< "Failed Condition: " << condition_string << std::endl;
std::cout << "... terminating ..." << std::endl;
abort();
}
}
#define Assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
#define AssertNotReachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
#else
// In release build, these macros turn into NOPs. The compiler will optimize these out.
#define Assert(x) \
do { \
} while (false)
#define AssertNotReachable() \
do { \
} while (false)
#endif // DEBUG

View File

@ -2,10 +2,15 @@
/// Created by Anonymous275 on 4/2/2020.
///
#pragma once
#include <string>
#include <iostream>
#include <mutex>
#include <string>
extern std::mutex MLock;
void InitLog();
#define DebugPrintTID() DebugPrintTIDInternal(__func__)
void DebugPrintTIDInternal(const std::string& func); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier
void ConsoleOut(const std::string& msg);
void QueueAbort();
void except(const std::string& toPrint);
void debug(const std::string& toPrint);
void error(const std::string& toPrint);

View File

@ -3,65 +3,76 @@
///
#pragma once
#include "lua.hpp"
#include <any>
#include <filesystem>
#include <iostream>
#include "lua.hpp"
#include <vector>
#include <thread>
#include <memory>
#include <mutex>
#include <set>
#include <any>
namespace fs = std::experimental::filesystem;
struct LuaArg{
#include <thread>
#include <vector>
namespace fs = std::filesystem;
struct LuaArg {
std::vector<std::any> args;
void PushArgs(lua_State *State){
for(std::any arg : args){
if(!arg.has_value())return;
void PushArgs(lua_State* State) {
for (std::any arg : args) {
if (!arg.has_value())
return;
std::string Type = arg.type().name();
if(Type.find("bool") != -1){
lua_pushboolean(State,std::any_cast<bool>(arg));
if (Type.find("bool") != std::string::npos) {
lua_pushboolean(State, std::any_cast<bool>(arg));
}
if(Type.find("basic_string") != -1 || Type.find("char") != -1){
lua_pushstring(State,std::any_cast<std::string>(arg).c_str());
if (Type.find("basic_string") != std::string::npos || Type.find("char") != std::string::npos) {
lua_pushstring(State, std::any_cast<std::string>(arg).c_str());
}
if(Type.find("int") != -1){
lua_pushinteger(State,std::any_cast<int>(arg));
if (Type.find("int") != std::string::npos) {
lua_pushinteger(State, std::any_cast<int>(arg));
}
if(Type.find("float") != -1){
lua_pushnumber(State,std::any_cast<float>(arg));
if (Type.find("float") != std::string::npos) {
lua_pushnumber(State, std::any_cast<float>(arg));
}
}
}
}
};
class Lua {
private:
std::set<std::pair<std::string,std::string>> RegisteredEvents;
lua_State *luaState = luaL_newstate();
fs::file_time_type LastWrote;
std::string PluginName;
std::string FileName;
std::set<std::pair<std::string, std::string>> _RegisteredEvents;
lua_State* luaState { nullptr };
fs::file_time_type _LastWrote;
std::string _PluginName;
std::string _FileName;
bool _StopThread = false;
bool _Console = false;
// this is called by the ctor to ensure RAII
void Init();
public:
void RegisterEvent(const std::string&Event,const std::string&FunctionName);
std::string GetRegistered(const std::string&Event);
void UnRegisterEvent(const std::string&Event);
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
std::string GetRegistered(const std::string& Event) const;
void UnRegisterEvent(const std::string& Event);
void SetLastWrite(fs::file_time_type time);
bool IsRegistered(const std::string&Event);
void SetPluginName(const std::string&Name);
bool IsRegistered(const std::string& Event);
void SetPluginName(const std::string& Name);
void Execute(const std::string& Command);
void SetFileName(const std::string&Name);
void SetFileName(const std::string& Name);
fs::file_time_type GetLastWrite();
std::string GetPluginName();
std::string GetFileName();
bool StopThread = false;
bool Console = false;
std::string GetPluginName() const;
std::string GetFileName() const;
lua_State* GetState();
char* GetOrigin();
const lua_State* GetState() const;
std::string GetOrigin();
std::mutex Lock;
void Reload();
void Init();
Lua(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote, bool Console = false);
Lua(bool Console = false);
~Lua();
void SetStopThread(bool StopThread) { _StopThread = StopThread; }
bool GetStopThread() const { return _StopThread; }
};
int CallFunction(Lua*lua,const std::string& FuncName,LuaArg* args);
int TriggerLuaEvent(const std::string& Event,bool local,Lua*Caller,LuaArg* arg,bool Wait);
extern std::set<Lua*> PluginEngine;
int CallFunction(Lua* lua, const std::string& FuncName, std::unique_ptr<LuaArg> args);
int TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::unique_ptr<LuaArg> arg, bool Wait);
extern std::set<std::unique_ptr<Lua>> PluginEngine;

View File

@ -706,7 +706,7 @@
** Define it as a help when debugging C code.
*/
#if defined(LUA_USE_APICHECK)
#include <assert.h>
#include <CustomAssert.h>
#define luai_apicheck(l,e) assert(e)
#endif

View File

@ -2,7 +2,11 @@
/// Created by Anonymous275 on 7/28/2020
///
#pragma once
#ifdef __linux
#define EXCEPTION_POINTERS void
#else
#include <WS2tcpip.h>
#endif
#include <string>
#include "Xor.h"
struct RSA{

View File

@ -5,6 +5,7 @@
#include <string>
#include <array>
#include <cstdarg>
#include <cstdio>
#define BEGIN_NAMESPACE(x) namespace x {
#define END_NAMESPACE }
@ -68,10 +69,10 @@ BEGIN_NAMESPACE(XorCompileTime)
public:
template <size_t... Is>
constexpr __forceinline 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])... }
{}
__forceinline decltype(auto) decrypt(){
inline decltype(auto) decrypt(){
for (size_t i = 0; i < N; ++i) {
_encrypted[i] = dec(_encrypted[i]);
}
@ -83,14 +84,14 @@ BEGIN_NAMESPACE(XorCompileTime)
static auto w_printf = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf_s(fmt, args);
vprintf(fmt, args);
va_end(args);
};
static auto w_printf_s = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf_s(fmt, args);
vprintf(fmt, args);
va_end(args);
};
@ -113,7 +114,7 @@ BEGIN_NAMESPACE(XorCompileTime)
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf_s(buf, buf_size, fmt, args);
vsnprintf(buf, buf_size, fmt, args);
va_end(args);
};
@ -121,7 +122,7 @@ BEGIN_NAMESPACE(XorCompileTime)
int ret;
va_list args;
va_start(args, fmt);
ret = vsprintf_s(buf, buf_size, fmt, args);
ret = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
return ret;
};

30
include/UnixCompat.h Normal file
View File

@ -0,0 +1,30 @@
// Author: lionkor
#pragma once
// This header defines unix equivalents of common win32 functions.
#ifndef WIN32
#include "CustomAssert.h"
#include <cstring>
#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) {
Assert(std::memset(dst, 0, len) != nullptr);
}
// provides unix equivalent of closesocket call in win32
inline void closesocket(int socket) {
close(socket);
}
#ifndef __try
#define __try
#endif
#ifndef __except
#define __except(x) /**/
#endif
#endif // WIN32

View File

@ -176,7 +176,7 @@
#if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS
#endif
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(WIN32__)
# ifndef WIN32
# define WIN32
# endif

View File

@ -133,7 +133,7 @@ extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
#if defined(MACOS) || defined(TARGET_OS_MAC)
# define OS_CODE 7
# ifndef Z_SOLO
# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != WIN32_os
# include <unix.h> /* for fdopen */
# else
# ifndef fdopen

View File

@ -3,11 +3,15 @@
///
#include "Zlib/zlib.h"
#include <iostream>
#include <cstring>
#include <algorithm>
#include <array>
#define Biggest 30000
std::string Comp(std::string Data){
char*C = new char[Biggest];
memset(C, 0, Biggest);
std::array<char, Biggest> C;
// obsolete
C.fill(0);
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
@ -15,20 +19,20 @@ std::string Comp(std::string Data){
defstream.avail_in = (uInt)Data.length();
defstream.next_in = (Bytef *)&Data[0];
defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef *>(C);
defstream.next_out = reinterpret_cast<Bytef *>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
int TO = defstream.total_out;
size_t TO = defstream.total_out;
std::string Ret(TO,0);
memcpy_s(&Ret[0],TO,C,TO);
delete [] C;
std::copy_n(C.begin(), TO, Ret.begin());
return Ret;
}
std::string DeComp(std::string Compressed){
char*C = new char[Biggest];
memset(C, 0, Biggest);
std::array<char, Biggest> C;
// not needed
C.fill(0);
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
@ -36,14 +40,13 @@ std::string DeComp(std::string Compressed){
infstream.avail_in = Biggest;
infstream.next_in = (Bytef *)(&Compressed[0]);
infstream.avail_out = Biggest;
infstream.next_out = (Bytef *)(C);
infstream.next_out = (Bytef *)(C.data());
inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH);
inflateEnd(&infstream);
int TO = infstream.total_out;
size_t TO = infstream.total_out;
std::string Ret(TO,0);
memcpy_s(&Ret[0],TO,C,TO);
delete [] C;
std::copy_n(C.begin(), TO, Ret.begin());
return Ret;
}
}

View File

@ -3,58 +3,95 @@
///
#include "Lua/LuaSystem.hpp"
#ifdef WIN32
#include <conio.h>
#include <windows.h>
#else // *nix
typedef unsigned long DWORD, *PDWORD, *LPDWORD;
#include <termios.h>
#include <unistd.h>
#endif // WIN32
#include "Logger.h"
#include <iostream>
#include <conio.h>
#include <mutex>
#include <string>
#include <thread>
#include <mutex>
std::vector<std::string> QConsoleOut;
std::string CInputBuff;
std::mutex MLock;
Lua* LuaConsole;
void HandleInput(const std::string& cmd){
std::unique_ptr<Lua> LuaConsole;
void HandleInput(const std::string& cmd) {
std::cout << std::endl;
if (cmd == "exit") {
exit(0);
}else LuaConsole->Execute(cmd);
} else
LuaConsole->Execute(cmd);
}
void ProcessOut(){
void ProcessOut() {
static size_t len = 2;
if(QConsoleOut.empty() && len == CInputBuff.length())return;
if (QConsoleOut.empty() && len == CInputBuff.length())
return;
printf("%c[2K\r", 27);
for(const std::string& msg : QConsoleOut)
if(!msg.empty())std::cout << msg;
for (const std::string& msg : QConsoleOut)
if (!msg.empty())
std::cout << msg;
MLock.lock();
QConsoleOut.clear();
MLock.unlock();
std::cout << "> " << CInputBuff;
std::cout << "> " << CInputBuff << std::flush;
len = CInputBuff.length();
}
void ConsoleOut(const std::string& msg){
void ConsoleOut(const std::string& msg) {
MLock.lock();
QConsoleOut.emplace_back(msg);
MLock.unlock();
}
[[noreturn]] void OutputRefresh(){
while(true){
[[noreturn]] void OutputRefresh() {
DebugPrintTID();
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ProcessOut();
}
}
void SetupConsole(){
#ifndef WIN32
static int _getch() {
char buf = 0;
struct termios old;
fflush(stdout);
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~unsigned(ICANON);
old.c_lflag &= ~unsigned(ECHO);
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror("tcsetattr ~ICANON");
// no echo printf("%c\n", buf);
return buf;
}
#endif // WIN32
void SetupConsole() {
#ifdef WIN32
DWORD outMode = 0;
HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (stdoutHandle == INVALID_HANDLE_VALUE){
if (stdoutHandle == INVALID_HANDLE_VALUE) {
error("Invalid handle");
std::this_thread::sleep_for(std::chrono::seconds(3));
exit(GetLastError());
}
if (!GetConsoleMode(stdoutHandle, &outMode)){
if (!GetConsoleMode(stdoutHandle, &outMode)) {
error("Invalid console mode");
std::this_thread::sleep_for(std::chrono::seconds(3));
exit(GetLastError());
@ -66,28 +103,37 @@ void SetupConsole(){
std::this_thread::sleep_for(std::chrono::seconds(3));
exit(GetLastError());
}
#else
#endif // WIN32
}
[[noreturn]] void ReadCin(){
while (true){
[[noreturn]] void ReadCin() {
DebugPrintTID();
while (true) {
int In = _getch();
if (In == 13) {
if(!CInputBuff.empty()) {
if (In == 13 || In == '\n') {
if (!CInputBuff.empty()) {
HandleInput(CInputBuff);
CInputBuff.clear();
}
}else if(In == 8){
if(!CInputBuff.empty())CInputBuff.pop_back();
}else CInputBuff += char(In);
} else if (In == 8) {
if (!CInputBuff.empty())
CInputBuff.pop_back();
} else if (In == 4) {
CInputBuff = "exit";
HandleInput(CInputBuff);
CInputBuff.clear();
} else {
CInputBuff += char(In);
}
}
}
void ConsoleInit(){
void ConsoleInit() {
SetupConsole();
LuaConsole = new Lua();
LuaConsole->Console = true;
LuaConsole->Init();
LuaConsole = std::make_unique<Lua>(true);
printf("> ");
std::thread In(ReadCin);
In.detach();
std::thread Out(OutputRefresh);
Out.detach();
}
}

View File

@ -3,7 +3,8 @@
///
#include "Security/Enc.h"
#include "Settings.h"
#include <windows.h>
#include "CustomAssert.h"
//#include <windows.h>
#include "Logger.h"
#include <sstream>
#include <thread>
@ -84,7 +85,9 @@ int Dec(int value,int d,int n){
return log_power(value, d, n);
}
#ifdef WIN32
int Handle(EXCEPTION_POINTERS *ep,char* Origin){
Assert(false);
std::stringstream R;
R << Sec("Code : ") << std::hex
<< ep->ExceptionRecord->ExceptionCode
@ -92,6 +95,10 @@ int Handle(EXCEPTION_POINTERS *ep,char* Origin){
except(R.str());
return 1;
}
#else
// stub
int Handle(EXCEPTION_POINTERS *, char*) { return 1; }
#endif // WIN32
std::string RSA_E(const std::string& Data, RSA*k){
std::stringstream stream;
@ -116,4 +123,4 @@ std::string RSA_D(const std::string& Data, RSA*k){
ret += char(Dec(c,k->d,k->n));
}
return ret;
}
}

View File

@ -3,6 +3,7 @@
///
#include "Security/Enc.h"
#include "Logger.h"
#include "CustomAssert.h"
#include <fstream>
#include <string>
#include <thread>
@ -33,13 +34,13 @@ void SetValues(const std::string& Line, int Index) {
}
Data = Data.substr(1);
std::string::size_type sz;
bool Boolean = std::string(Data).find("true") != -1;//searches for "true"
bool FoundTrue = std::string(Data).find("true") != std::string::npos;//searches for "true"
switch (Index) {
case 1 :
Debug = Boolean;//checks and sets the Debug Value
Debug = FoundTrue;//checks and sets the Debug Value
break;
case 2 :
Private = Boolean;//checks and sets the Private Value
Private = FoundTrue;//checks and sets the Private Value
break;
case 3 :
Port = std::stoi(Data, &sz);//sets the Port
@ -77,6 +78,7 @@ std::string RemoveComments(const std::string& Line){
return Return;
}
void LoadConfig(std::ifstream& IFS){
Assert(IFS.is_open());
std::string line;
int index = 1;
while (getline(IFS, line)) {
@ -146,4 +148,4 @@ void InitConfig(){
exit(0);
}
if(Debug)DebugData();
}
}

View File

@ -29,6 +29,7 @@ std::string GenerateCall(){
return ret;
}
void Heartbeat(){
DebugPrintTID();
std::string R,T;
while(true){
R = GenerateCall();
@ -56,4 +57,4 @@ void Heartbeat(){
void HBInit(){
std::thread HB(Heartbeat);
HB.detach();
}
}

View File

@ -6,7 +6,9 @@
#include "Settings.h"
#include <algorithm>
#include "Logger.h"
namespace fs = std::experimental::filesystem;
namespace fs = std::filesystem;
uint64_t MaxModSize = 0;
std::string FileSizes;
std::string FileList;
@ -30,4 +32,4 @@ void InitRes(){
if(ModsLoaded){
info(Sec("Loaded ")+std::to_string(ModsLoaded)+Sec(" Mods"));
}
}
}

View File

@ -5,6 +5,7 @@
#include "Client.hpp"
#include "Logger.h"
#include <string>
#include <algorithm>
std::string CustomIP;
std::string GetSVer(){
@ -31,4 +32,4 @@ void InitServer(int argc, char* argv[]){
InitLog();
Args(argc,argv);
CI = new ClientInterface;
}
}

View File

@ -2,80 +2,84 @@
/// Created by Anonymous275 on 5/20/2020
///
#include "Logger.h"
#include "Lua/LuaSystem.hpp"
#include "Security/Enc.h"
#include "Settings.h"
#include "Logger.h"
#include <thread>
std::set<Lua*> PluginEngine;
bool NewFile(const std::string&Path){
for(Lua*Script : PluginEngine){
if(Path == Script->GetFileName())return false;
#ifdef __linux
// we need this for `struct stat`
#include <sys/stat.h>
#endif // __linux
std::set<std::unique_ptr<Lua>> PluginEngine;
bool NewFile(const std::string& Path) {
for (auto& Script : PluginEngine) {
if (Path == Script->GetFileName())
return false;
}
return true;
}
void RegisterFiles(const std::string& Path,bool HotSwap){
std::string Name = Path.substr(Path.find_last_of('\\')+1);
if(!HotSwap)info(Sec("Loading plugin : ") + Name);
for (const auto &entry : fs::directory_iterator(Path)){
void RegisterFiles(const std::string& Path, bool HotSwap) {
std::string Name = Path.substr(Path.find_last_of('\\') + 1);
if (!HotSwap)
info(Sec("Loading plugin : ") + Name);
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().string().find(Sec(".lua"));
if (pos != std::string::npos && entry.path().string().length() - pos == 4) {
if(!HotSwap || NewFile(entry.path().string())){
Lua *Script = new Lua();
PluginEngine.insert(Script);
Script->SetFileName(entry.path().string());
Script->SetPluginName(Name);
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
Script->Init();
if(HotSwap)info(Sec("[HOTSWAP] Added : ") +
Script->GetFileName().substr(Script->GetFileName().find('\\')));
if (!HotSwap || NewFile(entry.path().string())) {
auto FileName = entry.path().string();
std::unique_ptr<Lua> ScriptToInsert(new Lua(Name, FileName, fs::last_write_time(FileName)));
auto& Script = *ScriptToInsert;
PluginEngine.insert(std::move(ScriptToInsert));
if (HotSwap)
info(Sec("[HOTSWAP] Added : ") + Script.GetFileName().substr(Script.GetFileName().find('\\')));
}
}
}
}
void FolderList(const std::string& Path,bool HotSwap){
for (const auto &entry : fs::directory_iterator(Path)) {
void FolderList(const std::string& Path, bool HotSwap) {
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().filename().string().find('.');
if (pos == std::string::npos) {
RegisterFiles(entry.path().string(),HotSwap);
RegisterFiles(entry.path().string(), HotSwap);
}
}
}
[[noreturn]]void HotSwaps(const std::string& path){
while(true){
for(Lua*Script : PluginEngine){
struct stat Info{};
if(stat(Script->GetFileName().c_str(), &Info) != 0){
Script->StopThread = true;
[[noreturn]] void HotSwaps(const std::string& path) {
DebugPrintTID();
while (true) {
for (auto& Script : PluginEngine) {
struct stat Info {};
if (stat(Script->GetFileName().c_str(), &Info) != 0) {
Script->SetStopThread(true);
PluginEngine.erase(Script);
info(Sec("[HOTSWAP] Removed : ")+
Script->GetFileName().substr(Script->GetFileName().find('\\')));
info(Sec("[HOTSWAP] Removed : ") + Script->GetFileName().substr(Script->GetFileName().find('\\')));
break;
}
if(Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())){
Script->StopThread = true;
info(Sec("[HOTSWAP] Updated : ")+
Script->GetFileName().substr(Script->GetFileName().find('\\')));
if (Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())) {
Script->SetStopThread(true);
info(Sec("[HOTSWAP] Updated : ") + Script->GetFileName().substr(Script->GetFileName().find('\\')));
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
Script->Reload();
}
}
FolderList(path,true);
FolderList(path, true);
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
void InitLua(){
if(!fs::exists(Resource)){
void InitLua() {
if (!fs::exists(Resource)) {
fs::create_directory(Resource);
}
std::string Path = Resource + Sec("/Server");
if(!fs::exists(Path)){
if (!fs::exists(Path)) {
fs::create_directory(Path);
}
FolderList(Path,false);
std::thread t1(HotSwaps,Path);
FolderList(Path, false);
std::thread t1(HotSwaps, Path);
t1.detach();
info(Sec("Lua system online"));
}

File diff suppressed because it is too large Load Diff

View File

@ -8,23 +8,50 @@
#include "Logger.h"
#include <sstream>
#include <thread>
#include <cstring>
#include <algorithm>
#include "UnixCompat.h"
struct Hold{
SOCKET TCPSock{};
bool Done = false;
};
bool Send(SOCKET TCPSock,std::string Data){
#ifdef WIN32
int BytesSent;
BytesSent = send(TCPSock, Data.c_str(), int(Data.size()), 0);
int len = static_cast<int>(Data.size());
#else
int64_t BytesSent;
size_t len = Data.size();
#endif // WIN32
BytesSent = send(TCPSock, Data.c_str(), len, 0);
Data.clear();
if (BytesSent <= 0)return false;
return true;
}
std::string Rcv(SOCKET TCPSock){
char buf[6768];
int len = 6768;
ZeroMemory(buf, len);
int BytesRcv = recv(TCPSock, buf, len,0);
if (BytesRcv <= 0)return "";
uint32_t RealSize;
int64_t BytesRcv = recv(TCPSock, &RealSize, sizeof(RealSize), 0);
if (BytesRcv != sizeof(RealSize)) {
error(std::string(Sec("invalid packet: expected 4, got ")) + std::to_string(BytesRcv));
return "";
}
// RealSize is big-endian, so we convert it to host endianness
RealSize = ntohl(RealSize);
debug(std::string("got ") + std::to_string(RealSize) + " as size");
if (RealSize > 7000) {
error(Sec("Larger than allowed TCP packet received"));
return "";
}
char buf[7000];
std::fill_n(buf, 7000, 0);
BytesRcv = recv(TCPSock, buf, RealSize, 0);
if (BytesRcv != RealSize) {
debug("expected " + std::to_string(RealSize) + " bytes, got " + std::to_string(BytesRcv) + " instead");
}
if (BytesRcv <= 0)
return "";
return std::string(buf);
}
std::string GetRole(const std::string &DID){
@ -86,17 +113,21 @@ std::string GenerateM(RSA*key){
}
void Identification(SOCKET TCPSock,Hold*S,RSA*Skey){
Assert(S);
Assert(Skey);
S->TCPSock = TCPSock;
std::thread Timeout(Check,S);
Timeout.detach();
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))){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
@ -108,26 +139,31 @@ void Identification(SOCKET TCPSock,Hold*S,RSA*Skey){
if(Ver.size() > 3 && Ver.substr(0,2) == Sec("VC")){
Ver = Ver.substr(2);
if(Ver.length() > 4 || Ver != GetCVer()){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
}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")) {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
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);
Role = GetRole(DID);
if(Role.empty() || Role.find(Sec("Error")) != -1){
if(Role.empty() || Role.find(Sec("Error")) != std::string::npos){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
return;
}
@ -135,6 +171,7 @@ void Identification(SOCKET TCPSock,Hold*S,RSA*Skey){
for(Client*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);
break;
@ -142,23 +179,40 @@ void Identification(SOCKET TCPSock,Hold*S,RSA*Skey){
}
}
if(Role == Sec("MDEV") || CI->Size() < Max()){
debug("Identification success");
CreateClient(TCPSock,Name,DID,Role);
}else closesocket(TCPSock);
} else {
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
}
}
void Identify(SOCKET TCPSock){
auto* S = new Hold;
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
__try{
#endif // WIN32
Identification(TCPSock,S,Skey);
#ifdef WIN32
}__except(1){
if(TCPSock != -1){
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(TCPSock);
}
}
#endif // WIN32
delete Skey;
delete S;
}
void TCPServerMain(){
DebugPrintTID();
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(514, &wsaData)){
error(Sec("Can't start Winsock!"));
@ -195,4 +249,39 @@ void TCPServerMain(){
closesocket(client);
WSACleanup();
}
#else // unix
// wondering why we need slightly different implementations of this?
// ask ms.
SOCKET client, Listener = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
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){
error(Sec("Can't bind socket! ") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
}
if(Listener == -1){
error(Sec("Invalid listening socket"));
return;
}
if(listen(Listener,SOMAXCONN)){
error(Sec("listener failed ")+ std::string(strerror(errno)));
return;
}
info(Sec("Vehicle event network online"));
do{
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();
}while(client);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
closesocket(client);
#endif // WIN32
}

View File

@ -7,8 +7,10 @@
#include "Settings.h"
#include "Network.h"
#include "Logger.h"
#include "UnixCompat.h"
#include <sstream>
int FC(const std::string& s,const std::string& p,int n) {
auto i = s.find(p);
int j;
@ -19,6 +21,7 @@ int FC(const std::string& s,const std::string& p,int n) {
else return -1;
}
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);
@ -29,6 +32,7 @@ void Apply(Client*c,int VID,const std::string& pckt){
}
void VehicleParser(Client*c,const std::string& Pckt){
Assert(c);
if(c == nullptr || Pckt.length() < 4)return;
std::string Packet = Pckt;
char Code = Packet.at(1);
@ -43,7 +47,8 @@ void VehicleParser(Client*c,const std::string& Pckt){
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,
new LuaArg{{c->GetID(),CarID,Packet.substr(3)}},true)){
std::unique_ptr<LuaArg>(new 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);
@ -63,7 +68,8 @@ void VehicleParser(Client*c,const std::string& Pckt){
}
if(PID != -1 && VID != -1 && PID == c->GetID()){
if(!TriggerLuaEvent(Sec("onVehicleEdited"),false,nullptr,
new LuaArg{{c->GetID(),VID,Packet.substr(3)}},true)) {
std::unique_ptr<LuaArg>(new LuaArg{{c->GetID(),VID,Packet.substr(3)}}),
true)) {
SendToAll(c, Packet, false, true);
Apply(c,VID,Packet);
}else{
@ -83,7 +89,7 @@ void VehicleParser(Client*c,const std::string& Pckt){
if(PID != -1 && VID != -1 && PID == c->GetID()){
SendToAll(nullptr,Packet,true,true);
TriggerLuaEvent(Sec("onVehicleDeleted"),false,nullptr,
new LuaArg{{c->GetID(),VID}},false);
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));
}
@ -92,16 +98,18 @@ void VehicleParser(Client*c,const std::string& Pckt){
SendToAll(c,Packet,false,true);
return;
default:
AssertNotReachable();
return;
}
}
void SyncClient(Client*c){
Assert(c);
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,new LuaArg{{c->GetID()}},false);
TriggerLuaEvent(Sec("onPlayerJoin"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false);
for (Client*client : CI->Clients) {
if(client != nullptr){
if (client != c) {
@ -116,13 +124,19 @@ 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"))){}
#else // unix
VehicleParser(c,Packet);
#endif // WIN32
}
void HandleEvent(Client*c ,const std::string&Data){
Assert(c);
std::stringstream ss(Data);
std::string t,Name;
int a = 0;
@ -132,7 +146,7 @@ void HandleEvent(Client*c ,const std::string&Data){
Name = t;
break;
case 2:
TriggerLuaEvent(Name, false, nullptr,new LuaArg{{c->GetID(),t}},false);
TriggerLuaEvent(Name, false, nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID(),t}}),false);
break;
default:
break;
@ -143,7 +157,8 @@ void HandleEvent(Client*c ,const std::string&Data){
}
void GlobalParser(Client*c, const std::string& Pack){
static int lastRecv = 0;
Assert(c);
[[maybe_unused]] static int lastRecv = 0;
if(Pack.empty() || c == nullptr)return;
std::string Packet = Pack.substr(0,Pack.find(char(0)));
std::string pct;
@ -157,7 +172,7 @@ void GlobalParser(Client*c, const std::string& Pack){
}
switch (Code) {
case 'P':
case 'P': // initial connection
Respond(c, Sec("P") + std::to_string(c->GetID()),true);
SyncClient(c);
return;
@ -175,10 +190,11 @@ void GlobalParser(Client*c, const std::string& Pack){
SendToAll(c,Packet,false,true);
return;
case 'C':
if(Packet.length() < 4 || Packet.find(':', 3) == -1)break;
if (TriggerLuaEvent(Sec("onChatMessage"), false, nullptr,new LuaArg{
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;
}),true))break;
SendToAll(nullptr, Packet, true, true);
return;
case 'E':
@ -189,8 +205,13 @@ void GlobalParser(Client*c, const std::string& Pack){
}
}
void GParser(Client*c, const std::string&Packet){
void GParser(Client*c, const std::string& Packet){
Assert(c);
#ifdef WIN32
__try{
GlobalParser(c, Packet);
}__except(Handle(GetExceptionInformation(),Sec("Global Handler"))){}
}
#else
GlobalParser(c, Packet);
#endif // WIN32
}

View File

@ -3,6 +3,7 @@
///
#define CURL_STATICLIB
#include "Curl/curl.h"
#include "CustomAssert.h"
#include <iostream>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp){
((std::string*)userp)->append((char*)contents, size * nmemb);
@ -13,6 +14,7 @@ std::string HttpRequest(const std::string& IP,int port){
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
Assert(curl);
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_PORT, port);
@ -30,6 +32,7 @@ std::string PostHTTP(const std::string& IP,const std::string& Fields){
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
Assert(curl);
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, Fields.size());
@ -42,4 +45,4 @@ std::string PostHTTP(const std::string& IP,const std::string& Fields){
if(res != CURLE_OK)return "-1";
}
return readBuffer;
}
}

View File

@ -24,6 +24,7 @@ int OpenID(){
return ID;
}
void Respond(Client*c, const std::string& MSG, bool Rel){
Assert(c);
char C = MSG.at(0);
if(Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E'){
if(C == 'O' || C == 'T' || MSG.length() > 1000)SendLarge(c,MSG);
@ -31,6 +32,9 @@ void Respond(Client*c, const std::string& MSG, bool Rel){
}else UDPSend(c,MSG);
}
void SendToAll(Client*c, const std::string& Data, bool Self, bool Rel){
if (!Self) {
Assert(c);
}
char C = Data.at(0);
for(Client*client : CI->Clients){
if(client != nullptr) {
@ -55,6 +59,7 @@ void UpdatePlayers(){
SendToAll(nullptr, Packet,true,true);
}
void OnDisconnect(Client*c,bool kicked){
Assert(c);
info(c->GetName() + Sec(" Connection Terminated"));
if(c == nullptr)return;
std::string Packet;
@ -68,18 +73,19 @@ void OnDisconnect(Client*c,bool kicked){
Packet = Sec("L")+c->GetName()+Sec(" Left the server!");
SendToAll(c, Packet,false,true);
Packet.clear();
TriggerLuaEvent(Sec("onPlayerDisconnect"),false,nullptr,new LuaArg{{c->GetID()}},false);
TriggerLuaEvent(Sec("onPlayerDisconnect"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false);
c->ClearCars();
CI->RemoveClient(c); ///Removes the Client from existence
}
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,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
info(c->GetName() + Sec(" : Connected"));
TriggerLuaEvent(Sec("onPlayerJoining"),false,nullptr,new LuaArg{{c->GetID()}},false);
}
TriggerLuaEvent(Sec("onPlayerJoining"),false,nullptr,std::unique_ptr<LuaArg>(new LuaArg{{c->GetID()}}),false);
}

View File

@ -30,6 +30,7 @@ void Monitor() {
}
[[noreturn]]void Stat(){
DebugPrintTID();
while(true){
Monitor();
std::this_thread::sleep_for(std::chrono::seconds(1));

View File

@ -1,103 +1,134 @@
///
/// Created by Anonymous275 on 8/1/2020
///
#include "Security/Enc.h"
#include "Client.hpp"
#include "Settings.h"
#include "Logger.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <fstream>
void STCPSend(Client*c,std::string Data){
if(c == nullptr)return;
#ifdef __linux
// we need this for `struct stat`
#include <sys/stat.h>
#endif // __linux
void STCPSend(Client* c, std::string Data) {
Assert(c);
if (c == nullptr)
return;
#ifdef WIN32
int BytesSent;
BytesSent = send(c->GetTCPSock(), Data.c_str(), int(Data.size()), 0);
int len = static_cast<int>(Data.size());
#else
int64_t BytesSent;
size_t len = Data.size();
#endif // WIN32
BytesSent = send(c->GetTCPSock(), Data.c_str(), len, 0);
Data.clear();
if (BytesSent == 0){
if(c->GetStatus() > -1)c->SetStatus(-1);
}else if (BytesSent < 0) {
if(c->GetStatus() > -1)c->SetStatus(-1);
if (BytesSent == 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
} else if (BytesSent < 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
closesocket(c->GetTCPSock());
}
}
void SendFile(Client*c,const std::string&Name){
info(c->GetName()+Sec(" requesting : ")+Name.substr(Name.find_last_of('/')));
struct stat Info{};
if(stat(Name.c_str(), &Info) != 0){
STCPSend(c,Sec("Cannot Open"));
void SendFile(Client* c, const std::string& Name) {
Assert(c);
info(c->GetName() + Sec(" requesting : ") + Name.substr(Name.find_last_of('/')));
struct stat Info {};
if (stat(Name.c_str(), &Info) != 0) {
STCPSend(c, Sec("Cannot Open"));
return;
}
std::ifstream f(Name.c_str(), std::ios::binary);
f.seekg(0, std::ios_base::end);
std::streampos fileSize = f.tellg();
size_t Size = fileSize,Sent = 0,Diff;
int Split = 64000;
while(c->GetStatus() > -1 && Sent < Size){
size_t Size = size_t(fileSize);
size_t Sent = 0;
size_t Diff;
int64_t Split = 64000;
while (c->GetStatus() > -1 && Sent < Size) {
Diff = Size - Sent;
if(Diff > Split){
std::string Data(Split,0);
f.seekg(Sent, std::ios_base::beg);
if (Diff > size_t(Split)) {
std::string Data(size_t(Split), 0);
f.seekg(int64_t(Sent), std::ios_base::beg);
f.read(&Data[0], Split);
STCPSend(c,Data);
Sent += Split;
}else{
std::string Data(Diff,0);
f.seekg(Sent, std::ios_base::beg);
f.read(&Data[0], Diff);
STCPSend(c,Data);
STCPSend(c, Data);
Sent += size_t(Split);
} else {
std::string Data(Diff, 0);
f.seekg(int64_t(Sent), std::ios_base::beg);
f.read(&Data[0], int64_t(Diff));
STCPSend(c, Data);
Sent += Diff;
}
}
f.close();
}
void Parse(Client*c,const std::string&Packet){
if(c == nullptr || Packet.empty())return;
char Code = Packet.at(0),SubCode = 0;
if(Packet.length() > 1)SubCode = Packet.at(1);
void Parse(Client* c, const std::string& Packet) {
Assert(c);
if (c == nullptr || Packet.empty())
return;
char Code = Packet.at(0), SubCode = 0;
if (Packet.length() > 1)
SubCode = Packet.at(1);
switch (Code) {
case 'f':
SendFile(c,Packet.substr(1));
return;
case 'S':
if(SubCode == 'R'){
debug(Sec("Sending Mod Info"));
std::string ToSend = FileList+FileSizes;
if(ToSend.empty())ToSend = "-";
STCPSend(c,ToSend);
}
return;
default:
return;
case 'f':
SendFile(c, Packet.substr(1));
return;
case 'S':
if (SubCode == 'R') {
debug(Sec("Sending Mod Info"));
std::string ToSend = FileList + FileSizes;
if (ToSend.empty())
ToSend = "-";
STCPSend(c, ToSend);
}
return;
default:
return;
}
}
bool STCPRecv(Client*c){
if(c == nullptr)return false;
bool STCPRecv(Client* c) {
Assert(c);
if (c == nullptr)
return false;
char buf[200];
int len = 200;
size_t len = 200;
ZeroMemory(buf, len);
int BytesRcv = recv(c->GetTCPSock(), buf, len,0);
if (BytesRcv == 0){
if(c->GetStatus() > -1)c->SetStatus(-1);
int64_t BytesRcv = recv(c->GetTCPSock(), buf, len, 0);
if (BytesRcv == 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
closesocket(c->GetTCPSock());
return false;
}else if (BytesRcv < 0) {
if(c->GetStatus() > -1)c->SetStatus(-1);
} else if (BytesRcv < 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
closesocket(c->GetTCPSock());
return false;
}
if(strcmp(buf,"Done") == 0)return false;
std::string Ret(buf,BytesRcv);
Parse(c,Ret);
if (strcmp(buf, "Done") == 0)
return false;
std::string Ret(buf, size_t(BytesRcv));
Parse(c, Ret);
return true;
}
void SyncResources(Client*c){
if(c == nullptr)return;
try{
STCPSend(c,Sec("WS"));
while(c->GetStatus() > -1 && STCPRecv(c));
}catch (std::exception& e){
void SyncResources(Client* c) {
Assert(c);
if (c == nullptr)
return;
try {
STCPSend(c, Sec("WS"));
while (c->GetStatus() > -1 && STCPRecv(c))
;
} catch (std::exception& e) {
except(Sec("Exception! : ") + std::string(e.what()));
c->SetStatus(-1);
}
}
}

View File

@ -4,12 +4,21 @@
#include "Security/Enc.h"
#include "Network.h"
#include "Logger.h"
#include "UnixCompat.h"
#include <thread>
void TCPSend(Client*c,const std::string&Data){
Assert(c);
if(c == nullptr)return;
std::string Send = "\n" + Data.substr(0,Data.find(char(0))) + "\n";
size_t Sent = send(c->GetTCPSock(), Send.c_str(), int(Send.size()), 0);
#ifdef WIN32
int Sent;
int len = static_cast<int>(Send.size());
#else
int64_t Sent;
size_t len = Send.size();
#endif // WIN32
Sent = send(c->GetTCPSock(), Send.c_str(), len, 0);
if (Sent == 0){
if(c->GetStatus() > -1)c->SetStatus(-1);
}else if (Sent < 0) {
@ -18,43 +27,53 @@ void TCPSend(Client*c,const std::string&Data){
}
}
void TCPHandle(Client*c,const std::string& data){
Assert(c);
#ifdef WIN32
__try{
#endif // WIN32
c->Handler.Handle(c,data);
#ifdef WIN32
}__except(1){
c->Handler.clear();
}
#endif // WIN32
}
void TCPRcv(Client*c){
Assert(c);
if(c == nullptr || c->GetStatus() < 0)return;
char buf[4096];
int len = 4096;
size_t len = 4096;
ZeroMemory(buf, len);
int BytesRcv = recv(c->GetTCPSock(), buf, len,0);
int64_t BytesRcv = recv(c->GetTCPSock(), buf, len,0);
if (BytesRcv == 0){
debug(Sec("(TCP) Connection closing..."));
if(c->GetStatus() > -1)c->SetStatus(-1);
return;
}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);
closesocket(c->GetTCPSock());
return;
}
std::string Buf(buf,BytesRcv);
std::string Buf(buf,(size_t(BytesRcv)));
TCPHandle(c,Buf);
}
void TCPClient(Client*c){
DebugPrintTID();
Assert(c);
if(c->GetTCPSock() == -1){
CI->RemoveClient(c);
return;
}
OnConnect(c);
while (c->GetStatus() > -1)TCPRcv(c);
__try{
OnDisconnect(c, c->GetStatus() == -2);
}__except(Handle(GetExceptionInformation(),Sec("OnDisconnect"))){}
OnDisconnect(c, c->GetStatus() == -2);
}
void InitClient(Client*c){
std::thread NewClient(TCPClient,c);
NewClient.detach();
}
}

View File

@ -2,137 +2,171 @@
/// Created by Anonymous275 on 5/8/2020
///
///UDP
#include "Security/Enc.h"
#include "Compressor.h"
#include "Client.hpp"
#include "Settings.h"
#include "Network.h"
#include "Compressor.h"
#include "Logger.h"
#include <sstream>
#include <vector>
#include <thread>
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <array>
int FC(const std::string& s,const std::string& p,int n);
struct PacketData{
#include <cmath>
#include <cstring>
#include <sstream>
#include <thread>
#include <vector>
int FC(const std::string& s, const std::string& p, int n);
struct PacketData {
int ID;
Client* Client;
::Client* Client;
std::string Data;
int Tries;
};
struct SplitData{
int Total{};
int ID{};
std::set<std::pair<int,std::string>> Fragments;
struct SplitData {
int Total {};
int ID {};
std::set<std::pair<int, std::string>> Fragments;
};
SOCKET UDPSock;
std::set<PacketData*> DataAcks;
std::set<SplitData*> SplitPackets;
void UDPSend(Client*c,std::string Data){
if(c == nullptr || !c->isConnected || c->GetStatus() < 0)return;
void UDPSend(Client* c, std::string Data) {
Assert(c);
if (c == nullptr || !c->isConnected || c->GetStatus() < 0)
return;
sockaddr_in Addr = c->GetUDPAddr();
int AddrSize = sizeof(c->GetUDPAddr());
Data = Data.substr(0,Data.find(char(0)));
if(Data.length() > 400){
socklen_t AddrSize = sizeof(c->GetUDPAddr());
Data = Data.substr(0, Data.find(char(0)));
if (Data.length() > 400) {
std::string CMP(Comp(Data));
Data = "ABG:" + CMP;
}
int sendOk = sendto(UDPSock, Data.c_str(), int(Data.size()), 0, (sockaddr *) &Addr, AddrSize);
if (sendOk == SOCKET_ERROR) {
#ifdef WIN32
int sendOk;
int len = static_cast<int>(Data.size());
#else
int64_t sendOk;
size_t len = Data.size();
#endif // WIN32
sendOk = sendto(UDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, AddrSize);
#ifdef WIN32
if (sendOk != 0) {
debug(Sec("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
if(c->GetStatus() > -1)c->SetStatus(-1);
if (c->GetStatus() > -1)
c->SetStatus(-1);
}
#else // unix
if (sendOk == -1) {
debug(Sec("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
if (c->GetStatus() > -1)
c->SetStatus(-1);
} else if (sendOk == 0) {
debug(Sec("(UDP) sendto returned 0"));
if (c->GetStatus() > -1)
c->SetStatus(-1);
}
#endif // WIN32
}
void AckID(int ID){
for(PacketData* p : DataAcks){
if(p != nullptr && p->ID == ID){
void AckID(int ID) {
for (PacketData* p : DataAcks) {
if (p != nullptr && p->ID == ID) {
DataAcks.erase(p);
break;
}
}
}
int PacktID(){
int PacktID() {
static int ID = -1;
if(ID > 999999)ID = 0;
else ID++;
if (ID > 999999)
ID = 0;
else
ID++;
return ID;
}
int SplitID(){
int SplitID() {
static int SID = -1;
if(SID > 999999)SID = 0;
else SID++;
if (SID > 999999)
SID = 0;
else
SID++;
return SID;
}
void SendLarge(Client*c,std::string Data){
Data = Data.substr(0,Data.find(char(0)));
void SendLarge(Client* c, std::string Data) {
Assert(c);
Data = Data.substr(0, Data.find(char(0)));
int ID = PacktID();
std::string Packet;
if(Data.length() > 1000){
if (Data.length() > 1000) {
std::string pckt = Data;
int S = 1,Split = int(ceil(float(pckt.length()) / 1000));
int S = 1, Split = int(ceil(float(pckt.length()) / 1000));
int SID = SplitID();
while(pckt.length() > 1000){
Packet = "SC|"+std::to_string(S)+"|"+std::to_string(Split)+"|"+std::to_string(ID)+"|"+
std::to_string(SID)+"|"+pckt.substr(0,1000);
DataAcks.insert(new PacketData{ID,c,Packet,1});
UDPSend(c,Packet);
while (pckt.length() > 1000) {
Packet = "SC|" + std::to_string(S) + "|" + std::to_string(Split) + "|" + std::to_string(ID) + "|" + std::to_string(SID) + "|" + pckt.substr(0, 1000);
DataAcks.insert(new PacketData { ID, c, Packet, 1 });
UDPSend(c, Packet);
pckt = pckt.substr(1000);
S++;
ID = PacktID();
}
Packet = "SC|"+std::to_string(S)+"|"+std::to_string(Split)+"|"+
std::to_string(ID)+"|"+std::to_string(SID)+"|"+pckt;
DataAcks.insert(new PacketData{ID,c,Packet,1});
UDPSend(c,Packet);
}else{
Packet = "SC|" + std::to_string(S) + "|" + std::to_string(Split) + "|" + std::to_string(ID) + "|" + std::to_string(SID) + "|" + pckt;
DataAcks.insert(new PacketData { ID, c, Packet, 1 });
UDPSend(c, Packet);
} else {
Packet = "BD:" + std::to_string(ID) + ":" + Data;
DataAcks.insert(new PacketData{ID,c,Packet,1});
UDPSend(c,Packet);
DataAcks.insert(new PacketData { ID, c, Packet, 1 });
UDPSend(c, Packet);
}
}
struct HandledC{
int Pos = 0;
Client *c = nullptr;
std::array<int, 100> HandledIDs = {-1};
struct HandledC {
size_t Pos = 0;
Client* c = nullptr;
std::array<int, 100> HandledIDs = { -1 };
};
std::set<HandledC*> HandledIDs;
void ResetIDs(HandledC*H){
for(int C = 0;C < 100;C++){
void ResetIDs(HandledC* H) {
for (size_t C = 0; C < 100; C++) {
H->HandledIDs.at(C) = -1;
}
}
HandledC*GetHandled(Client*c){
for(HandledC*h : HandledIDs){
if(h->c == c){
HandledC* GetHandled(Client* c) {
Assert(c);
for (HandledC* h : HandledIDs) {
if (h->c == c) {
return h;
}
}
return new HandledC();
}
bool Handled(Client*c,int ID){
bool Handled(Client* c, int ID) {
Assert(c);
bool handle = false;
for(HandledC*h : HandledIDs){
if(h->c == c){
for(int id : h->HandledIDs){
if(id == ID)return true;
for (HandledC* h : HandledIDs) {
if (h->c == c) {
for (int id : h->HandledIDs) {
if (id == ID)
return true;
}
if(h->Pos > 99)h->Pos = 0;
if (h->Pos > 99)
h->Pos = 0;
h->HandledIDs.at(h->Pos) = ID;
h->Pos++;
handle = true;
}
}
for(HandledC*h : HandledIDs){
if(h->c == nullptr || !h->c->isConnected){
for (HandledC* h : HandledIDs) {
if (h->c == nullptr || !h->c->isConnected) {
HandledIDs.erase(h);
break;
}
}
if(!handle){
HandledC *h = GetHandled(c);
if (!handle) {
HandledC* h = GetHandled(c);
ResetIDs(h);
if (h->Pos > 99)h->Pos = 0;
if (h->Pos > 99)
h->Pos = 0;
h->HandledIDs.at(h->Pos) = ID;
h->Pos++;
h->c = c;
@ -140,89 +174,99 @@ bool Handled(Client*c,int ID){
}
return false;
}
std::string UDPRcvFromClient(sockaddr_in& client){
int clientLength = sizeof(client);
std::string UDPRcvFromClient(sockaddr_in& client) {
size_t clientLength = sizeof(client);
ZeroMemory(&client, clientLength);
std::string Ret(10240,0);
int Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&client, &clientLength);
if (Rcv == -1){
std::string Ret(10240, 0);
int64_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&client, (socklen_t*)&clientLength);
if (Rcv == -1) {
#ifdef WIN32
error(Sec("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
#else // unix
error(Sec("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
#endif // WIN32
return "";
}
return Ret;
}
SplitData*GetSplit(int SplitID){
for(SplitData* a : SplitPackets){
if(a->ID == SplitID)return a;
SplitData* GetSplit(int SplitID) {
for (SplitData* a : SplitPackets) {
if (a->ID == SplitID)
return a;
}
auto* SP = new SplitData();
SplitPackets.insert(SP);
return SP;
}
void HandleChunk(Client*c,const std::string&Data){
int pos = FC(Data,"|",5);
if(pos == -1)return;
std::stringstream ss(Data.substr(0,pos++));
void HandleChunk(Client* c, const std::string& Data) {
Assert(c);
int pos = FC(Data, "|", 5);
if (pos == -1)
return;
std::stringstream ss(Data.substr(0, size_t(pos++)));
std::string t;
int I = -1;
//Current Max ID SID
std::vector<int> Num(4,0);
std::vector<int> Num(4, 0);
while (std::getline(ss, t, '|')) {
if(I != -1)Num.at(I) = std::stoi(t);
if (I >= 0)
Num.at(size_t(I)) = std::stoi(t);
I++;
}
std::string ack = "TRG:" + std::to_string(Num.at(2));
UDPSend(c,ack);
if(Handled(c,Num.at(2))){
UDPSend(c, ack);
if (Handled(c, Num.at(2))) {
return;
}
std::string Packet = Data.substr(pos);
std::string Packet = Data.substr(size_t(pos));
SplitData* SData = GetSplit(Num.at(3));
SData->Total = Num.at(1);
SData->ID = Num.at(3);
SData->Fragments.insert(std::make_pair(Num.at(0),Packet));
if(SData->Fragments.size() == SData->Total){
SData->Fragments.insert(std::make_pair(Num.at(0), Packet));
if (SData->Fragments.size() == size_t(SData->Total)) {
std::string ToHandle;
for(const std::pair<int,std::string>& a : SData->Fragments){
for (const std::pair<int, std::string>& a : SData->Fragments) {
ToHandle += a.second;
}
GParser(c,ToHandle);
GParser(c, ToHandle);
SplitPackets.erase(SData);
delete SData;
SData = nullptr;
}
}
void UDPParser(Client*c,std::string Packet){
if(Packet.substr(0,4) == "ABG:"){
void UDPParser(Client* c, std::string Packet) {
Assert(c);
if (Packet.substr(0, 4) == "ABG:") {
Packet = DeComp(Packet.substr(4));
}
if(Packet.substr(0,4) == "TRG:"){
if (Packet.substr(0, 4) == "TRG:") {
std::string pkt = Packet.substr(4);
if(Packet.find_first_not_of("0123456789") == -1){
if (Packet.find_first_not_of("0123456789") == std::string::npos) {
AckID(stoi(Packet));
}
return;
}else if(Packet.substr(0,3) == "BD:"){
auto pos = Packet.find(':',4);
int ID = stoi(Packet.substr(3,pos-3));
} else if (Packet.substr(0, 3) == "BD:") {
auto pos = Packet.find(':', 4);
int ID = stoi(Packet.substr(3, pos - 3));
std::string pkt = "TRG:" + std::to_string(ID);
UDPSend(c,pkt);
if(!Handled(c,ID)) {
UDPSend(c, pkt);
if (!Handled(c, ID)) {
pkt = Packet.substr(pos + 1);
GParser(c, pkt);
}
return;
}else if(Packet.substr(0,2) == "SC"){
HandleChunk(c,Packet);
} else if (Packet.substr(0, 2) == "SC") {
HandleChunk(c, Packet);
return;
}
GParser(c,Packet);
GParser(c, Packet);
}
void LOOP(){
while(UDPSock != -1) {
for (PacketData* p : DataAcks){
if(p != nullptr) {
void LOOP() {
DebugPrintTID();
while (UDPSock != -1) {
for (PacketData* p : DataAcks) {
if (p != nullptr) {
if (p->Client == nullptr || p->Client->GetTCPSock() == -1) {
DataAcks.erase(p);
break;
@ -239,22 +283,23 @@ void LOOP(){
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
}
[[noreturn]] void UDPServerMain(){
[[noreturn]] void UDPServerMain() {
#ifdef WIN32
WSADATA data;
if (WSAStartup(514, &data)){
if (WSAStartup(514, &data)) {
error(Sec("Can't start Winsock!"));
//return;
}
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
// Create a server hint structure for the server
sockaddr_in serverAddr{};
sockaddr_in serverAddr {};
serverAddr.sin_addr.S_un.S_addr = ADDR_ANY; //Any Local
serverAddr.sin_family = AF_INET; // Address format is IPv4
serverAddr.sin_port = htons(Port); // Convert from little to big endian
// Try and bind the socket to the IP and port
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR){
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
error(Sec("Can't bind socket!") + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
@ -265,25 +310,69 @@ void LOOP(){
std::thread Ack(LOOP);
Ack.detach();
info(Sec("Vehicle data network online on port ")+std::to_string(Port)+Sec(" with a Max of ")+std::to_string(MaxPlayers)+Sec(" Clients"));
while (true){
sockaddr_in client{};
info(Sec("Vehicle data network online on port ") + std::to_string(Port) + Sec(" with a Max of ") + std::to_string(MaxPlayers) + Sec(" Clients"));
while (true) {
sockaddr_in client {};
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
auto Pos = Data.find(':');
if(Data.empty() || Pos < 0 || Pos > 2)continue;
if (Data.empty() || Pos < 0 || Pos > 2)
continue;
/*char clientIp[256];
ZeroMemory(clientIp, 256); ///Code to get IP we don't need that yet
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);*/
uint8_t ID = Data.at(0)-1;
for(Client*c : CI->Clients){
if(c != nullptr && c->GetID() == ID){
uint8_t ID = Data.at(0) - 1;
for (Client* c : CI->Clients) {
if (c != nullptr && c->GetID() == ID) {
c->SetUDPAddr(client);
c->isConnected = true;
UDPParser(c,Data.substr(2));
UDPParser(c, Data.substr(2));
}
}
}
/*closesocket(UDPSock);
WSACleanup();
return;*/
}
#else // unix
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
// Create a server hint structure for the server
sockaddr_in serverAddr {};
serverAddr.sin_addr.s_addr = INADDR_ANY; //Any Local
serverAddr.sin_family = AF_INET; // Address format is IPv4
serverAddr.sin_port = htons(uint16_t(Port)); // Convert from little to big endian
// Try and bind the socket to the IP and port
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
error(Sec("Can't bind socket!") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
//return;
}
DataAcks.clear();
std::thread Ack(LOOP);
Ack.detach();
info(Sec("Vehicle data network online on port ") + std::to_string(Port) + Sec(" with a Max of ") + std::to_string(MaxPlayers) + Sec(" Clients"));
while (true) {
sockaddr_in client {};
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
size_t Pos = Data.find(':');
if (Data.empty() || Pos > 2)
continue;
/*char clientIp[256];
ZeroMemory(clientIp, 256); ///Code to get IP we don't need that yet
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);*/
uint8_t ID = uint8_t(Data.at(0)) - 1;
for (Client* c : CI->Clients) {
if (c != nullptr && c->GetID() == ID) {
c->SetUDPAddr(client);
c->isConnected = true;
UDPParser(c, Data.substr(2));
}
}
}
/*closesocket(UDPSock); // TODO: Why not this? We did this in TCPServerMain?
return;
*/
#endif // WIN32
}

View File

@ -1,25 +1,45 @@
///
/// Created by Anonymous275 on 7/17/2020
///
#include "Logger.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "Logger.h"
#include <fstream>
#include <sstream>
#include <chrono>
#include <fstream>
#include <mutex>
#include <sstream>
#include <thread>
void DebugPrintTIDInternal(const std::string& func) {
// we need to print to cout here as we might crash before all console output is handled,
// due to segfaults or asserts.
#ifdef DEBUG
MLock.lock();
printf("%c[2K\r", 27);
std::cout << "(debug build) Thread '" << std::this_thread::get_id() << "' is " << func << std::endl;
MLock.unlock();
#endif // DEBUG
}
std::string getDate() {
typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>::type> days;
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::system_clock::duration tp = now.time_since_epoch();
days d = std::chrono::duration_cast<days>(tp);tp -= d;
auto h = std::chrono::duration_cast<std::chrono::hours>(tp);tp -= h;
auto m = std::chrono::duration_cast<std::chrono::minutes>(tp);tp -= m;
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp);tp -= s;
days d = std::chrono::duration_cast<days>(tp);
tp -= d;
auto h = std::chrono::duration_cast<std::chrono::hours>(tp);
tp -= h;
auto m = std::chrono::duration_cast<std::chrono::minutes>(tp);
tp -= m;
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp);
tp -= s;
time_t tt = std::chrono::system_clock::to_time_t(now);
tm local_tm{};
localtime_s(&local_tm,&tt);
tm local_tm {};
#ifdef WIN32
localtime_s(&local_tm, &tt);
#else // unix
localtime_r(&tt, &local_tm);
#endif // WIN32
std::stringstream date;
int S = local_tm.tm_sec;
int M = local_tm.tm_min;
@ -28,27 +48,28 @@ std::string getDate() {
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
date
<< "["
<< local_tm.tm_mday << "/"
<< local_tm.tm_mon + 1 << "/"
<< local_tm.tm_year + 1900 << " "
<< Hour << ":"
<< Min << ":"
<< Secs
<< "] ";
<< "["
<< local_tm.tm_mday << "/"
<< local_tm.tm_mon + 1 << "/"
<< local_tm.tm_year + 1900 << " "
<< Hour << ":"
<< Min << ":"
<< Secs
<< "] ";
return date.str();
}
void InitLog(){
void InitLog() {
std::ofstream LFS;
LFS.open (Sec("Server.log"));
if(!LFS.is_open()){
LFS.open(Sec("Server.log"));
if (!LFS.is_open()) {
error(Sec("logger file init failed!"));
}else LFS.close();
} else
LFS.close();
}
std::mutex LogLock;
void addToLog(const std::string& Line){
void addToLog(const std::string& Line) {
std::ofstream LFS;
LFS.open (Sec("Server.log"), std::ios_base::app);
LFS.open(Sec("Server.log"), std::ios_base::app);
LFS << Line.c_str();
LFS.close();
}
@ -60,14 +81,15 @@ void info(const std::string& toPrint) {
LogLock.unlock();
}
void debug(const std::string& toPrint) {
if(!Debug)return;
if (!Debug)
return;
LogLock.lock();
std::string Print = getDate() + Sec("[DEBUG] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
LogLock.unlock();
}
void warn(const std::string& toPrint){
void warn(const std::string& toPrint) {
LogLock.lock();
std::string Print = getDate() + Sec("[WARN] ") + toPrint + "\n";
ConsoleOut(Print);
@ -80,7 +102,8 @@ void error(const std::string& toPrint) {
std::string Print = getDate() + Sec("[ERROR] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
if(ECounter > 10)exit(7);
if (ECounter > 10)
exit(7);
ECounter++;
LogLock.unlock();
}

View File

@ -1,13 +1,19 @@
#include "Startup.h"
#include "CustomAssert.h"
#include "Curl/curl.h"
#include <thread>
#include <iostream>
[[noreturn]] void loop(){
DebugPrintTID();
while(true){
std::cout.flush();
std::this_thread::sleep_for(std::chrono::milliseconds(600));
}
}
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();
@ -20,5 +26,7 @@ int main(int argc, char* argv[]) {
HBInit();
StatInit();
NetMain();
// clean up curl at the end to be sure
curl_global_cleanup();
return 0;
}