Finalize master&new-lua-features merge

This commit is contained in:
Lion Kortlepel
2021-09-17 14:58:40 +02:00
parent 9dfe9f659a
commit 48caae25fd
13 changed files with 143 additions and 124 deletions

View File

@@ -141,11 +141,15 @@ void RegisterThread(const std::string& str);
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x)) #define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x)) #define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
#define error(x) \ #define beammp_error(x) \
do { \ do { \
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \ Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \ Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
} while (false) } while (false)
#define beammp_lua_error(x) \
do { \
Application::Console().Write(_this_location + std::string("[LUA_ERROR] ") + (x)); \
} while (false)
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x)) #define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
#define beammp_debug(x) \ #define beammp_debug(x) \
do { \ do { \
@@ -158,14 +162,14 @@ void RegisterThread(const std::string& str);
#define beammp_ignore(x) (void)x #define beammp_ignore(x) (void)x
// trace() is a debug-build debug() // trace() is a debug-build debug()
#if defined(DEBUG) #if defined(DEBUG)
#define trace(x) \ #define beammp_trace(x) \
do { \ do { \
if (Application::Settings.DebugModeEnabled) { \ if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \ Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
} \ } \
} while (false) } while (false)
#else #else
#define trace(x) #define beammp_trace(x)
#endif // defined(DEBUG) #endif // defined(DEBUG)
void LogChatMessage(const std::string& name, int id, const std::string& msg); void LogChatMessage(const std::string& name, int id, const std::string& msg);

View File

@@ -29,19 +29,19 @@ void Application::GracefullyShutdown() {
++ShutdownAttempts; ++ShutdownAttempts;
// hard shutdown at 2 additional tries // hard shutdown at 2 additional tries
if (ShutdownAttempts == 2) { if (ShutdownAttempts == 2) {
info("hard shutdown forced by multiple shutdown requests"); beammp_info("hard shutdown forced by multiple shutdown requests");
std::exit(0); std::exit(0);
} }
info("already shutting down!"); beammp_info("already shutting down!");
return; return;
} else { } else {
AlreadyShuttingDown = true; AlreadyShuttingDown = true;
} }
trace("waiting for lock release"); beammp_trace("waiting for lock release");
std::unique_lock Lock(mShutdownHandlersMutex); std::unique_lock Lock(mShutdownHandlersMutex);
info("please wait while all subsystems are shutting down..."); beammp_info("please wait while all subsystems are shutting down...");
for (size_t i = 0; i < mShutdownHandlers.size(); ++i) { for (size_t i = 0; i < mShutdownHandlers.size(); ++i) {
info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down"); beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
mShutdownHandlers[i](); mShutdownHandlers[i]();
} }
} }
@@ -84,13 +84,13 @@ void Application::CheckForUpdates() {
auto RemoteVersion = Version(VersionStrToInts(Response)); auto RemoteVersion = Version(VersionStrToInts(Response));
if (IsOutdated(MyVersion, RemoteVersion)) { if (IsOutdated(MyVersion, RemoteVersion)) {
std::string RealVersionString = RemoteVersion.AsString(); std::string RealVersionString = RemoteVersion.AsString();
warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION OUT! There's a new version (v" + RealVersionString + ") of the BeamMP-Server available! For more info visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server." + std::string(ANSI_RESET)); beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION OUT! There's a new version (v" + RealVersionString + ") of the BeamMP-Server available! For more info visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server." + std::string(ANSI_RESET));
} else { } else {
info("Server up-to-date!"); beammp_info("Server up-to-date!");
} }
} else { } else {
warn("Unable to fetch version from backend."); beammp_warn("Unable to fetch version from backend.");
trace("got " + Response); beammp_trace("got " + Response);
auto Lock = Sentry.CreateExclusiveContext(); auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("get-response", { { "response", Response } }); Sentry.SetContext("get-response", { { "response", Response } });
Sentry.LogError("failed to get server version", _file_basename, _line); Sentry.LogError("failed to get server version", _file_basename, _line);

View File

@@ -63,11 +63,11 @@ std::string GenericRequest(http::verb verb, const std::string& host, int port, c
req.set(http::field::content_length, std::to_string(body.size())); req.set(http::field::content_length, std::to_string(body.size()));
req.body() = body; req.body() = body;
// info("body is " + body + " (" + req.body() + ")"); // beammp_info("body is " + body + " (" + req.body() + ")");
// info("content size is " + std::to_string(body.size()) + " (" + boost::lexical_cast<std::string>(body.size()) + ")"); // beammp_info("content size is " + std::to_string(body.size()) + " (" + boost::lexical_cast<std::string>(body.size()) + ")");
} }
for (const auto& pair : fields) { for (const auto& pair : fields) {
// info("setting " + pair.first + " to " + pair.second); // beammp_info("setting " + pair.first + " to " + pair.second);
req.set(pair.first, pair.second); req.set(pair.first, pair.second);
} }
@@ -119,7 +119,7 @@ std::string GenericRequest(http::verb verb, const std::string& host, int port, c
stream.shutdown(ec); stream.shutdown(ec);
// IGNORING ec // IGNORING ec
// info(result.str()); // beammp_info(result.str());
std::string debug_response_str; std::string debug_response_str;
std::getline(result, debug_response_str); std::getline(result, debug_response_str);

View File

@@ -131,7 +131,7 @@ void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!c->IsSynced()) if (!c->IsSynced())
return; return;
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, msg); LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
Engine->Network().Respond(*c, Packet, true); Engine->Network().Respond(*c, Packet, true);
} else { } else {
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID"); beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");

