mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-15 03:04:55 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c0c7c5275d |
@@ -7,7 +7,7 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
linux-build:
|
linux-build:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
@@ -20,7 +20,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
echo ${#beammp_sentry_url}
|
echo ${#beammp_sentry_url}
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
@@ -56,7 +56,7 @@ jobs:
|
|||||||
|
|
||||||
run-tests:
|
run-tests:
|
||||||
needs: linux-build
|
needs: linux-build
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@master
|
- uses: actions/download-artifact@master
|
||||||
@@ -68,7 +68,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y liblua5.3-0 libssl3 curl
|
sudo apt-get install -y liblua5.3 openssl
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
working-directory: ${{github.workspace}}
|
working-directory: ${{github.workspace}}
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ jobs:
|
|||||||
uses: lukka/run-vcpkg@v7
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio boost-uuid'
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: "06b5f4a769d848d1a20fa0acd556019728b56273"
|
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ jobs:
|
|||||||
|
|
||||||
upload-release-files-linux:
|
upload-release-files-linux:
|
||||||
name: Upload Linux Release Files
|
name: Upload Linux Release Files
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-latest
|
||||||
needs: create-release
|
needs: create-release
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
@@ -42,7 +42,7 @@ jobs:
|
|||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev libboost-dev libboost1.74-all-dev libboost1.74-dev
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
@@ -83,9 +83,9 @@ jobs:
|
|||||||
uses: lukka/run-vcpkg@v7
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio'
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: '06b5f4a769d848d1a20fa0acd556019728b56273'
|
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
|
|||||||
@@ -31,6 +31,3 @@
|
|||||||
[submodule "deps/doctest"]
|
[submodule "deps/doctest"]
|
||||||
path = deps/doctest
|
path = deps/doctest
|
||||||
url = https://github.com/doctest/doctest
|
url = https://github.com/doctest/doctest
|
||||||
[submodule "deps/lk-result"]
|
|
||||||
path = deps/lk-result
|
|
||||||
url = https://gitlab.com/lionkor/lk-result.git
|
|
||||||
|
|||||||
+37
-125
@@ -4,32 +4,11 @@ cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
|
|||||||
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
||||||
https://github.com/BeamMP/BeamMP-Server")
|
https://github.com/BeamMP/BeamMP-Server")
|
||||||
|
|
||||||
include(FetchContent)
|
|
||||||
FetchContent_Declare(
|
|
||||||
cmake-tools
|
|
||||||
GIT_REPOSITORY https://github.com/brobeson/cmake-tools.git
|
|
||||||
GIT_TAG main
|
|
||||||
)
|
|
||||||
FetchContent_MakeAvailable(cmake-tools)
|
|
||||||
list(APPEND CMAKE_MODULE_PATH "${cmake-tools_SOURCE_DIR}")
|
|
||||||
|
|
||||||
include(CMakeToolsVersionFromGit)
|
|
||||||
|
|
||||||
execute_process(
|
|
||||||
COMMAND git log -1 --format=%h
|
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
|
|
||||||
OUTPUT_VARIABLE GIT_HASH
|
|
||||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
|
||||||
)
|
|
||||||
|
|
||||||
project(BeamMP-Server
|
project(BeamMP-Server
|
||||||
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
|
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
|
||||||
HOMEPAGE_URL https://beammp.com
|
HOMEPAGE_URL https://beammp.com
|
||||||
LANGUAGES CXX C)
|
LANGUAGES CXX C)
|
||||||
|
|
||||||
# quality of life stuff
|
|
||||||
set(CMAKE_COLOR_DIAGNOSTICS ON)
|
|
||||||
|
|
||||||
find_package(Git REQUIRED)
|
find_package(Git REQUIRED)
|
||||||
# Update submodules as needed
|
# Update submodules as needed
|
||||||
option(GIT_SUBMODULE "Check submodules during build" ON)
|
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||||
@@ -43,46 +22,47 @@ if(GIT_SUBMODULE)
|
|||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|
||||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
||||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
||||||
|
|
||||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/websocketpp")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps")
|
||||||
|
|
||||||
option(WIN32_STATIC_RUNTIME "Build statically-linked runtime on windows (don't touch unless you know what you're doing)" ON)
|
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
||||||
|
|
||||||
# ------------------------ APPLE ---------------------------------
|
# ------------------------ APPLE ---------------------------------
|
||||||
if(APPLE)
|
if(APPLE)
|
||||||
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
|
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||||
set(LUA_INCLUDE_DIR /opt/homebrew/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
|
||||||
link_directories(/opt/homebrew/Cellar/lua@5.3/5.3.6/lib)
|
|
||||||
else()
|
|
||||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
|
||||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
|
||||||
endif()
|
|
||||||
set(LUA_LIBRARIES lua)
|
set(LUA_LIBRARIES lua)
|
||||||
if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
|
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||||
include_directories(/opt/homebrew/opt/openssl@1.1/include)
|
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||||
link_directories(/opt/homebrew/opt/openssl@1.1/lib)
|
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||||
else()
|
|
||||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
|
||||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
|
||||||
endif()
|
|
||||||
# ------------------------ WINDOWS ---------------------------------
|
# ------------------------ WINDOWS ---------------------------------
|
||||||
elseif (WIN32)
|
elseif (WIN32)
|
||||||
if (WIN32_STATIC_RUNTIME)
|
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||||
endif()
|
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||||
# ------------------------ UNIX ------------------------------------
|
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||||
|
# ------------------------ LINUX ---------------------------------
|
||||||
elseif (UNIX)
|
elseif (UNIX)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++ -static-libgcc")
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
||||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2")
|
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
||||||
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
||||||
if (SANITIZE)
|
if (SANITIZE)
|
||||||
message(STATUS "sanitize is ON")
|
message(STATUS "sanitize is ON")
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize={address,thread,undefined}")
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
||||||
endif (SANITIZE)
|
endif (SANITIZE)
|
||||||
endif ()
|
endif ()
|
||||||
|
|
||||||
|
include_directories("include/sentry-native/include")
|
||||||
set(BUILD_SHARED_LIBS OFF)
|
set(BUILD_SHARED_LIBS OFF)
|
||||||
# ------------------------ SENTRY ---------------------------------
|
# ------------------------ SENTRY ---------------------------------
|
||||||
message(STATUS "Checking for Sentry URL")
|
message(STATUS "Checking for Sentry URL")
|
||||||
@@ -99,7 +79,10 @@ endif()
|
|||||||
add_subdirectory("deps/sentry-native")
|
add_subdirectory("deps/sentry-native")
|
||||||
|
|
||||||
# ------------------------ C++ SETUP ---------------------------------
|
# ------------------------ C++ SETUP ---------------------------------
|
||||||
set(CMAKE_CXX_STANDARD 20)
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
if (MSVC)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
||||||
|
endif ()
|
||||||
|
|
||||||
# ------------------------ DEPENDENCIES ------------------------------
|
# ------------------------ DEPENDENCIES ------------------------------
|
||||||
message(STATUS "Adding local source dependencies")
|
message(STATUS "Adding local source dependencies")
|
||||||
@@ -113,8 +96,6 @@ include(FindOpenSSL)
|
|||||||
include(FindThreads)
|
include(FindThreads)
|
||||||
include(FindZLIB)
|
include(FindZLIB)
|
||||||
|
|
||||||
find_package(Boost 1.70 REQUIRED COMPONENTS system)
|
|
||||||
|
|
||||||
set(BeamMP_Sources
|
set(BeamMP_Sources
|
||||||
include/TConsole.h src/TConsole.cpp
|
include/TConsole.h src/TConsole.cpp
|
||||||
include/TServer.h src/TServer.cpp
|
include/TServer.h src/TServer.cpp
|
||||||
@@ -137,86 +118,33 @@ set(BeamMP_Sources
|
|||||||
include/ArgsParser.h src/ArgsParser.cpp
|
include/ArgsParser.h src/ArgsParser.cpp
|
||||||
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
||||||
include/Environment.h
|
include/Environment.h
|
||||||
include/BoostAliases.h
|
|
||||||
include/Uuid.h src/Uuid.cpp
|
|
||||||
)
|
)
|
||||||
|
|
||||||
set(BeamMP_Includes
|
set(BeamMP_Includes
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
|
||||||
${LUA_INCLUDE_DIR}
|
${LUA_INCLUDE_DIR}
|
||||||
${CURL_INCLUDE_DIRS}
|
${CURL_INCLUDE_DIRS}
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib"
|
"include/tomlplusplus"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline"
|
"include/sentry-native/include"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include"
|
"include/curl/include"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/lk-result/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/fmt/include"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
set(BeamMP_Definitions
|
set(BeamMP_Definitions
|
||||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
||||||
BEAMMP_GIT_HASH="${GIT_HASH}"
|
|
||||||
LK_RESULT_USE_FMT
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if (WIN32)
|
|
||||||
list(APPEND BeamMP_Definitions _WIN32_WINNT=0x0601)
|
|
||||||
list(APPEND BeamMP_Definitions _CRT_SECURE_NO_WARNINGS)
|
|
||||||
endif()
|
|
||||||
if (UNIX)
|
|
||||||
set(BeamMP_CompileOptions
|
|
||||||
-Wall
|
|
||||||
-Wextra
|
|
||||||
-Wpedantic
|
|
||||||
|
|
||||||
-Werror=uninitialized
|
|
||||||
-Werror=float-equal
|
|
||||||
-Werror=pointer-arith
|
|
||||||
-Werror=double-promotion
|
|
||||||
-Werror=write-strings
|
|
||||||
-Werror=cast-qual
|
|
||||||
-Werror=init-self
|
|
||||||
-Werror=cast-align
|
|
||||||
-Werror=unreachable-code
|
|
||||||
-Werror=strict-aliasing -fstrict-aliasing
|
|
||||||
-Werror=redundant-decls
|
|
||||||
-Werror=missing-declarations
|
|
||||||
-Werror=missing-field-initializers
|
|
||||||
-Werror=write-strings
|
|
||||||
-Werror=ctor-dtor-privacy
|
|
||||||
-Wswitch-enum
|
|
||||||
-Wswitch-default
|
|
||||||
-Werror=old-style-cast
|
|
||||||
-Werror=overloaded-virtual
|
|
||||||
-Werror=overloaded-virtual
|
|
||||||
-Werror=missing-include-dirs
|
|
||||||
-Werror=unused-result
|
|
||||||
|
|
||||||
-fstack-protector
|
|
||||||
-Wzero-as-null-pointer-constant
|
|
||||||
)
|
|
||||||
else()
|
|
||||||
set(BeamMP_CompileOptions
|
|
||||||
/bigobj
|
|
||||||
/INCREMENTAL:NO /NODEFAULTLIB:MSVCRT /NODEFAULTLIB:LIBCMT
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
set(BeamMP_Libraries
|
set(BeamMP_Libraries
|
||||||
Boost::boost
|
|
||||||
Boost::system
|
|
||||||
doctest::doctest
|
doctest::doctest
|
||||||
OpenSSL::SSL
|
OpenSSL::SSL
|
||||||
OpenSSL::Crypto
|
OpenSSL::Crypto
|
||||||
sol2::sol2
|
sol2::sol2
|
||||||
|
fmt::fmt
|
||||||
Threads::Threads
|
Threads::Threads
|
||||||
ZLIB::ZLIB
|
ZLIB::ZLIB
|
||||||
${LUA_LIBRARIES}
|
${LUA_LIBRARIES}
|
||||||
commandline
|
commandline
|
||||||
sentry
|
sentry
|
||||||
fmt::fmt
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if (WIN32)
|
if (WIN32)
|
||||||
@@ -235,19 +163,11 @@ target_compile_definitions(BeamMP-Server PRIVATE
|
|||||||
DOCTEST_CONFIG_DISABLE
|
DOCTEST_CONFIG_DISABLE
|
||||||
)
|
)
|
||||||
|
|
||||||
target_compile_options(BeamMP-Server PRIVATE
|
target_include_directories(BeamMP-Server PUBLIC
|
||||||
${BeamMP_CompileOptions}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server PRIVATE
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server SYSTEM PRIVATE
|
|
||||||
${BeamMP_Includes}
|
${BeamMP_Includes}
|
||||||
)
|
)
|
||||||
|
|
||||||
target_link_libraries(BeamMP-Server
|
target_link_libraries(BeamMP-Server
|
||||||
${BeamMP_Libraries}
|
${BeamMP_Libraries}
|
||||||
${BeamMP_PlatformLibs}
|
${BeamMP_PlatformLibs}
|
||||||
)
|
)
|
||||||
@@ -265,19 +185,11 @@ if(BUILD_TESTS)
|
|||||||
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
||||||
${BeamMP_Definitions}
|
${BeamMP_Definitions}
|
||||||
)
|
)
|
||||||
|
|
||||||
target_compile_options(BeamMP-Server-tests PRIVATE
|
|
||||||
${BeamMP_CompileOptions}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server-tests PRIVATE
|
target_include_directories(BeamMP-Server-tests PUBLIC
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server-tests SYSTEM PRIVATE
|
|
||||||
${BeamMP_Includes}
|
${BeamMP_Includes}
|
||||||
)
|
)
|
||||||
|
|
||||||
target_link_libraries(BeamMP-Server-tests
|
target_link_libraries(BeamMP-Server-tests
|
||||||
${BeamMP_Libraries}
|
${BeamMP_Libraries}
|
||||||
${BeamMP_PlatformLibs}
|
${BeamMP_PlatformLibs}
|
||||||
|
|||||||
-111
@@ -1,111 +0,0 @@
|
|||||||
# Contributing to BeamMP-Server
|
|
||||||
|
|
||||||
Unlike other parts of BeamMP, the BeamMP-Server does not have any dependency to the BeamNG.drive game.
|
|
||||||
|
|
||||||
To contribute *C++ code*, you'll need a MacOS, Linux or Windows PC, and intermediate to advanced knowledge of C++.
|
|
||||||
For reference, you should know be reasonably comfortable with the STL, the concept of RAII, templates, and generally know how to read & write post-C++17 code. To contribute anything else, you won't need most of this (though it'd be helpful to have some vocabulary about computers).
|
|
||||||
|
|
||||||
# Ways to Contribute
|
|
||||||
|
|
||||||
## Bug Reports
|
|
||||||
|
|
||||||
If you work with BeamMP-Server, either by simply using it, or even writing plugins for it, and you run into any issues, we definitely want to know about it. Please use [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues) and select the "Bug" template, read it, and fill it out accordingly.
|
|
||||||
|
|
||||||
## Bug Fixes
|
|
||||||
|
|
||||||
If you are interested in fixing bugs, check out the [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues). There, you can pick any issue that has nobody assigned to it. For example, some bugs which we definitely need some help with are marked with the "help wanted" tag.
|
|
||||||
|
|
||||||
Once you picked a bug, you need to reproduce it. Start by following the instructions in the bug report, and don't be afraid to ask for more information or clarification on the issue itself.
|
|
||||||
|
|
||||||
Refer to [getting started with the codebase](#getting-started-with-the-codebase) for more information on how to build the server. You can also ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
If you want to add new features, please make an issue for it first or ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
|
||||||
|
|
||||||
You need to make sure the feature isn't being worked on by someone else, and aligns with the vision we have for the server.
|
|
||||||
|
|
||||||
# Git Guidelines
|
|
||||||
|
|
||||||
**Read this carefully. Failing to follow these rules results in your changes not being accepted**. This applies for outside contributors, members of the BeamMP development team ("BeamMP Developers"), project owners, maintainers, frequent contributors, and literally everyone else. **It applies to everyone**.
|
|
||||||
|
|
||||||
## How to Commit
|
|
||||||
|
|
||||||
Commit messages **MUST** (mandatory):
|
|
||||||
|
|
||||||
- start with a **lower case action verb in present tense**, for example `add`, `fix`, `implement`, `refactor`, `remove`, `rename`. *Counter examples (these are bad): ~~`Fixed`, `fixing`, `added`, `removing`~~*.
|
|
||||||
- not have a first line much longer than 70 characters.
|
|
||||||
- explain briefly the changes made.
|
|
||||||
- reference the issue by number, if there is an issue the commit addresses, like so: `#<number>`. Example: `#123`.
|
|
||||||
|
|
||||||
If any of these are not followed, **your changes will not be accepted.**
|
|
||||||
|
|
||||||
Commit messages **SHOULD** (optional, "nice to have"):
|
|
||||||
|
|
||||||
- only address one "atomic" change.
|
|
||||||
- have an empty second line, and the subsequent lines explaining the changes in more detail (if more detail is available).
|
|
||||||
|
|
||||||
Commits may be squashed (via a Git "interactive rebase") in order to satisfy these rules, but history that is >1h old should not be rewritten if possible. Force pushes are ugly ;)
|
|
||||||
|
|
||||||
## Pulling, Merging
|
|
||||||
|
|
||||||
Do **NOT** pull with merge. This is the default git behavior for `git pull`, but creates ugly and unnecessary commit messages like `"merge origin/master into master"`. Instead, pull with rebase, for example via `git pull -r`. If you get conflicts, resolve them properly.
|
|
||||||
|
|
||||||
The only acceptable merge commits are those which actually merge functionally different branches into each other, for example for merging one feature branch into another.
|
|
||||||
|
|
||||||
## Branches
|
|
||||||
|
|
||||||
### Which branch should I base my work on?
|
|
||||||
|
|
||||||
Each *feature* or *bug-fix* is implemented on a new Git branch, branched off of the branch it should be based on. The `master` branch is usually stable, so we don't do development on it. It is always a safe bet to branch off of `master`, but it may be more work to merge later. Branches to base your work on are usually branches like `rc-v3.3.0`, when the latest public version is `3.2.0`, for example. These can often be found in Pull-Requests on GitHub which are tagged `Release Candidate`.
|
|
||||||
|
|
||||||
## Unit tests & CI/CD
|
|
||||||
|
|
||||||
We use GitHub Actions, which runs our unit-tests. PR's which fail these tests, or even fail any of our actions (which run automatically), will not be merged and require further changes until they compile, link, and all tests pass properly. If you have issues with this, feel free to ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`)
|
|
||||||
|
|
||||||
### What should I call by branch?
|
|
||||||
|
|
||||||
Keep branch names **unique**, **descriptive**, and **shorter than 30 characters**. Names must be in present-tense, such as `fix-xyz`, **not** ~~`fixing-xyz`~~.
|
|
||||||
|
|
||||||
We generally use *feature branches*, so we keep one branch per feature or fix.
|
|
||||||
|
|
||||||
For example:
|
|
||||||
- You want to fix issue number #123? You could call the branch `fix-123`.
|
|
||||||
- You want to add a feature described in issue #456? You could call the branch `implement-456`.
|
|
||||||
- You want to add a feature or fix a bug that has no issue? You should probably make an issue for it first! Or, if you're not ready for that yet, you could call it by the feature name or bug description, for example for a bug that makes cars disappear: `fix-disappearing-cars`.
|
|
||||||
|
|
||||||
## Pull Requests, Code Review
|
|
||||||
|
|
||||||
Once you are ready to show what you did, and get feedback on it, you open a Pull-Request on GitHub. Please make sure to pick the right branches, and a descriptive title. Mention any related issues with `#<issue number>`, for example `#123`.
|
|
||||||
|
|
||||||
Make sure to explain what the PR does, what it fixes, and what needs to still be done (if anything).
|
|
||||||
|
|
||||||
A BeamMP-Developer must review your code in detail, and leave a review. If this takes too long, feel free to @ a maintainer/developer, or leave another comment on the PR. It helps to say something like "Ready for review", for example.
|
|
||||||
|
|
||||||
# Getting Started with the Codebase
|
|
||||||
|
|
||||||
1. Look at current Pull-Requests, look at the git branches, or ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`), in order to find out which branch you should work on to minimize conflict. See [this section on branches](#branches) for more info.
|
|
||||||
2. Fork the repository (with that branch) on GitHub. GitHub, by default, gives you only the `master` branch when forking, so make sure you fork with other branches enabled when you want to work on a branch that isn't master (it's a checkbox when you fork).
|
|
||||||
3. Clone the fork to your local machine.
|
|
||||||
4. Check out the branch you want to work on (see 1.).
|
|
||||||
5. Run `git submodule update --init --recursive`.
|
|
||||||
6. Make a new branch for your feature or fix from the branch you are on. You can do this via `git checkout -b <branch name>`. See [this section on branches](#branches) for more info on branch naming.
|
|
||||||
7. Install all dependencies. Those are usually listed in the `README.md` in the branch you're in, or, more reliably, in one of the files in `.github/workflows` (if you can read `yaml`).
|
|
||||||
8. Run CMake to configure the project. You can find tutorials on this online. You will want to tell CMake to build with `CMAKE_BUILD_TYPE=Debug`, for example by passing it to CMake via the commandline switch `-DCMAKE_BUILD_TYPE=Debug`. You may also want to turn off sentry by setting `SENTRY_BACKEND=none` (for example via commandline switch `-DSENTRY_BACKEND=none`). An example invocation on Linux with GNU make would be
|
|
||||||
`cmake . -DCMAKE_BUILD_TYPE=Debug -DSENTRY_BACKEND=none` .
|
|
||||||
9. Build the `BeamMP-Server` target to build the BeamMP-Server, or the `BeamMP-Server-tests` target to build the unit-tests (does not include a working server). In the example from 8. (on Linux), you could build with `make BeamMP-Server`, `make -j BeamMP-Server` or `cmake --build . --parallel --target BeamMP-Server` . Or, on Windows, (in Visual Studio), you would just press some big green "run" or "debug" button.
|
|
||||||
10. When making changes, refer to [this section on how to commit properly](#how-to-commit). Not following those guidelines will result in your changes being rejected, so please take a look.
|
|
||||||
11. Make sure to add Unit-tests with `doctest` if you build new stuff. You can find examples all over the latest version of the codebase (search for `TEST_CASE`).
|
|
||||||
|
|
||||||
# Code Guidelines
|
|
||||||
|
|
||||||
## Formatting
|
|
||||||
|
|
||||||
1. Use `clang-format` to format your code before committig. A `.clang-format` file is provided in the root of the repository.
|
|
||||||
2. All identifiers, type names, function names, etc. should be `PascalCase`. Type names may also have the `T` prefix, although this is not enforced (for example `TNetwork`).
|
|
||||||
|
|
||||||
## Modular code
|
|
||||||
|
|
||||||
Write code that is modular and testable. Generally, if you can write a good unit-test for it, it's modular. If you can't, it's not.
|
|
||||||
|
|
||||||
Don't overdo it though - sometimes its okay to just write code, do the job, be done with it. You'll get feedback on this in the code review for your PR.
|
|
||||||
+3
-29
@@ -1,44 +1,18 @@
|
|||||||
# v3.2.0
|
|
||||||
|
|
||||||
- ADDED `settings` command, which lets you `get`, `list`, and `set` config options from the console
|
|
||||||
- ADDED `debug` command, which shows info about connected clients & networking (for developers)
|
|
||||||
- ADDED `Util.GenerateUUID()`, which generates an RFC4122 UUID (universally unique identifier)
|
|
||||||
- ADDED `version` command, which shows version information
|
|
||||||
- ADDED `onPlayerRequestMods` event, letting Lua disallow individual mods from being sent to clients
|
|
||||||
- CHANGED `onShutdown` to be called before all players are kicked
|
|
||||||
|
|
||||||
# v3.1.1
|
|
||||||
|
|
||||||
- FIXED bug which caused GetPlayerIdentifiers, GetPlayerName, etc not to work in `onPlayerDisconnect`
|
|
||||||
- FIXED some issues which could cause the server to crash when receiving malformed data
|
|
||||||
- FIXED a bug which caused a server to crash during authentication when receiving malformed data
|
|
||||||
- FIXED minor vulnerability in chat message handling
|
|
||||||
- FIXED a minor formatting bug in the `status` command
|
|
||||||
|
|
||||||
# v3.1.0
|
# v3.1.0
|
||||||
|
|
||||||
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
|
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
|
||||||
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
|
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
|
||||||
- ADDED Util.JsonEncode() and Util.JsonDecode(), which turn lua tables into json and vice-versa
|
- ADDED MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa
|
||||||
- ADDED FS.ListFiles and FS.ListDirectories
|
- ADDED FS.ListFiles and FS.ListDirectories
|
||||||
- ADDED onFileChanged event, triggered when a server plugin file changes
|
- ADDED onFileChanged event, triggered when a server plugin file changes
|
||||||
- ADDED MP.GetPositionRaw(), which can be used to retrieve the latest position packet per player, per vehicle
|
- FIXED `ip` in MP.GetIdentifiers
|
||||||
- ADDED error messages to some lua functions
|
- FIXED issue with client->server events which contain ':'
|
||||||
- ADDED HOME and END button working in console
|
|
||||||
- ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON
|
|
||||||
- ADDED identifiers (beammp id, ip) to onPlayerAuth (4th argument)
|
|
||||||
- ADDED more network debug logging
|
|
||||||
- CHANGED all networking to be more stable, performant, and safe
|
|
||||||
- FIXED `ip` in MP.GetPlayerIdentifiers
|
|
||||||
- FIXED issue with client->server events which contain `:`
|
|
||||||
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||||
- FIXED onInit not being called on hot-reload
|
- FIXED onInit not being called on hot-reload
|
||||||
- FIXED incorrect timing calculation of Lua EventTimer loop
|
- FIXED incorrect timing calculation of Lua EventTimer loop
|
||||||
- FIXED bug which caused hot-reload not to report syntax errors
|
- FIXED bug which caused hot-reload not to report syntax errors
|
||||||
- FIXED missing error messages on some event handler calls
|
- FIXED missing error messages on some event handler calls
|
||||||
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
|
|
||||||
- FIXED server not handling binary UDP packets properly
|
|
||||||
- REMOVED "Backend response failed to parse as valid json" message
|
|
||||||
|
|
||||||
# v3.0.2
|
# v3.0.2
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
||||||
|
|
||||||
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
||||||
The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
The server is the point throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
||||||
|
|
||||||
**For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
|
**For Linux, you __need__ the runtime dependencies, listed below under "prerequisites".**
|
||||||
|
|
||||||
## Support + Contact
|
## Support + Contact
|
||||||
|
|
||||||
@@ -14,7 +14,6 @@ Feel free to ask any questions via the following channels:
|
|||||||
|
|
||||||
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
|
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
|
||||||
- **Discord**: [click for invite](https://discord.gg/beammp)
|
- **Discord**: [click for invite](https://discord.gg/beammp)
|
||||||
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
|
|
||||||
|
|
||||||
## Minimum Requirements
|
## Minimum Requirements
|
||||||
|
|
||||||
@@ -29,21 +28,21 @@ These values are guesstimated and are subject to change with each release.
|
|||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" or "good first issue" label or with nobody assigned.
|
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column.
|
||||||
|
|
||||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) and at the [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer). Any issues that have the "help wanted" label or don't have anyone assigned and any trello cards that aren't assigned or in the "In-Progress" section are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||||
|
|
||||||
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
||||||
|
|
||||||
If you need support with understanding the codebase, please write us in the Discord. You'll need to be proficient in modern C++.
|
If you need support with understanding the codebase, please write us in the discord. You'll need to be proficient in modern C++.
|
||||||
|
|
||||||
## About Building from Source
|
## About Building from Source
|
||||||
|
|
||||||
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.1.0`.
|
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`.
|
||||||
|
|
||||||
## Supported Operating Systems
|
## Supported Operating Systems
|
||||||
|
|
||||||
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and sometimes Linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
|
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute windows binaries and sometimes linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
|
||||||
|
|
||||||
Recommended compilers: MSVC, GCC, CLANG.
|
Recommended compilers: MSVC, GCC, CLANG.
|
||||||
|
|
||||||
@@ -51,132 +50,72 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__**
|
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
||||||
|
|
||||||
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
#### Windows
|
#### Windows
|
||||||
|
|
||||||
There are **no runtime libraries** needed for Windows.
|
|
||||||
|
|
||||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||||
|
|
||||||
Dependencies for **Windows** can be installed with `vcpkg`.
|
Dependencies for **windows** can be installed with `vcpkg`.
|
||||||
These are:
|
These are:
|
||||||
```
|
```
|
||||||
lua zlib rapidjson openssl websocketpp curl boost
|
lua
|
||||||
|
zlib
|
||||||
|
rapidjson
|
||||||
|
openssl
|
||||||
|
websocketpp
|
||||||
|
curl
|
||||||
```
|
```
|
||||||
The triplet we use for releases is `x64-windows-static`.
|
|
||||||
|
|
||||||
#### Linux
|
#### Linux
|
||||||
|
|
||||||
We recommend Ubuntu 22.04 or Arch Linux. Any Linux distribution will work, but you have to figure out the package names yourself (please feel free to PR in a change to this README with that info).
|
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
||||||
|
|
||||||
##### Runtime Dependencies
|
Runtime dependencies for **linux** are (debian/ubuntu):
|
||||||
|
|
||||||
These are needed to *run* the server.
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>
|
|
||||||
Ubuntu 22.04
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
`apt-get install` the following libraries:
|
|
||||||
```
|
```
|
||||||
liblua5.3-0
|
|
||||||
libssl3
|
|
||||||
curl
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>
|
|
||||||
Arch Linux
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
`pacman -Syu` the following libraries:
|
|
||||||
```
|
|
||||||
lua53
|
|
||||||
openssl
|
|
||||||
curl
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
##### Build Dependencies
|
|
||||||
These are needed for you to *build* the server, in addition to the [runtime dependencies](#runtime-dependencies).
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>
|
|
||||||
Ubuntu 22.04
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
`apt-get install` the following libraries and programs:
|
|
||||||
```
|
|
||||||
git
|
|
||||||
libz-dev
|
libz-dev
|
||||||
rapidjson-dev
|
rapidjson-dev
|
||||||
liblua5.3
|
liblua5.3
|
||||||
libssl-dev
|
libssl-dev
|
||||||
libwebsocketpp-dev
|
libwebsocketpp-dev
|
||||||
libcurl4-openssl-dev
|
libcurl4-openssl-dev
|
||||||
cmake
|
|
||||||
g++-10
|
|
||||||
libboost1.74-all-dev
|
|
||||||
libssl3
|
|
||||||
curl
|
|
||||||
```
|
```
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
Build-time dependencies for **linux** are:
|
||||||
<summary>
|
|
||||||
Arch Linux
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
`pacman -Syu` the following libraries and programs:
|
|
||||||
```
|
```
|
||||||
lua53
|
|
||||||
openssl
|
|
||||||
curl
|
|
||||||
git
|
git
|
||||||
|
make
|
||||||
cmake
|
cmake
|
||||||
g++
|
g++
|
||||||
cmake
|
|
||||||
zlib
|
|
||||||
boost
|
|
||||||
websocketpp
|
|
||||||
```
|
```
|
||||||
</details>
|
|
||||||
|
|
||||||
#### macOS
|
For other distributions (e.g. Arch) you want to find packages for:
|
||||||
|
- libz
|
||||||
Dependencies for **macOS** can be installed with homebrew.
|
- rapidjson
|
||||||
```
|
- lua5.3
|
||||||
brew install lua@5.3 rapidjson websocketpp cmake openssl@1.1
|
- ssl / openssl
|
||||||
```
|
- websocketpp
|
||||||
Some packages are included in **macOS** but you might want to install homebrew versions.
|
- curl (with ssl support)
|
||||||
```
|
- \+ the build time dependencies from above
|
||||||
brew install curl zlib git make
|
|
||||||
```
|
|
||||||
|
|
||||||
### How to build
|
### How to build
|
||||||
|
|
||||||
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
|
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||||
|
|
||||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
1. Make sure you have all [prerequisites](#prerequisites) installed
|
||||||
2. Clone the repository in a location of your choice with `git clone https://github.com/BeamMP/BeamMP-Server` .
|
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
||||||
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
|
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
||||||
4. Checkout the branch or tag of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v3.0.1` for version 3.0.1. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`). This may take some time, and will update all submodules and prepare the build.
|
5. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||||
7. Run `make -j` . This step will take some time and will use a lot of CPU and RAM. Remove the `-j` if you run out of memory. *If you change something in the source code, you only have to re-run this step.*
|
6. Run `make`
|
||||||
8. You now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||||
|
|
||||||
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
||||||
|
|
||||||
## Support
|
|
||||||
The BeamMP project is supported by community donations via our [Patreon](https://www.patreon.com/BeamMP). This brings perks such as Patreon-only channels on our Discord, early access to new updates, and more server keys.
|
|
||||||
|
|
||||||
## Copyright
|
## Copyright
|
||||||
|
|
||||||
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
|
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
|
||||||
|
|||||||
Vendored
+1
@@ -1,4 +1,5 @@
|
|||||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
||||||
|
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||||
|
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
||||||
|
|||||||
Vendored
+1
-1
Submodule deps/asio updated: 4915cfd8a1...d038fb3c2f
Vendored
+1
-1
Submodule deps/commandline updated: 470cf2df4a...d6b1c32c8a
Vendored
+1
-1
Submodule deps/cpp-httplib updated: d92c314466...47044c05a8
Vendored
+1
-1
Submodule deps/doctest updated: b7c21ec5ce...7b98851331
Vendored
+1
-1
Submodule deps/fmt updated: c4ee726532...ce246aaf74
Vendored
+1
-1
Submodule deps/json updated: 69d744867f...ede6667858
Vendored
+1
-1
Submodule deps/libzip updated: 5532f9baa0...76df02f86b
Vendored
-1
Submodule deps/lk-result deleted from 4a4eda8092
Vendored
+1
-1
Submodule deps/sentry-native updated: 28be51f5e3...90966cc102
Vendored
+1
-1
Submodule deps/sol2 updated: eba86625b7...c068aefbed
Vendored
+1
-1
Submodule deps/toml11 updated: c7627ff6a1...1400dd223f
@@ -1,6 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <boost/asio.hpp>
|
|
||||||
#include <boost/system/error_code.hpp>
|
|
||||||
|
|
||||||
using namespace boost::asio;
|
|
||||||
+21
-51
@@ -7,10 +7,8 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
|
|
||||||
class TServer;
|
class TServer;
|
||||||
@@ -21,8 +19,9 @@ class TServer;
|
|||||||
#endif // WINDOWS
|
#endif // WINDOWS
|
||||||
|
|
||||||
struct TConnection final {
|
struct TConnection final {
|
||||||
ip::tcp::socket Socket;
|
SOCKET Socket;
|
||||||
ip::tcp::endpoint SockAddr;
|
struct sockaddr SockAddr;
|
||||||
|
socklen_t SockAddrLen;
|
||||||
};
|
};
|
||||||
|
|
||||||
class TClient final {
|
class TClient final {
|
||||||
@@ -34,34 +33,27 @@ public:
|
|||||||
std::unique_lock<std::mutex> Lock;
|
std::unique_lock<std::mutex> Lock;
|
||||||
};
|
};
|
||||||
|
|
||||||
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
explicit TClient(TServer& Server);
|
||||||
TClient(const TClient&) = delete;
|
TClient(const TClient&) = delete;
|
||||||
~TClient();
|
|
||||||
TClient& operator=(const TClient&) = delete;
|
TClient& operator=(const TClient&) = delete;
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
void AddNewCar(int Ident, const std::string& Data);
|
||||||
void SetCarData(int Ident, const std::string& Data);
|
void SetCarData(int Ident, const std::string& Data);
|
||||||
void SetCarPosition(int Ident, const std::string& Data);
|
|
||||||
TVehicleDataLockPair GetAllCars();
|
TVehicleDataLockPair GetAllCars();
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
void SetName(const std::string& Name) { mName = Name; }
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||||
std::string GetCarData(int Ident);
|
std::string GetCarData(int Ident);
|
||||||
std::string GetCarPositionRaw(int Ident);
|
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
||||||
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
||||||
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
||||||
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
void SetStatus(int Status) { mStatus = Status; }
|
||||||
void Disconnect(std::string_view Reason);
|
|
||||||
bool IsDisconnected() const { return !mSocket.is_open(); }
|
|
||||||
// locks
|
// locks
|
||||||
void DeleteCar(int Ident);
|
void DeleteCar(int Ident);
|
||||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||||
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
||||||
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
||||||
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
||||||
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
|
||||||
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
|
||||||
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
|
||||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||||
[[nodiscard]] std::string GetName() const { return mName; }
|
[[nodiscard]] std::string GetName() const { return mName; }
|
||||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
||||||
@@ -69,9 +61,9 @@ public:
|
|||||||
[[nodiscard]] int GetOpenCarID() const;
|
[[nodiscard]] int GetOpenCarID() const;
|
||||||
[[nodiscard]] int GetCarCount() const;
|
[[nodiscard]] int GetCarCount() const;
|
||||||
void ClearCars();
|
void ClearCars();
|
||||||
|
[[nodiscard]] int GetStatus() const { return mStatus; }
|
||||||
[[nodiscard]] int GetID() const { return mID; }
|
[[nodiscard]] int GetID() const { return mID; }
|
||||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||||
bool mUDPCONNECTED = false;
|
|
||||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||||
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
|
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
|
||||||
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
|
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
|
||||||
@@ -79,9 +71,9 @@ public:
|
|||||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
||||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
||||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
||||||
void EnqueuePacket(const std::vector<uint8_t>& Packet);
|
void EnqueuePacket(const std::string& Packet);
|
||||||
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
|
||||||
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
|
||||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||||
@@ -89,24 +81,6 @@ public:
|
|||||||
void UpdatePingTime();
|
void UpdatePingTime();
|
||||||
int SecondsSinceLastPing();
|
int SecondsSinceLastPing();
|
||||||
|
|
||||||
// bytes received on UDP
|
|
||||||
std::atomic_size_t UdpReceived = 0;
|
|
||||||
// number of packets received on UDP
|
|
||||||
std::atomic_size_t UdpPacketsReceived = 0;
|
|
||||||
// bytes sent on UDP
|
|
||||||
std::atomic_size_t UdpSent = 0;
|
|
||||||
// number of packets sent on UDP
|
|
||||||
std::atomic_size_t UdpPacketsSent = 0;
|
|
||||||
|
|
||||||
// bytes received on TCP
|
|
||||||
std::atomic_size_t TcpReceived = 0;
|
|
||||||
// bytes sent on TCP
|
|
||||||
std::atomic_size_t TcpSent = 0;
|
|
||||||
|
|
||||||
TimeType::time_point ConnectionTime {};
|
|
||||||
|
|
||||||
ModMap AllowedMods;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void InsertVehicle(int ID, const std::string& Data);
|
void InsertVehicle(int ID, const std::string& Data);
|
||||||
|
|
||||||
@@ -115,24 +89,20 @@ private:
|
|||||||
bool mIsSynced = false;
|
bool mIsSynced = false;
|
||||||
bool mIsSyncing = false;
|
bool mIsSyncing = false;
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
mutable std::mutex mMissedPacketsMutex;
|
||||||
std::queue<std::vector<uint8_t>> mPacketsSync;
|
std::queue<std::string> mPacketsSync;
|
||||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||||
bool mIsGuest = false;
|
bool mIsGuest = false;
|
||||||
mutable std::mutex mVehicleDataMutex;
|
mutable std::mutex mVehicleDataMutex;
|
||||||
mutable std::mutex mVehiclePositionMutex;
|
|
||||||
TSetOfVehicleData mVehicleData;
|
TSetOfVehicleData mVehicleData;
|
||||||
SparseArray<std::string> mVehiclePosition;
|
|
||||||
std::string mName = "Unknown Client";
|
std::string mName = "Unknown Client";
|
||||||
ip::tcp::socket mSocket;
|
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
||||||
ip::tcp::socket mDownSocket;
|
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
||||||
ip::udp::endpoint mUDPAddress {};
|
|
||||||
int mUnicycleID = -1;
|
int mUnicycleID = -1;
|
||||||
std::string mRole;
|
std::string mRole;
|
||||||
std::string mDID;
|
std::string mDID;
|
||||||
|
int mStatus = 0;
|
||||||
int mID = -1;
|
int mID = -1;
|
||||||
std::chrono::time_point<TimeType> mLastPingTime;
|
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||||
std::mutex mDisconnectMtx;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Returns a valid client, or nullptr if no such client exists
|
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
||||||
std::shared_ptr<TClient> GetClient(class TServer& Server, int ID);
|
|
||||||
|
|||||||
+69
-165
@@ -1,6 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "TSentry.h"
|
#include "TSentry.h"
|
||||||
extern TSentry Sentry;
|
extern TSentry Sentry;
|
||||||
|
|
||||||
@@ -15,59 +14,16 @@ extern TSentry Sentry;
|
|||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <shared_mutex>
|
#include <shared_mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <unordered_map>
|
|
||||||
#include <zlib.h>
|
#include <zlib.h>
|
||||||
|
|
||||||
#include <doctest/doctest.h>
|
#include <doctest/doctest.h>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
#include "Compat.h"
|
||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
#include <boost/container/flat_map.hpp>
|
|
||||||
#include <boost/variant.hpp>
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <variant>
|
|
||||||
|
|
||||||
using TimeType = std::chrono::system_clock;
|
|
||||||
|
|
||||||
#include <lk/Result.h>
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
using Result = lk::Result<T>;
|
|
||||||
using Error = lk::Error;
|
|
||||||
|
|
||||||
// General
|
|
||||||
constexpr std::string_view StrDebug = "Debug";
|
|
||||||
constexpr std::string_view StrPrivate = "Private";
|
|
||||||
constexpr std::string_view StrPort = "Port";
|
|
||||||
constexpr std::string_view StrMaxCars = "MaxCars";
|
|
||||||
constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
|
||||||
constexpr std::string_view StrMap = "Map";
|
|
||||||
constexpr std::string_view StrName = "Name";
|
|
||||||
constexpr std::string_view StrDescription = "Description";
|
|
||||||
constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
|
||||||
constexpr std::string_view StrAuthKey = "AuthKey";
|
|
||||||
constexpr std::string_view StrLogChat = "LogChat";
|
|
||||||
|
|
||||||
// Misc
|
|
||||||
constexpr std::string_view StrSendErrors = "SendErrors";
|
|
||||||
constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
|
||||||
constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
|
||||||
constexpr std::string_view StrIncludeSubdirectories = "IncludeSubdirectories";
|
|
||||||
|
|
||||||
// HTTP
|
|
||||||
constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
|
||||||
constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
|
||||||
constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
|
||||||
constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
|
||||||
constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
|
||||||
constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
|
||||||
|
|
||||||
// Unused
|
|
||||||
constexpr std::string_view StrCustomIP = "Unused.CustomIP";
|
|
||||||
|
|
||||||
struct Version {
|
struct Version {
|
||||||
uint8_t major;
|
uint8_t major;
|
||||||
uint8_t minor;
|
uint8_t minor;
|
||||||
@@ -77,15 +33,6 @@ struct Version {
|
|||||||
std::string AsString();
|
std::string AsString();
|
||||||
};
|
};
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
using SparseArray = std::unordered_map<size_t, T>;
|
|
||||||
|
|
||||||
template <typename K, typename V>
|
|
||||||
using HashMap = std::unordered_map<K, V>;
|
|
||||||
|
|
||||||
using boost::variant;
|
|
||||||
using boost::container::flat_map;
|
|
||||||
|
|
||||||
// static class handling application start, shutdown, etc.
|
// static class handling application start, shutdown, etc.
|
||||||
// yes, static classes, singletons, globals are all pretty
|
// yes, static classes, singletons, globals are all pretty
|
||||||
// bad idioms. In this case we need a central way to access
|
// bad idioms. In this case we need a central way to access
|
||||||
@@ -94,17 +41,30 @@ using boost::container::flat_map;
|
|||||||
class Application final {
|
class Application final {
|
||||||
public:
|
public:
|
||||||
// types
|
// types
|
||||||
|
struct TSettings {
|
||||||
using SettingValue = std::variant<std::string, bool, int>;
|
std::string ServerName { "BeamMP Server" };
|
||||||
using SettingsMap = flat_map<std::string_view, SettingValue>;
|
std::string ServerDesc { "BeamMP Default Description" };
|
||||||
|
std::string Resource { "Resources" };
|
||||||
static SettingsMap mSettings;
|
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||||
|
std::string Key {};
|
||||||
static std::string GetSettingString(std::string_view Name);
|
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||||
static int GetSettingInt(std::string_view Name);
|
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||||
static bool GetSettingBool(std::string_view Name);
|
bool HTTPServerEnabled { false };
|
||||||
|
int MaxPlayers { 8 };
|
||||||
static void SetSetting(std::string_view Name, const SettingValue& value);
|
bool Private { true };
|
||||||
|
int MaxCars { 1 };
|
||||||
|
bool DebugModeEnabled { false };
|
||||||
|
int Port { 30814 };
|
||||||
|
std::string CustomIP {};
|
||||||
|
bool LogChat { true };
|
||||||
|
bool SendErrors { true };
|
||||||
|
bool SendErrorsMessageEnabled { true };
|
||||||
|
int HTTPServerPort { 8080 };
|
||||||
|
std::string HTTPServerIP { "127.0.0.1" };
|
||||||
|
bool HTTPServerUseSSL { false };
|
||||||
|
bool HideUpdateMessages { false };
|
||||||
|
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||||
|
};
|
||||||
|
|
||||||
using TShutdownHandler = std::function<void()>;
|
using TShutdownHandler = std::function<void()>;
|
||||||
|
|
||||||
@@ -118,10 +78,12 @@ public:
|
|||||||
static TConsole& Console() { return *mConsole; }
|
static TConsole& Console() { return *mConsole; }
|
||||||
static std::string ServerVersionString();
|
static std::string ServerVersionString();
|
||||||
static const Version& ServerVersion() { return mVersion; }
|
static const Version& ServerVersion() { return mVersion; }
|
||||||
static uint8_t ClientMajorVersion() { return 2; }
|
static std::string ClientVersionString() { return "2.0"; }
|
||||||
static std::string PPS() { return mPPS; }
|
static std::string PPS() { return mPPS; }
|
||||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||||
|
|
||||||
|
static TSettings Settings;
|
||||||
|
|
||||||
static std::vector<std::string> GetBackendUrlsInOrder() {
|
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||||
return {
|
return {
|
||||||
"backend.beammp.com",
|
"backend.beammp.com",
|
||||||
@@ -161,16 +123,6 @@ public:
|
|||||||
|
|
||||||
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
||||||
|
|
||||||
static std::string SettingToString(const SettingValue& Value);
|
|
||||||
|
|
||||||
// Keeps track of how many packets we dropped on UDP due to fundamentally being malformed
|
|
||||||
static inline std::atomic_size_t MalformedUdpPackets { 0 };
|
|
||||||
// Keeps track of how many packets we dropped on UDP due to
|
|
||||||
// 1) not having a valid (known) player id
|
|
||||||
// 2) player disconnecting
|
|
||||||
// 3) packet failing to parse
|
|
||||||
static inline std::atomic_size_t InvalidUdpPackets { 0 };
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static void SetShutdown(bool Val);
|
static void SetShutdown(bool Val);
|
||||||
|
|
||||||
@@ -183,7 +135,7 @@ private:
|
|||||||
static inline std::mutex mShutdownHandlersMutex {};
|
static inline std::mutex mShutdownHandlersMutex {};
|
||||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||||
|
|
||||||
static inline Version mVersion { 3, 2, 0 };
|
static inline Version mVersion { 3, 1, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride = false);
|
std::string ThreadName(bool DebugModeOverride = false);
|
||||||
@@ -193,7 +145,6 @@ void RegisterThread(const std::string& str);
|
|||||||
#define KB 1024llu
|
#define KB 1024llu
|
||||||
#define MB (KB * 1024llu)
|
#define MB (KB * 1024llu)
|
||||||
#define GB (MB * 1024llu)
|
#define GB (MB * 1024llu)
|
||||||
#define TB (GB * 1024llu)
|
|
||||||
#define SSU_UNRAW SECRET_SENTRY_URL
|
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||||
|
|
||||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||||
@@ -234,88 +185,41 @@ void RegisterThread(const std::string& str);
|
|||||||
|
|
||||||
#endif // defined(DEBUG)
|
#endif // defined(DEBUG)
|
||||||
|
|
||||||
#define beammp_internal_error(x) Application::Console().Write(_this_location + std::string("[INTERNAL ERROR] ") + (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_warn(x) \
|
#define beammp_error(x) \
|
||||||
do { \
|
do { \
|
||||||
try{ \
|
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
||||||
Application::Console().Write(_this_location + std::string("[WARN] ") + (x)); \
|
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_info(x) \
|
#define beammp_lua_error(x) \
|
||||||
do { \
|
do { \
|
||||||
try{ \
|
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
||||||
Application::Console().Write(_this_location + std::string("[INFO] ") + (x)); \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_error(x) \
|
#define beammp_lua_warn(x) \
|
||||||
do { \
|
do { \
|
||||||
try{ \
|
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||||
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
|
||||||
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_lua_error(x) \
|
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||||
do { \
|
#define beammp_debug(x) \
|
||||||
try{ \
|
do { \
|
||||||
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
} catch (const std::exception& e) { \
|
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
} \
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_lua_warn(x) \
|
#define beammp_event(x) \
|
||||||
do { \
|
do { \
|
||||||
try{ \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||||
} catch (const std::exception& e) { \
|
} \
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
|
||||||
#define luaprint(x) \
|
|
||||||
do { \
|
|
||||||
try{ \
|
|
||||||
Application::Console().Write(_this_location + std::string("[LUA] ") + (x)); \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
|
||||||
#define beammp_debug(x) \
|
|
||||||
do { \
|
|
||||||
try{ \
|
|
||||||
if (Application::GetSettingBool("Debug")) { \
|
|
||||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
|
||||||
} \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
|
||||||
#define beammp_event(x) \
|
|
||||||
do { \
|
|
||||||
try{ \
|
|
||||||
if (Application::GetSettingBool("Debug")) { \
|
|
||||||
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
|
||||||
} \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
|
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
// trace() is a debug-build debug()
|
// trace() is a debug-build debug()
|
||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
#define beammp_trace(x) \
|
#define beammp_trace(x) \
|
||||||
do { \
|
do { \
|
||||||
try{ \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
if (Application::GetSettingBool("Debug")) { \
|
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
} \
|
||||||
} \
|
|
||||||
} catch (const std::exception& e) { \
|
|
||||||
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}'", #x)); \
|
|
||||||
} \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#else
|
#else
|
||||||
#define beammp_trace(x)
|
#define beammp_trace(x)
|
||||||
@@ -369,11 +273,11 @@ inline T Comp(const T& Data) {
|
|||||||
// obsolete
|
// obsolete
|
||||||
C.fill(0);
|
C.fill(0);
|
||||||
z_stream defstream;
|
z_stream defstream;
|
||||||
defstream.zalloc = nullptr;
|
defstream.zalloc = Z_NULL;
|
||||||
defstream.zfree = nullptr;
|
defstream.zfree = Z_NULL;
|
||||||
defstream.opaque = nullptr;
|
defstream.opaque = Z_NULL;
|
||||||
defstream.avail_in = uInt(Data.size());
|
defstream.avail_in = (uInt)Data.size();
|
||||||
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
defstream.next_in = (Bytef*)&Data[0];
|
||||||
defstream.avail_out = Biggest;
|
defstream.avail_out = Biggest;
|
||||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||||
@@ -394,13 +298,13 @@ inline T DeComp(const T& Compressed) {
|
|||||||
// not needed
|
// not needed
|
||||||
C.fill(0);
|
C.fill(0);
|
||||||
z_stream infstream;
|
z_stream infstream;
|
||||||
infstream.zalloc = nullptr;
|
infstream.zalloc = Z_NULL;
|
||||||
infstream.zfree = nullptr;
|
infstream.zfree = Z_NULL;
|
||||||
infstream.opaque = nullptr;
|
infstream.opaque = Z_NULL;
|
||||||
infstream.avail_in = Biggest;
|
infstream.avail_in = Biggest;
|
||||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
infstream.next_in = (Bytef*)(&Compressed[0]);
|
||||||
infstream.avail_out = Biggest;
|
infstream.avail_out = Biggest;
|
||||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
infstream.next_out = (Bytef*)(C.data());
|
||||||
inflateInit(&infstream);
|
inflateInit(&infstream);
|
||||||
inflate(&infstream, Z_SYNC_FLUSH);
|
inflate(&infstream, Z_SYNC_FLUSH);
|
||||||
inflate(&infstream, Z_FINISH);
|
inflate(&infstream, Z_FINISH);
|
||||||
@@ -416,4 +320,4 @@ inline T DeComp(const T& Compressed) {
|
|||||||
std::string GetPlatformAgnosticErrorString();
|
std::string GetPlatformAgnosticErrorString();
|
||||||
#define S_DSN SU_RAW
|
#define S_DSN SU_RAW
|
||||||
|
|
||||||
std::string ToHumanReadableSize(size_t Size);
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|||||||
@@ -5,23 +5,54 @@
|
|||||||
// ======================= UNIX ========================
|
// ======================= UNIX ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_LINUX
|
#ifdef BEAMMP_LINUX
|
||||||
|
#include <arpa/inet.h>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
using SOCKET = int;
|
||||||
|
using DWORD = unsigned long;
|
||||||
|
using PDWORD = unsigned long*;
|
||||||
|
using LPDWORD = unsigned long*;
|
||||||
char _getch();
|
char _getch();
|
||||||
|
inline void CloseSocketProper(int TheSocket) {
|
||||||
|
shutdown(TheSocket, SHUT_RDWR);
|
||||||
|
close(TheSocket);
|
||||||
|
}
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= APPLE ========================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_APPLE
|
#ifdef BEAMMP_APPLE
|
||||||
|
#include <arpa/inet.h>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
|
using SOCKET = int;
|
||||||
|
using DWORD = unsigned long;
|
||||||
|
using PDWORD = unsigned long*;
|
||||||
|
using LPDWORD = unsigned long*;
|
||||||
char _getch();
|
char _getch();
|
||||||
|
inline void CloseSocketProper(int TheSocket) {
|
||||||
|
shutdown(TheSocket, SHUT_RDWR);
|
||||||
|
close(TheSocket);
|
||||||
|
}
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= WINDOWS =======================
|
// ======================= WINDOWS =======================
|
||||||
|
|
||||||
#ifdef BEAMMP_WINDOWS
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <conio.h>
|
#include <conio.h>
|
||||||
|
#include <winsock2.h>
|
||||||
|
inline void CloseSocketProper(SOCKET TheSocket) {
|
||||||
|
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
||||||
|
closesocket(TheSocket);
|
||||||
|
}
|
||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
|
#ifdef INVALID_SOCKET
|
||||||
|
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
|
||||||
|
#else
|
||||||
|
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
|
||||||
|
#endif
|
||||||
|
|||||||
+10
-11
@@ -58,17 +58,16 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||||
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||||
#else
|
#else
|
||||||
#define beammp_assert(cond) \
|
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
||||||
do { \
|
#define beammp_assert(cond) \
|
||||||
bool result = (cond); \
|
do { \
|
||||||
if (!result) { \
|
bool result = (cond); \
|
||||||
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
if (!result) { \
|
||||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_assert_not_reachable() \
|
#define beammp_assert_not_reachable() \
|
||||||
do { \
|
do { \
|
||||||
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
||||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
|
|||||||
@@ -9,8 +9,6 @@
|
|||||||
#if defined(BEAMMP_LINUX)
|
#if defined(BEAMMP_LINUX)
|
||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||||
#pragma GCC diagnostic ignored "-Wcast-qual"
|
|
||||||
#pragma GCC diagnostic ignored "-Wold-style-cast"
|
|
||||||
#endif
|
#endif
|
||||||
#include <httplib.h>
|
#include <httplib.h>
|
||||||
#if defined(BEAMMP_LINUX)
|
#if defined(BEAMMP_LINUX)
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
enum IterationDecision {
|
|
||||||
Continue,
|
|
||||||
Break,
|
|
||||||
};
|
|
||||||
+2
-2
@@ -3,7 +3,7 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "rapidjson/document.h"
|
|
||||||
#include "rapidjson/prettywriter.h"
|
|
||||||
#include "rapidjson/stringbuffer.h"
|
#include "rapidjson/stringbuffer.h"
|
||||||
|
#include "rapidjson/prettywriter.h"
|
||||||
|
#include "rapidjson/document.h"
|
||||||
#include "rapidjson/writer.h"
|
#include "rapidjson/writer.h"
|
||||||
|
|||||||
+5
-5
@@ -12,12 +12,12 @@ namespace MP {
|
|||||||
|
|
||||||
std::string GetOSName();
|
std::string GetOSName();
|
||||||
std::tuple<int, int, int> GetServerVersion();
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
bool TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
void DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
void SendChatMessage(int ID, const std::string& Message);
|
||||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
void RemoveVehicle(int PlayerID, int VehicleID);
|
||||||
void Set(int ConfigID, sol::object NewValue);
|
void Set(int ConfigID, sol::object NewValue);
|
||||||
bool IsPlayerGuest(int ID);
|
bool IsPlayerGuest(int ID);
|
||||||
bool IsPlayerConnected(int ID);
|
bool IsPlayerConnected(int ID);
|
||||||
|
|||||||
+1
-1
@@ -6,8 +6,8 @@
|
|||||||
* and write locks and read locks are mutually exclusive.
|
* and write locks and read locks are mutually exclusive.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <mutex>
|
|
||||||
#include <shared_mutex>
|
#include <shared_mutex>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
// Use ReadLock(m) and WriteLock(m) to lock it.
|
// Use ReadLock(m) and WriteLock(m) to lock it.
|
||||||
using RWMutex = std::shared_mutex;
|
using RWMutex = std::shared_mutex;
|
||||||
|
|||||||
+3
-1
@@ -22,7 +22,9 @@ private:
|
|||||||
void CreateConfigFile();
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void PrintDebug();
|
void PrintDebug();
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key);
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
bool IsDefault();
|
bool IsDefault();
|
||||||
|
|||||||
@@ -36,12 +36,6 @@ private:
|
|||||||
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
||||||
void Command_Debug(const std::string&, const std::vector<std::string>& args);
|
|
||||||
void Command_Version(const std::string&, const std::vector<std::string>& args);
|
|
||||||
|
|
||||||
void Autocomplete_Lua(const std::string&, std::vector<std::string>& suggestions);
|
|
||||||
void Autocomplete_Kick(const std::string&, std::vector<std::string>& suggestions);
|
|
||||||
void Autocomplete_Settings(const std::string&, std::vector<std::string>& suggestions);
|
|
||||||
|
|
||||||
void Command_Say(const std::string& FullCommand);
|
void Command_Say(const std::string& FullCommand);
|
||||||
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
||||||
@@ -58,17 +52,9 @@ private:
|
|||||||
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
|
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
|
||||||
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
||||||
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
||||||
{ "debug", [this](const auto& a, const auto& b) { Command_Debug(a, b); } },
|
|
||||||
{ "version", [this](const auto& a, const auto& b) { Command_Version(a, b); } },
|
|
||||||
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||||
};
|
};
|
||||||
|
|
||||||
std::unordered_map<std::string, std::function<void(const std::string&, std::vector<std::string>&)>> mCommandAutocompleteMap = {
|
|
||||||
{ "lua", [this](const auto& a, auto& b) { Autocomplete_Lua(a, b); } },
|
|
||||||
{ "kick", [this](const auto& a, auto& b) { Autocomplete_Kick(a, b); } },
|
|
||||||
{ "settings", [this](const auto& a, auto& b) { Autocomplete_Settings(a, b); } },
|
|
||||||
};
|
|
||||||
|
|
||||||
Commandline mCommandline;
|
Commandline mCommandline;
|
||||||
std::vector<std::string> mCachedLuaHistory;
|
std::vector<std::string> mCachedLuaHistory;
|
||||||
std::vector<std::string> mCachedRegularHistory;
|
std::vector<std::string> mCachedRegularHistory;
|
||||||
|
|||||||
+16
-50
@@ -10,7 +10,6 @@
|
|||||||
#include <lua.hpp>
|
#include <lua.hpp>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
@@ -19,40 +18,18 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#define SOL_ALL_SAFETIES_ON 1
|
#define SOL_ALL_SAFETIES_ON 1
|
||||||
#define SOL_USER_C_ASSERT SOL_ON
|
|
||||||
#define SOL_C_ASSERT(...) \
|
|
||||||
do { \
|
|
||||||
if (!(__VA_ARGS__)) { \
|
|
||||||
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__); \
|
|
||||||
std::abort(); \
|
|
||||||
} \
|
|
||||||
} while (0)
|
|
||||||
#include <sol/sol.hpp>
|
#include <sol/sol.hpp>
|
||||||
|
|
||||||
struct JsonString {
|
|
||||||
std::string value;
|
|
||||||
};
|
|
||||||
|
|
||||||
// value used to keep nils in a table or array, across serialization boundaries like
|
|
||||||
// JsonEncode, so that the nil stays at the same index and isn't treated like a special
|
|
||||||
// value (e.g. one that can be ignored or discarded).
|
|
||||||
const inline std::string BEAMMP_INTERNAL_NIL = "BEAMMP_SERVER_INTERNAL_NIL_VALUE";
|
|
||||||
|
|
||||||
using TLuaStateId = std::string;
|
using TLuaStateId = std::string;
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
/**
|
/**
|
||||||
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
||||||
*/
|
*/
|
||||||
using TLuaValue = std::variant<std::string, int, JsonString, bool, std::unordered_map<std::string, std::string>, std::unordered_map<std::string, size_t>, float>;
|
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>;
|
||||||
enum TLuaType {
|
static constexpr size_t TLuaArgTypes_String = 0;
|
||||||
String = 0,
|
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||||
Int = 1,
|
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||||
Json = 2,
|
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||||
Bool = 3,
|
|
||||||
StringStringMap = 4,
|
|
||||||
StringSizeTMap = 5,
|
|
||||||
Float = 6,
|
|
||||||
};
|
|
||||||
|
|
||||||
class TLuaPlugin;
|
class TLuaPlugin;
|
||||||
|
|
||||||
@@ -93,12 +70,12 @@ public:
|
|||||||
struct QueuedFunction {
|
struct QueuedFunction {
|
||||||
std::string FunctionName;
|
std::string FunctionName;
|
||||||
std::shared_ptr<TLuaResult> Result;
|
std::shared_ptr<TLuaResult> Result;
|
||||||
std::vector<TLuaValue> Args;
|
std::vector<TLuaArgTypes> Args;
|
||||||
std::string EventName; // optional, may be empty
|
std::string EventName; // optional, may be empty
|
||||||
};
|
};
|
||||||
|
|
||||||
TLuaEngine();
|
TLuaEngine();
|
||||||
virtual ~TLuaEngine() noexcept {
|
~TLuaEngine() noexcept {
|
||||||
beammp_debug("Lua Engine terminated");
|
beammp_debug("Lua Engine terminated");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,13 +96,6 @@ public:
|
|||||||
std::unique_lock Lock(mLuaStatesMutex);
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
return mLuaStates.size();
|
return mLuaStates.size();
|
||||||
}
|
}
|
||||||
std::vector<std::string> GetLuaStateNames() {
|
|
||||||
std::vector<std::string> names {};
|
|
||||||
for (auto const& [stateId, _] : mLuaStates) {
|
|
||||||
names.push_back(stateId);
|
|
||||||
}
|
|
||||||
return names;
|
|
||||||
}
|
|
||||||
size_t GetTimedEventsCount() {
|
size_t GetTimedEventsCount() {
|
||||||
std::unique_lock Lock(mTimedEventsMutex);
|
std::unique_lock Lock(mTimedEventsMutex);
|
||||||
return mTimedEvents.size();
|
return mTimedEvents.size();
|
||||||
@@ -142,11 +112,11 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
|
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
|
||||||
const std::optional<TimeType::duration>& Max = std::nullopt);
|
const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
|
||||||
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
||||||
bool HasState(TLuaStateId StateId);
|
bool HasState(TLuaStateId StateId);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||||
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||||
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||||
/**
|
/**
|
||||||
@@ -166,7 +136,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||||
|
|
||||||
for (const auto& Event : mLuaEvents.at(EventName)) {
|
for (const auto& Event : mLuaEvents.at(EventName)) {
|
||||||
for (const auto& Function : Event.second) {
|
for (const auto& Function : Event.second) {
|
||||||
@@ -185,7 +155,7 @@ public:
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||||
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||||
for (const auto& Handler : Handlers) {
|
for (const auto& Handler : Handlers) {
|
||||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||||
@@ -202,7 +172,6 @@ public:
|
|||||||
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
||||||
|
|
||||||
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
||||||
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
|
|
||||||
|
|
||||||
// Debugging functions (slow)
|
// Debugging functions (slow)
|
||||||
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||||
@@ -220,17 +189,16 @@ private:
|
|||||||
public:
|
public:
|
||||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||||
StateThreadData(const StateThreadData&) = delete;
|
StateThreadData(const StateThreadData&) = delete;
|
||||||
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
sol::state_view State() { return sol::state_view(mState); }
|
sol::state_view State() { return sol::state_view(mState); }
|
||||||
|
|
||||||
std::vector<std::string> GetStateGlobalKeys();
|
std::vector<std::string> GetStateGlobalKeys();
|
||||||
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
|
|
||||||
|
|
||||||
// Debug functions, slow
|
// Debug functions, slow
|
||||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||||
@@ -243,7 +211,6 @@ private:
|
|||||||
sol::table Lua_GetPlayers();
|
sol::table Lua_GetPlayers();
|
||||||
std::string Lua_GetPlayerName(int ID);
|
std::string Lua_GetPlayerName(int ID);
|
||||||
sol::table Lua_GetPlayerVehicles(int ID);
|
sol::table Lua_GetPlayerVehicles(int ID);
|
||||||
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
|
|
||||||
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
||||||
sol::table Lua_JsonDecode(const std::string& str);
|
sol::table Lua_JsonDecode(const std::string& str);
|
||||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||||
@@ -265,12 +232,11 @@ private:
|
|||||||
std::recursive_mutex mPathsMutex;
|
std::recursive_mutex mPathsMutex;
|
||||||
std::mt19937 mMersenneTwister;
|
std::mt19937 mMersenneTwister;
|
||||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||||
std::vector<sol::object> JsonStringToArray(JsonString Str);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
struct TimedEvent {
|
struct TimedEvent {
|
||||||
TimeType::duration Duration {};
|
std::chrono::high_resolution_clock::duration Duration {};
|
||||||
TimeType::time_point LastCompletion {};
|
std::chrono::high_resolution_clock::time_point LastCompletion {};
|
||||||
std::string EventName;
|
std::string EventName;
|
||||||
TLuaStateId StateId;
|
TLuaStateId StateId;
|
||||||
CallStrategy Strategy;
|
CallStrategy Strategy;
|
||||||
|
|||||||
+17
-23
@@ -1,11 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include <boost/asio/io_context.hpp>
|
|
||||||
#include <boost/asio/ip/udp.hpp>
|
|
||||||
|
|
||||||
struct TConnection;
|
struct TConnection;
|
||||||
|
|
||||||
@@ -13,18 +10,19 @@ class TNetwork {
|
|||||||
public:
|
public:
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
|
||||||
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
|
||||||
std::vector<uint8_t> TCPRcv(TClient& c);
|
std::string TCPRcv(TClient& c);
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
void ClientKick(TClient& c, const std::string& R);
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||||
void Identify(TConnection&& client);
|
void Identify(const TConnection& client);
|
||||||
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
void Authentication(const TConnection& ClientConnection);
|
||||||
|
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
||||||
void SyncResources(TClient& c);
|
void SyncResources(TClient& c);
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
||||||
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
|
||||||
void UpdatePlayer(TClient& Client);
|
void UpdatePlayer(TClient& Client);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -33,25 +31,21 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
TPPSMonitor& mPPSMonitor;
|
TPPSMonitor& mPPSMonitor;
|
||||||
ip::udp::socket mUDPSock;
|
SOCKET mUDPSock {};
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
std::thread mUDPThread;
|
std::thread mUDPThread;
|
||||||
std::thread mTCPThread;
|
std::thread mTCPThread;
|
||||||
std::mutex mOpenIDMutex;
|
|
||||||
|
|
||||||
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
std::string UDPRcvFromClient(sockaddr_in& client) const;
|
||||||
void HandleDownload(TConnection&& TCPSock);
|
void HandleDownload(SOCKET TCPSock);
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
void Looper(const std::weak_ptr<TClient>& c);
|
||||||
int OpenID();
|
int OpenID();
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
|
||||||
ModMap GetClientMods(TClient& Client);
|
void Parse(TClient& c, const std::string& Packet);
|
||||||
void HandleResourcePackets(TClient& c, const std::vector<uint8_t>& Packet);
|
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
void SendFile(TClient& c, const std::string& Name);
|
||||||
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||||
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
|
||||||
};
|
};
|
||||||
|
|
||||||
std::vector<uint8_t> StringToVector(const std::string& Str);
|
|
||||||
|
|||||||
+10
-11
@@ -1,22 +1,21 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
using ModMap = HashMap<std::string, size_t>;
|
|
||||||
|
|
||||||
class TResourceManager {
|
class TResourceManager {
|
||||||
public:
|
public:
|
||||||
TResourceManager();
|
TResourceManager();
|
||||||
|
|
||||||
[[nodiscard]] size_t TotalModsSize() const { return mTotalModSize; }
|
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
|
||||||
[[nodiscard]] ModMap FileMap() const { return mMods; }
|
[[nodiscard]] std::string FileList() const { return mFileList; }
|
||||||
[[nodiscard]] static std::string FormatForBackend(const ModMap& mods);
|
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
||||||
[[nodiscard]] static std::string FormatForClient(const ModMap& mods);
|
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
||||||
[[nodiscard]] static std::optional<std::string> IsModValid(std::string& pathString, const ModMap& mods);
|
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
||||||
[[nodiscard]] int LoadedModCount() const { return mMods.size(); }
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
size_t mTotalModSize = 0; // size of all mods
|
size_t mMaxModSize = 0;
|
||||||
ModMap mMods; // map of mod names
|
std::string mFileSizes;
|
||||||
|
std::string mFileList;
|
||||||
|
std::string mTrimmedList;
|
||||||
|
int mModsLoaded = 0;
|
||||||
};
|
};
|
||||||
@@ -4,8 +4,6 @@
|
|||||||
#include <functional>
|
#include <functional>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include "Common.h"
|
|
||||||
|
|
||||||
class TScopedTimer {
|
class TScopedTimer {
|
||||||
public:
|
public:
|
||||||
TScopedTimer();
|
TScopedTimer();
|
||||||
@@ -13,7 +11,7 @@ public:
|
|||||||
TScopedTimer(std::function<void(size_t)> OnDestroy);
|
TScopedTimer(std::function<void(size_t)> OnDestroy);
|
||||||
~TScopedTimer();
|
~TScopedTimer();
|
||||||
auto GetElapsedTime() const {
|
auto GetElapsedTime() const {
|
||||||
auto EndTime = TimeType::now();
|
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||||
auto Delta = EndTime - mStartTime;
|
auto Delta = EndTime - mStartTime;
|
||||||
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||||
return TimeDelta;
|
return TimeDelta;
|
||||||
@@ -22,6 +20,6 @@ public:
|
|||||||
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
|
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
|
||||||
|
|
||||||
private:
|
private:
|
||||||
TimeType::time_point mStartTime;
|
std::chrono::high_resolution_clock::time_point mStartTime;
|
||||||
std::string Name;
|
std::string Name;
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-72
@@ -1,37 +1,17 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "IThreaded.h"
|
#include "IThreaded.h"
|
||||||
#include "IterationDecision.h"
|
|
||||||
#include "RWMutex.h"
|
#include "RWMutex.h"
|
||||||
#include "TScopedTimer.h"
|
#include "TScopedTimer.h"
|
||||||
#include <concepts>
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <type_traits>
|
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
|
|
||||||
class TClient;
|
class TClient;
|
||||||
class TNetwork;
|
class TNetwork;
|
||||||
class TPPSMonitor;
|
class TPPSMonitor;
|
||||||
|
|
||||||
// clang-format doesn't know how to deal with concepts
|
|
||||||
// clang-format off
|
|
||||||
template <typename FnT>
|
|
||||||
concept ForEachHandlerWithDecision = requires(FnT Fn, const std::shared_ptr<TClient>& Ptr) {
|
|
||||||
requires std::invocable<FnT, const std::shared_ptr<TClient>&> ;
|
|
||||||
{ std::invoke(Fn, Ptr) } -> std::convertible_to<IterationDecision>;
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename FnT>
|
|
||||||
concept ForEachHandler = requires(FnT Fn, const std::shared_ptr<TClient>& Ptr) {
|
|
||||||
requires std::invocable <FnT, const std::shared_ptr<TClient>&> ;
|
|
||||||
{ std::invoke(Fn, Ptr) } -> std::same_as<void>;
|
|
||||||
};
|
|
||||||
// clang-format on
|
|
||||||
|
|
||||||
class TServer final {
|
class TServer final {
|
||||||
public:
|
public:
|
||||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
||||||
@@ -39,71 +19,23 @@ public:
|
|||||||
TServer(const std::vector<std::string_view>& Arguments);
|
TServer(const std::vector<std::string_view>& Arguments);
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||||
|
std::weak_ptr<TClient> InsertNewClient();
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||||
void RemoveClientById(int Id);
|
|
||||||
// in Fn, return true to continue, return false to break
|
// in Fn, return true to continue, return false to break
|
||||||
[[deprecated("use ForEachClient instead")]] void ForEachClientWeak(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||||
// in Fn, return Break or Continue
|
|
||||||
template <ForEachHandlerWithDecision FnT>
|
|
||||||
void ForEachClient(FnT Fn) {
|
|
||||||
decltype(mClients) Clients;
|
|
||||||
{
|
|
||||||
ReadLock lock(mClientsMutex);
|
|
||||||
Clients = mClients;
|
|
||||||
}
|
|
||||||
for (auto& Client : Clients) {
|
|
||||||
if (Client) [[likely]] {
|
|
||||||
IterationDecision Decision = std::invoke(Fn, Client);
|
|
||||||
if (Decision == IterationDecision::Break) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
template <ForEachHandler FnT>
|
|
||||||
void ForEachClient(FnT Fn) {
|
|
||||||
decltype(mClients) Clients;
|
|
||||||
{
|
|
||||||
ReadLock lock(mClientsMutex);
|
|
||||||
Clients = mClients;
|
|
||||||
}
|
|
||||||
for (auto& Client : Clients) {
|
|
||||||
if (Client) [[likely]] {
|
|
||||||
std::invoke(Fn, Client);
|
|
||||||
} else {
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
size_t ClientCount() const;
|
size_t ClientCount() const;
|
||||||
|
|
||||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TNetwork& Network);
|
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||||
static void HandleEvent(TClient& c, const std::string& Data);
|
static void HandleEvent(TClient& c, const std::string& Data);
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||||
|
|
||||||
|
|
||||||
const TScopedTimer UptimeTimer;
|
const TScopedTimer UptimeTimer;
|
||||||
|
|
||||||
// asio io context
|
|
||||||
io_context& IoCtx() { return mIoCtx; }
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
io_context mIoCtx {};
|
|
||||||
TClientSet mClients;
|
TClientSet mClients;
|
||||||
mutable RWMutex mClientsMutex;
|
mutable RWMutex mClientsMutex;
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
||||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||||
static bool HandlePosition(TClient& c, const std::string& PacketStr);
|
|
||||||
static bool HandleVehicleUpdate(const std::string& PacketStr, const int playerID);
|
|
||||||
};
|
|
||||||
|
|
||||||
struct BufferView {
|
|
||||||
uint8_t* Data { nullptr };
|
|
||||||
size_t Size { 0 };
|
|
||||||
const uint8_t* data() const { return Data; }
|
|
||||||
uint8_t* data() { return Data; }
|
|
||||||
size_t size() const { return Size; }
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace uuid {
|
|
||||||
|
|
||||||
std::string GenerateUuid();
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
FROM archlinux
|
|
||||||
|
|
||||||
RUN pacman -Syu --noconfirm lua53 openssl curl git cmake gcc make zlib boost websocketpp
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
FROM debian:11
|
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND noninteractive
|
|
||||||
|
|
||||||
RUN apt-get update -y
|
|
||||||
|
|
||||||
RUN apt-get install -y git cmake g++-10 curl libboost1.74-all-dev libssl-dev libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
|
||||||
|
|
||||||
ENV CXX=g++-10
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
FROM ubuntu:20.04
|
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND noninteractive
|
|
||||||
|
|
||||||
RUN apt-get update -y
|
|
||||||
|
|
||||||
RUN apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev git make cmake g++
|
|
||||||
|
|
||||||
RUN apt-get install -y libboost1.71-all-dev
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
FROM ubuntu:22.04
|
|
||||||
|
|
||||||
ENV DEBIAN_FRONTEND noninteractive
|
|
||||||
|
|
||||||
RUN apt-get update -y
|
|
||||||
|
|
||||||
RUN apt-get install -y git libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev libssl3 curl
|
|
||||||
|
|
||||||
ENV CXX=g++-10
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
printf "enter DSN (optional): "
|
|
||||||
read DSN
|
|
||||||
|
|
||||||
docker build -f Ubuntu-20.04-Dockerfile . -t beammp-server-build:Ubuntu-20.04
|
|
||||||
docker build -f Ubuntu-22.04-Dockerfile . -t beammp-server-build:Ubuntu-22.04
|
|
||||||
docker build -f ArchLinux-Dockerfile . -t beammp-server-build:ArchLinux
|
|
||||||
docker build -f Debian-11-Dockerfile . -t beammp-server-build:Debian-11
|
|
||||||
|
|
||||||
CMD="cd /beammp; cmake . -DGIT_SUBMODULE=OFF -DCMAKE_BUILD_TYPE=Release -DBEAMMP_SECRET_SENTRY_URL=\"${DSN}\" -B /build && make -j -C /build BeamMP-Server"
|
|
||||||
|
|
||||||
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-20.04:/build -it --rm beammp-server-build:Ubuntu-20.04 bash -c "${CMD}"
|
|
||||||
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-22.04:/build -it --rm beammp-server-build:Ubuntu-22.04 bash -c "${CMD}"
|
|
||||||
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-archlinux:/build -it --rm beammp-server-build:ArchLinux bash -c "${CMD}"
|
|
||||||
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-debian-11:/build -it --rm beammp-server-build:Debian-11 bash -c "${CMD}"
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
cmake . -B build -DCMAKE_BUILD_TYPE=Release -DGIT_SUBMODULE=OFF
|
|
||||||
|
|
||||||
make -j -C build BeamMP-Server
|
|
||||||
+6
-6
@@ -13,7 +13,7 @@ void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
|
|||||||
ConsumeLongFlag(std::string(Arg));
|
ConsumeLongFlag(std::string(Arg));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
fmt::print(stderr, "Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
|
beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,17 +22,17 @@ bool ArgsParser::Verify() {
|
|||||||
bool Ok = true;
|
bool Ok = true;
|
||||||
for (const auto& RegisteredArg : mRegisteredArguments) {
|
for (const auto& RegisteredArg : mRegisteredArguments) {
|
||||||
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
|
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
|
||||||
fmt::print(stderr, "Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
|
beammp_errorf("Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
|
||||||
Ok = false;
|
Ok = false;
|
||||||
continue;
|
continue;
|
||||||
} else if (FoundArgument(RegisteredArg.Names)) {
|
} else if (FoundArgument(RegisteredArg.Names)) {
|
||||||
if (RegisteredArg.Flags & Flags::HAS_VALUE) {
|
if (RegisteredArg.Flags & Flags::HAS_VALUE) {
|
||||||
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||||
fmt::print(stderr, "Error in commandline arguments: Argument '{}' expects a value, but no value was given.", RegisteredArg.Names.at(0));
|
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' expects a value, but no value was given.");
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||||
fmt::print(stderr, "Error in commandline arguments: Argument '{}' does not expect a value, but one was given.", RegisteredArg.Names.at(0));
|
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' does not expect a value, but one was given.");
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,7 +81,7 @@ void ArgsParser::ConsumeLongAssignment(const std::string& Arg) {
|
|||||||
auto Value = Arg.substr(Arg.rfind("=") + 1);
|
auto Value = Arg.substr(Arg.rfind("=") + 1);
|
||||||
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||||
if (!IsRegistered(Name)) {
|
if (!IsRegistered(Name)) {
|
||||||
fmt::print(stdout, "Argument '{}' was supplied but isn't a known argument, so it is likely being ignored.", Name);
|
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||||
}
|
}
|
||||||
mFoundArgs.push_back({ Name, Value });
|
mFoundArgs.push_back({ Name, Value });
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ void ArgsParser::ConsumeLongFlag(const std::string& Arg) {
|
|||||||
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||||
mFoundArgs.push_back({ Name, std::nullopt });
|
mFoundArgs.push_back({ Name, std::nullopt });
|
||||||
if (!IsRegistered(Name)) {
|
if (!IsRegistered(Name)) {
|
||||||
fmt::print(stdout, "Argument '{}' was supplied but isn't a known argument, so it is likely being ignored.", Name);
|
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-61
@@ -1,20 +1,16 @@
|
|||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
void TClient::DeleteCar(int Ident) {
|
||||||
// TODO: Send delete packets
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
||||||
return Ident == elem.ID();
|
return Ident == elem.ID();
|
||||||
});
|
});
|
||||||
if (iter != mVehicleData.end()) {
|
if (iter != mVehicleData.end()) {
|
||||||
std::string Destroy = "Od:" + std::to_string(GetID()) + "-" + std::to_string(iter->ID());
|
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
|
||||||
mVehicleData.erase(iter);
|
mVehicleData.erase(iter);
|
||||||
} else {
|
} else {
|
||||||
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
||||||
@@ -23,10 +19,6 @@ void TClient::DeleteCar(int Ident) {
|
|||||||
|
|
||||||
void TClient::ClearCars() {
|
void TClient::ClearCars() {
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
for (const auto& Car : mVehicleData) {
|
|
||||||
std::string Destroy = "Od:" + std::to_string(GetID()) + "-" + std::to_string(Car.ID());
|
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(this, StringToVector(Destroy), false, true);
|
|
||||||
}
|
|
||||||
mVehicleData.clear();
|
mVehicleData.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,40 +47,6 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|||||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
try {
|
|
||||||
return mVehiclePosition.at(Ident);
|
|
||||||
} catch (const std::out_of_range& oor) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::Disconnect(std::string_view Reason) {
|
|
||||||
// we need exclusivity here in case we can't
|
|
||||||
std::unique_lock Lock(mDisconnectMtx);
|
|
||||||
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
|
||||||
if (mSocket.is_open()) {
|
|
||||||
beammp_debugf("Socket for client {} already closed", GetID());
|
|
||||||
}
|
|
||||||
boost::system::error_code ec;
|
|
||||||
mSocket.shutdown(socket_base::shutdown_both, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
mSocket.close(ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to close client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
mServer.RemoveClientById(GetID());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
mVehiclePosition[Ident] = Data;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TClient::GetCarData(int Ident) {
|
std::string TClient::GetCarData(int Ident) {
|
||||||
{ // lock
|
{ // lock
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
@@ -123,40 +81,38 @@ TServer& TClient::Server() const {
|
|||||||
return mServer;
|
return mServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
void TClient::EnqueuePacket(const std::string& Packet) {
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
std::unique_lock Lock(mMissedPacketsMutex);
|
||||||
mPacketsSync.push(Packet);
|
mPacketsSync.push(Packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
TClient::TClient(TServer& Server)
|
||||||
: mServer(Server)
|
: mServer(Server)
|
||||||
, mSocket(std::move(Socket))
|
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||||
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
|
||||||
, mLastPingTime(TimeType::now()) {
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::~TClient() {
|
|
||||||
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
void TClient::UpdatePingTime() {
|
||||||
mLastPingTime = TimeType::now();
|
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
int TClient::SecondsSinceLastPing() {
|
int TClient::SecondsSinceLastPing() {
|
||||||
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
||||||
TimeType::now() - mLastPingTime)
|
std::chrono::high_resolution_clock::now() - mLastPingTime)
|
||||||
.count();
|
.count();
|
||||||
return int(seconds);
|
return int(seconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TClient> GetClient(TServer& Server, int ID) {
|
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
||||||
std::shared_ptr<TClient> Result {};
|
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
||||||
Server.ForEachClient([&](const auto& Client) {
|
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
||||||
if (Client->GetID() == ID) {
|
ReadLock Lock(Server.GetClientMutex());
|
||||||
Result = Client;
|
if (!CPtr.expired()) {
|
||||||
return Break;
|
auto C = CPtr.lock();
|
||||||
|
if (C->GetID() == ID) {
|
||||||
|
MaybeClient = CPtr;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return Continue;
|
return true;
|
||||||
});
|
});
|
||||||
return Result;
|
return MaybeClient;
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-103
@@ -9,89 +9,13 @@
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
#include "Compat.h"
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
Application::SettingsMap Application::mSettings = {
|
|
||||||
{ StrName, std::string("BeamMP Server") },
|
|
||||||
{ StrDescription, std::string("No description") },
|
|
||||||
{ StrResourceFolder, std::string("Resources") },
|
|
||||||
{ StrMap, std::string("/levels/gridmap_v2/info.json") },
|
|
||||||
{ StrSSLKeyPath, std::string("./.ssl/HttpServer/key.pem") },
|
|
||||||
{ StrSSLCertPath, std::string("./.ssl/HttpServer/cert.pem") },
|
|
||||||
{ StrHTTPServerEnabled, false },
|
|
||||||
{ StrMaxPlayers, int(8) },
|
|
||||||
{ StrPrivate, true },
|
|
||||||
{ StrMaxCars, int(1) },
|
|
||||||
{ StrDebug, false },
|
|
||||||
{ StrPort, int(30814) },
|
|
||||||
{ StrCustomIP, std::string("") },
|
|
||||||
{ StrLogChat, true },
|
|
||||||
{ StrSendErrors, true },
|
|
||||||
{ StrSendErrorsMessageEnabled, true },
|
|
||||||
{ StrHTTPServerPort, int(8080) },
|
|
||||||
{ StrHTTPServerIP, std::string("127.0.0.1") },
|
|
||||||
{ StrHTTPServerUseSSL, false },
|
|
||||||
{ StrHideUpdateMessages, false },
|
|
||||||
{ StrAuthKey, std::string("") },
|
|
||||||
{ StrIncludeSubdirectories, false },
|
|
||||||
};
|
|
||||||
|
|
||||||
// global, yes, this is ugly, no, it cant be done another way
|
// global, yes, this is ugly, no, it cant be done another way
|
||||||
TSentry Sentry {};
|
TSentry Sentry {};
|
||||||
|
|
||||||
std::string Application::SettingToString(const Application::SettingValue& Value) {
|
Application::TSettings Application::Settings = {};
|
||||||
switch (Value.index()) {
|
|
||||||
case 0:
|
|
||||||
return fmt::format("{}", std::get<std::string>(Value));
|
|
||||||
case 1:
|
|
||||||
return fmt::format("{}", std::get<bool>(Value));
|
|
||||||
case 2:
|
|
||||||
return fmt::format("{}", std::get<int>(Value));
|
|
||||||
default:
|
|
||||||
return "<unknown type>";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Application::GetSettingString(std::string_view Name) {
|
|
||||||
try {
|
|
||||||
return std::get<std::string>(Application::mSettings.at(Name));
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_errorf("Failed to get string setting '{}': {}", Name, e.what());
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int Application::GetSettingInt(std::string_view Name) {
|
|
||||||
try {
|
|
||||||
return std::get<int>(Application::mSettings.at(Name));
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_errorf("Failed to get int setting '{}': {}", Name, e.what());
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Application::GetSettingBool(std::string_view Name) {
|
|
||||||
try {
|
|
||||||
return std::get<bool>(Application::mSettings.at(Name));
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_errorf("Failed to get bool setting '{}': {}", Name, e.what());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Application::SetSetting(std::string_view Name, const Application::SettingValue& Value) {
|
|
||||||
if (mSettings.contains(Name)) {
|
|
||||||
if (mSettings[Name].index() == Value.index()) {
|
|
||||||
mSettings[Name] = Value;
|
|
||||||
} else {
|
|
||||||
beammp_errorf("Could not change value of setting '{}', because it has a different type.", Name);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
mSettings[Name] = Value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
@@ -246,8 +170,6 @@ void Application::SetSubsystemStatus(const std::string& Subsystem, Status status
|
|||||||
case Status::Shutdown:
|
case Status::Shutdown:
|
||||||
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
||||||
break;
|
break;
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
std::unique_lock Lock(mSystemStatusMapMutex);
|
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||||
mSystemStatusMap[Subsystem] = status;
|
mSystemStatusMap[Subsystem] = status;
|
||||||
@@ -273,7 +195,7 @@ void Application::CheckForUpdates() {
|
|||||||
// checks current version against latest version
|
// checks current version against latest version
|
||||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||||
auto Response = Http::GET(url, 443, "/v/s");
|
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/v/s");
|
||||||
bool Matches = std::regex_match(Response, VersionRegex);
|
bool Matches = std::regex_match(Response, VersionRegex);
|
||||||
if (Matches) {
|
if (Matches) {
|
||||||
auto MyVersion = ServerVersion();
|
auto MyVersion = ServerVersion();
|
||||||
@@ -314,7 +236,7 @@ static std::mutex ThreadNameMapMutex {};
|
|||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride) {
|
std::string ThreadName(bool DebugModeOverride) {
|
||||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||||
if (DebugModeOverride || Application::GetSettingBool(StrDebug)) {
|
if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
|
||||||
auto id = std::this_thread::get_id();
|
auto id = std::this_thread::get_id();
|
||||||
if (threadNameMap.find(id) != threadNameMap.end()) {
|
if (threadNameMap.find(id) != threadNameMap.end()) {
|
||||||
// found
|
// found
|
||||||
@@ -326,21 +248,21 @@ std::string ThreadName(bool DebugModeOverride) {
|
|||||||
|
|
||||||
TEST_CASE("ThreadName") {
|
TEST_CASE("ThreadName") {
|
||||||
RegisterThread("MyThread");
|
RegisterThread("MyThread");
|
||||||
auto OrigDebug = Application::GetSettingBool(StrDebug);
|
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
||||||
|
|
||||||
// ThreadName adds a space at the end, legacy but we need it still
|
// ThreadName adds a space at the end, legacy but we need it still
|
||||||
SUBCASE("Debug mode enabled") {
|
SUBCASE("Debug mode enabled") {
|
||||||
Application::SetSetting(StrDebug, true);
|
Application::Settings.DebugModeEnabled = true;
|
||||||
CHECK(ThreadName(true) == "MyThread ");
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
CHECK(ThreadName(false) == "MyThread ");
|
CHECK(ThreadName(false) == "MyThread ");
|
||||||
}
|
}
|
||||||
SUBCASE("Debug mode disabled") {
|
SUBCASE("Debug mode disabled") {
|
||||||
Application::SetSetting(StrDebug, false);
|
Application::Settings.DebugModeEnabled = false;
|
||||||
CHECK(ThreadName(true) == "MyThread ");
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
CHECK(ThreadName(false) == "");
|
CHECK(ThreadName(false) == "");
|
||||||
}
|
}
|
||||||
// cleanup
|
// cleanup
|
||||||
Application::SetSetting(StrDebug, OrigDebug);
|
Application::Settings.DebugModeEnabled = OrigDebug;
|
||||||
}
|
}
|
||||||
|
|
||||||
void RegisterThread(const std::string& str) {
|
void RegisterThread(const std::string& str) {
|
||||||
@@ -352,7 +274,7 @@ void RegisterThread(const std::string& str) {
|
|||||||
#elif defined(BEAMMP_LINUX)
|
#elif defined(BEAMMP_LINUX)
|
||||||
ThreadId = std::to_string(gettid());
|
ThreadId = std::to_string(gettid());
|
||||||
#endif
|
#endif
|
||||||
if (Application::GetSettingBool(StrDebug)) {
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
||||||
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
|
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
|
||||||
}
|
}
|
||||||
@@ -385,7 +307,7 @@ TEST_CASE("Version::AsString") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||||
if (Application::GetSettingBool(StrLogChat)) {
|
if (Application::Settings.LogChat) {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << ThreadName();
|
ss << ThreadName();
|
||||||
ss << "[CHAT] ";
|
ss << "[CHAT] ";
|
||||||
@@ -425,21 +347,5 @@ std::string GetPlatformAgnosticErrorString() {
|
|||||||
}
|
}
|
||||||
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
return std::strerror(errno);
|
return std::strerror(errno);
|
||||||
#else
|
|
||||||
return "(no human-readable errors on this platform)";
|
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string ToHumanReadableSize(size_t Size) {
|
|
||||||
if (Size > TB) {
|
|
||||||
return fmt::format("{:.2f} TiB", double(Size) / TB);
|
|
||||||
} else if (Size > GB) {
|
|
||||||
return fmt::format("{:.2f} GiB", double(Size) / GB);
|
|
||||||
} else if (Size > MB) {
|
|
||||||
return fmt::format("{:.2f} MiB", double(Size) / MB);
|
|
||||||
} else if (Size > KB) {
|
|
||||||
return fmt::format("{:.2f} KiB", double(Size) / KB);
|
|
||||||
} else {
|
|
||||||
return fmt::format("{} B", Size);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+5
-14
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
static struct termios old, current;
|
static struct termios old, current;
|
||||||
|
|
||||||
static void initTermios(int echo) {
|
void initTermios(int echo) {
|
||||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||||
current = old; /* make new settings same as old settings */
|
current = old; /* make new settings same as old settings */
|
||||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||||
@@ -19,7 +19,7 @@ static void initTermios(int echo) {
|
|||||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||||
}
|
}
|
||||||
|
|
||||||
static void resetTermios(void) {
|
void resetTermios(void) {
|
||||||
tcsetattr(0, TCSANOW, &old);
|
tcsetattr(0, TCSANOW, &old);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,23 +36,14 @@ TEST_CASE("init and reset termios") {
|
|||||||
resetTermios();
|
resetTermios();
|
||||||
struct termios current;
|
struct termios current;
|
||||||
tcgetattr(0, ¤t);
|
tcgetattr(0, ¤t);
|
||||||
CHECK_EQ(std::memcmp(¤t.c_cc, &original.c_cc, sizeof(current.c_cc)), 0);
|
CHECK(std::memcmp(&original, ¤t, sizeof(struct termios)) == 0);
|
||||||
CHECK_EQ(current.c_cflag, original.c_cflag);
|
|
||||||
CHECK_EQ(current.c_iflag, original.c_iflag);
|
|
||||||
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
|
||||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
|
||||||
CHECK_EQ(current.c_line, original.c_line);
|
|
||||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
|
||||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static char getch_(int echo) {
|
char getch_(int echo) {
|
||||||
char ch;
|
char ch;
|
||||||
initTermios(echo);
|
initTermios(echo);
|
||||||
if (read(STDIN_FILENO, &ch, 1) < 0) {
|
read(STDIN_FILENO, &ch, 1);
|
||||||
// ignore, not much we can do
|
|
||||||
}
|
|
||||||
resetTermios();
|
resetTermios();
|
||||||
return ch;
|
return ch;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-4
@@ -4,6 +4,7 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
|
#include "httplib.h"
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
@@ -154,7 +155,7 @@ Http::Server::THttpServerInstance::THttpServerInstance() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Http::Server::THttpServerInstance::operator()() try {
|
void Http::Server::THttpServerInstance::operator()() try {
|
||||||
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::GetSettingInt(StrHTTPServerPort)));
|
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
|
||||||
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
||||||
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
||||||
// todo: make this IP agnostic so people can set their own IP
|
// todo: make this IP agnostic so people can set their own IP
|
||||||
@@ -176,8 +177,6 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
case Application::Status::Bad:
|
case Application::Status::Bad:
|
||||||
SystemsBad++;
|
SystemsBad++;
|
||||||
break;
|
break;
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.set_content(
|
res.set_content(
|
||||||
@@ -196,7 +195,7 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
||||||
});
|
});
|
||||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||||
auto ret = HttpLibServerInstance->listen(Application::GetSettingString(StrHTTPServerIP).c_str(), Application::GetSettingInt(StrHTTPServerPort));
|
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
||||||
if (!ret) {
|
if (!ret) {
|
||||||
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
||||||
}
|
}
|
||||||
|
|||||||
+65
-98
@@ -1,7 +1,6 @@
|
|||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
@@ -75,10 +74,8 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
|
|||||||
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||||
return ss.str();
|
return ss.str();
|
||||||
}
|
}
|
||||||
case sol::type::poly:
|
|
||||||
return "<poly>";
|
|
||||||
default:
|
default:
|
||||||
return "<unprintable type>";
|
return "((unprintable type))";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,147 +110,128 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
|||||||
CHECK(pa == real.patch);
|
CHECK(pa == real.patch);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
static inline bool InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||||
std::string Packet = "E:" + EventName + ":" + Data;
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
if (PlayerID == -1) {
|
if (PlayerID == -1)
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||||
return { true, "" };
|
else {
|
||||||
} else {
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
auto Client = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
if (!Client) {
|
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
||||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
return false;
|
||||||
return { false, "Invalid Player ID" };
|
|
||||||
}
|
}
|
||||||
if (!LuaAPI::MP::Engine->Network().Respond(*Client, StringToVector(Packet), true)) {
|
auto c = MaybeClient.value().lock();
|
||||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*Client, "Disconnected after failing to receive packets");
|
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
||||||
return { false, "Respond failed, dropping client" };
|
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
return { true, "" };
|
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
bool LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||||
std::string Data = DataObj.as<std::string>();
|
std::string Data = DataObj.as<std::string>();
|
||||||
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
auto Client = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (!Client) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
beammp_lua_error("Tried to drop client with id " + std::to_string(ID) + ", who doesn't exist");
|
||||||
return { false, "Player does not exist" };
|
return;
|
||||||
}
|
}
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*Client, MaybeReason.value_or("No reason"));
|
auto c = MaybeClient.value().lock();
|
||||||
return { true, "" };
|
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||||
std::pair<bool, std::string> Result;
|
|
||||||
std::string Packet = "C:Server: " + Message;
|
std::string Packet = "C:Server: " + Message;
|
||||||
if (ID == -1) {
|
if (ID == -1) {
|
||||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||||
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||||
Result.first = true;
|
|
||||||
} else {
|
} else {
|
||||||
auto Client = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
if (!Client->IsSynced()) {
|
auto c = MaybeClient.value().lock();
|
||||||
Result.first = false;
|
if (!c->IsSynced())
|
||||||
Result.second = "Player still syncing data";
|
return;
|
||||||
return Result;
|
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||||
}
|
Engine->Network().Respond(*c, Packet, true);
|
||||||
LogChatMessage("<Server> (to \"" + Client->GetName() + "\")", -1, Message);
|
|
||||||
if (!Engine->Network().Respond(*Client, StringToVector(Packet), true)) {
|
|
||||||
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
|
||||||
// TODO: should we return an error here?
|
|
||||||
}
|
|
||||||
Result.first = true;
|
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||||
Result.first = false;
|
|
||||||
Result.second = "Invalid Player ID";
|
|
||||||
}
|
}
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
void LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||||
std::pair<bool, std::string> Result;
|
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||||
auto Client = GetClient(Engine->Server(), PID);
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
if (!Client) {
|
|
||||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||||
Result.first = false;
|
return;
|
||||||
Result.second = "Invalid Player ID";
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
if (!Client->GetCarData(VID).empty()) {
|
auto c = MaybeClient.value().lock();
|
||||||
|
if (!c->GetCarData(VID).empty()) {
|
||||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
Engine->Network().SendToAll(nullptr, Destroy, true, true);
|
||||||
Client->DeleteCar(VID);
|
c->DeleteCar(VID);
|
||||||
Result.first = true;
|
|
||||||
} else {
|
|
||||||
Result.first = false;
|
|
||||||
Result.second = "Vehicle does not exist";
|
|
||||||
}
|
}
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||||
switch (ConfigID) {
|
switch (ConfigID) {
|
||||||
case 0: // debug
|
case 0: // debug
|
||||||
if (NewValue.is<bool>()) {
|
if (NewValue.is<bool>()) {
|
||||||
Application::SetSetting(StrDebug, NewValue.as<bool>());
|
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
|
||||||
beammp_info(std::string("Set `Debug` to ") + (Application::GetSettingBool(StrDebug) ? "true" : "false"));
|
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 1: // private
|
case 1: // private
|
||||||
if (NewValue.is<bool>()) {
|
if (NewValue.is<bool>()) {
|
||||||
Application::SetSetting(StrPrivate, NewValue.as<bool>());
|
Application::Settings.Private = NewValue.as<bool>();
|
||||||
beammp_info(std::string("Set `Private` to ") + (Application::GetSettingBool(StrPrivate) ? "true" : "false"));
|
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 2: // max cars
|
case 2: // max cars
|
||||||
if (NewValue.is<int>()) {
|
if (NewValue.is<int>()) {
|
||||||
Application::SetSetting(StrMaxCars, NewValue.as<int>());
|
Application::Settings.MaxCars = NewValue.as<int>();
|
||||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::GetSettingInt(StrMaxCars)));
|
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected integer");
|
beammp_lua_error("set invalid argument [2] expected integer");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 3: // max players
|
case 3: // max players
|
||||||
if (NewValue.is<int>()) {
|
if (NewValue.is<int>()) {
|
||||||
Application::SetSetting(StrMaxPlayers, NewValue.as<int>());
|
Application::Settings.MaxPlayers = NewValue.as<int>();
|
||||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::GetSettingInt(StrMaxPlayers)));
|
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected integer");
|
beammp_lua_error("set invalid argument [2] expected integer");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 4: // Map
|
case 4: // Map
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::SetSetting(StrMap, NewValue.as<std::string>());
|
Application::Settings.MapName = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Map` to ") + Application::GetSettingString(StrMap));
|
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 5: // Name
|
case 5: // Name
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::SetSetting(StrName, NewValue.as<std::string>());
|
Application::Settings.ServerName = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Name` to ") + Application::GetSettingString(StrName));
|
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 6: // Desc
|
case 6: // Desc
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::SetSetting(StrDescription, NewValue.as<std::string>());
|
Application::Settings.ServerDesc = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Description` to ") + Application::GetSettingString(StrDescription));
|
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
@@ -269,18 +247,18 @@ void LuaAPI::MP::Sleep(size_t Ms) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||||
auto Client = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
return Client->IsConnected();
|
return MaybeClient.value().lock()->IsConnected();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||||
auto Client = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
return Client->IsGuest();
|
return MaybeClient.value().lock()->IsGuest();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -298,7 +276,6 @@ void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int LuaAPI::PanicHandler(lua_State* State) {
|
int LuaAPI::PanicHandler(lua_State* State) {
|
||||||
// FIXME: unsafe operation, can cause stack overflow
|
|
||||||
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -523,7 +500,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string key {};
|
std::string key;
|
||||||
switch (left.get_type()) {
|
switch (left.get_type()) {
|
||||||
case sol::type::lua_nil:
|
case sol::type::lua_nil:
|
||||||
case sol::type::none:
|
case sol::type::none:
|
||||||
@@ -542,8 +519,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
case sol::type::number:
|
case sol::type::number:
|
||||||
key = std::to_string(left.as<double>());
|
key = std::to_string(left.as<double>());
|
||||||
break;
|
break;
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
nlohmann::json value;
|
nlohmann::json value;
|
||||||
switch (right.get_type()) {
|
switch (right.get_type()) {
|
||||||
@@ -569,11 +544,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
value = right.as<std::string>();
|
value = right.as<std::string>();
|
||||||
break;
|
break;
|
||||||
case sol::type::number:
|
case sol::type::number:
|
||||||
if (right.is<int>()) {
|
value = right.as<double>();
|
||||||
value = right.as<int>();
|
|
||||||
} else {
|
|
||||||
value = right.as<float>();
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
case sol::type::function:
|
case sol::type::function:
|
||||||
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
||||||
@@ -583,7 +554,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
for (const auto& pair : right.as<sol::table>()) {
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
if (pair.first.get_type() != sol::type::number) {
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
local_is_array = false;
|
local_is_array = false;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const auto& pair : right.as<sol::table>()) {
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
@@ -591,8 +561,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
if (is_array) {
|
if (is_array) {
|
||||||
json.push_back(value);
|
json.push_back(value);
|
||||||
@@ -608,11 +576,10 @@ std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
|||||||
for (const auto& pair : object.as<sol::table>()) {
|
for (const auto& pair : object.as<sol::table>()) {
|
||||||
if (pair.first.get_type() != sol::type::number) {
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
is_array = false;
|
is_array = false;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const auto& [key, value] : object) {
|
for (const auto& entry : object) {
|
||||||
JsonEncodeRecursive(json, key, value, is_array);
|
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||||
}
|
}
|
||||||
return json.dump();
|
return json.dump();
|
||||||
}
|
}
|
||||||
@@ -678,6 +645,6 @@ std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
|||||||
return nlohmann::json::parse(json).unflatten().dump(-1);
|
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||||
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include "Compat.h"
|
|
||||||
|
|
||||||
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
#include <csignal>
|
#include <csignal>
|
||||||
static void UnixSignalHandler(int sig) {
|
static void UnixSignalHandler(int sig) {
|
||||||
|
|||||||
+151
-64
@@ -6,6 +6,32 @@
|
|||||||
#include <istream>
|
#include <istream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
// General
|
||||||
|
static constexpr std::string_view StrDebug = "Debug";
|
||||||
|
static constexpr std::string_view StrPrivate = "Private";
|
||||||
|
static constexpr std::string_view StrPort = "Port";
|
||||||
|
static constexpr std::string_view StrMaxCars = "MaxCars";
|
||||||
|
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
||||||
|
static constexpr std::string_view StrMap = "Map";
|
||||||
|
static constexpr std::string_view StrName = "Name";
|
||||||
|
static constexpr std::string_view StrDescription = "Description";
|
||||||
|
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||||
|
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||||
|
static constexpr std::string_view StrLogChat = "LogChat";
|
||||||
|
|
||||||
|
// Misc
|
||||||
|
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
|
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||||
|
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||||
|
|
||||||
|
// HTTP
|
||||||
|
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||||
|
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
||||||
|
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
||||||
|
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
||||||
|
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
||||||
|
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||||
|
|
||||||
TEST_CASE("TConfig::TConfig") {
|
TEST_CASE("TConfig::TConfig") {
|
||||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||||
fs::remove(CfgFile);
|
fs::remove(CfgFile);
|
||||||
@@ -18,10 +44,7 @@ TEST_CASE("TConfig::TConfig") {
|
|||||||
{
|
{
|
||||||
buf.resize(fs::file_size(CfgFile));
|
buf.resize(fs::file_size(CfgFile));
|
||||||
auto fp = std::fopen(CfgFile.c_str(), "r");
|
auto fp = std::fopen(CfgFile.c_str(), "r");
|
||||||
auto res = std::fread(buf.data(), 1, buf.size(), fp);
|
std::fread(buf.data(), 1, buf.size(), fp);
|
||||||
if (res != buf.size()) {
|
|
||||||
// IGNORE?
|
|
||||||
}
|
|
||||||
std::fclose(fp);
|
std::fclose(fp);
|
||||||
}
|
}
|
||||||
INFO("file contents are:", buf);
|
INFO("file contents are:", buf);
|
||||||
@@ -67,37 +90,35 @@ void SetComment(CommentsT& Comments, const std::string& Comment) {
|
|||||||
void TConfig::FlushToFile() {
|
void TConfig::FlushToFile() {
|
||||||
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||||
auto data = toml::value {};
|
auto data = toml::value {};
|
||||||
data["General"][StrAuthKey.data()] = Application::GetSettingString(StrAuthKey.data());
|
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
||||||
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
||||||
data["General"][StrLogChat.data()] = Application::GetSettingBool(StrLogChat.data());
|
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
|
||||||
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
||||||
data["General"][StrDebug.data()] = Application::GetSettingBool(StrDebug.data());
|
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||||
data["General"][StrPrivate.data()] = Application::GetSettingBool(StrPrivate.data());
|
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||||
data["General"][StrPort.data()] = Application::GetSettingInt(StrPort.data());
|
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||||
data["General"][StrName.data()] = Application::GetSettingString(StrName.data());
|
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||||
data["General"][StrMaxCars.data()] = Application::GetSettingInt(StrMaxCars.data());
|
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
||||||
data["General"][StrMaxPlayers.data()] = Application::GetSettingInt(StrMaxPlayers.data());
|
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||||
data["General"][StrMap.data()] = Application::GetSettingString(StrMap.data());
|
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||||
data["General"][StrDescription.data()] = Application::GetSettingString(StrDescription.data());
|
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||||
data["General"][StrResourceFolder.data()] = Application::GetSettingString(StrResourceFolder.data());
|
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||||
// Misc
|
// Misc
|
||||||
data["Misc"][StrHideUpdateMessages.data()] = Application::GetSettingBool(StrHideUpdateMessages.data());
|
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||||
data["Misc"][StrSendErrors.data()] = Application::GetSettingBool(StrSendErrors.data());
|
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::GetSettingBool(StrSendErrorsMessageEnabled.data());
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
data["Misc"][StrIncludeSubdirectories.data()] = Application::GetSettingBool(StrIncludeSubdirectories.data());
|
|
||||||
SetComment(data["Misc"][StrIncludeSubdirectories.data()].comments(), " Whether or not to include subdirectories in General.ResourceFolder/Client when searching for `.zip`s");
|
|
||||||
// HTTP
|
// HTTP
|
||||||
data["HTTP"][StrSSLKeyPath.data()] = Application::GetSettingString(StrSSLKeyPath.data());
|
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
||||||
data["HTTP"][StrSSLCertPath.data()] = Application::GetSettingString(StrSSLCertPath.data());
|
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
||||||
data["HTTP"][StrHTTPServerPort.data()] = Application::GetSettingInt(StrHTTPServerPort.data());
|
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
||||||
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
||||||
data["HTTP"][StrHTTPServerIP.data()] = Application::GetSettingString(StrHTTPServerIP.data());
|
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
||||||
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::GetSettingBool(StrHTTPServerUseSSL.data());
|
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
|
||||||
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
||||||
data["HTTP"][StrHTTPServerEnabled.data()] = Application::GetSettingBool(StrHTTPServerEnabled.data());
|
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
||||||
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
||||||
std::stringstream Ss;
|
std::stringstream Ss;
|
||||||
Ss << "# This is the BeamMP-Server config file.\n"
|
Ss << "# This is the BeamMP-Server config file.\n"
|
||||||
@@ -132,42 +153,50 @@ void TConfig::CreateConfigFile() {
|
|||||||
FlushToFile();
|
FlushToFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
||||||
if (Table[Category.c_str()][Key.data()].is_string()) {
|
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||||
Application::SetSetting(Key, std::string(Table[Category.c_str()][Key.data()].as_string()));
|
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||||
} else if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
|
||||||
Application::SetSetting(Key, bool(Table[Category.c_str()][Key.data()].as_boolean()));
|
|
||||||
} else if (Table[Category.c_str()][Key.data()].is_integer()) {
|
|
||||||
Application::SetSetting(Key, int(Table[Category.c_str()][Key.data()].as_integer()));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_integer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void TConfig::ParseFromFile(std::string_view name) {
|
void TConfig::ParseFromFile(std::string_view name) {
|
||||||
try {
|
try {
|
||||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
// GENERAL
|
// GENERAL
|
||||||
TryReadValue(data, "General", StrDebug);
|
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
||||||
TryReadValue(data, "General", StrPrivate);
|
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
||||||
TryReadValue(data, "General", StrPort);
|
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
||||||
TryReadValue(data, "General", StrMaxCars);
|
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
||||||
TryReadValue(data, "General", StrMaxPlayers);
|
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
TryReadValue(data, "General", StrMap);
|
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
||||||
TryReadValue(data, "General", StrName);
|
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
||||||
TryReadValue(data, "General", StrDescription);
|
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
||||||
TryReadValue(data, "General", StrResourceFolder);
|
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||||
TryReadValue(data, "General", StrAuthKey);
|
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||||
TryReadValue(data, "General", StrLogChat);
|
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||||
// Misc
|
// Misc
|
||||||
TryReadValue(data, "Misc", StrSendErrors);
|
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||||
TryReadValue(data, "Misc", StrHideUpdateMessages);
|
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled);
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
||||||
TryReadValue(data, "Misc", StrIncludeSubdirectories);
|
|
||||||
// HTTP
|
// HTTP
|
||||||
TryReadValue(data, "HTTP", StrSSLKeyPath);
|
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||||
TryReadValue(data, "HTTP", StrSSLCertPath);
|
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerPort);
|
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerIP);
|
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerEnabled);
|
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerUseSSL);
|
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
|
||||||
} 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;
|
||||||
@@ -179,28 +208,86 @@ void TConfig::ParseFromFile(std::string_view name) {
|
|||||||
// Update in any case
|
// Update in any case
|
||||||
FlushToFile();
|
FlushToFile();
|
||||||
// all good so far, let's check if there's a key
|
// all good so far, let's check if there's a key
|
||||||
if (Application::GetSettingString(StrAuthKey).empty()) {
|
if (Application::Settings.Key.empty()) {
|
||||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server. Alternatively, if you only want a private server (one that doesn't show up in the server list), you may put anything as your AuthKey, like \"hello\".");
|
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
mFailed = true;
|
mFailed = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
||||||
if (Application::GetSettingString(StrAuthKey).size() != 36) {
|
if (Application::Settings.Key.size() != 36) {
|
||||||
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::PrintDebug() {
|
void TConfig::PrintDebug() {
|
||||||
for (const auto& [k, v] : Application::mSettings) {
|
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||||
if (k == StrAuthKey) {
|
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||||
beammp_debugf("AuthKey: length {}", std::get<std::string>(v).size());
|
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||||
continue;
|
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||||
}
|
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||||
beammp_debugf("{}: {}", k, Application::SettingToString(v));
|
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||||
}
|
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||||
|
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||||
|
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||||
|
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||||
|
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
|
||||||
|
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
|
||||||
|
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
|
||||||
|
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
||||||
|
// special!
|
||||||
|
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseOldFormat() {
|
void TConfig::ParseOldFormat() {
|
||||||
beammp_warnf("You still have a 'Server.cfg' - this will not be used (this server uses 'ServerConfig.toml'. Since v3.0.2 we no longer parse and import these old settings. Remove the file to avoid confusion and disable this message.");
|
std::ifstream File("Server.cfg");
|
||||||
|
// read all, strip comments
|
||||||
|
std::string Content;
|
||||||
|
for (;;) {
|
||||||
|
std::string Line;
|
||||||
|
std::getline(File, Line);
|
||||||
|
if (!Line.empty() && Line.at(0) != '#') {
|
||||||
|
Line = Line.substr(0, Line.find_first_of('#'));
|
||||||
|
Content += Line + "\n";
|
||||||
|
}
|
||||||
|
if (!File.good()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::stringstream Str(Content);
|
||||||
|
std::string Key, Ignore, Value;
|
||||||
|
for (;;) {
|
||||||
|
Str >> Key >> std::ws >> Ignore >> std::ws;
|
||||||
|
std::getline(Str, Value);
|
||||||
|
if (Str.eof()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::stringstream ValueStream(Value);
|
||||||
|
ValueStream >> std::ws; // strip leading whitespace if any
|
||||||
|
Value = ValueStream.str();
|
||||||
|
if (Key == "Debug") {
|
||||||
|
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
|
||||||
|
} else if (Key == "Private") {
|
||||||
|
Application::Settings.Private = Value.find("true") != std::string::npos;
|
||||||
|
} else if (Key == "Port") {
|
||||||
|
ValueStream >> Application::Settings.Port;
|
||||||
|
} else if (Key == "Cars") {
|
||||||
|
ValueStream >> Application::Settings.MaxCars;
|
||||||
|
} else if (Key == "MaxPlayers") {
|
||||||
|
ValueStream >> Application::Settings.MaxPlayers;
|
||||||
|
} else if (Key == "Map") {
|
||||||
|
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "Name") {
|
||||||
|
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "Desc") {
|
||||||
|
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "use") {
|
||||||
|
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "AuthKey") {
|
||||||
|
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||||
|
} else {
|
||||||
|
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||||
|
}
|
||||||
|
Str >> std::ws;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+72
-321
@@ -7,34 +7,13 @@
|
|||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <boost/asio/ip/address.hpp>
|
|
||||||
#include <boost/spirit/home/qi/directive/lexeme.hpp>
|
|
||||||
#include <boost/spirit/home/qi/parse.hpp>
|
|
||||||
#include <chrono>
|
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
#include <fmt/chrono.h>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
#include <boost/phoenix.hpp>
|
|
||||||
#include <boost/spirit/include/qi.hpp>
|
|
||||||
|
|
||||||
#include <boost/algorithm/string.hpp>
|
|
||||||
|
|
||||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||||
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline bool StringStartsWithLower(const std::string& Name1, const std::string& Name2) {
|
|
||||||
std::string Name1Lower = boost::algorithm::to_lower_copy(Name1);
|
|
||||||
return StringStartsWith(Name1Lower, Name2) || StringStartsWith(Name2, Name1Lower);
|
|
||||||
};
|
|
||||||
|
|
||||||
static inline bool StringStartsWithLowerBoth(const std::string& Name1, const std::string& Name2) {
|
|
||||||
std::string Name1Lower = boost::algorithm::to_lower_copy(Name1);
|
|
||||||
std::string Name2Lower = boost::algorithm::to_lower_copy(Name2);
|
|
||||||
return StringStartsWith(Name1Lower, Name2Lower) || StringStartsWith(Name2Lower, Name1Lower);
|
|
||||||
};
|
|
||||||
|
|
||||||
TEST_CASE("StringStartsWith") {
|
TEST_CASE("StringStartsWith") {
|
||||||
CHECK(StringStartsWith("Hello, World", "Hello"));
|
CHECK(StringStartsWith("Hello, World", "Hello"));
|
||||||
CHECK(StringStartsWith("Hello, World", "H"));
|
CHECK(StringStartsWith("Hello, World", "H"));
|
||||||
@@ -72,25 +51,14 @@ TEST_CASE("TrimString") {
|
|||||||
CHECK(TrimString("") == "");
|
CHECK(TrimString("") == "");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: add unit tests to SplitString
|
std::string GetDate() {
|
||||||
static inline void SplitString(std::string const& str, const char delim, std::vector<std::string>& out) {
|
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||||
size_t start;
|
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||||
size_t end = 0;
|
|
||||||
|
|
||||||
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
|
|
||||||
end = str.find(delim, start);
|
|
||||||
out.push_back(str.substr(start, end - start));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::string GetDate() {
|
|
||||||
TimeType::time_point now = TimeType::now();
|
|
||||||
time_t tt = TimeType::to_time_t(now);
|
|
||||||
auto local_tm = std::localtime(&tt);
|
auto local_tm = std::localtime(&tt);
|
||||||
char buf[30];
|
char buf[30];
|
||||||
std::string date;
|
std::string date;
|
||||||
if (Application::GetSettingBool(StrDebug)) {
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
std::strftime(buf, sizeof(buf), "[%Y/%m/%d %T.", local_tm);
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||||
date += buf;
|
date += buf;
|
||||||
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||||
auto fraction = now - seconds;
|
auto fraction = now - seconds;
|
||||||
@@ -100,7 +68,7 @@ static std::string GetDate() {
|
|||||||
date += fracstr;
|
date += fracstr;
|
||||||
date += "] ";
|
date += "] ";
|
||||||
} else {
|
} else {
|
||||||
std::strftime(buf, sizeof(buf), "[%Y/%m/%d %T] ", local_tm);
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
|
||||||
date += buf;
|
date += buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,10 +144,10 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
|||||||
mStateId = LuaStateId;
|
mStateId = LuaStateId;
|
||||||
mIsLuaConsole = true;
|
mIsLuaConsole = true;
|
||||||
if (mStateId != mDefaultStateId) {
|
if (mStateId != mDefaultStateId) {
|
||||||
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`");
|
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:detach`");
|
||||||
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
||||||
} else {
|
} else {
|
||||||
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
|
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:detach`");
|
||||||
mCommandline.set_prompt("lua> ");
|
mCommandline.set_prompt("lua> ");
|
||||||
}
|
}
|
||||||
mCachedRegularHistory = mCommandline.history();
|
mCachedRegularHistory = mCommandline.history();
|
||||||
@@ -219,10 +187,10 @@ bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min,
|
|||||||
return EnsureArgsCount(args, min);
|
return EnsureArgsCount(args, min);
|
||||||
} else {
|
} else {
|
||||||
if (args.size() > max) {
|
if (args.size() > max) {
|
||||||
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
} else if (args.size() < min) {
|
} else if (args.size() < min) {
|
||||||
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -253,17 +221,14 @@ void TConsole::Command_Help(const std::string&, const std::vector<std::string>&
|
|||||||
static constexpr const char* sHelpString = R"(
|
static constexpr const char* sHelpString = R"(
|
||||||
Commands:
|
Commands:
|
||||||
help displays this help
|
help displays this help
|
||||||
exit
|
exit shuts down the server
|
||||||
quit shuts down the server
|
|
||||||
kick <name> [reason] kicks specified player with an optional reason
|
kick <name> [reason] kicks specified player with an optional reason
|
||||||
list lists all players and info about them
|
list lists all players and info about them
|
||||||
say <message> sends the message to all players in chat
|
say <message> sends the message to all players in chat
|
||||||
lua [state id] switches to lua, optionally into a specific state id's lua
|
lua [state id] switches to lua, optionally into a specific state id's lua
|
||||||
settings [command] sets or gets settings for the server, run `settings help` for more info
|
settings [command] sets or gets settings for the server, run `settings help` for more info
|
||||||
status how the server is doing and what it's up to
|
status how the server is doing and what it's up to
|
||||||
debug internal error and debug state of the server (for development)
|
clear clears the console window)";
|
||||||
clear clears the console window
|
|
||||||
version version info)";
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,114 +248,32 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
|
|||||||
mCommandline.write("\x1b[;H\x1b[2J");
|
mCommandline.write("\x1b[;H\x1b[2J");
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Debug(const std::string&, const std::vector<std::string>& args) {
|
|
||||||
if (!EnsureArgsCount(args, 0)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Application::Console().WriteRaw(fmt::format(R"(Debug info (for developers):
|
|
||||||
UDP:
|
|
||||||
Malformed packets: {}
|
|
||||||
Invalid packets: {})",
|
|
||||||
Application::MalformedUdpPackets,
|
|
||||||
Application::InvalidUdpPackets));
|
|
||||||
Application::Console().WriteRaw(fmt::format(R"( Clients:
|
|
||||||
Note: All data/second rates are an average across the total time since
|
|
||||||
connection and do not necessarily reflect the *current* data rate
|
|
||||||
of that client.
|
|
||||||
)"));
|
|
||||||
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
|
|
||||||
std::string State = "";
|
|
||||||
if (Client->IsSyncing()) {
|
|
||||||
State += "Syncing";
|
|
||||||
}
|
|
||||||
if (Client->IsSynced()) {
|
|
||||||
if (!State.empty()) {
|
|
||||||
State += " & ";
|
|
||||||
}
|
|
||||||
State += "Synced";
|
|
||||||
}
|
|
||||||
if (Client->IsConnected()) {
|
|
||||||
if (!State.empty()) {
|
|
||||||
State += " & ";
|
|
||||||
}
|
|
||||||
State += "Connected";
|
|
||||||
}
|
|
||||||
if (Client->IsDisconnected()) {
|
|
||||||
if (!State.empty()) {
|
|
||||||
State += " & ";
|
|
||||||
}
|
|
||||||
State += "Disconnected";
|
|
||||||
}
|
|
||||||
auto Now = TimeType::now();
|
|
||||||
auto Seconds = std::chrono::duration_cast<std::chrono::seconds>(Now - Client->ConnectionTime);
|
|
||||||
std::string ConnectedSince = fmt::format("{:%Y/%m/%d %H:%M:%S}, {:%H:%M:%S} ago ({} seconds)",
|
|
||||||
fmt::localtime(TimeType::to_time_t(Client->ConnectionTime)),
|
|
||||||
Seconds,
|
|
||||||
Seconds.count());
|
|
||||||
Application::Console().WriteRaw(fmt::format(
|
|
||||||
R"( {} ('{}'):
|
|
||||||
Roles: {}
|
|
||||||
Cars: {}
|
|
||||||
Is guest: {}
|
|
||||||
Has unicycle: {}
|
|
||||||
TCP: {} (on port {})
|
|
||||||
UDP: {} (on port {})
|
|
||||||
Sent via TCP: {}
|
|
||||||
Received via TCP: {}
|
|
||||||
Sent via UDP: {} ({} packets)
|
|
||||||
Received via UDP: {} ({} packets)
|
|
||||||
Status: {}
|
|
||||||
Queued packets: {}
|
|
||||||
Latest packet: {}s ago
|
|
||||||
Connected since: {}
|
|
||||||
Average send: {}/s
|
|
||||||
Average receive: {}/s)",
|
|
||||||
Client->GetID(), Client->GetName(),
|
|
||||||
Client->GetRoles(),
|
|
||||||
Client->GetCarCount(),
|
|
||||||
Client->IsGuest() ? "yes" : "no",
|
|
||||||
Client->GetUnicycleID() == -1 ? "no" : "yes",
|
|
||||||
Client->GetTCPSock().remote_endpoint().address() == ip::address::from_string("0.0.0.0") ? "not connected" : "connected", Client->GetTCPSock().remote_endpoint().port(),
|
|
||||||
Client->GetUDPAddr().address() == ip::address::from_string("0.0.0.0") ? "NOT connected" : "connected", Client->GetUDPAddr().port(),
|
|
||||||
ToHumanReadableSize(Client->TcpSent),
|
|
||||||
ToHumanReadableSize(Client->TcpReceived),
|
|
||||||
ToHumanReadableSize(Client->UdpSent), Client->UdpPacketsSent,
|
|
||||||
ToHumanReadableSize(Client->UdpReceived), Client->UdpPacketsReceived,
|
|
||||||
State.empty() ? "None (likely pre-sync)" : State,
|
|
||||||
Client->MissedPacketQueueSize(),
|
|
||||||
Client->SecondsSinceLastPing(),
|
|
||||||
ConnectedSince,
|
|
||||||
ToHumanReadableSize((Client->TcpSent + Client->UdpSent) / Seconds.count()),
|
|
||||||
ToHumanReadableSize((Client->TcpReceived + Client->UdpReceived) / Seconds.count())));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Command_Version(const std::string&, const std::vector<std::string>& args) {
|
|
||||||
if (!EnsureArgsCount(args, 0)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Application::Console().WriteRaw(fmt::format("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH));
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
auto Name = boost::algorithm::to_lower_copy(args.at(0));
|
auto Name = args.at(0);
|
||||||
std::string Reason = "Kicked by server console";
|
std::string Reason = "Kicked by server console";
|
||||||
if (args.size() > 1) {
|
if (args.size() > 1) {
|
||||||
Reason = ConcatArgs({ args.begin() + 1, args.end() });
|
Reason = ConcatArgs({ args.begin() + 1, args.end() });
|
||||||
}
|
}
|
||||||
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||||
bool Kicked = false;
|
bool Kicked = false;
|
||||||
|
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||||
mLuaEngine->Server().ForEachClient([&](const auto& Client) -> IterationDecision {
|
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
||||||
if (StringStartsWithLower(Client->GetName(), Name)) {
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
||||||
mLuaEngine->Network().ClientKick(*Client, Reason);
|
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||||
Kicked = true;
|
};
|
||||||
return Break;
|
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
|
if (!Client.expired()) {
|
||||||
|
auto locked = Client.lock();
|
||||||
|
if (NameCompare(locked->GetName(), Name)) {
|
||||||
|
mLuaEngine->Network().ClientKick(*locked, Reason);
|
||||||
|
Kicked = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return Continue;
|
return true;
|
||||||
});
|
});
|
||||||
if (!Kicked) {
|
if (!Kicked) {
|
||||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||||
@@ -437,9 +320,7 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
}
|
}
|
||||||
++Ptr;
|
++Ptr;
|
||||||
}
|
}
|
||||||
// this is required, otherwise we get negative int to unsigned cast in the next operations
|
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
||||||
beammp_assert(PrevPtr <= Ptr);
|
|
||||||
Arg = std::string(PrevPtr, std::string::size_type(Ptr - PrevPtr));
|
|
||||||
// remove quotes if enclosed in quotes
|
// remove quotes if enclosed in quotes
|
||||||
for (char Quote : { '"', '\'', '`' }) {
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||||
@@ -455,80 +336,16 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (!EnsureArgsCount(args, 1, 100)) {
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
static const char* SETTINGS_HELP = R"(Settings:
|
|
||||||
settings help Displays this help
|
|
||||||
settings list Lists all settings
|
|
||||||
settings get <setting> Prints the current value of the specified setting
|
|
||||||
settings set <setting> <value> Sets the specified setting to the value)";
|
|
||||||
if (args.at(0) == "help") {
|
|
||||||
Application::Console().WriteRaw(SETTINGS_HELP);
|
|
||||||
} else if (args.at(0) == "list") {
|
|
||||||
Application::Console().WriteRaw("Available settings:");
|
|
||||||
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", "<NAME>", "<CURRENT VALUE>"));
|
|
||||||
for (const auto& [k, v] : Application::mSettings) {
|
|
||||||
if (k == StrAuthKey) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("\t{:<25} <key of length {}>", k, Application::SettingToString(v).size()));
|
|
||||||
} else {
|
|
||||||
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", k, Application::SettingToString(v)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (args.at(0) == "get") {
|
|
||||||
if (args.size() < 2) {
|
|
||||||
Application::Console().WriteRaw("Not enough arguments: `settings get` requires a setting name.");
|
|
||||||
} else {
|
|
||||||
if (Application::mSettings.contains(args.at(1))) {
|
|
||||||
if (args.at(1) != StrAuthKey) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} = {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
|
|
||||||
} else {
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} = <key of length {}>", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1))).size()));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Application::Console().WriteRaw(fmt::format("Setting '{}' doesn't exist.", args.at(1)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (args.at(0) == "set") {
|
|
||||||
if (args.size() < 3) {
|
|
||||||
Application::Console().WriteRaw("Not enough arguments: `settings set` requires a setting name and value.");
|
|
||||||
} else {
|
|
||||||
if (args.at(1) == StrAuthKey) {
|
|
||||||
Application::Console().WriteRaw("It's not allowed to set the AuthKey during runtime.");
|
|
||||||
} else {
|
|
||||||
using namespace boost::spirit;
|
|
||||||
using qi::_1;
|
|
||||||
std::string ValueString = args.at(2);
|
|
||||||
Application::SettingValue Value;
|
|
||||||
qi::rule<std::string::iterator, std::string()> StringRule;
|
|
||||||
StringRule
|
|
||||||
%= qi::lexeme['"' >> *(qi::char_ - '"') >> '"']
|
|
||||||
| +(qi::char_ - '"');
|
|
||||||
qi::rule<std::string::iterator, Application::SettingValue()> ValueRule
|
|
||||||
= qi::bool_
|
|
||||||
| qi::int_
|
|
||||||
| StringRule;
|
|
||||||
auto It = ValueString.begin();
|
|
||||||
if (qi::phrase_parse(It, ValueString.end(), ValueRule[boost::phoenix::ref(Value) = _1], ascii::space)
|
|
||||||
&& It == ValueString.end()) {
|
|
||||||
Application::SetSetting(args.at(1), Value);
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} := {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
|
|
||||||
} else {
|
|
||||||
Application::Console().WriteRaw(fmt::format("New value '{}' did not parse as a valid value.", ValueString));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Application::Console().WriteRaw(fmt::format("Unknown argument '{}' - 'settings {}' is not a valid command.", args.at(0), args.at(0)));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Say(const std::string& FullCmd) {
|
void TConsole::Command_Say(const std::string& FullCmd) {
|
||||||
if (FullCmd.size() > 3) {
|
if (FullCmd.size() > 3) {
|
||||||
auto Message = FullCmd.substr(4);
|
auto Message = FullCmd.substr(4);
|
||||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||||
if (!Application::GetSettingBool(StrLogChat)) {
|
if (!Application::Settings.LogChat) {
|
||||||
Application::Console().WriteRaw("Chat message sent!");
|
Application::Console().WriteRaw("Chat message sent!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -543,10 +360,14 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
|
|||||||
} else {
|
} else {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||||
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
|
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
ss << std::left << std::setw(25) << Client->GetName()
|
if (!Client.expired()) {
|
||||||
<< std::setw(6) << Client->GetID()
|
auto locked = Client.lock();
|
||||||
<< std::setw(6) << Client->GetCarCount() << "\n";
|
ss << std::left << std::setw(25) << locked->GetName()
|
||||||
|
<< std::setw(6) << locked->GetID()
|
||||||
|
<< std::setw(6) << locked->GetCarCount() << "\n";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
auto Str = ss.str();
|
auto Str = ss.str();
|
||||||
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||||
@@ -566,16 +387,20 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
size_t SyncingCount = 0;
|
size_t SyncingCount = 0;
|
||||||
size_t MissedPacketQueueSum = 0;
|
size_t MissedPacketQueueSum = 0;
|
||||||
int LargestSecondsSinceLastPing = 0;
|
int LargestSecondsSinceLastPing = 0;
|
||||||
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
|
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
CarCount += Client->GetCarCount();
|
if (!Client.expired()) {
|
||||||
ConnectedCount += Client->IsConnected() ? 1 : 0;
|
auto Locked = Client.lock();
|
||||||
GuestCount += Client->IsGuest() ? 1 : 0;
|
CarCount += Locked->GetCarCount();
|
||||||
SyncedCount += Client->IsSynced() ? 1 : 0;
|
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
||||||
SyncingCount += Client->IsSyncing() ? 1 : 0;
|
GuestCount += Locked->IsGuest() ? 1 : 0;
|
||||||
MissedPacketQueueSum += Client->MissedPacketQueueSize();
|
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
||||||
if (Client->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
||||||
LargestSecondsSinceLastPing = Client->SecondsSinceLastPing();
|
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
||||||
|
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
||||||
|
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
size_t SystemsStarting = 0;
|
size_t SystemsStarting = 0;
|
||||||
@@ -611,8 +436,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
SystemsShutdown++;
|
SystemsShutdown++;
|
||||||
SystemsShutdownList += NameStatusPair.first + ", ";
|
SystemsShutdownList += NameStatusPair.first + ", ";
|
||||||
break;
|
break;
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// remove ", " at the end
|
// remove ", " at the end
|
||||||
@@ -631,7 +454,7 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
<< "\tConnected Players: " << ConnectedCount << "\n"
|
||||||
<< "\tGuests: " << GuestCount << "\n"
|
<< "\tGuests: " << GuestCount << "\n"
|
||||||
<< "\tCars: " << CarCount << "\n"
|
<< "\tCars: " << CarCount << "\n"
|
||||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||||
<< "\tLua:\n"
|
<< "\tLua:\n"
|
||||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||||
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||||
@@ -639,66 +462,17 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
||||||
<< "\tSubsystems:\n"
|
<< "\tSubsystems:\n"
|
||||||
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
||||||
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
||||||
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
||||||
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
||||||
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
||||||
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
||||||
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||||
<< "";
|
<< "";
|
||||||
|
|
||||||
Application::Console().WriteRaw(Status.str());
|
Application::Console().WriteRaw(Status.str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Autocomplete_Lua(const std::string& stub, std::vector<std::string>& suggestions) {
|
|
||||||
auto stateNames = mLuaEngine->GetLuaStateNames();
|
|
||||||
|
|
||||||
for (const auto& name : stateNames) {
|
|
||||||
if (name.find(stub) == 0) {
|
|
||||||
suggestions.push_back("lua " + name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Autocomplete_Kick(const std::string& stub, std::vector<std::string>& suggestions) {
|
|
||||||
std::string stub_lower = boost::algorithm::to_lower_copy(stub);
|
|
||||||
|
|
||||||
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
|
|
||||||
if (StringStartsWithLower(Client->GetName(), stub_lower)) {
|
|
||||||
suggestions.push_back("kick " + Client->GetName());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Autocomplete_Settings(const std::string& stub, std::vector<std::string>& suggestions) {
|
|
||||||
const std::string subcommands[] = { "help", "list", "set", "get" };
|
|
||||||
|
|
||||||
auto [command, args] = ParseCommand(stub);
|
|
||||||
|
|
||||||
std::string arg;
|
|
||||||
if (!args.empty())
|
|
||||||
arg = boost::algorithm::to_lower_copy(args.at(0));
|
|
||||||
|
|
||||||
// suggest setting names
|
|
||||||
if (command == "set" || command == "get") {
|
|
||||||
for (const auto& [k, v] : Application::mSettings) {
|
|
||||||
std::string key = std::string(k);
|
|
||||||
if (StringStartsWithLower(key, arg)) {
|
|
||||||
suggestions.push_back("settings " + command + " " + key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// suggest subcommands
|
|
||||||
for (const auto& cmd : subcommands) {
|
|
||||||
if (cmd.find(command) == 0) {
|
|
||||||
suggestions.push_back("settings " + cmd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||||
auto FutureIsNonNil =
|
auto FutureIsNonNil =
|
||||||
[](const std::shared_ptr<TLuaResult>& Future) {
|
[](const std::shared_ptr<TLuaResult>& Future) {
|
||||||
@@ -800,6 +574,7 @@ Commands
|
|||||||
TConsole::TConsole() {
|
TConsole::TConsole() {
|
||||||
mCommandline.enable_history();
|
mCommandline.enable_history();
|
||||||
mCommandline.set_history_limit(20);
|
mCommandline.set_history_limit(20);
|
||||||
|
mCommandline.set_prompt("> ");
|
||||||
BackupOldLog();
|
BackupOldLog();
|
||||||
mCommandline.on_command = [this](Commandline& c) {
|
mCommandline.on_command = [this](Commandline& c) {
|
||||||
try {
|
try {
|
||||||
@@ -824,7 +599,7 @@ TConsole::TConsole() {
|
|||||||
} else {
|
} else {
|
||||||
if (!mLuaEngine) {
|
if (!mLuaEngine) {
|
||||||
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
|
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
|
||||||
} else if (cmd == "exit" || cmd == "quit") {
|
} else if (cmd == "exit") {
|
||||||
beammp_info("gracefully shutting down");
|
beammp_info("gracefully shutting down");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
} else if (cmd == "say") {
|
} else if (cmd == "say") {
|
||||||
@@ -846,66 +621,42 @@ TConsole::TConsole() {
|
|||||||
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||||
std::vector<std::string> suggestions;
|
std::vector<std::string> suggestions;
|
||||||
try {
|
try {
|
||||||
|
auto cmd = TrimString(stub);
|
||||||
|
// beammp_error("yes 1");
|
||||||
|
// beammp_error(stub);
|
||||||
if (mIsLuaConsole) { // if lua
|
if (mIsLuaConsole) { // if lua
|
||||||
if (!mLuaEngine) {
|
if (!mLuaEngine) {
|
||||||
beammp_info("Lua not started yet, please try again in a second");
|
beammp_info("Lua not started yet, please try again in a second");
|
||||||
} else {
|
} else {
|
||||||
std::string prefix {}; // stores non-table part of input
|
std::string prefix {};
|
||||||
for (size_t i = stub.length(); i > 0; i--) { // separate table from input
|
for (size_t i = stub.length(); i > 0; i--) {
|
||||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
|
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') {
|
||||||
prefix = stub.substr(0, i);
|
prefix = stub.substr(0, i);
|
||||||
stub = stub.substr(i);
|
stub = stub.substr(i);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
|
||||||
// turn string into vector of keys
|
for (const auto& key : keys) {
|
||||||
std::vector<std::string> tablekeys;
|
std::string::size_type n = key.find(stub);
|
||||||
|
|
||||||
SplitString(stub, '.', tablekeys);
|
|
||||||
|
|
||||||
// remove last key if incomplete
|
|
||||||
if (stub.rfind('.') != stub.size() - 1 && !tablekeys.empty()) {
|
|
||||||
tablekeys.pop_back();
|
|
||||||
}
|
|
||||||
|
|
||||||
auto keys = mLuaEngine->GetStateTableKeysForState(mStateId, tablekeys);
|
|
||||||
|
|
||||||
for (const auto& key : keys) { // go through each bottom-level key
|
|
||||||
auto last_dot = stub.rfind('.');
|
|
||||||
std::string last_atom;
|
|
||||||
if (last_dot != std::string::npos) {
|
|
||||||
last_atom = stub.substr(last_dot + 1);
|
|
||||||
}
|
|
||||||
std::string before_last_atom = stub.substr(0, last_dot + 1); // get last confirmed key
|
|
||||||
auto last = stub.substr(stub.rfind('.') + 1);
|
|
||||||
std::string::size_type n = key.find(last);
|
|
||||||
if (n == 0) {
|
if (n == 0) {
|
||||||
suggestions.push_back(prefix + before_last_atom + key);
|
suggestions.push_back(prefix + key);
|
||||||
|
// beammp_warn(cmd_name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else { // if not lua
|
} else { // if not lua
|
||||||
for (const auto& [cmd_name, autocomplete_fn] : mCommandAutocompleteMap) {
|
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||||
if (stub.find(cmd_name) == 0) { // input starts with a full command (that has autocomplete)
|
std::string::size_type n = cmd_name.find(stub);
|
||||||
std::size_t cmd_len = cmd_name.length();
|
if (n == 0) {
|
||||||
std::string trimmed = TrimString(stub.substr(cmd_len));
|
suggestions.push_back(cmd_name);
|
||||||
autocomplete_fn(trimmed, suggestions);
|
// beammp_warn(cmd_name);
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (suggestions.empty()) {
|
|
||||||
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
|
||||||
if (cmd_name.find(stub) == 0) {
|
|
||||||
suggestions.push_back(cmd_name);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||||
}
|
}
|
||||||
std::sort(suggestions.begin(), suggestions.end());
|
|
||||||
return suggestions;
|
return suggestions;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-23
@@ -17,14 +17,14 @@ void THeartbeatThread::operator()() {
|
|||||||
// these are "hot-change" related variables
|
// these are "hot-change" related variables
|
||||||
static std::string Last;
|
static std::string Last;
|
||||||
|
|
||||||
static TimeType::time_point LastNormalUpdateTime = TimeType::now();
|
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||||
bool isAuth = false;
|
bool isAuth = false;
|
||||||
size_t UpdateReminderCounter = 0;
|
size_t UpdateReminderCounter = 0;
|
||||||
while (!Application::IsShuttingDown()) {
|
while (!Application::IsShuttingDown()) {
|
||||||
++UpdateReminderCounter;
|
++UpdateReminderCounter;
|
||||||
Body = GenerateCall();
|
Body = GenerateCall();
|
||||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||||
auto Now = TimeType::now();
|
auto Now = std::chrono::high_resolution_clock::now();
|
||||||
bool Unchanged = Last == Body;
|
bool Unchanged = Last == Body;
|
||||||
auto TimePassed = (Now - LastNormalUpdateTime);
|
auto TimePassed = (Now - LastNormalUpdateTime);
|
||||||
auto Threshold = Unchanged ? 30 : 5;
|
auto Threshold = Unchanged ? 30 : 5;
|
||||||
@@ -36,10 +36,14 @@ void THeartbeatThread::operator()() {
|
|||||||
|
|
||||||
Last = Body;
|
Last = Body;
|
||||||
LastNormalUpdateTime = Now;
|
LastNormalUpdateTime = Now;
|
||||||
if (!Application::GetSettingString(StrCustomIP).empty()) {
|
if (!Application::Settings.CustomIP.empty()) {
|
||||||
Body += "&ip=" + Application::GetSettingString(StrCustomIP);
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Body += "&pps=" + Application::PPS();
|
||||||
|
|
||||||
|
beammp_trace("heartbeat body: '" + Body + "'");
|
||||||
|
|
||||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
auto SentryReportError = [&](const std::string& transaction, int status) {
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
Sentry.SetContext("heartbeat",
|
Sentry.SetContext("heartbeat",
|
||||||
@@ -57,10 +61,11 @@ void THeartbeatThread::operator()() {
|
|||||||
bool Ok = false;
|
bool Ok = false;
|
||||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
|
beammp_trace(T);
|
||||||
Doc.Parse(T.data(), T.size());
|
Doc.Parse(T.data(), T.size());
|
||||||
if (Doc.HasParseError() || !Doc.IsObject()) {
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
if (!Application::GetSettingBool(StrPrivate)) {
|
if (!Application::Settings.Private) {
|
||||||
beammp_trace("Backend response failed to parse as valid json");
|
beammp_error("Backend response failed to parse as valid json");
|
||||||
beammp_trace("Response was: `" + T + "`");
|
beammp_trace("Response was: `" + T + "`");
|
||||||
}
|
}
|
||||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
||||||
@@ -105,12 +110,12 @@ void THeartbeatThread::operator()() {
|
|||||||
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!Application::GetSettingBool(StrPrivate)) {
|
if (!Application::Settings.Private) {
|
||||||
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Ok && !isAuth && !Application::GetSettingBool(StrPrivate)) {
|
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||||
if (Status == "2000") {
|
if (Status == "2000") {
|
||||||
beammp_info(("Authenticated! " + Message));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
@@ -124,10 +129,10 @@ void THeartbeatThread::operator()() {
|
|||||||
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isAuth || Application::GetSettingBool(StrPrivate)) {
|
if (isAuth || Application::Settings.Private) {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
}
|
}
|
||||||
if (!Application::GetSettingBool(StrHideUpdateMessages) && UpdateReminderCounter % 5) {
|
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,20 +141,20 @@ void THeartbeatThread::operator()() {
|
|||||||
std::string THeartbeatThread::GenerateCall() {
|
std::string THeartbeatThread::GenerateCall() {
|
||||||
std::stringstream Ret;
|
std::stringstream Ret;
|
||||||
|
|
||||||
Ret << "uuid=" << Application::GetSettingString(StrAuthKey)
|
Ret << "uuid=" << Application::Settings.Key
|
||||||
<< "&players=" << mServer.ClientCount()
|
<< "&players=" << mServer.ClientCount()
|
||||||
<< "&maxplayers=" << Application::GetSettingInt(StrMaxPlayers)
|
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||||
<< "&port=" << Application::GetSettingInt(StrPort)
|
<< "&port=" << Application::Settings.Port
|
||||||
<< "&map=" << Application::GetSettingString(StrMap)
|
<< "&map=" << Application::Settings.MapName
|
||||||
<< "&private=" << (Application::GetSettingBool(StrPrivate) ? "true" : "false")
|
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||||
<< "&version=" << Application::ServerVersionString()
|
<< "&version=" << Application::ServerVersionString()
|
||||||
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
<< "&clientversion=" << Application::ClientVersionString()
|
||||||
<< "&name=" << Application::GetSettingString(StrName)
|
<< "&name=" << Application::Settings.ServerName
|
||||||
<< "&modlist=" << TResourceManager::FormatForBackend(mResourceManager.FileMap())
|
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||||
<< "&modstotalsize=" << mResourceManager.TotalModsSize()
|
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||||
<< "&modstotal=" << mResourceManager.LoadedModCount()
|
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||||
<< "&playerslist=" << GetPlayers()
|
<< "&playerslist=" << GetPlayers()
|
||||||
<< "&desc=" << Application::GetSettingString(StrDescription);
|
<< "&desc=" << Application::Settings.ServerDesc;
|
||||||
return Ret.str();
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||||
@@ -167,8 +172,12 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
|
|||||||
}
|
}
|
||||||
std::string THeartbeatThread::GetPlayers() {
|
std::string THeartbeatThread::GetPlayers() {
|
||||||
std::string Return;
|
std::string Return;
|
||||||
mServer.ForEachClient([&](const auto& Client) {
|
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||||
Return += Client->GetName() + ";";
|
ReadLock Lock(mServer.GetClientMutex());
|
||||||
|
if (!ClientPtr.expired()) {
|
||||||
|
Return += ClientPtr.lock()->GetName() + ";";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
return Return;
|
return Return;
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-226
@@ -4,11 +4,10 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaPlugin.h"
|
#include "TLuaPlugin.h"
|
||||||
#include "Uuid.h"
|
|
||||||
#include "sol/types.hpp"
|
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
|
#include <httplib.h>
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
@@ -17,11 +16,11 @@
|
|||||||
TLuaEngine* LuaAPI::MP::Engine;
|
TLuaEngine* LuaAPI::MP::Engine;
|
||||||
|
|
||||||
TLuaEngine::TLuaEngine()
|
TLuaEngine::TLuaEngine()
|
||||||
: mResourceServerPath(fs::path(Application::GetSettingString(StrResourceFolder)) / "Server") {
|
: mResourceServerPath(fs::path(Application::Settings.Resource) / "Server") {
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
|
||||||
LuaAPI::MP::Engine = this;
|
LuaAPI::MP::Engine = this;
|
||||||
if (!fs::exists(Application::GetSettingString(StrResourceFolder))) {
|
if (!fs::exists(Application::Settings.Resource)) {
|
||||||
fs::create_directory(Application::GetSettingString(StrResourceFolder));
|
fs::create_directory(Application::Settings.Resource);
|
||||||
}
|
}
|
||||||
if (!fs::exists(mResourceServerPath)) {
|
if (!fs::exists(mResourceServerPath)) {
|
||||||
fs::create_directory(mResourceServerPath);
|
fs::create_directory(mResourceServerPath);
|
||||||
@@ -37,7 +36,7 @@ TLuaEngine::TLuaEngine()
|
|||||||
}
|
}
|
||||||
|
|
||||||
TEST_CASE("TLuaEngine ctor & dtor") {
|
TEST_CASE("TLuaEngine ctor & dtor") {
|
||||||
Application::SetSetting(StrResourceFolder, "beammp_server_test_resources");
|
Application::Settings.Resource = "beammp_server_test_resources";
|
||||||
TLuaEngine engine;
|
TLuaEngine engine;
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
@@ -72,12 +71,13 @@ void TLuaEngine::operator()() {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
mResultsToCheckCond.wait_for(Lock, std::chrono::milliseconds(20));
|
||||||
}
|
}
|
||||||
mResultsToCheckCond.wait_for(Lock, std::chrono::milliseconds(10));
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// event loop
|
// event loop
|
||||||
auto Before = TimeType::now();
|
auto Before = std::chrono::high_resolution_clock::now();
|
||||||
while (!Application::IsShuttingDown()) {
|
while (!Application::IsShuttingDown()) {
|
||||||
{ // Timed Events Scope
|
{ // Timed Events Scope
|
||||||
std::unique_lock Lock(mTimedEventsMutex);
|
std::unique_lock Lock(mTimedEventsMutex);
|
||||||
@@ -110,14 +110,14 @@ void TLuaEngine::operator()() {
|
|||||||
} else {
|
} else {
|
||||||
constexpr double NsFactor = 1000000.0;
|
constexpr double NsFactor = 1000000.0;
|
||||||
constexpr double Expected = 10.0; // ms
|
constexpr double Expected = 10.0; // ms
|
||||||
const auto Diff = (TimeType::now() - Before).count() / NsFactor;
|
const auto Diff = (std::chrono::high_resolution_clock::now() - Before).count() / NsFactor;
|
||||||
if (Diff < Expected) {
|
if (Diff < Expected) {
|
||||||
std::this_thread::sleep_for(std::chrono::nanoseconds(size_t((Expected - Diff) * NsFactor)));
|
std::this_thread::sleep_for(std::chrono::nanoseconds(size_t((Expected - Diff) * NsFactor)));
|
||||||
} else {
|
} else {
|
||||||
beammp_tracef("Event loop cannot keep up! Running {}ms behind", Diff);
|
beammp_tracef("Event loop cannot keep up! Running {}ms behind", Diff);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Before = TimeType::now();
|
Before = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ResultCheckThread.joinable()) {
|
if (ResultCheckThread.joinable()) {
|
||||||
@@ -221,71 +221,7 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::string> TLuaEngine::GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys) {
|
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
|
||||||
std::unique_lock Lock(mLuaStatesMutex);
|
|
||||||
auto Result = mLuaStates.at(StateId)->GetStateTableKeys(keys);
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const std::vector<std::string>& keys) {
|
|
||||||
auto globals = mStateView.globals();
|
|
||||||
|
|
||||||
sol::table current = globals;
|
|
||||||
std::vector<std::string> Result {};
|
|
||||||
|
|
||||||
for (const auto& [key, value] : current) {
|
|
||||||
std::string s = key.as<std::string>();
|
|
||||||
if (value.get_type() == sol::type::function) {
|
|
||||||
s += "(";
|
|
||||||
}
|
|
||||||
Result.push_back(s);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!keys.empty()) {
|
|
||||||
Result.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
for (size_t i = 0; i < keys.size(); ++i) {
|
|
||||||
auto obj = current.get<sol::object>(keys.at(i));
|
|
||||||
if (obj.get_type() == sol::type::nil) {
|
|
||||||
// error
|
|
||||||
break;
|
|
||||||
} else if (i == keys.size() - 1) {
|
|
||||||
if (obj.get_type() == sol::type::table) {
|
|
||||||
for (const auto& [key, value] : obj.as<sol::table>()) {
|
|
||||||
if (key.get_type() == sol::type::string) {
|
|
||||||
std::string s = key.as<std::string>();
|
|
||||||
|
|
||||||
if (value.get_type() == sol::type::function) {
|
|
||||||
s += "(";
|
|
||||||
}
|
|
||||||
|
|
||||||
Result.push_back(s);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Result = { obj.as<std::string>() };
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (obj.get_type() == sol::type::table) {
|
|
||||||
current = obj;
|
|
||||||
} else {
|
|
||||||
// error
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
|
|
||||||
_G.a.b.c.d.
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<TimeType::duration>& Max) {
|
|
||||||
for (const auto& Result : Results) {
|
for (const auto& Result : Results) {
|
||||||
bool Cancelled = false;
|
bool Cancelled = false;
|
||||||
size_t ms = 0;
|
size_t ms = 0;
|
||||||
@@ -334,7 +270,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::EnqueueScript(TLuaStateId StateID, const
|
|||||||
return mLuaStates.at(StateID)->EnqueueScript(Script);
|
return mLuaStates.at(StateID)->EnqueueScript(Script);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args) {
|
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
|
||||||
std::unique_lock Lock(mLuaStatesMutex);
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args);
|
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args);
|
||||||
}
|
}
|
||||||
@@ -414,56 +350,15 @@ std::set<std::string> TLuaEngine::GetEventHandlersForState(const std::string& Ev
|
|||||||
return mLuaEvents[EventName][StateId];
|
return mLuaEvents[EventName][StateId];
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<sol::object> TLuaEngine::StateThreadData::JsonStringToArray(JsonString Str) {
|
|
||||||
auto LocalTable = Lua_JsonDecode(Str.value).as<std::vector<sol::object>>();
|
|
||||||
for (auto& value : LocalTable) {
|
|
||||||
if (value.is<std::string>() && value.as<std::string>() == BEAMMP_INTERNAL_NIL) {
|
|
||||||
value = sol::object {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return LocalTable;
|
|
||||||
}
|
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
||||||
auto Table = mStateView.create_table();
|
auto Return = mEngine->TriggerEvent(EventName, mStateId, EventArgs);
|
||||||
for (const sol::stack_proxy& Arg : EventArgs) {
|
|
||||||
switch (Arg.get_type()) {
|
|
||||||
case sol::type::none:
|
|
||||||
case sol::type::userdata:
|
|
||||||
case sol::type::lightuserdata:
|
|
||||||
case sol::type::thread:
|
|
||||||
case sol::type::function:
|
|
||||||
case sol::type::poly:
|
|
||||||
Table.add(BEAMMP_INTERNAL_NIL);
|
|
||||||
beammp_warnf("Passed a value of type '{}' to TriggerGlobalEvent(\"{}\", ...). This type can not be serialized, and cannot be passed between states. It will arrive as <nil> in handlers.", sol::type_name(EventArgs.lua_state(), Arg.get_type()), EventName);
|
|
||||||
break;
|
|
||||||
case sol::type::lua_nil:
|
|
||||||
Table.add(BEAMMP_INTERNAL_NIL);
|
|
||||||
break;
|
|
||||||
case sol::type::string:
|
|
||||||
case sol::type::number:
|
|
||||||
case sol::type::boolean:
|
|
||||||
case sol::type::table:
|
|
||||||
Table.add(Arg);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
JsonString Str { "" };
|
|
||||||
if (!Table.empty()) {
|
|
||||||
Str.value = LuaAPI::MP::JsonEncode(Table);
|
|
||||||
}
|
|
||||||
|
|
||||||
auto Return = mEngine->TriggerEvent(EventName, mStateId, Str);
|
|
||||||
mEngine->ReportErrors(Return);
|
|
||||||
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
||||||
|
|
||||||
sol::variadic_results LocalArgs = Str.value.empty() ? sol::variadic_results {} : JsonStringToArray(Str);
|
|
||||||
|
|
||||||
for (const auto& Handler : MyHandlers) {
|
for (const auto& Handler : MyHandlers) {
|
||||||
auto Fn = mStateView[Handler];
|
auto Fn = mStateView[Handler];
|
||||||
if (Fn.valid()) {
|
if (Fn.valid()) {
|
||||||
auto LuaResult = LocalArgs.empty() ? Fn() : Fn(LocalArgs);
|
auto LuaResult = Fn(EventArgs);
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
|
Result->Ready = true;
|
||||||
if (LuaResult.valid()) {
|
if (LuaResult.valid()) {
|
||||||
Result->Error = false;
|
Result->Error = false;
|
||||||
Result->Result = LuaResult;
|
Result->Result = LuaResult;
|
||||||
@@ -471,7 +366,6 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
||||||
}
|
}
|
||||||
Result->Ready = true;
|
|
||||||
Return.push_back(Result);
|
Return.push_back(Result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -501,44 +395,31 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
});
|
});
|
||||||
AsyncEventReturn.set_function("Wait",
|
|
||||||
[](const sol::table& Self, std::optional<float> TimeoutS) {
|
|
||||||
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
|
|
||||||
if (TimeoutS.has_value()) {
|
|
||||||
TLuaEngine::WaitForAll(Vector, std::chrono::milliseconds(size_t(TimeoutS.value() * 1000.0f)));
|
|
||||||
} else {
|
|
||||||
TLuaEngine::WaitForAll(Vector);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return AsyncEventReturn;
|
return AsyncEventReturn;
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
||||||
// TODO: make asynchronous?
|
// TODO: make asynchronous?
|
||||||
auto Result = mStateView.create_table();
|
sol::table Result = mStateView.create_table();
|
||||||
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
|
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
|
||||||
auto Fn = mStateView[Handler];
|
auto Fn = mStateView[Handler];
|
||||||
if (Fn.valid() && Fn.get_type() == sol::type::function) {
|
if (Fn.valid() && Fn.get_type() == sol::type::function) {
|
||||||
auto FnRet = Fn(EventArgs);
|
auto FnRet = Fn(EventArgs);
|
||||||
if (FnRet.valid()) {
|
if (FnRet.valid()) {
|
||||||
for (const auto& Res : FnRet) {
|
Result.add(FnRet);
|
||||||
Result.add(Res);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
sol::error Err = FnRet;
|
sol::error Err = FnRet;
|
||||||
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
|
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
beammp_lua_errorf("Handler '{}' for event '{}' in state '{}' is NOT a function, and will be ignored.", Handler, EventName, mStateId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
||||||
auto Client = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
auto IDs = Client->GetIdentifiers();
|
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
|
||||||
if (IDs.empty()) {
|
if (IDs.empty()) {
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
@@ -554,20 +435,27 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
|||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
|
||||||
sol::table Result = mStateView.create_table();
|
sol::table Result = mStateView.create_table();
|
||||||
mEngine->Server().ForEachClient([&](const auto& Client) {
|
mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
Result[Client->GetID()] = Client->GetName();
|
if (!Client.expired()) {
|
||||||
|
auto locked = Client.lock();
|
||||||
|
Result[locked->GetID()] = locked->GetName();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
||||||
int Id = -1;
|
int Id = -1;
|
||||||
mEngine->mServer->ForEachClient([&Id, &Name](const auto& Client) -> IterationDecision {
|
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
|
||||||
if (Client->GetName() == Name) {
|
if (!Client.expired()) {
|
||||||
Id = Client->GetID();
|
auto locked = Client.lock();
|
||||||
return Break;
|
if (locked->GetName() == Name) {
|
||||||
|
Id = locked->GetID();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return Continue;
|
return true;
|
||||||
});
|
});
|
||||||
return Id;
|
return Id;
|
||||||
}
|
}
|
||||||
@@ -599,17 +487,18 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
||||||
auto Client = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
return Client->GetName();
|
return MaybeClient.value().lock()->GetName();
|
||||||
} else {
|
} else {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
||||||
auto Client = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
||||||
if (Client) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
|
auto Client = MaybeClient.value().lock();
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
TClient::TSetOfVehicleData VehicleData;
|
||||||
{ // Vehicle Data Lock Scope
|
{ // Vehicle Data Lock Scope
|
||||||
auto LockedData = Client->GetAllCars();
|
auto LockedData = Client->GetAllCars();
|
||||||
@@ -628,32 +517,6 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
|||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
|
|
||||||
std::pair<sol::table, std::string> Result;
|
|
||||||
auto Client = GetClient(mEngine->Server(), PID);
|
|
||||||
if (Client) {
|
|
||||||
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
|
||||||
|
|
||||||
if (VehiclePos.empty()) {
|
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
|
||||||
Result.second = "Vehicle not found";
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
|
|
||||||
sol::table t = Lua_JsonDecode(VehiclePos);
|
|
||||||
if (t == sol::lua_nil) {
|
|
||||||
Result.second = "Packet decode failed";
|
|
||||||
}
|
|
||||||
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
|
||||||
Result.first = t;
|
|
||||||
return Result;
|
|
||||||
} else {
|
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
|
||||||
Result.second = "Client expired";
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
||||||
auto table = mStateView.create_table();
|
auto table = mStateView.create_table();
|
||||||
constexpr const char* InternalClient = "__InternalClient";
|
constexpr const char* InternalClient = "__InternalClient";
|
||||||
@@ -727,8 +590,6 @@ static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, c
|
|||||||
return;
|
return;
|
||||||
case nlohmann::detail::value_t::discarded:
|
case nlohmann::detail::value_t::discarded:
|
||||||
return;
|
return;
|
||||||
default:
|
|
||||||
beammp_assert_not_reachable();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -776,14 +637,14 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("CreateTimer", [&]() -> sol::table {
|
MPTable.set_function("CreateTimer", [&]() -> sol::table {
|
||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
sol::table Result = StateView.create_table();
|
sol::table Result = StateView.create_table();
|
||||||
Result["__StartTime"] = TimeType::now();
|
Result["__StartTime"] = std::chrono::high_resolution_clock::now();
|
||||||
Result.set_function("GetCurrent", [&](const sol::table& Table) -> float {
|
Result.set_function("GetCurrent", [&](const sol::table& Table) -> float {
|
||||||
auto End = TimeType::now();
|
auto End = std::chrono::high_resolution_clock::now();
|
||||||
auto Start = Table.get<TimeType::time_point>("__StartTime");
|
auto Start = Table.get<std::chrono::high_resolution_clock::time_point>("__StartTime");
|
||||||
return std::chrono::duration_cast<std::chrono::microseconds>(End - Start).count() / 1000000.0f;
|
return std::chrono::duration_cast<std::chrono::microseconds>(End - Start).count() / 1000000.0f;
|
||||||
});
|
});
|
||||||
Result.set_function("Start", [&](sol::table Table) {
|
Result.set_function("Start", [&](sol::table Table) {
|
||||||
Table["__StartTime"] = TimeType::now();
|
Table["__StartTime"] = std::chrono::high_resolution_clock::now();
|
||||||
});
|
});
|
||||||
return Result;
|
return Result;
|
||||||
});
|
});
|
||||||
@@ -795,10 +656,9 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("TriggerGlobalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
|
MPTable.set_function("TriggerGlobalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
|
||||||
return Lua_TriggerGlobalEvent(EventName, EventArgs);
|
return Lua_TriggerGlobalEvent(EventName, EventArgs);
|
||||||
});
|
});
|
||||||
MPTable.set_function(
|
MPTable.set_function("TriggerLocalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
|
||||||
"TriggerLocalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> auto{
|
return Lua_TriggerLocalEvent(EventName, EventArgs);
|
||||||
return Lua_TriggerLocalEvent(EventName, EventArgs);
|
});
|
||||||
});
|
|
||||||
MPTable.set_function("TriggerClientEvent", &LuaAPI::MP::TriggerClientEvent);
|
MPTable.set_function("TriggerClientEvent", &LuaAPI::MP::TriggerClientEvent);
|
||||||
MPTable.set_function("TriggerClientEventJson", &LuaAPI::MP::TriggerClientEventJson);
|
MPTable.set_function("TriggerClientEventJson", &LuaAPI::MP::TriggerClientEventJson);
|
||||||
MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
|
MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
|
||||||
@@ -813,9 +673,6 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
||||||
return Lua_GetPlayerVehicles(ID);
|
return Lua_GetPlayerVehicles(ID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> {
|
|
||||||
return Lua_GetPositionRaw(PID, VID);
|
|
||||||
});
|
|
||||||
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
||||||
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
||||||
return Lua_GetPlayers();
|
return Lua_GetPlayers();
|
||||||
@@ -869,7 +726,15 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten);
|
UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten);
|
||||||
UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify);
|
UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify);
|
||||||
UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify);
|
UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify);
|
||||||
UtilTable.set_function("GenerateUUID", &uuid::GenerateUuid);
|
UtilTable.set_function("Stress", [](size_t n) {
|
||||||
|
std::vector<std::thread> s;
|
||||||
|
for (size_t i = 0; i < n; ++i) {
|
||||||
|
s.emplace_back([]{ while (true); });
|
||||||
|
}
|
||||||
|
for (auto& t : s) {
|
||||||
|
t.detach();
|
||||||
|
}
|
||||||
|
});
|
||||||
UtilTable.set_function("Random", [this] {
|
UtilTable.set_function("Random", [this] {
|
||||||
return mUniformRealDistribution01(mMersenneTwister);
|
return mUniformRealDistribution01(mMersenneTwister);
|
||||||
});
|
});
|
||||||
@@ -926,7 +791,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLu
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy) {
|
||||||
// TODO: Document all this
|
// TODO: Document all this
|
||||||
decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end();
|
decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end();
|
||||||
if (Strategy == CallStrategy::BestEffort) {
|
if (Strategy == CallStrategy::BestEffort) {
|
||||||
@@ -948,7 +813,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFrom
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
Result->StateId = mStateId;
|
Result->StateId = mStateId;
|
||||||
Result->Function = FunctionName;
|
Result->Function = FunctionName;
|
||||||
@@ -999,6 +864,7 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
}
|
}
|
||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
||||||
|
S.second->Ready = true;
|
||||||
if (Res.valid()) {
|
if (Res.valid()) {
|
||||||
S.second->Error = false;
|
S.second->Error = false;
|
||||||
S.second->Result = std::move(Res);
|
S.second->Result = std::move(Res);
|
||||||
@@ -1007,7 +873,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
S.second->ErrorMessage = Err.what();
|
S.second->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
S.second->Ready = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{ // StateFunctionQueue Scope
|
{ // StateFunctionQueue Scope
|
||||||
@@ -1033,41 +898,18 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
switch (Arg.index()) {
|
switch (Arg.index()) {
|
||||||
case TLuaType::String:
|
case TLuaArgTypes_String:
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::Int:
|
case TLuaArgTypes_Int:
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::Json: {
|
case TLuaArgTypes_VariadicArgs:
|
||||||
auto Str = std::get<JsonString>(Arg);
|
LuaArgs.push_back(sol::make_object(StateView, std::get<sol::variadic_args>(Arg)));
|
||||||
if (!Str.value.empty()) {
|
|
||||||
auto LocalArgs = JsonStringToArray(Str);
|
|
||||||
LuaArgs.insert(LuaArgs.end(), LocalArgs.begin(), LocalArgs.end());
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
case TLuaArgTypes_Bool:
|
||||||
case TLuaType::Bool:
|
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::StringStringMap: {
|
|
||||||
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
|
|
||||||
auto Table = StateView.create_table();
|
|
||||||
for (const auto& [k, v] : Map) {
|
|
||||||
Table[k] = v;
|
|
||||||
}
|
|
||||||
LuaArgs.push_back(sol::make_object(StateView, Table));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case TLuaType::StringSizeTMap: {
|
|
||||||
auto Map = std::get<std::unordered_map<std::string, size_t>>(Arg);
|
|
||||||
auto Table = StateView.create_table();
|
|
||||||
for (const auto& [k, v] : Map) {
|
|
||||||
Table[k] = v;
|
|
||||||
}
|
|
||||||
LuaArgs.push_back(sol::make_object(StateView, Table));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
beammp_error("Unknown argument type, passed as nil");
|
beammp_error("Unknown argument type, passed as nil");
|
||||||
break;
|
break;
|
||||||
@@ -1106,8 +948,8 @@ std::vector<TLuaEngine::QueuedFunction> TLuaEngine::StateThreadData::Debug_GetSt
|
|||||||
void TLuaEngine::CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy) {
|
void TLuaEngine::CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy) {
|
||||||
std::unique_lock Lock(mTimedEventsMutex);
|
std::unique_lock Lock(mTimedEventsMutex);
|
||||||
TimedEvent Event {
|
TimedEvent Event {
|
||||||
TimeType::duration { std::chrono::milliseconds(IntervalMS) },
|
std::chrono::high_resolution_clock::duration { std::chrono::milliseconds(IntervalMS) },
|
||||||
TimeType::now(),
|
std::chrono::high_resolution_clock::now(),
|
||||||
EventName,
|
EventName,
|
||||||
StateId,
|
StateId,
|
||||||
Strategy
|
Strategy
|
||||||
@@ -1150,10 +992,10 @@ TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName,
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool TLuaEngine::TimedEvent::Expired() {
|
bool TLuaEngine::TimedEvent::Expired() {
|
||||||
auto Waited = (TimeType::now() - LastCompletion);
|
auto Waited = (std::chrono::high_resolution_clock::now() - LastCompletion);
|
||||||
return Waited >= Duration;
|
return Waited >= Duration;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::TimedEvent::Reset() {
|
void TLuaEngine::TimedEvent::Reset() {
|
||||||
LastCompletion = TimeType::now();
|
LastCompletion = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
|
|||||||
+534
-441
File diff suppressed because it is too large
Load Diff
+16
-6
@@ -33,16 +33,26 @@ void TPPSMonitor::operator()() {
|
|||||||
Application::SetPPS("-");
|
Application::SetPPS("-");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
mServer.ForEachClient([&](const auto& Client) {
|
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||||
if (Client->GetCarCount() > 0) {
|
std::shared_ptr<TClient> c;
|
||||||
|
{
|
||||||
|
ReadLock Lock(mServer.GetClientMutex());
|
||||||
|
if (!ClientPtr.expired()) {
|
||||||
|
c = ClientPtr.lock();
|
||||||
|
} else
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (c->GetCarCount() > 0) {
|
||||||
C++;
|
C++;
|
||||||
V += Client->GetCarCount();
|
V += c->GetCarCount();
|
||||||
}
|
}
|
||||||
// kick on "no ping"
|
// kick on "no ping"
|
||||||
if (Client->SecondsSinceLastPing() > (20 * 60)) {
|
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||||
beammp_debugf("Client {} ({}) timing out: {}s since last contact", Client->GetName(), Client->GetID(), Client->SecondsSinceLastPing());
|
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
||||||
TimedOutClients.push_back(Client);
|
TimedOutClients.push_back(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
});
|
});
|
||||||
for (auto& ClientToKick : TimedOutClients) {
|
for (auto& ClientToKick : TimedOutClients) {
|
||||||
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
||||||
|
|||||||
+20
-68
@@ -5,79 +5,31 @@
|
|||||||
|
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
std::string TResourceManager::FormatForBackend(const ModMap& mods) {
|
|
||||||
std::string monkey;
|
|
||||||
for (const auto& [name, size] : mods) {
|
|
||||||
monkey += fs::path(name).filename().string() + ';';
|
|
||||||
}
|
|
||||||
return monkey;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TResourceManager::FormatForClient(const ModMap& mods) {
|
|
||||||
std::string monkey;
|
|
||||||
for (const auto& [name, size] : mods) {
|
|
||||||
monkey += '/' + name + ';';
|
|
||||||
}
|
|
||||||
for (const auto& [name, size] : mods) {
|
|
||||||
monkey += std::to_string(size) + ';';
|
|
||||||
}
|
|
||||||
return monkey;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// @brief Sanitizes a requested mod string
|
|
||||||
/// @param pathString Raw mod path string
|
|
||||||
/// @param mods List of allowed mods for this client
|
|
||||||
/// @return Error, if any
|
|
||||||
std::optional<std::string> TResourceManager::IsModValid(std::string& pathString, const ModMap& mods) {
|
|
||||||
auto path = fs::path(pathString);
|
|
||||||
if (!path.has_filename()) {
|
|
||||||
beammp_warn("File " + pathString + " is not a file!");
|
|
||||||
return { "the requested file doesn't contain a valid filename" };
|
|
||||||
}
|
|
||||||
|
|
||||||
auto BasePath = fs::path(Application::GetSettingString(StrResourceFolder) + "/Client");
|
|
||||||
|
|
||||||
auto CombinedPath = fs::path(BasePath.string() + pathString).lexically_normal();
|
|
||||||
|
|
||||||
// beammp_infof("path: {}, base: {}, combined: {}", pathString, BasePath.string(), CombinedPath.string());
|
|
||||||
|
|
||||||
if (!std::filesystem::exists(CombinedPath)) {
|
|
||||||
beammp_warn("File " + pathString + " could not be accessed!");
|
|
||||||
return { "the requested file doesn't exist or couldn't be accessed" };
|
|
||||||
}
|
|
||||||
|
|
||||||
auto relative = fs::relative(CombinedPath, BasePath);
|
|
||||||
|
|
||||||
if (mods.count(relative.string()) == 0) {
|
|
||||||
beammp_warn("File " + pathString + " is disallowed for this player!");
|
|
||||||
return { "the requested file is disallowed for this player" };
|
|
||||||
}
|
|
||||||
|
|
||||||
pathString = CombinedPath.string();
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
TResourceManager::TResourceManager() {
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||||
std::string BasePath = Application::GetSettingString(StrResourceFolder) + "/Client";
|
std::string Path = Application::Settings.Resource + "/Client";
|
||||||
if (!fs::exists(BasePath))
|
if (!fs::exists(Path))
|
||||||
fs::create_directories(BasePath);
|
fs::create_directories(Path);
|
||||||
std::vector<std::string> modNames;
|
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||||
|
std::string File(entry.path().string());
|
||||||
auto iterator = fs::recursive_directory_iterator(BasePath, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied);
|
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
||||||
for (const auto& entry : iterator) {
|
if (File.length() - pos == 4) {
|
||||||
if (iterator.depth() > 0 && !Application::GetSettingBool(StrIncludeSubdirectories))
|
std::replace(File.begin(), File.end(), '\\', '/');
|
||||||
continue;
|
mFileList += File + ';';
|
||||||
if ((entry.is_regular_file() || entry.is_symlink()) && entry.path().extension() == ".zip") {
|
if (auto i = File.find_last_of('/'); i != std::string::npos) {
|
||||||
auto relativePath = fs::relative(entry.path(), BasePath);
|
++i;
|
||||||
|
File = File.substr(i, pos - i);
|
||||||
mMods[relativePath.string()] = entry.file_size();
|
}
|
||||||
mTotalModSize += entry.file_size();
|
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
||||||
|
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
||||||
|
mMaxModSize += size_t(fs::file_size(entry.path()));
|
||||||
|
mModsLoaded++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mMods.empty()) {
|
if (mModsLoaded) {
|
||||||
beammp_infof("Loaded {} mod{}", mMods.size(), mMods.size() != 1 ? 's' : ' ');
|
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
||||||
}
|
}
|
||||||
|
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
||||||
|
|||||||
@@ -2,21 +2,21 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
TScopedTimer::TScopedTimer()
|
TScopedTimer::TScopedTimer()
|
||||||
: mStartTime(TimeType::now()) {
|
: mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
TScopedTimer::TScopedTimer(const std::string& mName)
|
TScopedTimer::TScopedTimer(const std::string& mName)
|
||||||
: mStartTime(TimeType::now())
|
: mStartTime(std::chrono::high_resolution_clock::now())
|
||||||
, Name(mName) {
|
, Name(mName) {
|
||||||
}
|
}
|
||||||
|
|
||||||
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
|
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
|
||||||
: OnDestroy(OnDestroy)
|
: OnDestroy(OnDestroy)
|
||||||
, mStartTime(TimeType::now()) {
|
, mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
TScopedTimer::~TScopedTimer() {
|
TScopedTimer::~TScopedTimer() {
|
||||||
auto EndTime = TimeType::now();
|
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||||
auto Delta = EndTime - mStartTime;
|
auto Delta = EndTime - mStartTime;
|
||||||
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||||
if (OnDestroy) {
|
if (OnDestroy) {
|
||||||
|
|||||||
+7
-7
@@ -6,7 +6,7 @@
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
TSentry::TSentry() {
|
TSentry::TSentry() {
|
||||||
if (std::strlen(S_DSN) == /* DISABLES CODE */ (0)) {
|
if (std::strlen(S_DSN) == 0) {
|
||||||
mValid = false;
|
mValid = false;
|
||||||
} else {
|
} else {
|
||||||
mValid = true;
|
mValid = true;
|
||||||
@@ -28,22 +28,22 @@ TSentry::~TSentry() {
|
|||||||
|
|
||||||
void TSentry::PrintWelcome() {
|
void TSentry::PrintWelcome() {
|
||||||
if (mValid) {
|
if (mValid) {
|
||||||
if (!Application::GetSettingBool("SendErrors")) {
|
if (!Application::Settings.SendErrors) {
|
||||||
mValid = false;
|
mValid = false;
|
||||||
if (Application::GetSettingBool(StrSendErrors)) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("Sentry disabled");
|
beammp_info("Sentry disabled");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::GetSettingBool(StrSendErrors)) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
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.");
|
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 {
|
||||||
beammp_info("Sentry started");
|
beammp_info("Sentry started");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::GetSettingBool(StrSendErrors)) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("Sentry disabled in unofficial build");
|
beammp_info("Sentry disabled in unofficial build");
|
||||||
@@ -57,8 +57,8 @@ void TSentry::SetupUser() {
|
|||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
||||||
sentry_value_t user = sentry_value_new_object();
|
sentry_value_t user = sentry_value_new_object();
|
||||||
if (Application::GetSettingString(StrAuthKey).size() == 36) {
|
if (Application::Settings.Key.size() == 36) {
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::GetSettingString(StrAuthKey).c_str()));
|
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
||||||
} else {
|
} else {
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
||||||
}
|
}
|
||||||
|
|||||||
+88
-264
@@ -1,170 +1,29 @@
|
|||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "IterationDecision.h"
|
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include <TLuaPlugin.h>
|
#include <TLuaPlugin.h>
|
||||||
#include <algorithm>
|
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
#undef GetObject // Fixes Windows
|
||||||
|
|
||||||
#include "Json.h"
|
#include "Json.h"
|
||||||
|
|
||||||
struct VehiclePacket {
|
|
||||||
std::string Data;
|
|
||||||
int Pid;
|
|
||||||
int Vid;
|
|
||||||
};
|
|
||||||
|
|
||||||
static Result<std::pair<int, int>> GetPidVid(const std::string& str) {
|
|
||||||
auto IDSep = str.find('-');
|
|
||||||
if (IDSep == std::string::npos) {
|
|
||||||
return Error("Invalid packet: Could not parse pid/vid from packet, as there is no '-' separator: '{}'", str);
|
|
||||||
}
|
|
||||||
std::string pid = str.substr(0, IDSep);
|
|
||||||
std::string vid = str.substr(IDSep + 1);
|
|
||||||
|
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
|
||||||
try {
|
|
||||||
int PID = std::stoi(pid);
|
|
||||||
int VID = std::stoi(vid);
|
|
||||||
return { { PID, VID } };
|
|
||||||
} catch (const std::exception&) {
|
|
||||||
return Error("Invalid packet: Could not parse pid/vid from packet, as one or both are not valid numbers: '{}'", str);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Error("Invalid packet: Could not parse pid/vid from packet: '{}'", str);
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::optional<VehiclePacket> ParseVehiclePacket(const std::string& Packet, const int playerID) {
|
|
||||||
if (Packet.size() < 8) { // 2 for code, 3<= for pidvid, 1<= for data, 2 for dividers
|
|
||||||
// invalid packet
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
// Zp:serverVehicleID:data
|
|
||||||
// 0-0:data
|
|
||||||
std::string withoutCode = Packet.substr(3);
|
|
||||||
|
|
||||||
auto NameDataSep = withoutCode.find(':', 3);
|
|
||||||
if (NameDataSep == std::string::npos) {
|
|
||||||
beammp_debugf("Invalid packet from {} in ParseVehiclePacket: No ':' separator, assuming corrupted packet. Packet: '{}'", playerID, Packet);
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
if (NameDataSep + 1 > withoutCode.size()) {
|
|
||||||
beammp_debugf("Invalid packet from {} in ParseVehiclePacket: Separator in unexpected place, assuming corrupted packet. Packet: '{}'", playerID, Packet);
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string ServerVehicleID = withoutCode.substr(0, NameDataSep);
|
|
||||||
|
|
||||||
std::string Data = withoutCode.substr(NameDataSep + 1);
|
|
||||||
|
|
||||||
// parse veh ID
|
|
||||||
auto MaybePidVid = GetPidVid(ServerVehicleID);
|
|
||||||
if (MaybePidVid) {
|
|
||||||
int PID, VID;
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
|
|
||||||
if (PID == playerID) {
|
|
||||||
return { { Data, PID, VID } }; // std::vector<char>(Data.begin(), Data.end())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
beammp_debugf("Failed to parse packet from player {}", playerID);
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("GetPidVid") {
|
|
||||||
SUBCASE("Valid singledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-1");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 0);
|
|
||||||
CHECK_EQ(vid, 1);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("10-12");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 10);
|
|
||||||
CHECK_EQ(vid, 12);
|
|
||||||
}
|
|
||||||
SUBCASE("Empty string") {
|
|
||||||
const auto MaybePidVid = GetPidVid("");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid separator") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0x0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("x-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-x");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("ParseVehiclePacket") {
|
|
||||||
SUBCASE("Valid packet") {
|
|
||||||
const auto valid = ParseVehiclePacket("Zp:0-0:{jsonstring}", 0);
|
|
||||||
CHECK(valid.has_value());
|
|
||||||
}
|
|
||||||
SUBCASE("Valid packet 2") {
|
|
||||||
const auto packet = ParseVehiclePacket("Zp:12-3:{jsonstring}", 12);
|
|
||||||
CHECK(packet.has_value());
|
|
||||||
CHECK_EQ(packet.value().Pid, 12);
|
|
||||||
CHECK_EQ(packet.value().Vid, 3);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing packet") {
|
|
||||||
const auto valid = ParseVehiclePacket("", 0);
|
|
||||||
CHECK(!valid.has_value());
|
|
||||||
}
|
|
||||||
SUBCASE("Missing ServerVehicleID") {
|
|
||||||
const auto valid = ParseVehiclePacket("Zp:{jsonstring}", 0);
|
|
||||||
CHECK(!valid.has_value());
|
|
||||||
}
|
|
||||||
SUBCASE("Missing data") {
|
|
||||||
const auto valid = ParseVehiclePacket("Zp:0-0:", 0);
|
|
||||||
CHECK(!valid.has_value());
|
|
||||||
}
|
|
||||||
SUBCASE("Incorrect Pid") {
|
|
||||||
const auto valid = ParseVehiclePacket("Zp:0-0:{jsonstring}", 1);
|
|
||||||
CHECK(!valid.has_value());
|
|
||||||
}
|
|
||||||
SUBCASE("Incorrect Pid 2") {
|
|
||||||
const auto valid = ParseVehiclePacket("Zp:12-0:{jsonstring}", 13);
|
|
||||||
CHECK(!valid.has_value());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||||
|
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||||
if (Arguments.size() > 1) {
|
if (Arguments.size() > 1) {
|
||||||
Application::SetSetting(StrCustomIP, std::string(Arguments[0]));
|
Application::Settings.CustomIP = Arguments[0];
|
||||||
auto CustomIP = Application::GetSettingString(StrCustomIP);
|
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
||||||
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
|
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
||||||
auto p = Application::GetSettingString(StrCustomIP).find_first_not_of(".0123456789");
|
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
||||||
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == "127") {
|
Application::Settings.CustomIP.clear();
|
||||||
Application::SetSetting(StrCustomIP, "");
|
|
||||||
beammp_warn("IP Specified is invalid! Ignoring");
|
beammp_warn("IP Specified is invalid! Ignoring");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("server started with custom IP");
|
beammp_info("server started with custom IP");
|
||||||
@@ -174,32 +33,23 @@ TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||||
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
if (!WeakClientPtr.expired()) {
|
||||||
try {
|
TClient& Client = *WeakClientPtr.lock();
|
||||||
LockedClientPtr = WeakClientPtr.lock();
|
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||||
} catch (const std::exception&) {
|
Client.ClearCars();
|
||||||
// silently fail, as there's nothing to do
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
beammp_assert(LockedClientPtr != nullptr);
|
|
||||||
TClient& Client = *LockedClientPtr;
|
|
||||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
|
||||||
// TODO: Send delete packets for all cars
|
|
||||||
Client.ClearCars();
|
|
||||||
WriteLock Lock(mClientsMutex);
|
|
||||||
mClients.erase(WeakClientPtr.lock());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::RemoveClientById(int Id) {
|
|
||||||
auto Client = GetClient(*this, Id);
|
|
||||||
if (Client) {
|
|
||||||
Client->ClearCars();
|
|
||||||
WriteLock Lock(mClientsMutex);
|
WriteLock Lock(mClientsMutex);
|
||||||
mClients.erase(Client);
|
mClients.erase(WeakClientPtr.lock());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ForEachClientWeak(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
||||||
|
beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
||||||
|
WriteLock Lock(mClientsMutex);
|
||||||
|
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
||||||
|
return *Iter;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||||
decltype(mClients) Clients;
|
decltype(mClients) Clients;
|
||||||
{
|
{
|
||||||
ReadLock lock(mClientsMutex);
|
ReadLock lock(mClientsMutex);
|
||||||
@@ -217,11 +67,12 @@ size_t TServer::ClientCount() const {
|
|||||||
return mClients.size();
|
return mClients.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TNetwork& Network) {
|
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||||
constexpr std::string_view ABG = "ABG:";
|
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||||
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
// abort();
|
||||||
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
}
|
||||||
Packet = DeComp(Packet);
|
if (Packet.substr(0, 4) == "ABG:") {
|
||||||
|
Packet = DeComp(Packet.substr(4));
|
||||||
}
|
}
|
||||||
if (Packet.empty()) {
|
if (Packet.empty()) {
|
||||||
return;
|
return;
|
||||||
@@ -235,53 +86,46 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
|||||||
std::any Res;
|
std::any Res;
|
||||||
char Code = Packet.at(0);
|
char Code = Packet.at(0);
|
||||||
|
|
||||||
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
// V to Z
|
||||||
|
if (Code <= 90 && Code >= 86) {
|
||||||
// V to Y
|
PPSMonitor.IncrementInternalPPS();
|
||||||
if (Code <= 89 && Code >= 86) {
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
if (HandleVehicleUpdate(StringPacket, LockedClient->GetID())) {
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
} else {
|
|
||||||
beammp_debugf("Invalid vehicle update packet received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (Code) {
|
switch (Code) {
|
||||||
case 'H': // initial connection
|
case 'H': // initial connection
|
||||||
|
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
||||||
if (!Network.SyncClient(Client)) {
|
if (!Network.SyncClient(Client)) {
|
||||||
// TODO handle
|
// TODO handle
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'p':
|
case 'p':
|
||||||
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
if (!Network.Respond(*LockedClient, ("p"), false)) {
|
||||||
// failed to send
|
// failed to send
|
||||||
LockedClient->Disconnect("Failed to send ping");
|
if (LockedClient->GetStatus() > -1) {
|
||||||
|
LockedClient->SetStatus(-1);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Network.UpdatePlayer(*LockedClient);
|
Network.UpdatePlayer(*LockedClient);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'O':
|
case 'O':
|
||||||
if (Packet.size() > 1000) {
|
if (Packet.length() > 1000) {
|
||||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
||||||
}
|
}
|
||||||
ParseVehicle(*LockedClient, StringPacket, Network);
|
ParseVehicle(*LockedClient, Packet, Network);
|
||||||
|
return;
|
||||||
|
case 'J':
|
||||||
|
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
case 'C': {
|
case 'C': {
|
||||||
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
|
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
||||||
break;
|
break;
|
||||||
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
||||||
std::string Message = "";
|
|
||||||
const auto ColonPos = PacketAsString.find(':', 3);
|
|
||||||
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
|
|
||||||
Message = PacketAsString.substr(ColonPos + 2);
|
|
||||||
}
|
|
||||||
if (Message.empty()) {
|
|
||||||
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
TLuaEngine::WaitForAll(Futures);
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1));
|
||||||
if (std::any_of(Futures.begin(), Futures.end(),
|
if (std::any_of(Futures.begin(), Futures.end(),
|
||||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||||
return !Elem->Error
|
return !Elem->Error
|
||||||
@@ -290,23 +134,17 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
|||||||
})) {
|
})) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'E':
|
case 'E':
|
||||||
HandleEvent(*LockedClient, StringPacket);
|
beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
|
HandleEvent(*LockedClient, Packet);
|
||||||
return;
|
return;
|
||||||
case 'N':
|
case 'N':
|
||||||
beammp_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;
|
||||||
case 'Z': // position packet
|
|
||||||
if (HandlePosition(*LockedClient, StringPacket)) {
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
} else {
|
|
||||||
beammp_debugf("Invalid vehicle position packet received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -315,10 +153,6 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
|||||||
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||||
// E:Name:Data
|
// E:Name:Data
|
||||||
// Data is allowed to have ':'
|
// Data is allowed to have ':'
|
||||||
if (RawData.size() < 2) {
|
|
||||||
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto NameDataSep = RawData.find(':', 2);
|
auto NameDataSep = RawData.find(':', 2);
|
||||||
if (NameDataSep == std::string::npos) {
|
if (NameDataSep == std::string::npos) {
|
||||||
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||||
@@ -336,7 +170,7 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -346,24 +180,24 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
|||||||
c.SetUnicycleID(ID);
|
c.SetUnicycleID(ID);
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
return c.GetCarCount() < Application::GetSettingInt(StrMaxCars);
|
return c.GetCarCount() < Application::Settings.MaxCars;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||||
if (Pckt.length() < 6)
|
if (Pckt.length() < 4)
|
||||||
return;
|
return;
|
||||||
std::string Packet = Pckt;
|
std::string Packet = Pckt;
|
||||||
char Code = Packet.at(1);
|
char Code = Packet.at(1);
|
||||||
int PID = -1;
|
int PID = -1;
|
||||||
int VID = -1;
|
int VID = -1, Pos;
|
||||||
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':
|
||||||
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, 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_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
std::string CarJson = Packet.substr(5);
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||||
@@ -376,24 +210,26 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||||
c.AddNewCar(CarID, Packet);
|
c.AddNewCar(CarID, Packet);
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
} else {
|
} else {
|
||||||
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
if (!Network.Respond(c, Packet, true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||||
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
if (!Network.Respond(c, Destroy, true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'c': {
|
case 'c':
|
||||||
beammp_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()) + (")"));
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
pid = Data.substr(0, Data.find('-'));
|
||||||
if (MaybePidVid) {
|
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
|
PID = stoi(pid);
|
||||||
|
VID = stoi(vid);
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||||
@@ -407,57 +243,62 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||||
&& !ShouldntAllow) {
|
&& !ShouldntAllow) {
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
Apply(c, VID, Packet);
|
Apply(c, VID, Packet);
|
||||||
} else {
|
} else {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||||
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
if (!Network.Respond(c, Destroy, true)) {
|
||||||
|
// TODO: handle
|
||||||
|
}
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
case 'd':
|
||||||
case 'd': {
|
|
||||||
beammp_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()) + (")"));
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
pid = Data.substr(0, Data.find('-'));
|
||||||
if (MaybePidVid) {
|
vid = Data.substr(Data.find('-') + 1);
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
|
PID = stoi(pid);
|
||||||
|
VID = stoi(vid);
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
// TODO: should this trigger on all vehicle deletions?
|
// TODO: should this trigger on all vehicle deletions?
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
case 'r':
|
||||||
case 'r': {
|
|
||||||
beammp_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()) + (")"));
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
Pos = int(Data.find('-'));
|
||||||
if (MaybePidVid) {
|
pid = Data.substr(0, Pos++);
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
vid = Data.substr(Pos, Data.find(':') - Pos);
|
||||||
|
|
||||||
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
|
PID = stoi(pid);
|
||||||
|
VID = stoi(vid);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
Data = Data.substr(Data.find('{'));
|
Data = Data.substr(Data.find('{'));
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
case 't':
|
case 't':
|
||||||
beammp_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, StringToVector(Packet), false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
return;
|
return;
|
||||||
case 'm':
|
case 'm':
|
||||||
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
Network.SendToAll(&c, Packet, true, true);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
beammp_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()) + (")")));
|
||||||
@@ -524,20 +365,3 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
|||||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||||
(void)mClients.insert(NewClient);
|
(void)mClients.insert(NewClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::HandlePosition(TClient& c, const std::string& PacketStr) {
|
|
||||||
auto MaybePacket = ParseVehiclePacket(PacketStr, c.GetID());
|
|
||||||
|
|
||||||
if (MaybePacket) {
|
|
||||||
auto packet = MaybePacket.value();
|
|
||||||
c.SetCarPosition(packet.Vid, packet.Data);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TServer::HandleVehicleUpdate(const std::string& PacketStr, const int playerID) {
|
|
||||||
auto MaybePacket = ParseVehiclePacket(PacketStr, playerID);
|
|
||||||
|
|
||||||
return MaybePacket.has_value();
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
#include "Uuid.h"
|
|
||||||
|
|
||||||
#include <boost/uuid/uuid.hpp>
|
|
||||||
|
|
||||||
#include <boost/uuid/random_generator.hpp>
|
|
||||||
#include <boost/uuid/uuid_generators.hpp>
|
|
||||||
#include <boost/uuid/uuid_io.hpp>
|
|
||||||
#include <fmt/format.h>
|
|
||||||
#include <fmt/ostream.h>
|
|
||||||
|
|
||||||
std::string uuid::GenerateUuid() {
|
|
||||||
static thread_local boost::uuids::random_generator Generator {};
|
|
||||||
boost::uuids::uuid Id { Generator() };
|
|
||||||
return boost::uuids::to_string(Id);
|
|
||||||
}
|
|
||||||
+25
-23
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include "ArgsParser.h"
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
@@ -12,6 +13,7 @@
|
|||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include "TPluginMonitor.h"
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
@@ -54,7 +56,7 @@ int BeamMPServerMain(MainArguments Arguments);
|
|||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
MainArguments Args { argc, argv, {}, argv[0] };
|
MainArguments Args { argc, argv, {}, argv[0] };
|
||||||
Args.List.reserve(size_t(argc));
|
Args.List.reserve(argc);
|
||||||
for (int i = 1; i < argc; ++i) {
|
for (int i = 1; i < argc; ++i) {
|
||||||
Args.List.push_back(argv[i]);
|
Args.List.push_back(argv[i]);
|
||||||
}
|
}
|
||||||
@@ -73,7 +75,6 @@ int main(int argc, char** argv) {
|
|||||||
int BeamMPServerMain(MainArguments Arguments) {
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
setlocale(LC_ALL, "C");
|
setlocale(LC_ALL, "C");
|
||||||
Application::InitializeConsole();
|
Application::InitializeConsole();
|
||||||
Application::Console().Internal().set_prompt("");
|
|
||||||
ArgsParser Parser;
|
ArgsParser Parser;
|
||||||
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||||
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||||
@@ -84,14 +85,16 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
if (Parser.FoundArgument({ "help" })) {
|
if (Parser.FoundArgument({ "help" })) {
|
||||||
|
Application::Console().Internal().set_prompt("");
|
||||||
Application::Console().WriteRaw(sCommandlineArguments);
|
Application::Console().WriteRaw(sCommandlineArguments);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
if (Parser.FoundArgument({ "version" })) {
|
if (Parser.FoundArgument({ "version" })) {
|
||||||
Application::Console().WriteRaw(fmt::format("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH));
|
Application::Console().Internal().set_prompt("");
|
||||||
|
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string ConfigPath = "ServerConfig.toml";
|
std::string ConfigPath = "ServerConfig.toml";
|
||||||
if (Parser.FoundArgument({ "config" })) {
|
if (Parser.FoundArgument({ "config" })) {
|
||||||
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||||
@@ -114,37 +117,36 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
|
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||||
|
|
||||||
SetupSignalHandlers();
|
|
||||||
|
|
||||||
beammp_infof("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH);
|
|
||||||
|
|
||||||
TConfig Config(ConfigPath);
|
|
||||||
|
|
||||||
if (Config.Failed()) {
|
|
||||||
beammp_info("Closing in 10 seconds");
|
|
||||||
// loop to make it possible to ctrl+c instead
|
|
||||||
Application::SleepSafeSeconds(5);
|
|
||||||
beammp_info("Closing in 5 seconds");
|
|
||||||
Application::SleepSafeSeconds(5);
|
|
||||||
Application::GracefullyShutdown();
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Application::Console().Internal().set_prompt("> ");
|
|
||||||
Application::Console().StartLoggingToFile();
|
Application::Console().StartLoggingToFile();
|
||||||
|
|
||||||
|
SetupSignalHandlers();
|
||||||
|
|
||||||
bool Shutdown = false;
|
bool Shutdown = false;
|
||||||
Application::RegisterShutdownHandler([&Shutdown] {
|
Application::RegisterShutdownHandler([&Shutdown] {
|
||||||
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
|
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
|
||||||
Shutdown = true;
|
Shutdown = true;
|
||||||
});
|
});
|
||||||
|
Application::RegisterShutdownHandler([] {
|
||||||
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
|
||||||
|
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||||
|
});
|
||||||
|
|
||||||
TServer Server(Arguments.List);
|
TServer Server(Arguments.List);
|
||||||
|
TConfig Config(ConfigPath);
|
||||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
LuaEngine->SetServer(&Server);
|
LuaEngine->SetServer(&Server);
|
||||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
|
if (Config.Failed()) {
|
||||||
|
beammp_info("Closing in 10 seconds");
|
||||||
|
// loop to make it possible to ctrl+c instead
|
||||||
|
for (size_t i = 0; i < 20; ++i) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
RegisterThread("Main");
|
RegisterThread("Main");
|
||||||
|
|
||||||
beammp_trace("Running in debug mode on a debug build");
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
@@ -158,9 +160,9 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
PPSMonitor.SetNetwork(Network);
|
PPSMonitor.SetNetwork(Network);
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
TPluginMonitor PluginMonitor(fs::path(Application::GetSettingString(StrResourceFolder)) / "Server", LuaEngine);
|
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||||
|
|
||||||
if (Application::GetSettingBool(StrHTTPServerEnabled)) {
|
if (Application::Settings.HTTPServerEnabled) {
|
||||||
Http::Server::THttpServerInstance HttpServerInstance {};
|
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user