View File

@@ -6,18 +6,18 @@
static void UnixSignalHandler(int sig) { static void UnixSignalHandler(int sig) {
switch (sig) { switch (sig) {
case SIGPIPE: case SIGPIPE:
warn("ignoring SIGPIPE"); beammp_warn("ignoring SIGPIPE");
break; break;
case SIGTERM: case SIGTERM:
info("gracefully shutting down via SIGTERM"); beammp_info("gracefully shutting down via SIGTERM");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
break; break;
case SIGINT: case SIGINT:
info("gracefully shutting down via SIGINT"); beammp_info("gracefully shutting down via SIGINT");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
break; break;
default: default:
debug("unhandled signal: " + std::to_string(sig)); beammp_debug("unhandled signal: " + std::to_string(sig));
break; break;
} }
} }
@@ -29,15 +29,15 @@ static void UnixSignalHandler(int sig) {
BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) { BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
switch (CtrlType) { switch (CtrlType) {
case CTRL_C_EVENT: case CTRL_C_EVENT:
info("gracefully shutting down via CTRL+C"); beammp_info("gracefully shutting down via CTRL+C");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
return TRUE; return TRUE;
case CTRL_BREAK_EVENT: case CTRL_BREAK_EVENT:
info("gracefully shutting down via CTRL+BREAK"); beammp_info("gracefully shutting down via CTRL+BREAK");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
return TRUE; return TRUE;
case CTRL_CLOSE_EVENT: case CTRL_CLOSE_EVENT:
info("gracefully shutting down via close"); beammp_info("gracefully shutting down via close");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
return TRUE; return TRUE;
} }
@@ -49,7 +49,7 @@ BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
void SetupSignalHandlers() { void SetupSignalHandlers() {
// signal handlers for unix#include <windows.h> // signal handlers for unix#include <windows.h>
#ifdef __unix #ifdef __unix
trace("registering handlers for SIGINT, SIGTERM, SIGPIPE"); beammp_trace("registering handlers for SIGINT, SIGTERM, SIGPIPE");
signal(SIGPIPE, UnixSignalHandler); signal(SIGPIPE, UnixSignalHandler);
signal(SIGTERM, UnixSignalHandler); signal(SIGTERM, UnixSignalHandler);
#ifndef DEBUG #ifndef DEBUG
@@ -59,7 +59,7 @@ void SetupSignalHandlers() {
// signal handlers for win32 // signal handlers for win32
#ifdef WIN32 #ifdef WIN32
trace("registering handlers for CTRL_*_EVENTs"); beammp_trace("registering handlers for CTRL_*_EVENTs");
SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE); SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE);
#endif // WIN32 #endif // WIN32
} }

View File

@@ -58,6 +58,8 @@ void TConfig::FlushToFile() {
data["General"][StrMap.data()] = Application::Settings.MapName; data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::Settings.ServerDesc; data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::Settings.Resource; data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
data["General"][StrSendErrors.data()] = Application::Settings.SendErrors;
data["General"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
std::ofstream Stream(ConfigFileName); std::ofstream Stream(ConfigFileName);
Stream << data << std::flush; Stream << data << std::flush;
} }
@@ -79,7 +81,7 @@ void TConfig::CreateConfigFile(std::string_view name) {
} }
auto data = toml::parse<toml::preserve_comments>(name.data()); auto data = toml::parse<toml::preserve_comments>(name.data());
//{ StrSendErrors, Application::Settings.SendErrors }, //{ StrSendErrors, Application::Settings.SendErrors },
data["General"] = toml::table(); data["General"] = toml::table();
data["General"][StrAuthKey.data()] = Application::Settings.Key; data["General"][StrAuthKey.data()] = Application::Settings.Key;
@@ -92,6 +94,8 @@ void TConfig::CreateConfigFile(std::string_view name) {
data["General"][StrMap.data()] = Application::Settings.MapName; data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::Settings.ServerDesc; data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::Settings.Resource; data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
data["General"][StrSendErrors.data()] = Application::Settings.SendErrors;
data["General"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
std::ofstream ofs { std::string(name) }; std::ofstream ofs { std::string(name) };
if (ofs.good()) { if (ofs.good()) {
@@ -123,19 +127,13 @@ void TConfig::ParseFromFile(std::string_view name) {
Application::Settings.ServerDesc = data["General"][StrDescription.data()].as_string(); Application::Settings.ServerDesc = data["General"][StrDescription.data()].as_string();
Application::Settings.Resource = data["General"][StrResourceFolder.data()].as_string(); Application::Settings.Resource = data["General"][StrResourceFolder.data()].as_string();
Application::Settings.Key = data["General"][StrAuthKey.data()].as_string(); Application::Settings.Key = data["General"][StrAuthKey.data()].as_string();
} if (!data["General"][StrSendErrors.data()].is_boolean()
// added later, so behaves differently || !data["General"][StrSendErrorsMessageEnabled.data()].is_boolean()) {
if (auto val = GeneralTable[StrSendErrors].value<bool>(); val.has_value()) {
Application::Settings.SendErrors = val.value();
} else {
// dont throw, instead write it into the file and use default
WriteSendErrors(std::string(name)); WriteSendErrors(std::string(name));
}
if (auto val = GeneralTable[StrSendErrorsMessageEnabled].value<bool>(); val.has_value()) {
Application::Settings.SendErrorsMessageEnabled = val.value();
} else { } else {
// no idea what to do here, ignore...? Application::Settings.SendErrors = data["General"][StrSendErrors.data()].as_boolean();
// this entire toml parser sucks and is replaced in the upcoming lua. Application::Settings.SendErrorsMessageEnabled = data["General"][StrSendErrorsMessageEnabled.data()].as_boolean();
}
} catch (const std::exception& err) { } catch (const std::exception& err) {
beammp_error("Error parsing config file value: " + std::string(err.what())); beammp_error("Error parsing config file value: " + std::string(err.what()));
mFailed = true; mFailed = true;

View File

@@ -26,7 +26,7 @@ void THeartbeatThread::operator()() {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue; continue;
} }
debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)"); beammp_debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
Last = Body; Last = Body;
LastNormalUpdateTime = Now; LastNormalUpdateTime = Now;
@@ -42,7 +42,7 @@ void THeartbeatThread::operator()() {
{ { "response-body", T }, { { "response-body", T },
{ "request-body", Body } }); { "request-body", Body } });
Sentry.SetTransaction(transaction); Sentry.SetTransaction(transaction);
trace("sending log to sentry: " + std::to_string(status) + " for " + transaction); beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")"); Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
}; };
@@ -51,7 +51,7 @@ void THeartbeatThread::operator()() {
T = Http::POST(Application::GetBackendHostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode); T = Http::POST(Application::GetBackendHostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) { if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) {
trace("got " + T + " from backend"); beammp_trace("got " + T + " from backend");
SentryReportError(Application::GetBackendHostname() + Target, ResponseCode); SentryReportError(Application::GetBackendHostname() + Target, ResponseCode);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::this_thread::sleep_for(std::chrono::milliseconds(500));
T = Http::POST(Application::GetBackup1Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode); T = Http::POST(Application::GetBackup1Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
@@ -60,7 +60,7 @@ void THeartbeatThread::operator()() {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::this_thread::sleep_for(std::chrono::milliseconds(500));
T = Http::POST(Application::GetBackup2Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode); T = Http::POST(Application::GetBackup2Hostname(), 443, Target, {}, Body, "application/x-www-form-urlencoded", &ResponseCode);
if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) { if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) {
warn("Backend system refused server! Server will not show in the public server list."); beammp_warn("Backend system refused server! Server will not show in the public server list.");
isAuth = false; isAuth = false;
SentryReportError(Application::GetBackup2Hostname() + Target, ResponseCode); SentryReportError(Application::GetBackup2Hostname() + Target, ResponseCode);
@@ -70,10 +70,10 @@ void THeartbeatThread::operator()() {
if (!isAuth) { if (!isAuth) {
if (T == "2000") { if (T == "2000") {
info(("Authenticated!")); beammp_info(("Authenticated!"));
isAuth = true; isAuth = true;
} else if (T == "200") { } else if (T == "200") {
info(("Resumed authenticated session!")); beammp_info(("Resumed authenticated session!"));
isAuth = true; isAuth = true;
} }
} }

View File

@@ -295,7 +295,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomi
Table.set_function("RemoveVehicle", &LuaAPI::MP::RemoveVehicle); Table.set_function("RemoveVehicle", &LuaAPI::MP::RemoveVehicle);
Table.set_function("GetPlayerVehicles", [&](int ID) -> sol::table { Table.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
return Lua_GetPlayerVehicles(ID); return Lua_GetPlayerVehicles(ID);
})); });
Table.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage); Table.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
Table.set_function("GetPlayers", [&]() -> sol::table { Table.set_function("GetPlayers", [&]() -> sol::table {
return Lua_GetPlayers(); return Lua_GetPlayers();

View File

@@ -1,5 +1,7 @@
#include "TNetwork.h" #include "TNetwork.h"
#include "Client.h" #include "Client.h"
#include "LuaAPI.h"
#include "TLuaEngine.h"
#include <CustomAssert.h> #include <CustomAssert.h>
#include <Http.h> #include <Http.h>
#include <array> #include <array>
@@ -10,7 +12,7 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
, mPPSMonitor(PPSMonitor) , mPPSMonitor(PPSMonitor)
, mResourceManager(ResourceManager) { , mResourceManager(ResourceManager) {
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
debug("Kicking all players due to shutdown"); beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool { Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
if (!client.expired()) { if (!client.expired()) {
ClientKick(*client.lock(), "Server shutdown"); ClientKick(*client.lock(), "Server shutdown");
@@ -39,7 +41,7 @@ void TNetwork::UDPServerMain() {
#ifdef WIN32 #ifdef WIN32
WSADATA data; WSADATA data;
if (WSAStartup(514, &data)) { if (WSAStartup(514, &data)) {
error(("Can't start Winsock!")); beammp_error(("Can't start Winsock!"));
//return; //return;
} }
#endif // WIN32 #endif // WIN32
@@ -52,13 +54,13 @@ void TNetwork::UDPServerMain() {
// Try and bind the socket to the IP and port // Try and bind the socket to the IP and port
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) { if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
error("bind() failed: " + GetPlatformAgnosticErrorString()); beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1); exit(-1);
//return; //return;
} }
info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ") beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients")); + std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
while (!mShutdown) { while (!mShutdown) {
try { try {
@@ -90,7 +92,7 @@ void TNetwork::UDPServerMain() {
return true; return true;
}); });
} catch (const std::exception& e) { } catch (const std::exception& e) {
error(("fatal: ") + std::string(e.what())); beammp_error(("fatal: ") + std::string(e.what()));
} }
} }
} }
@@ -100,7 +102,7 @@ void TNetwork::TCPServerMain() {
#ifdef WIN32 #ifdef WIN32
WSADATA wsaData; WSADATA wsaData;
if (WSAStartup(514, &wsaData)) { if (WSAStartup(514, &wsaData)) {
error("Can't start Winsock!"); beammp_error("Can't start Winsock!");
return; return;
} }
#endif // WIN32 #endif // WIN32
@@ -119,40 +121,40 @@ void TNetwork::TCPServerMain() {
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_port = htons(uint16_t(Application::Settings.Port)); addr.sin_port = htons(uint16_t(Application::Settings.Port));
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) { if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
error("bind() failed: " + GetPlatformAgnosticErrorString()); beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1); exit(-1);
} }
if (Listener == -1) { if (Listener == -1) {
error("Invalid listening socket"); beammp_error("Invalid listening socket");
return; return;
} }
if (listen(Listener, SOMAXCONN)) { if (listen(Listener, SOMAXCONN)) {
error("listen() failed: " + GetPlatformAgnosticErrorString()); beammp_error("listen() failed: " + GetPlatformAgnosticErrorString());
// FIXME leak Listener // FIXME leak Listener
return; return;
} }
info(("Vehicle event network online")); beammp_info(("Vehicle event network online"));
do { do {
try { try {
if (mShutdown) { if (mShutdown) {
debug("shutdown during TCP wait for accept loop"); beammp_debug("shutdown during TCP wait for accept loop");
break; break;
} }
client.SockAddrLen = sizeof(client.SockAddr); client.SockAddrLen = sizeof(client.SockAddr);
client.Socket = accept(Listener, &client.SockAddr, &client.SockAddrLen); client.Socket = accept(Listener, &client.SockAddr, &client.SockAddrLen);
if (client.Socket == -1) { if (client.Socket == -1) {
warn(("Got an invalid client socket on connect! Skipping...")); beammp_warn(("Got an invalid client socket on connect! Skipping..."));
continue; continue;
} }
std::thread ID(&TNetwork::Identify, this, client); std::thread ID(&TNetwork::Identify, this, client);
ID.detach(); // TODO: Add to a queue and attempt to join periodically ID.detach(); // TODO: Add to a queue and attempt to join periodically
} catch (const std::exception& e) { } catch (const std::exception& e) {
error(("fatal: ") + std::string(e.what())); beammp_error(("fatal: ") + std::string(e.what()));
} }
} while (client.Socket); } while (client.Socket);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__)); beammp_debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
CloseSocketProper(client.Socket); CloseSocketProper(client.Socket);
#ifdef WIN32 #ifdef WIN32
@@ -209,7 +211,7 @@ void TNetwork::Authentication(const TConnection& ClientConnection) {
Client->SetIdentifier("ip", str); Client->SetIdentifier("ip", str);
std::string Rc; std::string Rc;
info("Identifying new ClientConnection..."); beammp_info("Identifying new ClientConnection...");
Rc = TCPRcv(*Client); Rc = TCPRcv(*Client);
@@ -259,7 +261,7 @@ void TNetwork::Authentication(const TConnection& ClientConnection) {
Sentry.Log(SentryLevel::Info, "default", "backend returned 0 instead of json (" + std::to_string(ResponseCode) + ")"); Sentry.Log(SentryLevel::Info, "default", "backend returned 0 instead of json (" + std::to_string(ResponseCode) + ")");
} else { // Rc != "0" } else { // Rc != "0"
ClientKick(*Client, "Backend returned invalid auth response format."); ClientKick(*Client, "Backend returned invalid auth response format.");
error("Backend returned invalid auth response format. This should never happen."); beammp_error("Backend returned invalid auth response format. This should never happen.");
auto Lock = Sentry.CreateExclusiveContext(); auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("auth", Sentry.SetContext("auth",
{ { "response-body", Rc }, { { "response-body", Rc },
@@ -286,7 +288,7 @@ void TNetwork::Authentication(const TConnection& ClientConnection) {
return; return;
} }
debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles()); beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> Cl; std::shared_ptr<TClient> Cl;
{ {
@@ -305,18 +307,32 @@ void TNetwork::Authentication(const TConnection& ClientConnection) {
return true; return true;
}); });
auto arg = std::make_unique<TLuaArg>(TLuaArg { { Client->GetName(), Client->GetRoles(), Client->IsGuest() } }); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", Client->GetName(), Client->GetRoles(), Client->IsGuest());
std::any Res = TriggerLuaEvent("onPlayerAuth", false, nullptr, std::move(arg), true); TLuaEngine::WaitForAll(Futures);
if (Res.type() == typeid(int) && std::any_cast<int>(Res)) { bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && bool(Result->Result.as<int>());
});
std::string Reason;
bool NotAllowedWithReason = std::any_of(Futures.begin(), Futures.end(),
[&Reason](const std::shared_ptr<TLuaResult>& Result) -> bool {
if (!Result->Error && Result->Result.is<std::string>()) {
Reason = Result->Result.as<std::string>();
return true;
}
return false;
});
if (NotAllowed) {
ClientKick(*Client, "you are not allowed on the server!"); ClientKick(*Client, "you are not allowed on the server!");
return; return;
} else if (Res.type() == typeid(std::string)) { } else if (NotAllowedWithReason) {
ClientKick(*Client, std::any_cast<std::string>(Res)); ClientKick(*Client, Reason);
return; return;
} }
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) { if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
info("Identification success"); beammp_info("Identification success");
mServer.InsertClient(Client); mServer.InsertClient(Client);
TCPClient(Client); TCPClient(Client);
} else } else
@@ -355,12 +371,12 @@ bool TNetwork::TCPSend(TClient& c, const std::string& Data, bool IsSync) {
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, MSG_NOSIGNAL); int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, MSG_NOSIGNAL);
#endif //WIN32 #endif //WIN32
if (Temp == 0) { if (Temp == 0) {
debug("send() == 0: " + GetPlatformAgnosticErrorString()); beammp_debug("send() == 0: " + GetPlatformAgnosticErrorString());
if (c.GetStatus() > -1) if (c.GetStatus() > -1)
c.SetStatus(-1); c.SetStatus(-1);
return false; return false;
} else if (Temp < 0) { } else if (Temp < 0) {
debug("send() < 0: " + GetPlatformAgnosticErrorString()); //TODO fix it was spamming yet everyone stayed on the server beammp_debug("send() < 0: " + GetPlatformAgnosticErrorString()); //TODO fix it was spamming yet everyone stayed on the server
if (c.GetStatus() > -1) if (c.GetStatus() > -1)
c.SetStatus(-1); c.SetStatus(-1);
CloseSocketProper(c.GetTCPSock()); CloseSocketProper(c.GetTCPSock());
@@ -374,12 +390,12 @@ bool TNetwork::TCPSend(TClient& c, const std::string& Data, bool IsSync) {
bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) { bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
if (BytesRcv == 0) { if (BytesRcv == 0) {
trace("(TCP) Connection closing..."); beammp_trace("(TCP) Connection closing...");
if (c.GetStatus() > -1) if (c.GetStatus() > -1)
c.SetStatus(-1); c.SetStatus(-1);
return false; return false;
} else if (BytesRcv < 0) { } else if (BytesRcv < 0) {
debug("(TCP) recv() failed: " + GetPlatformAgnosticErrorString()); beammp_debug("(TCP) recv() failed: " + GetPlatformAgnosticErrorString());
if (c.GetStatus() > -1) if (c.GetStatus() > -1)
c.SetStatus(-1); c.SetStatus(-1);
CloseSocketProper(c.GetTCPSock()); CloseSocketProper(c.GetTCPSock());
@@ -410,7 +426,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
Data.resize(Header); Data.resize(Header);
} else { } else {
ClientKick(c, "Header size limit exceeded"); ClientKick(c, "Header size limit exceeded");
warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client."); beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
return ""; return "";
} }
BytesRcv = 0; BytesRcv = 0;
@@ -430,7 +446,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
} }
void TNetwork::ClientKick(TClient& c, const std::string& R) { void TNetwork::ClientKick(TClient& c, const std::string& R) {
info("Client kicked: " + R); beammp_info("Client kicked: " + R);
if (!TCPSend(c, "E" + R)) { if (!TCPSend(c, "E" + R)) {
// TODO handle // TODO handle
} }
@@ -446,7 +462,7 @@ void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
while (!c.expired()) { while (!c.expired()) {
auto Client = c.lock(); auto Client = c.lock();
if (Client->GetStatus() < 0) { if (Client->GetStatus() < 0) {
debug("client status < 0, breaking client loop"); beammp_debug("client status < 0, breaking client loop");
break; break;
} }
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) { if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
@@ -461,7 +477,7 @@ void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
QData = Client->MissedPacketQueue().front(); QData = Client->MissedPacketQueue().front();
Client->MissedPacketQueue().pop(); Client->MissedPacketQueue().pop();
} // end locked context } // end locked context
// debug("sending a missed packet: " + QData); // beammp_debug("sending a missed packet: " + QData);
if (!TCPSend(*Client, QData, true)) { if (!TCPSend(*Client, QData, true)) {
if (Client->GetStatus() > -1) if (Client->GetStatus() > -1)
Client->SetStatus(-1); Client->SetStatus(-1);
@@ -496,13 +512,13 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
break; break;
auto Client = c.lock(); auto Client = c.lock();
if (Client->GetStatus() < 0) { if (Client->GetStatus() < 0) {
debug("client status < 0, breaking client loop"); beammp_debug("client status < 0, breaking client loop");
break; break;
} }
auto res = TCPRcv(*Client); auto res = TCPRcv(*Client);
if (res == "") { if (res == "") {
debug("TCPRcv error, break client loop"); beammp_debug("TCPRcv error, break client loop");
break; break;
} }
TServer::GlobalParser(c, res, mPPSMonitor, *this); TServer::GlobalParser(c, res, mPPSMonitor, *this);
@@ -514,7 +530,7 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
auto Client = c.lock(); auto Client = c.lock();
OnDisconnect(c, Client->GetStatus() == -2); OnDisconnect(c, Client->GetStatus() == -2);
} else { } else {
warn("client expired in TCPClient, should never happen"); beammp_warn("client expired in TCPClient, should never happen");
} }
} }
@@ -534,10 +550,10 @@ void TNetwork::UpdatePlayer(TClient& Client) {
} }
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked) { void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked) {
Assert(!ClientPtr.expired()); beammp_assert(!ClientPtr.expired());
auto LockedClientPtr = ClientPtr.lock(); auto LockedClientPtr = ClientPtr.lock();
TClient& c = *LockedClientPtr; TClient& c = *LockedClientPtr;
info(c.GetName() + (" Connection Terminated")); beammp_info(c.GetName() + (" Connection Terminated"));
std::string Packet; std::string Packet;
TClient::TSetOfVehicleData VehicleData; TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope { // Vehicle Data Lock Scope
@@ -554,7 +570,8 @@ void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked
Packet = ("L") + c.GetName() + (" left the server!"); Packet = ("L") + c.GetName() + (" left the server!");
SendToAll(&c, Packet, false, true); SendToAll(&c, Packet, false, true);
Packet.clear(); Packet.clear();
TriggerLuaEvent(("onPlayerDisconnect"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID() } }), false); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", c.GetID());
beammp_ignore(Futures);
if (c.GetTCPSock()) if (c.GetTCPSock())
CloseSocketProper(c.GetTCPSock()); CloseSocketProper(c.GetTCPSock());
if (c.GetDownSock()) if (c.GetDownSock())
@@ -583,18 +600,18 @@ int TNetwork::OpenID() {
} }
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) { void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
Assert(!c.expired()); beammp_assert(!c.expired());
info("Client connected"); beammp_info("Client connected");
auto LockedClient = c.lock(); auto LockedClient = c.lock();
LockedClient->SetID(OpenID()); LockedClient->SetID(OpenID());
info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName()); beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
TriggerLuaEvent("onPlayerConnecting", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false); beammp_ignore(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", LockedClient->GetID()));
SyncResources(*LockedClient); SyncResources(*LockedClient);
if (LockedClient->GetStatus() < 0) if (LockedClient->GetStatus() < 0)
return; return;
(void)Respond(*LockedClient, "M" + Application::Settings.MapName, true); //Send the Map on connect (void)Respond(*LockedClient, "M" + Application::Settings.MapName, true); //Send the Map on connect
info(LockedClient->GetName() + " : Connected"); beammp_info(LockedClient->GetName() + " : Connected");
TriggerLuaEvent("onPlayerJoining", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false); beammp_ignore(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", LockedClient->GetID()));
} }
void TNetwork::SyncResources(TClient& c) { void TNetwork::SyncResources(TClient& c) {
@@ -613,7 +630,7 @@ void TNetwork::SyncResources(TClient& c) {
} }
#ifndef DEBUG #ifndef DEBUG
} catch (std::exception& e) { } catch (std::exception& e) {
error("Exception! : " + std::string(e.what())); beammp_error("Exception! : " + std::string(e.what()));
c.SetStatus(-1); c.SetStatus(-1);
} }
#endif #endif
@@ -631,7 +648,7 @@ void TNetwork::Parse(TClient& c, const std::string& Packet) {
return; return;
case 'S': case 'S':
if (SubCode == 'R') { if (SubCode == 'R') {
debug("Sending Mod Info"); beammp_debug("Sending Mod Info");
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes(); std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
if (ToSend.empty()) if (ToSend.empty())
ToSend = "-"; ToSend = "-";
@@ -646,13 +663,13 @@ void TNetwork::Parse(TClient& c, const std::string& Packet) {
} }
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) { void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/'))); beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
if (!fs::path(UnsafeName).has_filename()) { if (!fs::path(UnsafeName).has_filename()) {
if (!TCPSend(c, "CO")) { if (!TCPSend(c, "CO")) {
// TODO: handle // TODO: handle
} }
warn("File " + UnsafeName + " is not a file!"); beammp_warn("File " + UnsafeName + " is not a file!");
return; return;
} }
auto FileName = fs::path(UnsafeName).filename().string(); auto FileName = fs::path(UnsafeName).filename().string();
@@ -662,7 +679,7 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
if (!TCPSend(c, "CO")) { if (!TCPSend(c, "CO")) {
// TODO: handle // TODO: handle
} }
warn("File " + UnsafeName + " could not be accessed!"); beammp_warn("File " + UnsafeName + " could not be accessed!");
return; return;
} }
@@ -678,7 +695,7 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
} }
if (c.GetDownSock() < 1) { if (c.GetDownSock() < 1) {
error("Client doesn't have a download socket!"); beammp_error("Client doesn't have a download socket!");
if (c.GetStatus() > -1) if (c.GetStatus() > -1)
c.SetStatus(-1); c.SetStatus(-1);
return; return;
@@ -715,7 +732,7 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
TCPSock = c.GetDownSock(); TCPSock = c.GetDownSock();
else else
TCPSock = c.GetTCPSock(); TCPSock = c.GetTCPSock();
info("Split load Socket " + std::to_string(TCPSock)); beammp_info("Split load Socket " + std::to_string(TCPSock));
while (c.GetStatus() > -1 && Sent < Size) { while (c.GetStatus() > -1 && Sent < Size) {
size_t Diff = Size - Sent; size_t Diff = Size - Sent;
if (Diff > Split) { if (Diff > Split) {
@@ -747,7 +764,7 @@ bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
do { do {
intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), 0); intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), 0);
if (Temp < 1) { if (Temp < 1) {
info("Socket Closed! " + std::to_string(socket)); beammp_info("Socket Closed! " + std::to_string(socket));
CloseSocketProper(socket); CloseSocketProper(socket);
return false; return false;
} }
@@ -793,7 +810,7 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
// ignore error // ignore error
(void)SendToAll(LockedClient.get(), ("JWelcome ") + LockedClient->GetName() + "!", false, true); (void)SendToAll(LockedClient.get(), ("JWelcome ") + LockedClient->GetName() + "!", false, true);
TriggerLuaEvent(("onPlayerJoin"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false); beammp_ignore(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", LockedClient->GetID()));
LockedClient->SetIsSyncing(true); LockedClient->SetIsSyncing(true);
bool Return = false; bool Return = false;
bool res = true; bool res = true;
@@ -829,13 +846,13 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
return res; return res;
} }
LockedClient->SetIsSynced(true); LockedClient->SetIsSynced(true);
info(LockedClient->GetName() + (" is now synced!")); beammp_info(LockedClient->GetName() + (" is now synced!"));
return true; return true;
} }
void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel) { void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel) {
if (!Self) if (!Self)
Assert(c); beammp_assert(c);
char C = Data.at(0); char C = Data.at(0);
bool ret = true; bool ret = true;
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool { mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
@@ -899,12 +916,12 @@ bool TNetwork::UDPSend(TClient& Client, std::string Data) const {
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize)); sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize));
if (sendOk == -1) { if (sendOk == -1) {
debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString()); beammp_debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString());
if (Client.GetStatus() > -1) if (Client.GetStatus() > -1)
Client.SetStatus(-1); Client.SetStatus(-1);
return false; return false;
} else if (sendOk == 0) { } else if (sendOk == 0) {
debug(("(UDP) sendto() returned 0")); beammp_debug(("(UDP) sendto() returned 0"));
if (Client.GetStatus() > -1) if (Client.GetStatus() > -1)
Client.SetStatus(-1); Client.SetStatus(-1);
return false; return false;
@@ -922,7 +939,7 @@ std::string TNetwork::UDPRcvFromClient(sockaddr_in& client) const {
#endif // WIN32 #endif // WIN32
if (Rcv == -1) { if (Rcv == -1) {
error("(UDP) Error receiving from client! recvfrom() failed: " + GetPlatformAgnosticErrorString()); beammp_error("(UDP) Error receiving from client! recvfrom() failed: " + GetPlatformAgnosticErrorString());
return ""; return "";
} }
return std::string(Ret.begin(), Ret.begin() + Rcv); return std::string(Ret.begin(), Ret.begin() + Rcv);

View File

@@ -31,22 +31,22 @@ void TSentry::PrintWelcome() {
if (!Application::Settings.SendErrors) { if (!Application::Settings.SendErrors) {
mValid = false; mValid = false;
if (Application::Settings.SendErrorsMessageEnabled) { if (Application::Settings.SendErrorsMessageEnabled) {
info("Opted out of error reporting (SendErrors), Sentry disabled."); beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
} else { } else {
info("Sentry disabled"); beammp_info("Sentry disabled");
} }
} else { } else {
if (Application::Settings.SendErrorsMessageEnabled) { if (Application::Settings.SendErrorsMessageEnabled) {
info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml."); beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
} else { } else {
info("Sentry started"); beammp_info("Sentry started");
} }
} }
} else { } else {
if (Application::Settings.SendErrorsMessageEnabled) { if (Application::Settings.SendErrorsMessageEnabled) {
info("Sentry disabled in unofficial build. Automatic error reporting disabled."); beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
} else { } else {
info("Sentry disabled in unofficial build"); beammp_info("Sentry disabled in unofficial build");
} }
} }
} }

View File

@@ -92,7 +92,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
} }
switch (Code) { switch (Code) {
case 'H': // initial connection case 'H': // initial connection
trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")"); beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
beammp_debug(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")"); beammp_debug(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
if (!Network.SyncClient(Client)) { if (!Network.SyncClient(Client)) {
// TODO handle // TODO handle
@@ -115,12 +115,12 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
ParseVehicle(*LockedClient, Packet, Network); ParseVehicle(*LockedClient, Packet, Network);
return; return;
case 'J': case 'J':
trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
beammp_debug(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_debug(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(LockedClient.get(), Packet, false, true); Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
case 'C': { case 'C': {
trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
beammp_debug(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_debug(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos) if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break; break;
@@ -139,12 +139,12 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
return; return;
} }
case 'E': case 'E':
trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
beammp_debug(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_debug(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
HandleEvent(*LockedClient, Packet); HandleEvent(*LockedClient, Packet);
return; return;
case 'N': case 'N':
trace("got 'N' packet (" + std::to_string(Packet.size()) + ")"); beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true); Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
default: default:
@@ -206,7 +206,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
std::string Data = Packet.substr(3), pid, vid; std::string Data = Packet.substr(3), pid, vid;
switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
case 's': case 's':
trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Data.at(0) == '0') { if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID(); int CarID = c.GetOpenCarID();
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID)); beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
@@ -236,7 +236,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
return; return;
case 'c': case 'c':
trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
pid = Data.substr(0, Data.find('-')); pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1); vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) { if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
@@ -270,7 +270,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
return; return;
case 'd': case 'd':
trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
pid = Data.substr(0, Data.find('-')); pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1); vid = Data.substr(Data.find('-') + 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) { if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
@@ -288,7 +288,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
return; return;
case 'r': case 'r':
trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Pos = int(Data.find('-')); Pos = int(Data.find('-'));
pid = Data.substr(0, Pos++); pid = Data.substr(0, Pos++);
vid = Data.substr(Pos, Data.find(':') - Pos); vid = Data.substr(Pos, Data.find(':') - Pos);
@@ -305,11 +305,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
return; return;
case 't': case 't':
trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(&c, Packet, false, true); Network.SendToAll(&c, Packet, false, true);
return; return;
default: default:
trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")"))); beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
return; return;
} }
} }

View File

@@ -6,9 +6,9 @@
TVehicleData::TVehicleData(int ID, std::string Data) TVehicleData::TVehicleData(int ID, std::string Data)
: mID(ID) : mID(ID)
, mData(std::move(Data)) { , mData(std::move(Data)) {
trace("vehicle " + std::to_string(mID) + " constructed"); beammp_trace("vehicle " + std::to_string(mID) + " constructed");
} }
TVehicleData::~TVehicleData() { TVehicleData::~TVehicleData() {
trace("vehicle " + std::to_string(mID) + " destroyed"); beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
} }

View File

@@ -48,7 +48,7 @@ int main(int argc, char** argv) try {
RegisterThread("Main"); RegisterThread("Main");
trace("Running in debug mode on a debug build"); beammp_trace("Running in debug mode on a debug build");
Sentry.SetupUser(); Sentry.SetupUser();
Sentry.PrintWelcome(); Sentry.PrintWelcome();
@@ -65,8 +65,8 @@ int main(int argc, char** argv) try {
while (!Shutdown) { while (!Shutdown) {
std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::this_thread::sleep_for(std::chrono::milliseconds(50));
} }
info("Shutdown."); beammp_info("Shutdown.");
} catch (const std::exception& e) { } catch (const std::exception& e) {
error(e.what()); beammp_error(e.what());
Sentry.LogException(e, _file_basename, _line); Sentry.LogException(e, _file_basename, _line);
} }