mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-14 10:44:30 +00:00
Compare commits
76 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c8826a337 | |||
| 9fccc27741 | |||
| b0021d42b5 | |||
| 5598d75fd5 | |||
| 48bb1373e1 | |||
| 8fce2fc67f | |||
| f7acd1e819 | |||
| b46dc664c6 | |||
| 18b4c698fc | |||
| 62c300f285 | |||
| d8e974429d | |||
| 634955660d | |||
| 1e9e068aec | |||
| 87ecfdbc72 | |||
| 2f1881bbe7 | |||
| 1e60ac5ba2 | |||
| cd2752a525 | |||
| 66b10f19c2 | |||
| ed03096cf5 | |||
| 88f1976668 | |||
| 952631bb80 | |||
| 23af76dba1 | |||
| 5755ead9be | |||
| 450f0a6875 | |||
| 104737571c | |||
| d86efabb1a | |||
| b2f27c21be | |||
| b780a08f73 | |||
| cd4332b790 | |||
| 7a814ed35e | |||
| 9e0d02c6db | |||
| d0bb32ec63 | |||
| 5180c96e2b | |||
| dbfe4a4d11 | |||
| 4cb299061e | |||
| ef902a03f3 | |||
| c1e216957b | |||
| 39db1a5e42 | |||
| be498be661 | |||
| 0466ae55a4 | |||
| 6a43694c0f | |||
| fe06726d75 | |||
| 3c08e54471 | |||
| 710b15535e | |||
| 2caa74d913 | |||
| e3d9d11bbd | |||
| 09c9b24cbf | |||
| a450531b8a | |||
| ace7aaada7 | |||
| ca3314b416 | |||
| 7d97c3b560 | |||
| dd5cf1a4af | |||
| 9a0cdc6517 | |||
| 965935a0e6 | |||
| 96a0e4b6fb | |||
| b52677e585 | |||
| 95b417bb36 | |||
| 588c68ebe1 | |||
| 548b2512cc | |||
| 8ff94a57d7 | |||
| a44684f6e7 | |||
| 944b68c6d5 | |||
| 01268821dc | |||
| 17c571811a | |||
| fdb7c9ce71 | |||
| c391abcc93 | |||
| 144ccf14ec | |||
| 40b23cbbe6 | |||
| 7b458e3e27 | |||
| 69656f95db | |||
| 0f5c476d09 | |||
| 86b6aed350 | |||
| 81780294f8 | |||
| 7c1fb12625 | |||
| 9f892af997 | |||
| fd12ee672d |
@@ -35,7 +35,7 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
working-directory: ${{github.workspace}}/build-linux
|
||||||
shell: bash
|
shell: bash
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
||||||
|
|
||||||
- name: Archive artifacts
|
- name: Archive artifacts
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ jobs:
|
|||||||
working-directory: ${{github.workspace}}/build-windows
|
working-directory: ${{github.workspace}}/build-windows
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
cmake --build . --config Debug
|
cmake --build . --config Debug -t BeamMP-Server --parallel
|
||||||
|
|
||||||
- name: Archive debug artifacts
|
- name: Archive debug artifacts
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
working-directory: ${{github.workspace}}/build-linux
|
||||||
shell: bash
|
shell: bash
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
||||||
|
|
||||||
- name: Upload Release Asset
|
- name: Upload Release Asset
|
||||||
id: upload-release-asset
|
id: upload-release-asset
|
||||||
@@ -101,7 +101,7 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
working-directory: ${{github.workspace}}/build-windows
|
||||||
shell: bash
|
shell: bash
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
||||||
|
|
||||||
- name: Upload Release Asset
|
- name: Upload Release Asset
|
||||||
id: upload-release-asset
|
id: upload-release-asset
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
[submodule "deps/commandline"]
|
[submodule "deps/commandline"]
|
||||||
path = deps/commandline
|
path = deps/commandline
|
||||||
url = https://github.com/lionkor/commandline
|
url = https://github.com/lionkor/commandline
|
||||||
|
[submodule "deps/fmt"]
|
||||||
|
path = deps/fmt
|
||||||
|
url = https://github.com/fmtlib/fmt
|
||||||
[submodule "deps/asio"]
|
[submodule "deps/asio"]
|
||||||
path = deps/asio
|
path = deps/asio
|
||||||
url = https://github.com/chriskohlhoff/asio
|
url = https://github.com/chriskohlhoff/asio
|
||||||
|
|||||||
+60
-76
@@ -1,4 +1,5 @@
|
|||||||
cmake_minimum_required(VERSION 3.0)
|
# 3.4 is required for imported targets.
|
||||||
|
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")
|
||||||
@@ -8,7 +9,22 @@ project(BeamMP-Server
|
|||||||
HOMEPAGE_URL https://beammp.com
|
HOMEPAGE_URL https://beammp.com
|
||||||
LANGUAGES CXX C)
|
LANGUAGES CXX C)
|
||||||
|
|
||||||
|
find_package(Git REQUIRED)
|
||||||
|
# Update submodules as needed
|
||||||
|
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||||
|
if(GIT_SUBMODULE)
|
||||||
|
message(STATUS "Submodule update")
|
||||||
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|
||||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
||||||
|
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
||||||
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/asio/asio/include")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/asio/asio/include")
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/rapidjson/include")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/rapidjson/include")
|
||||||
@@ -16,31 +32,46 @@ include_directories("${PROJECT_SOURCE_DIR}/deps/websocketpp")
|
|||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/sol2/include")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/sol2/include")
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/cpp-httplib")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/cpp-httplib")
|
||||||
|
include_directories("${PROJECT_SOURCE_DIR}/deps/toml11")
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/json/single_include")
|
include_directories("${PROJECT_SOURCE_DIR}/deps/json/single_include")
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
||||||
|
|
||||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT)
|
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||||
|
|
||||||
|
# ------------------------ APPLE ---------------------------------
|
||||||
if(APPLE)
|
if(APPLE)
|
||||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||||
set(LUA_LIBRARIES lua)
|
set(LUA_LIBRARIES lua)
|
||||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||||
endif()
|
# ------------------------ WINDOWS ---------------------------------
|
||||||
|
elseif (WIN32)
|
||||||
if (WIN32)
|
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||||
endif()
|
if (MSVC)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
||||||
|
set(SENTRY_BUILD_RUNTIMESTATIC ON)
|
||||||
|
endif ()
|
||||||
|
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
|
||||||
|
include_directories(${VcpkgRoot}/include)
|
||||||
|
link_directories(${VcpkgRoot}/lib)
|
||||||
|
# ------------------------ LINUX ---------------------------------
|
||||||
|
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_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
||||||
|
if (SANITIZE)
|
||||||
|
message(STATUS "sanitize is ON")
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
||||||
|
endif (SANITIZE)
|
||||||
|
endif ()
|
||||||
|
|
||||||
include_directories("include/sentry-native/include")
|
include_directories("include/sentry-native/include")
|
||||||
set(BUILD_SHARED_LIBS OFF)
|
|
||||||
if (MSVC)
|
# ------------------------ SENTRY ---------------------------------
|
||||||
set(SENTRY_BUILD_RUNTIMESTATIC ON)
|
|
||||||
endif()
|
|
||||||
message(STATUS "Checking for Sentry URL")
|
message(STATUS "Checking for Sentry URL")
|
||||||
# this is set by the build system.
|
# this is set by the build system.
|
||||||
# IMPORTANT: if you're building from source, just leave this empty
|
# IMPORTANT: if you're building from source, just leave this empty
|
||||||
@@ -50,42 +81,19 @@ if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
|
|||||||
set(BEAMMP_SECRET_SENTRY_URL "")
|
set(BEAMMP_SECRET_SENTRY_URL "")
|
||||||
set(SENTRY_BACKEND none)
|
set(SENTRY_BACKEND none)
|
||||||
else()
|
else()
|
||||||
string(LENGTH ${BEAMMP_SECRET_SENTRY_URL} URL_LEN)
|
|
||||||
message(STATUS "Sentry URL is length ${URL_LEN}")
|
|
||||||
set(SENTRY_BACKEND breakpad)
|
set(SENTRY_BACKEND breakpad)
|
||||||
endif()
|
endif()
|
||||||
add_subdirectory("deps/sentry-native")
|
add_subdirectory("deps/sentry-native")
|
||||||
|
|
||||||
if (MSVC)
|
# ------------------------ C++ SETUP ---------------------------------
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
endif ()
|
|
||||||
|
|
||||||
|
# ------------------------ DEPENDENCIES ------------------------------
|
||||||
message(STATUS "Adding local source dependencies")
|
message(STATUS "Adding local source dependencies")
|
||||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
||||||
add_subdirectory(deps)
|
add_subdirectory(deps)
|
||||||
|
|
||||||
message(STATUS "Setting compiler flags")
|
# ------------------------ BEAMMP SERVER -----------------------------
|
||||||
if (WIN32)
|
|
||||||
|
|
||||||
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
|
||||||
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
|
|
||||||
include_directories(${VcpkgRoot}/include)
|
|
||||||
link_directories(${VcpkgRoot}/lib)
|
|
||||||
elseif (UNIX)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
|
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
|
||||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
|
||||||
if (SANITIZE)
|
|
||||||
message(STATUS "sanitize is ON")
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
|
||||||
endif (SANITIZE)
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
|
||||||
|
|
||||||
add_executable(BeamMP-Server
|
add_executable(BeamMP-Server
|
||||||
src/main.cpp
|
src/main.cpp
|
||||||
@@ -117,12 +125,10 @@ target_include_directories(BeamMP-Server PUBLIC
|
|||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline")
|
"${CMAKE_CURRENT_SOURCE_DIR}/commandline")
|
||||||
|
|
||||||
if (APPLE)
|
include(FindLua)
|
||||||
message(STATUS "NOT looking for Lua on APPLE")
|
include(FindOpenSSL)
|
||||||
else()
|
include(FindThreads)
|
||||||
message(STATUS "Looking for Lua")
|
include(FindZLIB)
|
||||||
find_package(Lua REQUIRED VERSION 5.3)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
target_include_directories(BeamMP-Server PUBLIC
|
||||||
${LUA_INCLUDE_DIR}
|
${LUA_INCLUDE_DIR}
|
||||||
@@ -131,39 +137,17 @@ target_include_directories(BeamMP-Server PUBLIC
|
|||||||
"include/sentry-native/include"
|
"include/sentry-native/include"
|
||||||
"include/curl/include")
|
"include/curl/include")
|
||||||
|
|
||||||
message(STATUS "Looking for SSL")
|
target_link_libraries(BeamMP-Server
|
||||||
|
OpenSSL::SSL
|
||||||
|
OpenSSL::Crypto
|
||||||
|
sol2::sol2
|
||||||
|
fmt::fmt
|
||||||
|
Threads::Threads
|
||||||
|
ZLIB::ZLIB
|
||||||
|
${LUA_LIBRARIES}
|
||||||
|
commandline
|
||||||
|
sentry)
|
||||||
|
|
||||||
if (APPLE)
|
if (WIN32)
|
||||||
set(OPENSSL_LIBRARIES ssl crypto)
|
target_link_libraries(BeamMP-Server wsock32 ws2_32)
|
||||||
else()
|
|
||||||
find_package(OpenSSL REQUIRED)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
target_link_libraries(BeamMP-Server sol2::sol2 ${LUA_LIBRARIES})
|
|
||||||
message(STATUS "CURL IS ${CURL_LIBRARIES}")
|
|
||||||
|
|
||||||
if (UNIX)
|
|
||||||
target_link_libraries(BeamMP-Server
|
|
||||||
z
|
|
||||||
pthread
|
|
||||||
${LUA_LIBRARIES}
|
|
||||||
crypto
|
|
||||||
${OPENSSL_LIBRARIES}
|
|
||||||
commandline
|
|
||||||
sentry
|
|
||||||
ssl)
|
|
||||||
elseif (WIN32)
|
|
||||||
include(FindLua)
|
|
||||||
message(STATUS "Looking for libz")
|
|
||||||
find_package(ZLIB REQUIRED)
|
|
||||||
message(STATUS "Looking for RapidJSON")
|
|
||||||
find_package(RapidJSON CONFIG REQUIRED)
|
|
||||||
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS})
|
|
||||||
target_link_libraries(BeamMP-Server
|
|
||||||
ws2_32
|
|
||||||
ZLIB::ZLIB
|
|
||||||
${LUA_LIBRARIES}
|
|
||||||
${OPENSSL_LIBRARIES}
|
|
||||||
commandline
|
|
||||||
sentry)
|
|
||||||
endif ()
|
endif ()
|
||||||
|
|||||||
-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.
|
|
||||||
+8
-1
@@ -1,3 +1,11 @@
|
|||||||
|
# v3.1.0
|
||||||
|
|
||||||
|
- 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 MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa
|
||||||
|
- ADDED FS.ListFiles and FS.ListDirectories
|
||||||
|
- FIXED issue with client->server events which contain ':'
|
||||||
|
|
||||||
# v3.0.2
|
# v3.0.2
|
||||||
|
|
||||||
- ADDED Periodic update message if a new server is released
|
- ADDED Periodic update message if a new server is released
|
||||||
@@ -7,7 +15,6 @@
|
|||||||
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
|
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
|
||||||
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
|
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
|
||||||
- FIXED Lua result queue handling not checking all results
|
- FIXED Lua result queue handling not checking all results
|
||||||
- FIXED bug which caused ServerConfig.toml to generate incorrectly
|
|
||||||
|
|
||||||
# v3.0.1
|
# v3.0.1
|
||||||
|
|
||||||
|
|||||||
@@ -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,13 +28,13 @@ 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" 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
|
||||||
|
|
||||||
@@ -43,7 +42,7 @@ We only allow building unmodified (original) source code for public use. `master
|
|||||||
|
|
||||||
## 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.
|
||||||
|
|
||||||
@@ -53,7 +52,7 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
**__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
|
||||||
|
|
||||||
@@ -61,7 +60,7 @@ Currently only Linux and Windows are supported (generally). See [Releases](https
|
|||||||
|
|
||||||
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
|
lua
|
||||||
@@ -74,15 +73,19 @@ curl
|
|||||||
|
|
||||||
#### Linux
|
#### Linux
|
||||||
|
|
||||||
Runtime dependencies - you want to find packages for:
|
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
||||||
- libz
|
|
||||||
- rapidjson
|
|
||||||
- lua5.3
|
|
||||||
- ssl / openssl
|
|
||||||
- websocketpp
|
|
||||||
- curl (with ssl support)
|
|
||||||
|
|
||||||
Build-time dependencies are:
|
Runtime dependencies for **linux** are (debian/ubuntu):
|
||||||
|
```
|
||||||
|
libz-dev
|
||||||
|
rapidjson-dev
|
||||||
|
liblua5.3
|
||||||
|
libssl-dev
|
||||||
|
libwebsocketpp-dev
|
||||||
|
libcurl4-openssl-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Build-time dependencies for **linux** are:
|
||||||
```
|
```
|
||||||
git
|
git
|
||||||
make
|
make
|
||||||
@@ -90,24 +93,29 @@ cmake
|
|||||||
g++
|
g++
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For other distributions (e.g. Arch) you want to find packages for:
|
||||||
|
- libz
|
||||||
|
- rapidjson
|
||||||
|
- lua5.3
|
||||||
|
- ssl / openssl
|
||||||
|
- websocketpp
|
||||||
|
- curl (with ssl support)
|
||||||
|
- \+ the build time dependencies from above
|
||||||
|
|
||||||
### 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 --recurse-submodules 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 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/v2.3.3` for version 2.3.3. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||||
5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
|
5. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
6. Run `make`
|
||||||
7. Run `make`
|
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.
|
||||||
8. 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-installation) 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
+3
-5
@@ -1,9 +1,7 @@
|
|||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/asio/asio/include")
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/rapidjson/include")
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/websocketpp")
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/sol2/include")
|
|
||||||
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/sol2")
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
||||||
|
|||||||
+1
Submodule deps/fmt added at 17dda58391
Vendored
+1
-1
Submodule deps/toml11 updated: 1400dd223f...fda0a2b9ab
+15
-3
@@ -8,6 +8,7 @@ extern TSentry Sentry;
|
|||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
#include <fmt/format.h>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
@@ -41,8 +42,6 @@ public:
|
|||||||
std::string Resource { "Resources" };
|
std::string Resource { "Resources" };
|
||||||
std::string MapName { "/levels/gridmap_v2/info.json" };
|
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||||
std::string Key {};
|
std::string Key {};
|
||||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
|
||||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
|
||||||
bool HTTPServerEnabled { false };
|
bool HTTPServerEnabled { false };
|
||||||
int MaxPlayers { 8 };
|
int MaxPlayers { 8 };
|
||||||
bool Private { true };
|
bool Private { true };
|
||||||
@@ -50,6 +49,7 @@ public:
|
|||||||
bool DebugModeEnabled { false };
|
bool DebugModeEnabled { false };
|
||||||
int Port { 30814 };
|
int Port { 30814 };
|
||||||
std::string CustomIP {};
|
std::string CustomIP {};
|
||||||
|
bool LogChat { true };
|
||||||
bool SendErrors { true };
|
bool SendErrors { true };
|
||||||
bool SendErrorsMessageEnabled { true };
|
bool SendErrorsMessageEnabled { true };
|
||||||
int HTTPServerPort { 8080 };
|
int HTTPServerPort { 8080 };
|
||||||
@@ -122,7 +122,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, 0, 2 };
|
static inline Version mVersion { 3, 1, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride = false);
|
std::string ThreadName(bool DebugModeOverride = false);
|
||||||
@@ -148,6 +148,10 @@ void RegisterThread(const std::string& str);
|
|||||||
#define _function_name std::string(__func__)
|
#define _function_name std::string(__func__)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef NDEBUG
|
||||||
|
#define DEBUG
|
||||||
|
#endif
|
||||||
|
|
||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
|
|
||||||
// if this is defined, we will show the full function signature infront of
|
// if this is defined, we will show the full function signature infront of
|
||||||
@@ -209,6 +213,14 @@ void RegisterThread(const std::string& str);
|
|||||||
#define beammp_trace(x)
|
#define beammp_trace(x)
|
||||||
#endif // defined(DEBUG)
|
#endif // defined(DEBUG)
|
||||||
|
|
||||||
|
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|
||||||
#define Biggest 30000
|
#define Biggest 30000
|
||||||
|
|||||||
+8
-3
@@ -6,10 +6,10 @@
|
|||||||
|
|
||||||
#ifdef BEAMMP_LINUX
|
#ifdef BEAMMP_LINUX
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <errno.h>
|
|
||||||
using SOCKET = int;
|
using SOCKET = int;
|
||||||
using DWORD = unsigned long;
|
using DWORD = unsigned long;
|
||||||
using PDWORD = unsigned long*;
|
using PDWORD = unsigned long*;
|
||||||
@@ -25,10 +25,10 @@ inline void CloseSocketProper(int TheSocket) {
|
|||||||
|
|
||||||
#ifdef BEAMMP_APPLE
|
#ifdef BEAMMP_APPLE
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <errno.h>
|
|
||||||
using SOCKET = int;
|
using SOCKET = int;
|
||||||
using DWORD = unsigned long;
|
using DWORD = unsigned long;
|
||||||
using PDWORD = unsigned long*;
|
using PDWORD = unsigned long*;
|
||||||
@@ -48,6 +48,11 @@ inline void CloseSocketProper(int TheSocket) {
|
|||||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
inline void CloseSocketProper(SOCKET TheSocket) {
|
||||||
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
||||||
closesocket(TheSocket);
|
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
|
||||||
|
|||||||
+8
-18
@@ -3,8 +3,6 @@
|
|||||||
#include <Common.h>
|
#include <Common.h>
|
||||||
#include <IThreaded.h>
|
#include <IThreaded.h>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <openssl/pem.h>
|
|
||||||
#include <openssl/x509.h>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
@@ -19,9 +17,9 @@
|
|||||||
|
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
namespace Crypto {
|
class TServer;
|
||||||
constexpr size_t RSA_DEFAULT_KEYLENGTH { 2048 };
|
class TNetwork;
|
||||||
}
|
class TResourceManager;
|
||||||
|
|
||||||
namespace Http {
|
namespace Http {
|
||||||
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
||||||
@@ -32,11 +30,10 @@ namespace Status {
|
|||||||
const std::string ErrorString = "-1";
|
const std::string ErrorString = "-1";
|
||||||
|
|
||||||
namespace Server {
|
namespace Server {
|
||||||
void SetupEnvironment();
|
|
||||||
// todo: Add non TLS Server Instance, this one is TLS only
|
|
||||||
class THttpServerInstance {
|
class THttpServerInstance {
|
||||||
public:
|
public:
|
||||||
THttpServerInstance();
|
THttpServerInstance(TServer&, TNetwork&, TResourceManager&);
|
||||||
|
~THttpServerInstance();
|
||||||
static fs::path KeyFilePath;
|
static fs::path KeyFilePath;
|
||||||
static fs::path CertFilePath;
|
static fs::path CertFilePath;
|
||||||
|
|
||||||
@@ -45,16 +42,9 @@ namespace Server {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
std::thread mThread;
|
std::thread mThread;
|
||||||
};
|
TServer& mServer;
|
||||||
// todo: all of these functions are likely unsafe,
|
TNetwork& mNetwork;
|
||||||
// todo: replace with something that's managed by a domain specific crypto library
|
TResourceManager& mResourceManager;
|
||||||
class Tx509KeypairGenerator {
|
|
||||||
public:
|
|
||||||
static long GenerateRandomId();
|
|
||||||
static bool EnsureTLSConfigExists();
|
|
||||||
static X509* GenerateCertificate(EVP_PKEY& pkey);
|
|
||||||
static EVP_PKEY* GenerateKey();
|
|
||||||
static void GenerateAndWriteToDisk(const fs::path& KeyFilePath, const fs::path& CertFilePath);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-1
@@ -12,7 +12,8 @@ namespace MP {
|
|||||||
|
|
||||||
std::string GetOSName();
|
std::string GetOSName();
|
||||||
std::tuple<int, int, int> GetServerVersion();
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data);
|
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& 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(); }
|
||||||
void DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
void DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
void SendChatMessage(int ID, const std::string& Message);
|
void SendChatMessage(int ID, const std::string& Message);
|
||||||
@@ -22,7 +23,15 @@ namespace MP {
|
|||||||
bool IsPlayerConnected(int ID);
|
bool IsPlayerConnected(int ID);
|
||||||
void Sleep(size_t Ms);
|
void Sleep(size_t Ms);
|
||||||
void PrintRaw(sol::variadic_args);
|
void PrintRaw(sol::variadic_args);
|
||||||
|
std::string JsonEncode(const sol::table& object);
|
||||||
|
std::string JsonDiff(const std::string& a, const std::string& b);
|
||||||
|
std::string JsonDiffApply(const std::string& data, const std::string& patch);
|
||||||
|
std::string JsonPrettify(const std::string& json);
|
||||||
|
std::string JsonMinify(const std::string& json);
|
||||||
|
std::string JsonFlatten(const std::string& json);
|
||||||
|
std::string JsonUnflatten(const std::string& json);
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace FS {
|
namespace FS {
|
||||||
std::pair<bool, std::string> CreateDirectory(const std::string& Path);
|
std::pair<bool, std::string> CreateDirectory(const std::string& Path);
|
||||||
std::pair<bool, std::string> Remove(const std::string& Path);
|
std::pair<bool, std::string> Remove(const std::string& Path);
|
||||||
|
|||||||
+2
-1
@@ -3,9 +3,10 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
||||||
#include <toml11/toml.hpp> // header-only version of TOML++
|
#include <toml.hpp> // header-only version of TOML++
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
|||||||
+29
-6
@@ -4,6 +4,11 @@
|
|||||||
#include "commandline.h"
|
#include "commandline.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
|
#include <tuple>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
class TLuaEngine;
|
class TLuaEngine;
|
||||||
|
|
||||||
@@ -22,13 +27,31 @@ private:
|
|||||||
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
||||||
void ChangeToLuaConsole(const std::string& LuaStateId);
|
void ChangeToLuaConsole(const std::string& LuaStateId);
|
||||||
void ChangeToRegularConsole();
|
void ChangeToRegularConsole();
|
||||||
|
void HandleLuaInternalCommand(const std::string& cmd);
|
||||||
|
|
||||||
void Command_Lua(const std::string& cmd);
|
void Command_Lua(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Help(const std::string& cmd);
|
void Command_Help(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Kick(const std::string& cmd);
|
void Command_Kick(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Say(const std::string& cmd);
|
void Command_List(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_List(const std::string& cmd);
|
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Status(const std::string& cmd);
|
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
|
||||||
|
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 min, size_t max);
|
||||||
|
|
||||||
|
static std::tuple<std::string, std::vector<std::string>> ParseCommand(const std::string& cmd);
|
||||||
|
static std::string ConcatArgs(const std::vector<std::string>& args, char space = ' ');
|
||||||
|
|
||||||
|
std::unordered_map<std::string, std::function<void(const std::string&, const std::vector<std::string>&)>> mCommandMap = {
|
||||||
|
{ "lua", [this](const auto& a, const auto& b) { Command_Lua(a, b); } },
|
||||||
|
{ "help", [this](const auto& a, const auto& b) { Command_Help(a, b); } },
|
||||||
|
{ "kick", [this](const auto& a, const auto& b) { Command_Kick(a, b); } },
|
||||||
|
{ "list", [this](const auto& a, const auto& b) { Command_List(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); } },
|
||||||
|
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||||
|
};
|
||||||
|
|
||||||
Commandline mCommandline;
|
Commandline mCommandline;
|
||||||
std::vector<std::string> mCachedLuaHistory;
|
std::vector<std::string> mCachedLuaHistory;
|
||||||
|
|||||||
+24
-3
@@ -11,8 +11,9 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <toml11/toml.hpp>
|
#include <toml.hpp>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -33,8 +34,8 @@ static constexpr size_t TLuaArgTypes_Bool = 3;
|
|||||||
class TLuaPlugin;
|
class TLuaPlugin;
|
||||||
|
|
||||||
struct TLuaResult {
|
struct TLuaResult {
|
||||||
std::atomic_bool Ready;
|
bool Ready;
|
||||||
std::atomic_bool Error;
|
bool Error;
|
||||||
std::string ErrorMessage;
|
std::string ErrorMessage;
|
||||||
sol::object Result { sol::lua_nil };
|
sol::object Result { sol::lua_nil };
|
||||||
TLuaStateId StateId;
|
TLuaStateId StateId;
|
||||||
@@ -102,6 +103,7 @@ public:
|
|||||||
std::unique_lock Lock(mResultsToCheckMutex);
|
std::unique_lock Lock(mResultsToCheckMutex);
|
||||||
return mResultsToCheck.size();
|
return mResultsToCheck.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t GetLuaStateCount() {
|
size_t GetLuaStateCount() {
|
||||||
std::unique_lock Lock(mLuaStatesMutex);
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
return mLuaStates.size();
|
return mLuaStates.size();
|
||||||
@@ -166,6 +168,14 @@ 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);
|
||||||
|
|
||||||
|
// Debugging functions (slow)
|
||||||
|
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
|
||||||
|
std::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
|
||||||
|
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void CollectAndInitPlugins();
|
void CollectAndInitPlugins();
|
||||||
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
||||||
@@ -185,6 +195,12 @@ private:
|
|||||||
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();
|
||||||
|
|
||||||
|
// Debug functions, slow
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||||
|
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||||
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||||
@@ -193,7 +209,10 @@ private:
|
|||||||
std::string Lua_GetPlayerName(int ID);
|
std::string Lua_GetPlayerName(int ID);
|
||||||
sol::table Lua_GetPlayerVehicles(int ID);
|
sol::table Lua_GetPlayerVehicles(int ID);
|
||||||
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);
|
||||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||||
|
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||||
|
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||||
|
|
||||||
std::string mName;
|
std::string mName;
|
||||||
std::atomic_bool& mShutdown;
|
std::atomic_bool& mShutdown;
|
||||||
@@ -209,6 +228,8 @@ private:
|
|||||||
sol::state_view mStateView { mState };
|
sol::state_view mStateView { mState };
|
||||||
std::queue<fs::path> mPaths;
|
std::queue<fs::path> mPaths;
|
||||||
std::recursive_mutex mPathsMutex;
|
std::recursive_mutex mPathsMutex;
|
||||||
|
std::mt19937 mMersenneTwister;
|
||||||
|
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct TimedEvent {
|
struct TimedEvent {
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
|
using json = nlohmann::json;
|
||||||
|
|
||||||
class TVehicleData final {
|
class TVehicleData final {
|
||||||
public:
|
public:
|
||||||
TVehicleData(int ID, std::string Data);
|
TVehicleData(int ID, const std::string& Data);
|
||||||
~TVehicleData();
|
~TVehicleData();
|
||||||
// We cannot delete this, since vector needs to be able to copy when it resizes.
|
// We cannot delete this, since vector needs to be able to copy when it resizes.
|
||||||
// Deleting this causes some wacky template errors which are hard to decipher,
|
// Deleting this causes some wacky template errors which are hard to decipher,
|
||||||
@@ -19,9 +22,12 @@ public:
|
|||||||
|
|
||||||
bool operator==(const TVehicleData& v) const { return mID == v.mID; }
|
bool operator==(const TVehicleData& v) const { return mID == v.mID; }
|
||||||
|
|
||||||
|
const json& Json() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
int mID { -1 };
|
int mID { -1 };
|
||||||
std::string mData;
|
std::string mData;
|
||||||
|
json mJson;
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: unused now, remove?
|
// TODO: unused now, remove?
|
||||||
|
|||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
openapi: "3.0.2"
|
||||||
|
info:
|
||||||
|
title: BeamMP-Server
|
||||||
|
version: "api-v1"
|
||||||
|
description: |
|
||||||
|
The BeamMP-Server optionally runs an HTTP server
|
||||||
|
which can be used to query information about the server's
|
||||||
|
status, health, players, etc.
|
||||||
|
servers:
|
||||||
|
- url: http://localhost:{port}/api/v1
|
||||||
|
description: BeamMP-Server API v1
|
||||||
|
variables:
|
||||||
|
port:
|
||||||
|
default: "8000"
|
||||||
|
|
||||||
|
paths:
|
||||||
|
/player/{name}/vehicles:
|
||||||
|
parameters:
|
||||||
|
- name: "name"
|
||||||
|
in: path
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
example: "LionKor"
|
||||||
|
get:
|
||||||
|
summary: vehicles this player has spawend
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"application/json":
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
jbm:
|
||||||
|
type: string
|
||||||
|
example: "bolide"
|
||||||
|
/version:
|
||||||
|
get:
|
||||||
|
summary: server version
|
||||||
|
description: |
|
||||||
|
Server version in 'major.minor.patch' semver format
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"text/plain":
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
example: "3.1.0"
|
||||||
|
/players:
|
||||||
|
get:
|
||||||
|
summary: list of players on this server
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"application/json":
|
||||||
|
schema:
|
||||||
|
type: array
|
||||||
|
example:
|
||||||
|
- "LionKor"
|
||||||
|
- "Titch"
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
/config:
|
||||||
|
get:
|
||||||
|
summary: describes server configuration
|
||||||
|
description: |
|
||||||
|
An overview over the configuration currently
|
||||||
|
used by this server.
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"application/json":
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
example: "my awesome beammp server"
|
||||||
|
description:
|
||||||
|
type: string
|
||||||
|
example: "join!"
|
||||||
|
max_players:
|
||||||
|
type: integer
|
||||||
|
example: 7
|
||||||
|
max_cars:
|
||||||
|
type: integer
|
||||||
|
example: 2
|
||||||
|
map:
|
||||||
|
type: string
|
||||||
|
example: "/levels/gridmap_v2/info.json"
|
||||||
|
private:
|
||||||
|
type: boolean
|
||||||
|
/ready:
|
||||||
|
get:
|
||||||
|
summary: whether the server has started fully
|
||||||
|
description: |
|
||||||
|
True once all subsystems have started up.
|
||||||
|
This doesn't tell you whether they're healthy,
|
||||||
|
check /health for that information.
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"text/plain":
|
||||||
|
schema:
|
||||||
|
type: boolean
|
||||||
|
/health:
|
||||||
|
get:
|
||||||
|
summary: health of the server's systems
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
"application/json":
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
healthy:
|
||||||
|
type: boolean
|
||||||
|
good:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
example: "Heartbeat"
|
||||||
|
bad:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
example: "ResourceManager"
|
||||||
+2
-2
@@ -12,7 +12,7 @@ void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
|
|||||||
ConsumeLongFlag(std::string(Arg));
|
ConsumeLongFlag(std::string(Arg));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
beammp_error("Error parsing commandline arguments: Supplied argument '" + std::string(Arg) + "' is not a valid argument and was ignored.");
|
beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ 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)) {
|
||||||
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' is required but wasn't found.");
|
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)) {
|
||||||
|
|||||||
@@ -5,8 +5,6 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
// FIXME: add debug prints
|
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
void TClient::DeleteCar(int Ident) {
|
||||||
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) {
|
||||||
|
|||||||
+14
-14
@@ -43,6 +43,7 @@ void Application::GracefullyShutdown() {
|
|||||||
beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
|
beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
|
||||||
mShutdownHandlers[i]();
|
mShutdownHandlers[i]();
|
||||||
}
|
}
|
||||||
|
// std::exit(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Application::ServerVersionString() {
|
std::string Application::ServerVersionString() {
|
||||||
@@ -60,7 +61,6 @@ std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
|
|||||||
return Version;
|
return Version;
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME: This should be used by operator< on Version
|
|
||||||
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
||||||
if (Newest.major > Current.major) {
|
if (Newest.major > Current.major) {
|
||||||
return true;
|
return true;
|
||||||
@@ -162,7 +162,7 @@ void RegisterThread(const std::string& str) {
|
|||||||
ThreadId = std::to_string(gettid());
|
ThreadId = std::to_string(gettid());
|
||||||
#endif
|
#endif
|
||||||
if (Application::Settings.DebugModeEnabled) {
|
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;
|
||||||
}
|
}
|
||||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||||
@@ -179,22 +179,22 @@ Version::Version(const std::array<uint8_t, 3>& v)
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string Version::AsString() {
|
std::string Version::AsString() {
|
||||||
std::stringstream ss {};
|
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
|
||||||
ss << int(major) << "." << int(minor) << "." << int(patch);
|
|
||||||
return ss.str();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||||
std::stringstream ss;
|
if (Application::Settings.LogChat) {
|
||||||
ss << ThreadName();
|
std::stringstream ss;
|
||||||
ss << "[CHAT] ";
|
ss << ThreadName();
|
||||||
if (id != -1) {
|
ss << "[CHAT] ";
|
||||||
ss << "(" << id << ") <" << name << "> ";
|
if (id != -1) {
|
||||||
} else {
|
ss << "(" << id << ") <" << name << "> ";
|
||||||
ss << name << "";
|
} else {
|
||||||
|
ss << name << "";
|
||||||
|
}
|
||||||
|
ss << msg;
|
||||||
|
Application::Console().Write(ss.str());
|
||||||
}
|
}
|
||||||
ss << msg;
|
|
||||||
Application::Console().Write(ss.str());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string GetPlatformAgnosticErrorString() {
|
std::string GetPlatformAgnosticErrorString() {
|
||||||
|
|||||||
+127
-203
@@ -4,20 +4,19 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
|
#include "TNetwork.h"
|
||||||
|
#include "TResourceManager.h"
|
||||||
|
#include "TServer.h"
|
||||||
#include "httplib.h"
|
#include "httplib.h"
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <rapidjson/document.h>
|
|
||||||
#include <rapidjson/rapidjson.h>
|
|
||||||
#include <rapidjson/stringbuffer.h>
|
|
||||||
#include <rapidjson/writer.h>
|
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
fs::path Http::Server::THttpServerInstance::KeyFilePath;
|
|
||||||
fs::path Http::Server::THttpServerInstance::CertFilePath;
|
|
||||||
// TODO: Add sentry error handling back
|
// TODO: Add sentry error handling back
|
||||||
|
|
||||||
namespace json = rapidjson;
|
using json = nlohmann::json;
|
||||||
|
|
||||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||||
httplib::SSLClient client(host, port);
|
httplib::SSLClient client(host, port);
|
||||||
@@ -146,170 +145,115 @@ std::string Http::Status::ToString(int Code) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
long Http::Server::Tx509KeypairGenerator::GenerateRandomId() {
|
#define API_V1 "/api/v1"
|
||||||
std::random_device R;
|
|
||||||
std::default_random_engine E1(R());
|
|
||||||
std::uniform_int_distribution<long> UniformDist(0, ULONG_MAX);
|
|
||||||
return UniformDist(E1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Http::Server::THttpServerInstance::THttpServerInstance() { }
|
Http::Server::THttpServerInstance::THttpServerInstance(TServer& Server, TNetwork& Network, TResourceManager& ResMan)
|
||||||
EVP_PKEY* Http::Server::Tx509KeypairGenerator::GenerateKey() {
|
: mServer(Server)
|
||||||
/**
|
, mNetwork(Network)
|
||||||
* Allocate memory for the pkey
|
, mResourceManager(ResMan) {
|
||||||
*/
|
|
||||||
EVP_PKEY* PKey = EVP_PKEY_new();
|
|
||||||
if (PKey == nullptr) {
|
|
||||||
beammp_error("Could not allocate memory for X.509 private key (PKEY) generation.");
|
|
||||||
throw std::runtime_error { std::string { "X.509 PKEY allocation error" } };
|
|
||||||
}
|
|
||||||
BIGNUM* E = BN_new();
|
|
||||||
beammp_assert(E); // TODO: replace all these asserts with beammp_errors
|
|
||||||
unsigned char three = 3;
|
|
||||||
BIGNUM* EErr = BN_bin2bn(&three, sizeof(three), E);
|
|
||||||
beammp_assert(EErr);
|
|
||||||
RSA* Rsa = RSA_new();
|
|
||||||
beammp_assert(Rsa);
|
|
||||||
int Ret = RSA_generate_key_ex(Rsa, Crypto::RSA_DEFAULT_KEYLENGTH, E, nullptr);
|
|
||||||
beammp_assert(Ret == 1);
|
|
||||||
BN_free(E);
|
|
||||||
if (!EVP_PKEY_assign_RSA(PKey, Rsa)) {
|
|
||||||
EVP_PKEY_free(PKey);
|
|
||||||
beammp_error(std::string("Could not generate " + std::to_string(Crypto::RSA_DEFAULT_KEYLENGTH) + "-bit RSA key."));
|
|
||||||
throw std::runtime_error { std::string("X.509 RSA key generation error") };
|
|
||||||
}
|
|
||||||
// todo: figure out if returning by reference instead of passing pointers is a security breach
|
|
||||||
return PKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
X509* Http::Server::Tx509KeypairGenerator::GenerateCertificate(EVP_PKEY& PKey) {
|
|
||||||
X509* X509 = X509_new();
|
|
||||||
if (X509 == nullptr) {
|
|
||||||
X509_free(X509);
|
|
||||||
beammp_error("Could not allocate memory for X.509 certificate generation.");
|
|
||||||
throw std::runtime_error { std::string("X.509 certificate generation error") };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**Set the metadata of the certificate*/
|
|
||||||
ASN1_INTEGER_set(X509_get_serialNumber(X509), GenerateRandomId());
|
|
||||||
|
|
||||||
/**Set the cert validity to a year*/
|
|
||||||
X509_gmtime_adj(X509_get_notBefore(X509), 0);
|
|
||||||
X509_gmtime_adj(X509_get_notAfter(X509), 31536000L);
|
|
||||||
|
|
||||||
/**Set the public key of the cert*/
|
|
||||||
X509_set_pubkey(X509, &PKey);
|
|
||||||
|
|
||||||
X509_NAME* Name = X509_get_subject_name(X509);
|
|
||||||
|
|
||||||
/**Set cert metadata*/
|
|
||||||
X509_NAME_add_entry_by_txt(Name, "C", MBSTRING_ASC, (unsigned char*)"GB", -1, -1, 0);
|
|
||||||
X509_NAME_add_entry_by_txt(Name, "O", MBSTRING_ASC, (unsigned char*)"BeamMP Ltd.", -1, -1, 0);
|
|
||||||
X509_NAME_add_entry_by_txt(Name, "CN", MBSTRING_ASC, (unsigned char*)"localhost", -1, -1, 0);
|
|
||||||
|
|
||||||
X509_set_issuer_name(X509, Name);
|
|
||||||
|
|
||||||
// TODO: Hashing with sha256 might cause problems, check later
|
|
||||||
if (!X509_sign(X509, &PKey, EVP_sha1())) {
|
|
||||||
X509_free(X509);
|
|
||||||
beammp_error("Could not sign X.509 certificate.");
|
|
||||||
throw std::runtime_error { std::string("X.509 certificate signing error") };
|
|
||||||
}
|
|
||||||
return X509;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Http::Server::Tx509KeypairGenerator::GenerateAndWriteToDisk(const fs::path& KeyFilePath, const fs::path& CertFilePath) {
|
|
||||||
// todo: generate directories for ssl keys
|
|
||||||
FILE* KeyFile = std::fopen(reinterpret_cast<const char*>(KeyFilePath.c_str()), "wb");
|
|
||||||
if (!KeyFile) {
|
|
||||||
beammp_error("Could not create file 'key.pem', check your permissions");
|
|
||||||
throw std::runtime_error("Could not create file 'key.pem'");
|
|
||||||
}
|
|
||||||
|
|
||||||
EVP_PKEY* PKey = Http::Server::Tx509KeypairGenerator::GenerateKey();
|
|
||||||
|
|
||||||
bool WriteOpResult = PEM_write_PrivateKey(KeyFile, PKey, nullptr, nullptr, 0, nullptr, nullptr);
|
|
||||||
fclose(KeyFile);
|
|
||||||
|
|
||||||
if (!WriteOpResult) {
|
|
||||||
beammp_error("Could not write to file 'key.pem', check your permissions");
|
|
||||||
throw std::runtime_error("Could not write to file 'key.pem'");
|
|
||||||
}
|
|
||||||
|
|
||||||
FILE* CertFile = std::fopen(reinterpret_cast<const char*>(CertFilePath.c_str()), "wb"); // x509 file
|
|
||||||
if (!CertFile) {
|
|
||||||
beammp_error("Could not create file 'cert.pem', check your permissions");
|
|
||||||
throw std::runtime_error("Could not create file 'cert.pem'");
|
|
||||||
}
|
|
||||||
|
|
||||||
X509* x509 = Http::Server::Tx509KeypairGenerator::GenerateCertificate(*PKey);
|
|
||||||
WriteOpResult = PEM_write_X509(CertFile, x509);
|
|
||||||
fclose(CertFile);
|
|
||||||
|
|
||||||
if (!WriteOpResult) {
|
|
||||||
beammp_error("Could not write to file 'cert.pem', check your permissions");
|
|
||||||
throw std::runtime_error("Could not write to file 'cert.pem'");
|
|
||||||
}
|
|
||||||
EVP_PKEY_free(PKey);
|
|
||||||
X509_free(x509);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Http::Server::Tx509KeypairGenerator::EnsureTLSConfigExists() {
|
|
||||||
if (fs::is_regular_file(Application::Settings.SSLKeyPath)
|
|
||||||
&& fs::is_regular_file(Application::Settings.SSLCertPath)) {
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Http::Server::SetupEnvironment() {
|
|
||||||
if (!Application::Settings.HTTPServerUseSSL) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto parent = fs::path(Application::Settings.SSLKeyPath).parent_path();
|
|
||||||
if (!fs::exists(parent))
|
|
||||||
fs::create_directories(parent);
|
|
||||||
|
|
||||||
Application::TSettings defaultSettings {};
|
|
||||||
if (!Tx509KeypairGenerator::EnsureTLSConfigExists()) {
|
|
||||||
beammp_warn(std::string("No default TLS Key / Cert found. "
|
|
||||||
"IF YOU HAVE NOT MODIFIED THE SSLKeyPath OR SSLCertPath VALUES "
|
|
||||||
"THIS IS NORMAL ON FIRST STARTUP! BeamMP will generate it's own certs in the default directory "
|
|
||||||
"(Check for permissions or corrupted key-/certfile)"));
|
|
||||||
Tx509KeypairGenerator::GenerateAndWriteToDisk(defaultSettings.SSLKeyPath, defaultSettings.SSLCertPath);
|
|
||||||
Http::Server::THttpServerInstance::KeyFilePath = defaultSettings.SSLKeyPath;
|
|
||||||
Http::Server::THttpServerInstance::CertFilePath = defaultSettings.SSLCertPath;
|
|
||||||
} else {
|
|
||||||
Http::Server::THttpServerInstance::KeyFilePath = Application::Settings.SSLKeyPath;
|
|
||||||
Http::Server::THttpServerInstance::CertFilePath = Application::Settings.SSLCertPath;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Http::Server::THttpServerInstance::THttpServerInstance() {
|
|
||||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Starting);
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Starting);
|
||||||
mThread = std::thread(&Http::Server::THttpServerInstance::operator(), this);
|
mThread = std::thread(&Http::Server::THttpServerInstance::operator(), this);
|
||||||
|
}
|
||||||
|
|
||||||
|
Http::Server::THttpServerInstance::~THttpServerInstance() {
|
||||||
mThread.detach();
|
mThread.detach();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Http::Server::THttpServerInstance::operator()() try {
|
void Http::Server::THttpServerInstance::operator()() try {
|
||||||
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
|
beammp_infof("HTTP Server starting on [{}]:{}", Application::Settings.HTTPServerIP, Application::Settings.HTTPServerPort);
|
||||||
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
if (Application::Settings.Private
|
||||||
if (Application::Settings.HTTPServerUseSSL) {
|
&& Application::Settings.HTTPServerIP != "::"
|
||||||
HttpLibServerInstance = std::make_unique<httplib::SSLServer>(
|
&& Application::Settings.HTTPServerIP != "localhost"
|
||||||
reinterpret_cast<const char*>(Http::Server::THttpServerInstance::CertFilePath.c_str()),
|
&& Application::Settings.HTTPServerIP != "127.0.0.1") {
|
||||||
reinterpret_cast<const char*>(Http::Server::THttpServerInstance::KeyFilePath.c_str()));
|
beammp_warnf("HTTP Server is running on a possibly public IP ({}), but the server is private. The server's HTTP API supports viewing config, players, and other information, even though the server is private. (this is not an error)", Application::Settings.HTTPServerIP);
|
||||||
} else {
|
|
||||||
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
|
||||||
}
|
}
|
||||||
// todo: make this IP agnostic so people can set their own IP
|
std::unique_ptr<httplib::Server> Server = std::make_unique<httplib::Server>();
|
||||||
HttpLibServerInstance->Get("/", [](const httplib::Request&, httplib::Response& res) {
|
|
||||||
res.set_content("<!DOCTYPE html><article><h1>Hello World!</h1><section><p>BeamMP Server can now serve HTTP requests!</p></section></article></html>", "text/html");
|
Server->Get(API_V1 R"(/player/(.+)/vehicles)", [this](const httplib::Request& Req, httplib::Response& Res) {
|
||||||
|
if (Req.matches.empty()) {
|
||||||
|
Res.status = 404;
|
||||||
|
} else {
|
||||||
|
const std::string PlayerName = Req.matches[1];
|
||||||
|
bool Found = false;
|
||||||
|
json Result = json::array();
|
||||||
|
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) {
|
||||||
|
if (!ClientPtr.expired()) {
|
||||||
|
const auto Client = ClientPtr.lock();
|
||||||
|
if (Client->GetName() == PlayerName) {
|
||||||
|
const auto [Cars, Lock] = Client->GetAllCars();
|
||||||
|
for (const auto& Car : *Cars) {
|
||||||
|
Result.emplace_back().at("jbm") = Car.Json().at("jbm");
|
||||||
|
}
|
||||||
|
Found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (!Found) {
|
||||||
|
Res.status = 404;
|
||||||
|
} else {
|
||||||
|
Res.status = 200;
|
||||||
|
Res.set_content(Result.dump(), "application/json");
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
HttpLibServerInstance->Get("/health", [](const httplib::Request&, httplib::Response& res) {
|
|
||||||
|
Server->Get(API_V1 "/players", [this](const httplib::Request&, httplib::Response& res) {
|
||||||
|
res.status = 200;
|
||||||
|
json Players = json::array();
|
||||||
|
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) {
|
||||||
|
if (!ClientPtr.expired()) {
|
||||||
|
Players.push_back(ClientPtr.lock()->GetName());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
res.set_content(Players.dump(),
|
||||||
|
"application/json");
|
||||||
|
});
|
||||||
|
|
||||||
|
Server->Get(API_V1 "/version", [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
res.status = 200;
|
||||||
|
res.set_content(Application::ServerVersionString(), "text/plain");
|
||||||
|
});
|
||||||
|
|
||||||
|
Server->Get(API_V1 "/config", [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
res.status = 200;
|
||||||
|
res.set_content(json {
|
||||||
|
{ "name", Application::Settings.ServerName },
|
||||||
|
{ "description", Application::Settings.ServerDesc },
|
||||||
|
{ "max_players", Application::Settings.MaxPlayers },
|
||||||
|
{ "max_cars", Application::Settings.MaxCars },
|
||||||
|
{ "map", Application::Settings.MapName },
|
||||||
|
{ "private", Application::Settings.Private },
|
||||||
|
}
|
||||||
|
.dump(),
|
||||||
|
"application/json");
|
||||||
|
});
|
||||||
|
|
||||||
|
Server->Get(API_V1 "/ready", [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
|
bool Started = true;
|
||||||
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
|
switch (NameStatusPair.second) {
|
||||||
|
case Application::Status::Starting:
|
||||||
|
case Application::Status::ShuttingDown:
|
||||||
|
case Application::Status::Shutdown:
|
||||||
|
Started = false;
|
||||||
|
break;
|
||||||
|
case Application::Status::Good:
|
||||||
|
case Application::Status::Bad:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.status = 200;
|
||||||
|
res.set_content(Started ? "true" : "false", "text/plain");
|
||||||
|
});
|
||||||
|
|
||||||
|
Server->Get(API_V1 "/health", [](const httplib::Request&, httplib::Response& res) {
|
||||||
size_t SystemsGood = 0;
|
size_t SystemsGood = 0;
|
||||||
size_t SystemsBad = 0;
|
size_t SystemsBad = 0;
|
||||||
|
json Good = json::array();
|
||||||
|
json Bad = json::array();
|
||||||
auto Statuses = Application::GetSubsystemStatuses();
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
for (const auto& NameStatusPair : Statuses) {
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
switch (NameStatusPair.second) {
|
switch (NameStatusPair.second) {
|
||||||
@@ -317,64 +261,44 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
case Application::Status::ShuttingDown:
|
case Application::Status::ShuttingDown:
|
||||||
case Application::Status::Shutdown:
|
case Application::Status::Shutdown:
|
||||||
case Application::Status::Good:
|
case Application::Status::Good:
|
||||||
|
Good.push_back(NameStatusPair.first);
|
||||||
SystemsGood++;
|
SystemsGood++;
|
||||||
break;
|
break;
|
||||||
case Application::Status::Bad:
|
case Application::Status::Bad:
|
||||||
|
Bad.push_back(NameStatusPair.first);
|
||||||
SystemsBad++;
|
SystemsBad++;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.set_content(SystemsBad == 0 ? "0" : "1", "text/plain");
|
res.set_content(
|
||||||
|
json {
|
||||||
|
{ "healthy", SystemsBad == 0 },
|
||||||
|
{ "good", Good },
|
||||||
|
{ "bad", Bad },
|
||||||
|
}
|
||||||
|
.dump(),
|
||||||
|
"application/json");
|
||||||
res.status = 200;
|
res.status = 200;
|
||||||
});
|
});
|
||||||
/*
|
|
||||||
HttpLibServerInstance->Get("/status", [](const httplib::Request&, httplib::Response& res) {
|
|
||||||
try {
|
|
||||||
json::Document response;
|
|
||||||
response.SetObject();
|
|
||||||
rapidjson::Document::AllocatorType& Allocator = response.GetAllocator();
|
|
||||||
// add to response
|
|
||||||
auto& Server = LuaAPI::MP::Engine->Server();
|
|
||||||
size_t CarCount = 0;
|
|
||||||
size_t GuestCount = 0;
|
|
||||||
json::Value Array(rapidjson::kArrayType);
|
|
||||||
LuaAPI::MP::Engine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
|
||||||
if (!Client.expired()) {
|
|
||||||
auto Locked = Client.lock();
|
|
||||||
CarCount += Locked->GetCarCount();
|
|
||||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
|
||||||
json::Value Player(json::kObjectType);
|
|
||||||
Player.AddMember("name", json::StringRef(Locked->GetName().c_str()), Allocator);
|
|
||||||
Player.AddMember("id", Locked->GetID(), Allocator);
|
|
||||||
Array.PushBack(Player, Allocator);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
response.AddMember("players", Array, Allocator);
|
|
||||||
response.AddMember("player_count", Server.ClientCount(), Allocator);
|
|
||||||
response.AddMember("guest_count", GuestCount, Allocator);
|
|
||||||
response.AddMember("car_count", CarCount, Allocator);
|
|
||||||
|
|
||||||
// compile & send response
|
|
||||||
json::StringBuffer sb;
|
|
||||||
json::Writer<json::StringBuffer> writer(sb);
|
|
||||||
response.Accept(writer);
|
|
||||||
res.set_content(sb.GetString(), "application/json");
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_error("Exception in /status endpoint: " + std::string(e.what()));
|
|
||||||
res.status = 500;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
*/
|
|
||||||
// magic endpoint
|
// magic endpoint
|
||||||
HttpLibServerInstance->Get({ 0x2f, 0x6b, 0x69, 0x74, 0x74, 0x79 }, [](const httplib::Request&, httplib::Response& res) {
|
Server->Get({ 0x2f, 0x6b, 0x69, 0x74, 0x74, 0x79 }, [](const httplib::Request&, httplib::Response& res) {
|
||||||
res.set_content(std::string(Magic), "text/plain");
|
res.set_content(std::string(Magic), "text/plain");
|
||||||
});
|
});
|
||||||
HttpLibServerInstance->set_logger([](const httplib::Request& Req, const httplib::Response& Res) {
|
Server->set_logger([](const httplib::Request& Req, const httplib::Response& Res) {
|
||||||
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));
|
||||||
});
|
});
|
||||||
|
Server->set_error_handler([](const httplib::Request&, httplib::Response& Res) {
|
||||||
|
if (Res.status >= 400 && Res.body.empty()) {
|
||||||
|
Res.set_content("Error: " + std::to_string(Res.status) + " " + Map.at(Res.status), "text/plain");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Server->set_exception_handler([](const httplib::Request& Req, httplib::Response& Res, std::exception& e) {
|
||||||
|
Res.status = 500;
|
||||||
|
Res.set_content("Internal Server Error", "text/plain");
|
||||||
|
beammp_errorf("Exception in http server serving '{}': {}", Req.target, e.what());
|
||||||
|
});
|
||||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||||
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
auto ret = Server->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.");
|
||||||
}
|
}
|
||||||
|
|||||||
+166
-5
@@ -3,6 +3,8 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
#define SOL_ALL_SAFETIES_ON 1
|
#define SOL_ALL_SAFETIES_ON 1
|
||||||
#include <sol/sol.hpp>
|
#include <sol/sol.hpp>
|
||||||
|
|
||||||
@@ -100,26 +102,31 @@ void LuaAPI::Print(sol::variadic_args Args) {
|
|||||||
luaprint(ToPrint);
|
luaprint(ToPrint);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::TriggerClientEvent(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)
|
||||||
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||||
else {
|
else {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), PlayerID);
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
if (!Engine->Network().Respond(*c, Packet, true)) {
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
||||||
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
||||||
Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||||
|
std::string Data = DataObj.as<std::string>();
|
||||||
|
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||||
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
@@ -352,3 +359,157 @@ std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
|
|||||||
auto Result = Path.lexically_normal().string();
|
auto Result = Path.lexically_normal().string();
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, const sol::object& right, bool is_array, size_t depth = 0) {
|
||||||
|
if (depth > 100) {
|
||||||
|
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::string key;
|
||||||
|
switch (left.get_type()) {
|
||||||
|
case sol::type::lua_nil:
|
||||||
|
case sol::type::none:
|
||||||
|
case sol::type::poly:
|
||||||
|
case sol::type::boolean:
|
||||||
|
case sol::type::lightuserdata:
|
||||||
|
case sol::type::userdata:
|
||||||
|
case sol::type::thread:
|
||||||
|
case sol::type::function:
|
||||||
|
case sol::type::table:
|
||||||
|
beammp_lua_error("JsonEncode: left side of table field is unexpected type");
|
||||||
|
return;
|
||||||
|
case sol::type::string:
|
||||||
|
key = left.as<std::string>();
|
||||||
|
break;
|
||||||
|
case sol::type::number:
|
||||||
|
key = std::to_string(left.as<double>());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
nlohmann::json value;
|
||||||
|
switch (right.get_type()) {
|
||||||
|
case sol::type::lua_nil:
|
||||||
|
case sol::type::none:
|
||||||
|
return;
|
||||||
|
case sol::type::poly:
|
||||||
|
beammp_lua_warn("unsure what to do with poly type in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::boolean:
|
||||||
|
value = right.as<bool>();
|
||||||
|
break;
|
||||||
|
case sol::type::lightuserdata:
|
||||||
|
beammp_lua_warn("unsure what to do with lightuserdata in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::userdata:
|
||||||
|
beammp_lua_warn("unsure what to do with userdata in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::thread:
|
||||||
|
beammp_lua_warn("unsure what to do with thread in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::string:
|
||||||
|
value = right.as<std::string>();
|
||||||
|
break;
|
||||||
|
case sol::type::number:
|
||||||
|
value = right.as<double>();
|
||||||
|
break;
|
||||||
|
case sol::type::function:
|
||||||
|
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::table: {
|
||||||
|
bool local_is_array = true;
|
||||||
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
|
local_is_array = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
|
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is_array) {
|
||||||
|
json.push_back(value);
|
||||||
|
} else {
|
||||||
|
json[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
||||||
|
nlohmann::json json;
|
||||||
|
// table
|
||||||
|
bool is_array = true;
|
||||||
|
for (const auto& pair : object.as<sol::table>()) {
|
||||||
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
|
is_array = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& entry : object) {
|
||||||
|
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||||
|
}
|
||||||
|
return json.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonDiff(const std::string& a, const std::string& b) {
|
||||||
|
if (!nlohmann::json::accept(a)) {
|
||||||
|
beammp_lua_error("JsonDiff first argument is not valid json: `" + a + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (!nlohmann::json::accept(b)) {
|
||||||
|
beammp_lua_error("JsonDiff second argument is not valid json: `" + b + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
auto a_json = nlohmann::json::parse(a);
|
||||||
|
auto b_json = nlohmann::json::parse(b);
|
||||||
|
return nlohmann::json::diff(a_json, b_json).dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonDiffApply(const std::string& data, const std::string& patch) {
|
||||||
|
if (!nlohmann::json::accept(data)) {
|
||||||
|
beammp_lua_error("JsonDiffApply first argument is not valid json: `" + data + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (!nlohmann::json::accept(patch)) {
|
||||||
|
beammp_lua_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
auto a_json = nlohmann::json::parse(data);
|
||||||
|
auto b_json = nlohmann::json::parse(patch);
|
||||||
|
a_json.patch(b_json);
|
||||||
|
return a_json.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonPrettify(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonPrettify argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).dump(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonMinify(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonMinify argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonFlatten(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonFlatten argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).flatten().dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonUnflatten argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||||
|
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||||
|
}
|
||||||
|
|||||||
+33
-29
@@ -17,6 +17,7 @@ static constexpr std::string_view StrName = "Name";
|
|||||||
static constexpr std::string_view StrDescription = "Description";
|
static constexpr std::string_view StrDescription = "Description";
|
||||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||||
|
static constexpr std::string_view StrLogChat = "LogChat";
|
||||||
|
|
||||||
// Misc
|
// Misc
|
||||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
@@ -26,8 +27,6 @@ static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
|||||||
// HTTP
|
// HTTP
|
||||||
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||||
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
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 StrHTTPServerPort = "HTTPServerPort";
|
||||||
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||||
|
|
||||||
@@ -62,10 +61,11 @@ void SetComment(CommentsT& Comments, const std::string& Comment) {
|
|||||||
* whether it is in TConfig.cpp or the configuration file.
|
* whether it is in TConfig.cpp or the configuration file.
|
||||||
*/
|
*/
|
||||||
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 {};
|
|
||||||
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
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::Settings.LogChat;
|
||||||
|
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
||||||
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||||
@@ -83,31 +83,13 @@ void TConfig::FlushToFile() {
|
|||||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
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`");
|
||||||
// HTTP
|
// HTTP
|
||||||
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
|
||||||
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
|
||||||
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
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::Settings.HTTPServerIP;
|
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
||||||
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");
|
|
||||||
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
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::ofstream Stream(mConfigFileName, std::ios::trunc | std::ios::out);
|
||||||
Ss << "# This is the BeamMP-Server config file.\n"
|
Stream << data << std::flush;
|
||||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
|
||||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
|
||||||
<< data;
|
|
||||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
|
||||||
if (!File) {
|
|
||||||
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
|
||||||
throw std::runtime_error("Failed to create/write to config file");
|
|
||||||
}
|
|
||||||
auto Str = Ss.str();
|
|
||||||
auto N = std::fwrite(Str.data(), sizeof(char), Str.size(), File);
|
|
||||||
if (N != Str.size()) {
|
|
||||||
beammp_error("Failed to write to config file properly, config file might be misshapen");
|
|
||||||
}
|
|
||||||
std::fclose(File);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::CreateConfigFile(std::string_view name) {
|
void TConfig::CreateConfigFile(std::string_view name) {
|
||||||
@@ -122,7 +104,32 @@ void TConfig::CreateConfigFile(std::string_view name) {
|
|||||||
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{ // create file context
|
||||||
|
std::ofstream ofs(name.data());
|
||||||
|
}
|
||||||
|
|
||||||
FlushToFile();
|
FlushToFile();
|
||||||
|
|
||||||
|
size_t FileSize = fs::file_size(name);
|
||||||
|
std::fstream ofs { std::string(name), std::ios::in | std::ios::out };
|
||||||
|
if (ofs.good()) {
|
||||||
|
std::string Contents {};
|
||||||
|
Contents.resize(FileSize);
|
||||||
|
ofs.readsome(Contents.data(), FileSize);
|
||||||
|
ofs.seekp(0);
|
||||||
|
ofs << "# This is the BeamMP-Server config file.\n"
|
||||||
|
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||||
|
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
||||||
|
<< '\n'
|
||||||
|
<< Contents;
|
||||||
|
beammp_error("There was no \"" + std::string(mConfigFileName) + "\" file (this is normal for the first time running the server), so one was generated for you. It was automatically filled with the settings from your Server.cfg, if you have one. Please open ServerConfig.toml and ensure your AuthKey and other settings are filled in and correct, then restart the server. The old Server.cfg file will no longer be used and causes a warning if it exists from now on.");
|
||||||
|
mFailed = true;
|
||||||
|
ofs.close();
|
||||||
|
} else {
|
||||||
|
beammp_error("Couldn't create " + std::string(name) + ". Check permissions, try again, and contact support if it continues not to work.");
|
||||||
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
|
mFailed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
||||||
@@ -157,17 +164,15 @@ void TConfig::ParseFromFile(std::string_view name) {
|
|||||||
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
||||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||||
|
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||||
// Misc
|
// Misc
|
||||||
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||||
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
||||||
// HTTP
|
// HTTP
|
||||||
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
|
||||||
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
||||||
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;
|
||||||
@@ -200,9 +205,8 @@ void TConfig::PrintDebug() {
|
|||||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
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(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(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
|
||||||
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
||||||
// special!
|
// special!
|
||||||
|
|||||||
+268
-73
@@ -118,10 +118,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("Entered Lua console for state '" + mStateId + "'. To exit, 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("Entered Lua console. To exit, 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();
|
||||||
@@ -133,9 +133,9 @@ void TConsole::ChangeToRegularConsole() {
|
|||||||
if (mIsLuaConsole) {
|
if (mIsLuaConsole) {
|
||||||
mIsLuaConsole = false;
|
mIsLuaConsole = false;
|
||||||
if (mStateId != mDefaultStateId) {
|
if (mStateId != mDefaultStateId) {
|
||||||
Application::Console().WriteRaw("Left Lua console for state '" + mStateId + "'.");
|
Application::Console().WriteRaw("Detached from Lua state '" + mStateId + "'.");
|
||||||
} else {
|
} else {
|
||||||
Application::Console().WriteRaw("Left Lua console.");
|
Application::Console().WriteRaw("Detached from Lua.");
|
||||||
}
|
}
|
||||||
mCachedLuaHistory = mCommandline.history();
|
mCachedLuaHistory = mCommandline.history();
|
||||||
mCommandline.set_history(mCachedRegularHistory);
|
mCommandline.set_history(mCachedRegularHistory);
|
||||||
@@ -144,21 +144,54 @@ void TConsole::ChangeToRegularConsole() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Lua(const std::string& cmd) {
|
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t n) {
|
||||||
if (cmd.size() > 3) {
|
if (n == 0 && args.size() != 0) {
|
||||||
auto NewStateId = cmd.substr(4);
|
Application::Console().WriteRaw("This command expects no arguments.");
|
||||||
|
return false;
|
||||||
|
} else if (args.size() != n) {
|
||||||
|
Application::Console().WriteRaw("Expected " + std::to_string(n) + " argument(s), instead got " + std::to_string(args.size()));
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max) {
|
||||||
|
if (min == max) {
|
||||||
|
return EnsureArgsCount(args, min);
|
||||||
|
} else {
|
||||||
|
if (args.size() > max) {
|
||||||
|
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
|
return false;
|
||||||
|
} else if (args.size() < min) {
|
||||||
|
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0, 1)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (args.size() == 1) {
|
||||||
|
auto NewStateId = args.at(0);
|
||||||
beammp_assert(!NewStateId.empty());
|
beammp_assert(!NewStateId.empty());
|
||||||
if (mLuaEngine->HasState(NewStateId)) {
|
if (mLuaEngine->HasState(NewStateId)) {
|
||||||
ChangeToLuaConsole(NewStateId);
|
ChangeToLuaConsole(NewStateId);
|
||||||
} else {
|
} else {
|
||||||
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
||||||
}
|
}
|
||||||
} else {
|
} else if (args.size() == 0) {
|
||||||
ChangeToLuaConsole(mDefaultStateId);
|
ChangeToLuaConsole(mDefaultStateId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Help(const std::string&) {
|
void TConsole::Command_Help(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
static constexpr const char* sHelpString = R"(
|
static constexpr const char* sHelpString = R"(
|
||||||
Commands:
|
Commands:
|
||||||
help displays this help
|
help displays this help
|
||||||
@@ -167,53 +200,127 @@ void TConsole::Command_Help(const std::string&) {
|
|||||||
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
|
||||||
status how the server is doing and what it's up to)";
|
status how the server is doing and what it's up to)";
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Kick(const std::string& cmd) {
|
std::string TConsole::ConcatArgs(const std::vector<std::string>& args, char space) {
|
||||||
if (cmd.size() > 4) {
|
std::string Result;
|
||||||
auto Name = cmd.substr(5);
|
for (const auto& arg : args) {
|
||||||
std::string Reason = "Kicked by server console";
|
Result += arg + space;
|
||||||
auto SpacePos = Name.find(' ');
|
}
|
||||||
if (SpacePos != Name.npos) {
|
Result = Result.substr(0, Result.size() - 1); // strip trailing space
|
||||||
Reason = Name.substr(SpacePos + 1);
|
return Result;
|
||||||
Name = cmd.substr(5, cmd.size() - Reason.size() - 5 - 1);
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto Name = args.at(0);
|
||||||
|
std::string Reason = "Kicked by server console";
|
||||||
|
if (args.size() > 1) {
|
||||||
|
Reason = ConcatArgs({ args.begin() + 1, args.end() });
|
||||||
|
}
|
||||||
|
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||||
|
bool Kicked = false;
|
||||||
|
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||||
|
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
||||||
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
||||||
|
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||||
|
};
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
return true;
|
||||||
bool Kicked = false;
|
});
|
||||||
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
if (!Kicked) {
|
||||||
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
} else {
|
||||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
Application::Console().WriteRaw("Kicked player '" + Name + "' for reason: '" + Reason + "'.");
|
||||||
};
|
}
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
}
|
||||||
if (!Client.expired()) {
|
|
||||||
auto locked = Client.lock();
|
std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const std::string& CommandWithArgs) {
|
||||||
if (NameCompare(locked->GetName(), Name)) {
|
// Algorithm designed and implemented by Lion Kortlepel (c) 2022
|
||||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
// It correctly splits arguments, including respecting single and double quotes, as well as backticks
|
||||||
Kicked = true;
|
auto End_i = CommandWithArgs.find_first_of(' ');
|
||||||
return false;
|
std::string Command = CommandWithArgs.substr(0, End_i);
|
||||||
|
std::string ArgsStr {};
|
||||||
|
if (End_i != std::string::npos) {
|
||||||
|
ArgsStr = CommandWithArgs.substr(End_i);
|
||||||
|
}
|
||||||
|
std::vector<std::string> Args;
|
||||||
|
char* PrevPtr = ArgsStr.data();
|
||||||
|
char* Ptr = ArgsStr.data();
|
||||||
|
const char* End = ArgsStr.data() + ArgsStr.size();
|
||||||
|
while (Ptr != End) {
|
||||||
|
std::string Arg = "";
|
||||||
|
// advance while space
|
||||||
|
while (Ptr != End && std::isspace(*Ptr))
|
||||||
|
++Ptr;
|
||||||
|
PrevPtr = Ptr;
|
||||||
|
// advance while NOT space, also handle quotes
|
||||||
|
while (Ptr != End && !std::isspace(*Ptr)) {
|
||||||
|
// TODO: backslash escaping quotes
|
||||||
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
|
if (*Ptr == Quote) {
|
||||||
|
// seek if there's a closing quote
|
||||||
|
// if there is, go there and continue, otherwise ignore
|
||||||
|
char* Seeker = Ptr + 1;
|
||||||
|
while (Seeker != End && *Seeker != Quote)
|
||||||
|
++Seeker;
|
||||||
|
if (Seeker != End) {
|
||||||
|
// found closing quote
|
||||||
|
Ptr = Seeker;
|
||||||
|
}
|
||||||
|
break; // exit for loop
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
++Ptr;
|
||||||
});
|
}
|
||||||
if (!Kicked) {
|
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
||||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
// remove quotes if enclosed in quotes
|
||||||
} else {
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
Application::Console().WriteRaw("Kicked player '" + Name + "' for reason: '" + Reason + "'.");
|
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||||
|
Arg = Arg.substr(1, Arg.size() - 2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Arg.empty()) {
|
||||||
|
Args.push_back(Arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { Command, Args };
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Say(const std::string& FullCmd) {
|
||||||
|
if (FullCmd.size() > 3) {
|
||||||
|
auto Message = FullCmd.substr(4);
|
||||||
|
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||||
|
if (!Application::Settings.LogChat) {
|
||||||
|
Application::Console().WriteRaw("Chat message sent!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Say(const std::string& cmd) {
|
void TConsole::Command_List(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (cmd.size() > 3) {
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
auto Message = cmd.substr(4);
|
return;
|
||||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Command_List(const std::string&) {
|
|
||||||
if (mLuaEngine->Server().ClientCount() == 0) {
|
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||||
Application::Console().WriteRaw("No players online.");
|
Application::Console().WriteRaw("No players online.");
|
||||||
} else {
|
} else {
|
||||||
@@ -233,7 +340,10 @@ void TConsole::Command_List(const std::string&) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Status(const std::string&) {
|
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
std::stringstream Status;
|
std::stringstream Status;
|
||||||
|
|
||||||
size_t CarCount = 0;
|
size_t CarCount = 0;
|
||||||
@@ -318,12 +428,12 @@ void TConsole::Command_Status(const 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/Shutdown: " << 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\tShutdown: [ " << SystemsShutdownList << " ]\n"
|
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||||
<< "";
|
<< "";
|
||||||
|
|
||||||
Application::Console().WriteRaw(Status.str());
|
Application::Console().WriteRaw(Status.str());
|
||||||
@@ -375,6 +485,58 @@ void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TConsole::HandleLuaInternalCommand(const std::string& cmd) {
|
||||||
|
if (cmd == "exit") {
|
||||||
|
ChangeToRegularConsole();
|
||||||
|
} else if (cmd == "queued") {
|
||||||
|
auto QueuedFunctions = LuaAPI::MP::Engine->Debug_GetStateFunctionQueueForState(mStateId);
|
||||||
|
Application::Console().WriteRaw("Pending functions in State '" + mStateId + "'");
|
||||||
|
std::unordered_map<std::string, size_t> FunctionsCount;
|
||||||
|
std::vector<std::string> FunctionsInOrder;
|
||||||
|
while (!QueuedFunctions.empty()) {
|
||||||
|
auto Tuple = QueuedFunctions.front();
|
||||||
|
QueuedFunctions.erase(QueuedFunctions.begin());
|
||||||
|
FunctionsInOrder.push_back(Tuple.FunctionName);
|
||||||
|
FunctionsCount[Tuple.FunctionName] += 1;
|
||||||
|
}
|
||||||
|
std::set<std::string> Uniques;
|
||||||
|
for (const auto& Function : FunctionsInOrder) {
|
||||||
|
if (Uniques.count(Function) == 0) {
|
||||||
|
Uniques.insert(Function);
|
||||||
|
if (FunctionsCount.at(Function) > 1) {
|
||||||
|
Application::Console().WriteRaw(" " + Function + " (" + std::to_string(FunctionsCount.at(Function)) + "x)");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(" " + Function);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::Console().WriteRaw("Executed functions waiting to be checked in State '" + mStateId + "'");
|
||||||
|
for (const auto& Function : LuaAPI::MP::Engine->Debug_GetResultsToCheckForState(mStateId)) {
|
||||||
|
Application::Console().WriteRaw(" '" + Function.Function + "' (Ready? " + (Function.Ready ? "Yes" : "No") + ", Error? " + (Function.Error ? "Yes: '" + Function.ErrorMessage + "'" : "No") + ")");
|
||||||
|
}
|
||||||
|
} else if (cmd == "events") {
|
||||||
|
auto Events = LuaAPI::MP::Engine->Debug_GetEventsForState(mStateId);
|
||||||
|
Application::Console().WriteRaw("Registered Events + Handlers for State '" + mStateId + "'");
|
||||||
|
for (const auto& EventHandlerPair : Events) {
|
||||||
|
Application::Console().WriteRaw(" Event '" + EventHandlerPair.first + "'");
|
||||||
|
for (const auto& Handler : EventHandlerPair.second) {
|
||||||
|
Application::Console().WriteRaw(" " + Handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (cmd == "help") {
|
||||||
|
Application::Console().WriteRaw(R"(BeamMP Lua Debugger
|
||||||
|
All commands must be prefixed with a `:`. Non-prefixed commands are interpreted as Lua.
|
||||||
|
|
||||||
|
Commands
|
||||||
|
:exit detaches (exits) from this Lua console
|
||||||
|
:help displays this help
|
||||||
|
:events shows a list of currently registered events
|
||||||
|
:queued shows a list of all pending and queued functions)");
|
||||||
|
} else {
|
||||||
|
beammp_error("internal command '" + cmd + "' is not known");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
TConsole::TConsole() {
|
TConsole::TConsole() {
|
||||||
mCommandline.enable_history();
|
mCommandline.enable_history();
|
||||||
mCommandline.set_history_limit(20);
|
mCommandline.set_history_limit(20);
|
||||||
@@ -382,21 +544,22 @@ TConsole::TConsole() {
|
|||||||
BackupOldLog();
|
BackupOldLog();
|
||||||
mCommandline.on_command = [this](Commandline& c) {
|
mCommandline.on_command = [this](Commandline& c) {
|
||||||
try {
|
try {
|
||||||
auto cmd = c.get_command();
|
auto TrimmedCmd = c.get_command();
|
||||||
cmd = TrimString(cmd);
|
TrimmedCmd = TrimString(TrimmedCmd);
|
||||||
mCommandline.write(mCommandline.prompt() + cmd);
|
auto [cmd, args] = ParseCommand(TrimmedCmd);
|
||||||
|
mCommandline.write(mCommandline.prompt() + TrimmedCmd);
|
||||||
if (mIsLuaConsole) {
|
if (mIsLuaConsole) {
|
||||||
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 if (cmd == "exit()") {
|
} else if (!cmd.empty() && cmd.at(0) == ':') {
|
||||||
ChangeToRegularConsole();
|
HandleLuaInternalCommand(cmd.substr(1));
|
||||||
} else {
|
} else {
|
||||||
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(cmd), "", "" });
|
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
||||||
while (!Future->Ready) {
|
while (!Future->Ready) {
|
||||||
std::this_thread::yield(); // TODO: Add a timeout
|
std::this_thread::yield(); // TODO: Add a timeout
|
||||||
}
|
}
|
||||||
if (Future->Error) {
|
if (Future->Error) {
|
||||||
beammp_lua_error(Future->ErrorMessage);
|
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -405,31 +568,63 @@ TConsole::TConsole() {
|
|||||||
} else if (cmd == "exit") {
|
} else if (cmd == "exit") {
|
||||||
beammp_info("gracefully shutting down");
|
beammp_info("gracefully shutting down");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
} else if (StringStartsWith(cmd, "lua")) {
|
} else if (cmd == "say") {
|
||||||
Command_Lua(cmd);
|
RunAsCommand(TrimmedCmd, true);
|
||||||
} else if (StringStartsWith(cmd, "help")) {
|
Command_Say(TrimmedCmd);
|
||||||
RunAsCommand(cmd, true);
|
} else {
|
||||||
Command_Help(cmd);
|
if (mCommandMap.find(cmd) != mCommandMap.end()) {
|
||||||
} else if (StringStartsWith(cmd, "kick")) {
|
mCommandMap.at(cmd)(cmd, args);
|
||||||
RunAsCommand(cmd, true);
|
RunAsCommand(TrimmedCmd, true);
|
||||||
Command_Kick(cmd);
|
} else {
|
||||||
} else if (StringStartsWith(cmd, "say")) {
|
RunAsCommand(TrimmedCmd);
|
||||||
RunAsCommand(cmd, true);
|
}
|
||||||
Command_Say(cmd);
|
|
||||||
} else if (StringStartsWith(cmd, "list")) {
|
|
||||||
RunAsCommand(cmd, true);
|
|
||||||
Command_List(cmd);
|
|
||||||
} else if (StringStartsWith(cmd, "status")) {
|
|
||||||
RunAsCommand(cmd, true);
|
|
||||||
Command_Status(cmd);
|
|
||||||
} else if (!cmd.empty()) {
|
|
||||||
RunAsCommand(cmd);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} 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.");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||||
|
std::vector<std::string> suggestions;
|
||||||
|
try {
|
||||||
|
auto cmd = TrimString(stub);
|
||||||
|
// beammp_error("yes 1");
|
||||||
|
// beammp_error(stub);
|
||||||
|
if (mIsLuaConsole) { // if lua
|
||||||
|
if (!mLuaEngine) {
|
||||||
|
beammp_info("Lua not started yet, please try again in a second");
|
||||||
|
} else {
|
||||||
|
std::string prefix {};
|
||||||
|
for (size_t i = stub.length(); i > 0; i--) {
|
||||||
|
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') {
|
||||||
|
prefix = stub.substr(0, i);
|
||||||
|
stub = stub.substr(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
|
||||||
|
for (const auto& key : keys) {
|
||||||
|
std::string::size_type n = key.find(stub);
|
||||||
|
if (n == 0) {
|
||||||
|
suggestions.push_back(prefix + key);
|
||||||
|
// beammp_warn(cmd_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else { // if not lua
|
||||||
|
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||||
|
std::string::size_type n = cmd_name.find(stub);
|
||||||
|
if (n == 0) {
|
||||||
|
suggestions.push_back(cmd_name);
|
||||||
|
// beammp_warn(cmd_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} 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.");
|
||||||
|
}
|
||||||
|
return suggestions;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Write(const std::string& str) {
|
void TConsole::Write(const std::string& str) {
|
||||||
|
|||||||
+11
-10
@@ -7,7 +7,6 @@
|
|||||||
#include <rapidjson/rapidjson.h>
|
#include <rapidjson/rapidjson.h>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
namespace json = rapidjson;
|
|
||||||
|
|
||||||
void THeartbeatThread::operator()() {
|
void THeartbeatThread::operator()() {
|
||||||
RegisterThread("Heartbeat");
|
RegisterThread("Heartbeat");
|
||||||
@@ -57,15 +56,17 @@ void THeartbeatThread::operator()() {
|
|||||||
auto Target = "/heartbeat";
|
auto Target = "/heartbeat";
|
||||||
unsigned int ResponseCode = 0;
|
unsigned int ResponseCode = 0;
|
||||||
|
|
||||||
json::Document Doc;
|
rapidjson::Document Doc;
|
||||||
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);
|
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()) {
|
||||||
beammp_debug("Failed to contact backend at " + Url + " (this is not an error).");
|
if (!Application::Settings.Private) {
|
||||||
beammp_trace("Response was: " + T);
|
beammp_error("Backend response failed to parse as valid json");
|
||||||
|
beammp_trace("Response was: `" + T + "`");
|
||||||
|
}
|
||||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
||||||
SentryReportError(Url + Target, ResponseCode);
|
SentryReportError(Url + Target, ResponseCode);
|
||||||
} else if (ResponseCode != 200) {
|
} else if (ResponseCode != 200) {
|
||||||
@@ -113,21 +114,21 @@ void THeartbeatThread::operator()() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Ok && !isAuth) {
|
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||||
if (Status == "2000") {
|
if (Status == "2000") {
|
||||||
beammp_info(("Authenticated!"));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
} else if (Status == "200") {
|
} else if (Status == "200") {
|
||||||
beammp_info(("Resumed authenticated session!"));
|
beammp_info(("Resumed authenticated session! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
} else {
|
} else {
|
||||||
if (Message.empty()) {
|
if (Message.empty()) {
|
||||||
Message = "Backend didn't provide a reason";
|
Message = "Backend didn't provide a reason.";
|
||||||
}
|
}
|
||||||
beammp_error("Backend REFUSED the auth key. " + Message);
|
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isAuth) {
|
if (isAuth || Application::Settings.Private) {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
}
|
}
|
||||||
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||||
|
|||||||
+246
-32
@@ -8,6 +8,7 @@
|
|||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <httplib.h>
|
#include <httplib.h>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
@@ -154,10 +155,70 @@ void TLuaEngine::AddResultToCheck(const std::shared_ptr<TLuaResult>& Result) {
|
|||||||
mResultsToCheckCond.notify_one();
|
mResultsToCheckCond.notify_one();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> TLuaEngine::Debug_GetEventsForState(TLuaStateId StateId) {
|
||||||
|
std::unordered_map<std::string, std::vector<std::string>> Result;
|
||||||
|
std::unique_lock Lock(mLuaEventsMutex);
|
||||||
|
for (const auto& EventNameToEventMap : mLuaEvents) {
|
||||||
|
for (const auto& IdSetOfHandlersPair : EventNameToEventMap.second) {
|
||||||
|
if (IdSetOfHandlersPair.first == StateId) {
|
||||||
|
for (const auto& Handler : IdSetOfHandlersPair.second) {
|
||||||
|
Result[EventNameToEventMap.first].push_back(Handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> TLuaEngine::Debug_GetStateExecuteQueueForState(TLuaStateId StateId) {
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Result;
|
||||||
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
|
Result = mLuaStates.at(StateId)->Debug_GetStateExecuteQueue();
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<TLuaEngine::QueuedFunction> TLuaEngine::Debug_GetStateFunctionQueueForState(TLuaStateId StateId) {
|
||||||
|
std::vector<TLuaEngine::QueuedFunction> Result;
|
||||||
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
|
Result = mLuaStates.at(StateId)->Debug_GetStateFunctionQueue();
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<TLuaResult> TLuaEngine::Debug_GetResultsToCheckForState(TLuaStateId StateId) {
|
||||||
|
std::unique_lock Lock(mResultsToCheckMutex);
|
||||||
|
auto ResultsToCheckCopy = mResultsToCheck;
|
||||||
|
Lock.unlock();
|
||||||
|
std::vector<TLuaResult> Result;
|
||||||
|
while (!ResultsToCheckCopy.empty()) {
|
||||||
|
auto ResultToCheck = std::move(ResultsToCheckCopy.front());
|
||||||
|
ResultsToCheckCopy.pop_front();
|
||||||
|
if (ResultToCheck->StateId == StateId) {
|
||||||
|
Result.push_back(*ResultToCheck);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> TLuaEngine::GetStateGlobalKeysForState(TLuaStateId StateId) {
|
||||||
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
|
auto Result = mLuaStates.at(StateId)->GetStateGlobalKeys();
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
|
||||||
|
auto globals = mStateView.globals();
|
||||||
|
std::vector<std::string> Result;
|
||||||
|
for (const auto& [key, value] : globals) {
|
||||||
|
Result.push_back(key.as<std::string>());
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
|
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::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;
|
||||||
|
std::set<std::string> WarnedResults;
|
||||||
while (!Result->Ready && !Cancelled) {
|
while (!Result->Ready && !Cancelled) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
ms += 10;
|
ms += 10;
|
||||||
@@ -165,7 +226,11 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
|
|||||||
beammp_trace("'" + Result->Function + "' in '" + Result->StateId + "' did not finish executing in time (took: " + std::to_string(ms) + "ms).");
|
beammp_trace("'" + Result->Function + "' in '" + Result->StateId + "' did not finish executing in time (took: " + std::to_string(ms) + "ms).");
|
||||||
Cancelled = true;
|
Cancelled = true;
|
||||||
} else if (ms > 1000 * 60) {
|
} else if (ms > 1000 * 60) {
|
||||||
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' is taking very long. The event it's handling is too important to discard the result of this handler, but may block this event and possibly the whole lua state.");
|
auto ResultId = Result->StateId + "_" + Result->Function;
|
||||||
|
if (WarnedResults.count(ResultId) == 0) {
|
||||||
|
WarnedResults.insert(ResultId);
|
||||||
|
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' is taking very long. The event it's handling is too important to discard the result of this handler, but may block this event and possibly the whole lua state.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Cancelled) {
|
if (Cancelled) {
|
||||||
@@ -277,7 +342,6 @@ std::set<std::string> TLuaEngine::GetEventHandlersForState(const std::string& Ev
|
|||||||
|
|
||||||
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 Return = mEngine->TriggerEvent(EventName, mStateId, EventArgs);
|
auto Return = mEngine->TriggerEvent(EventName, mStateId, EventArgs);
|
||||||
// TODO Synchronous call to the event handlers
|
|
||||||
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
||||||
for (const auto& Handler : MyHandlers) {
|
for (const auto& Handler : MyHandlers) {
|
||||||
auto Fn = mStateView[Handler];
|
auto Fn = mStateView[Handler];
|
||||||
@@ -335,7 +399,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
|
|||||||
Result.add(FnRet);
|
Result.add(FnRet);
|
||||||
} else {
|
} else {
|
||||||
sol::error Err = FnRet;
|
sol::error Err = FnRet;
|
||||||
beammp_lua_error(Err.what());
|
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -386,6 +450,32 @@ int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name)
|
|||||||
return Id;
|
return Id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
|
||||||
|
if (!std::filesystem::exists(Path)) {
|
||||||
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
auto table = mStateView.create_table();
|
||||||
|
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
|
||||||
|
if (entry.is_regular_file() || entry.is_symlink()) {
|
||||||
|
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string& Path) {
|
||||||
|
if (!std::filesystem::exists(Path)) {
|
||||||
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
auto table = mStateView.create_table();
|
||||||
|
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
|
||||||
|
if (entry.is_directory()) {
|
||||||
|
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
@@ -439,6 +529,83 @@ sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::stri
|
|||||||
return table;
|
return table;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static void AddToTable(sol::table& table, const std::string& left, const T& value) {
|
||||||
|
if (left.empty()) {
|
||||||
|
table[table.size() + 1] = value;
|
||||||
|
} else {
|
||||||
|
table[left] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, const std::string& left, const nlohmann::json& right) {
|
||||||
|
switch (right.type()) {
|
||||||
|
case nlohmann::detail::value_t::null:
|
||||||
|
return;
|
||||||
|
case nlohmann::detail::value_t::object: {
|
||||||
|
auto value = table.create();
|
||||||
|
value.clear();
|
||||||
|
for (const auto& entry : right.items()) {
|
||||||
|
JsonDecodeRecursive(StateView, value, entry.key(), entry.value());
|
||||||
|
}
|
||||||
|
AddToTable(table, left, value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case nlohmann::detail::value_t::array: {
|
||||||
|
auto value = table.create();
|
||||||
|
value.clear();
|
||||||
|
for (const auto& entry : right.items()) {
|
||||||
|
JsonDecodeRecursive(StateView, value, "", entry.value());
|
||||||
|
}
|
||||||
|
AddToTable(table, left, value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case nlohmann::detail::value_t::string:
|
||||||
|
AddToTable(table, left, right.get<std::string>());
|
||||||
|
break;
|
||||||
|
case nlohmann::detail::value_t::boolean:
|
||||||
|
AddToTable(table, left, right.get<bool>());
|
||||||
|
break;
|
||||||
|
case nlohmann::detail::value_t::number_integer:
|
||||||
|
AddToTable(table, left, right.get<int64_t>());
|
||||||
|
break;
|
||||||
|
case nlohmann::detail::value_t::number_unsigned:
|
||||||
|
AddToTable(table, left, right.get<uint64_t>());
|
||||||
|
break;
|
||||||
|
case nlohmann::detail::value_t::number_float:
|
||||||
|
AddToTable(table, left, right.get<double>());
|
||||||
|
break;
|
||||||
|
case nlohmann::detail::value_t::binary:
|
||||||
|
beammp_lua_error("JsonDecode can't handle binary blob in json, ignoring");
|
||||||
|
return;
|
||||||
|
case nlohmann::detail::value_t::discarded:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sol::table TLuaEngine::StateThreadData::Lua_JsonDecode(const std::string& str) {
|
||||||
|
sol::state_view StateView(mState);
|
||||||
|
auto table = StateView.create_table();
|
||||||
|
if (!nlohmann::json::accept(str)) {
|
||||||
|
beammp_lua_error("string given to JsonDecode is not valid json: `" + str + "`");
|
||||||
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
nlohmann::json json = nlohmann::json::parse(str);
|
||||||
|
if (json.is_object()) {
|
||||||
|
for (const auto& entry : json.items()) {
|
||||||
|
JsonDecodeRecursive(StateView, table, entry.key(), entry.value());
|
||||||
|
}
|
||||||
|
} else if (json.is_array()) {
|
||||||
|
for (const auto& entry : json) {
|
||||||
|
JsonDecodeRecursive(StateView, table, "", entry);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
beammp_lua_error("JsonDecode expected array or object json, instead got " + std::string(json.type_name()));
|
||||||
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomic_bool& Shutdown, TLuaStateId StateId, TLuaEngine& Engine)
|
TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomic_bool& Shutdown, TLuaStateId StateId, TLuaEngine& Engine)
|
||||||
: mName(Name)
|
: mName(Name)
|
||||||
, mShutdown(Shutdown)
|
, mShutdown(Shutdown)
|
||||||
@@ -484,6 +651,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomi
|
|||||||
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("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
|
MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
|
||||||
MPTable.set_function("IsPlayerConnected", &LuaAPI::MP::IsPlayerConnected);
|
MPTable.set_function("IsPlayerConnected", &LuaAPI::MP::IsPlayerConnected);
|
||||||
MPTable.set_function("GetPlayerIDByName", [&](const std::string& Name) -> int {
|
MPTable.set_function("GetPlayerIDByName", [&](const std::string& Name) -> int {
|
||||||
@@ -538,6 +706,27 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomi
|
|||||||
mEngine->CancelEventTimers(EventName, mStateId);
|
mEngine->CancelEventTimers(EventName, mStateId);
|
||||||
});
|
});
|
||||||
MPTable.set_function("Set", &LuaAPI::MP::Set);
|
MPTable.set_function("Set", &LuaAPI::MP::Set);
|
||||||
|
|
||||||
|
auto UtilTable = StateView.create_named_table("Util");
|
||||||
|
UtilTable.set_function("JsonEncode", &LuaAPI::MP::JsonEncode);
|
||||||
|
UtilTable.set_function("JsonDecode", [this](const std::string& str) {
|
||||||
|
return Lua_JsonDecode(str);
|
||||||
|
});
|
||||||
|
UtilTable.set_function("JsonDiff", &LuaAPI::MP::JsonDiff);
|
||||||
|
UtilTable.set_function("JsonFlatten", &LuaAPI::MP::JsonFlatten);
|
||||||
|
UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten);
|
||||||
|
UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify);
|
||||||
|
UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify);
|
||||||
|
UtilTable.set_function("Random", [this] {
|
||||||
|
return mUniformRealDistribution01(mMersenneTwister);
|
||||||
|
});
|
||||||
|
UtilTable.set_function("RandomRange", [this](double min, double max) -> double {
|
||||||
|
return std::uniform_real_distribution(min, max)(mMersenneTwister);
|
||||||
|
});
|
||||||
|
UtilTable.set_function("RandomIntRange", [this](int64_t min, int64_t max) -> int64_t {
|
||||||
|
return std::uniform_int_distribution(min, max)(mMersenneTwister);
|
||||||
|
});
|
||||||
|
|
||||||
auto HttpTable = StateView.create_named_table("Http");
|
auto HttpTable = StateView.create_named_table("Http");
|
||||||
HttpTable.set_function("CreateConnection", [this](const std::string& host, uint16_t port) {
|
HttpTable.set_function("CreateConnection", [this](const std::string& host, uint16_t port) {
|
||||||
return Lua_HttpCreateConnection(host, port);
|
return Lua_HttpCreateConnection(host, port);
|
||||||
@@ -568,6 +757,12 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, std::atomi
|
|||||||
FSTable.set_function("IsDirectory", &LuaAPI::FS::IsDirectory);
|
FSTable.set_function("IsDirectory", &LuaAPI::FS::IsDirectory);
|
||||||
FSTable.set_function("IsFile", &LuaAPI::FS::IsFile);
|
FSTable.set_function("IsFile", &LuaAPI::FS::IsFile);
|
||||||
FSTable.set_function("ConcatPaths", &LuaAPI::FS::ConcatPaths);
|
FSTable.set_function("ConcatPaths", &LuaAPI::FS::ConcatPaths);
|
||||||
|
FSTable.set_function("ListFiles", [this](const std::string& Path) {
|
||||||
|
return Lua_FS_ListFiles(Path);
|
||||||
|
});
|
||||||
|
FSTable.set_function("ListDirectories", [this](const std::string& Path) {
|
||||||
|
return Lua_FS_ListDirectories(Path);
|
||||||
|
});
|
||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -722,6 +917,16 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> TLuaEngine::StateThreadData::Debug_GetStateExecuteQueue() {
|
||||||
|
std::unique_lock Lock(mStateExecuteQueueMutex);
|
||||||
|
return mStateExecuteQueue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<TLuaEngine::QueuedFunction> TLuaEngine::StateThreadData::Debug_GetStateFunctionQueue() {
|
||||||
|
std::unique_lock Lock(mStateFunctionQueueMutex);
|
||||||
|
return mStateFunctionQueue;
|
||||||
|
}
|
||||||
|
|
||||||
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 {
|
||||||
@@ -798,38 +1003,47 @@ void TPluginMonitor::operator()() {
|
|||||||
beammp_info("PluginMonitor started");
|
beammp_info("PluginMonitor started");
|
||||||
while (!mShutdown) {
|
while (!mShutdown) {
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||||
|
std::vector<std::string> ToRemove;
|
||||||
for (const auto& Pair : mFileTimes) {
|
for (const auto& Pair : mFileTimes) {
|
||||||
auto CurrentTime = fs::last_write_time(Pair.first);
|
try {
|
||||||
if (CurrentTime != Pair.second) {
|
auto CurrentTime = fs::last_write_time(Pair.first);
|
||||||
mFileTimes[Pair.first] = CurrentTime;
|
if (CurrentTime != Pair.second) {
|
||||||
// grandparent of the path should be Resources/Server
|
mFileTimes[Pair.first] = CurrentTime;
|
||||||
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
|
// grandparent of the path should be Resources/Server
|
||||||
beammp_info("File \"" + Pair.first + "\" changed, reloading");
|
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
|
||||||
// is in root folder, so reload
|
beammp_info("File \"" + Pair.first + "\" changed, reloading");
|
||||||
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
// is in root folder, so reload
|
||||||
auto Size = std::filesystem::file_size(Pair.first);
|
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
||||||
auto Contents = std::make_shared<std::string>();
|
auto Size = std::filesystem::file_size(Pair.first);
|
||||||
Contents->resize(Size);
|
auto Contents = std::make_shared<std::string>();
|
||||||
FileStream.read(Contents->data(), Contents->size());
|
Contents->resize(Size);
|
||||||
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
FileStream.read(Contents->data(), Contents->size());
|
||||||
auto StateID = mEngine.GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
||||||
auto Res = mEngine.EnqueueScript(StateID, Chunk);
|
auto StateID = mEngine.GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
||||||
// TODO: call onInit
|
auto Res = mEngine.EnqueueScript(StateID, Chunk);
|
||||||
mEngine.AddResultToCheck(Res);
|
// TODO: call onInit
|
||||||
} else {
|
mEngine.AddResultToCheck(Res);
|
||||||
// TODO: trigger onFileChanged event
|
} else {
|
||||||
beammp_trace("Change detected in file \"" + Pair.first + "\", event trigger not implemented yet");
|
// TODO: trigger onFileChanged event
|
||||||
/*
|
beammp_trace("Change detected in file \"" + Pair.first + "\", event trigger not implemented yet");
|
||||||
// is in subfolder, dont reload, just trigger an event
|
/*
|
||||||
auto Results = mEngine.TriggerEvent("onFileChanged", "", Pair.first);
|
// is in subfolder, dont reload, just trigger an event
|
||||||
mEngine.WaitForAll(Results);
|
auto Results = mEngine.TriggerEvent("onFileChanged", "", Pair.first);
|
||||||
for (const auto& Result : Results) {
|
mEngine.WaitForAll(Results);
|
||||||
if (Result->Error) {
|
for (const auto& Result : Results) {
|
||||||
beammp_lua_error(Result->ErrorMessage);
|
if (Result->Error) {
|
||||||
}
|
beammp_lua_error(Result->ErrorMessage);
|
||||||
}*/
|
}
|
||||||
|
}*/
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ToRemove.push_back(Pair.first);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const auto& File : ToRemove) {
|
||||||
|
mFileTimes.erase(File);
|
||||||
|
beammp_warn("file '" + File + "' couldn't be accessed, so it was removed from plugin hot reload monitor (probably got deleted)");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-36
@@ -108,40 +108,48 @@ void TNetwork::TCPServerMain() {
|
|||||||
#if defined(BEAMMP_WINDOWS)
|
#if defined(BEAMMP_WINDOWS)
|
||||||
WSADATA wsaData;
|
WSADATA wsaData;
|
||||||
if (WSAStartup(514, &wsaData)) {
|
if (WSAStartup(514, &wsaData)) {
|
||||||
beammp_error("Can't start Winsock!");
|
beammp_error("Can't start Winsock! Shutting down");
|
||||||
return;
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
#endif // WINDOWS
|
#endif // WINDOWS
|
||||||
TConnection client {};
|
TConnection client {};
|
||||||
SOCKET Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
SOCKET Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||||
int optval = 1;
|
if (Listener == BEAMMP_INVALID_SOCKET) {
|
||||||
|
beammp_error("Failed to create socket: " + GetPlatformAgnosticErrorString()
|
||||||
|
+ ". This is a fatal error, as a socket is needed for the server to operate. Shutting down.");
|
||||||
|
Application::GracefullyShutdown();
|
||||||
|
}
|
||||||
#if defined(BEAMMP_WINDOWS)
|
#if defined(BEAMMP_WINDOWS)
|
||||||
const char* optval_ptr = reinterpret_cast<const char*>(&optval);
|
const char optval = 0;
|
||||||
|
int ret = ::setsockopt(Listener, SOL_SOCKET, SO_DONTLINGER, &optval, sizeof(optval));
|
||||||
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
void* optval_ptr = reinterpret_cast<void*>(&optval);
|
int optval = true;
|
||||||
|
int ret = ::setsockopt(Listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void*>(&optval), sizeof(optval));
|
||||||
#endif
|
#endif
|
||||||
setsockopt(Listener, SOL_SOCKET, SO_REUSEADDR, optval_ptr, sizeof(optval));
|
// not a fatal error
|
||||||
// TODO: check optval or return value idk
|
if (ret < 0) {
|
||||||
|
beammp_error("Failed to set up listening socket to not linger / reuse address. "
|
||||||
|
"This may cause the socket to refuse to bind(). Error: "
|
||||||
|
+ GetPlatformAgnosticErrorString());
|
||||||
|
}
|
||||||
sockaddr_in addr {};
|
sockaddr_in addr {};
|
||||||
addr.sin_addr.s_addr = INADDR_ANY;
|
addr.sin_addr.s_addr = INADDR_ANY;
|
||||||
addr.sin_family = AF_INET;
|
addr.sin_family = AF_INET;
|
||||||
addr.sin_port = htons(uint16_t(Application::Settings.Port));
|
addr.sin_port = htons(uint16_t(Application::Settings.Port));
|
||||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
|
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) < 0) {
|
||||||
beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
|
beammp_error("bind() failed, the server cannot operate and will shut down now. "
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
"Error: "
|
||||||
exit(-1); // TODO: Wtf.
|
+ GetPlatformAgnosticErrorString());
|
||||||
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
if (Listener == -1) {
|
if (listen(Listener, SOMAXCONN) < 0) {
|
||||||
beammp_error("Invalid listening socket");
|
beammp_error("listen() failed, which is needed for the server to operate. "
|
||||||
return;
|
"Shutting down. Error: "
|
||||||
}
|
+ GetPlatformAgnosticErrorString());
|
||||||
if (listen(Listener, SOMAXCONN)) {
|
Application::GracefullyShutdown();
|
||||||
beammp_error("listen() failed: " + GetPlatformAgnosticErrorString());
|
|
||||||
// FIXME leak Listener
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
||||||
beammp_info(("Vehicle event network online"));
|
beammp_info("Vehicle event network online");
|
||||||
do {
|
do {
|
||||||
try {
|
try {
|
||||||
if (mShutdown) {
|
if (mShutdown) {
|
||||||
@@ -154,15 +162,15 @@ void TNetwork::TCPServerMain() {
|
|||||||
beammp_warn(("Got an invalid client socket on connect! Skipping..."));
|
beammp_warn(("Got an invalid client socket on connect! Skipping..."));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// set timeout (DWORD, aka uint32_t)
|
// set timeout
|
||||||
uint32_t SendTimeoutMS = 30 * 1000;
|
size_t SendTimeoutMS = 30 * 1000;
|
||||||
#if defined(BEAMMP_WINDOWS)
|
#if defined(BEAMMP_WINDOWS)
|
||||||
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS));
|
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS));
|
||||||
#else // POSIX
|
#else // POSIX
|
||||||
struct timeval optval;
|
struct timeval optval;
|
||||||
optval.tv_sec = (int)(SendTimeoutMS / 1000);
|
optval.tv_sec = (int)(SendTimeoutMS / 1000);
|
||||||
optval.tv_usec = (SendTimeoutMS % 1000) * 1000;
|
optval.tv_usec = (SendTimeoutMS % 1000) * 1000;
|
||||||
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval));
|
ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval));
|
||||||
#endif
|
#endif
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
throw std::runtime_error("setsockopt recv timeout: " + GetPlatformAgnosticErrorString());
|
throw std::runtime_error("setsockopt recv timeout: " + GetPlatformAgnosticErrorString());
|
||||||
@@ -170,9 +178,9 @@ void TNetwork::TCPServerMain() {
|
|||||||
std::thread ID(&TNetwork::Identify, this, client);
|
std::thread ID(&TNetwork::Identify, this, client);
|
||||||
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error(("fatal: ") + std::string(e.what()));
|
beammp_error("fatal: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
} while (client.Socket);
|
} while (client.Socket != BEAMMP_INVALID_SOCKET);
|
||||||
|
|
||||||
beammp_debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
beammp_debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||||
|
|
||||||
@@ -186,7 +194,6 @@ void TNetwork::TCPServerMain() {
|
|||||||
#undef GetObject // Fixes Windows
|
#undef GetObject // Fixes Windows
|
||||||
|
|
||||||
#include "Json.h"
|
#include "Json.h"
|
||||||
namespace json = rapidjson;
|
|
||||||
|
|
||||||
void TNetwork::Identify(const TConnection& client) {
|
void TNetwork::Identify(const TConnection& client) {
|
||||||
RegisterThreadAuto();
|
RegisterThreadAuto();
|
||||||
@@ -273,7 +280,7 @@ void TNetwork::Authentication(const TConnection& ClientConnection) {
|
|||||||
Rc = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, RequestString, "application/json", &ResponseCode);
|
Rc = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, RequestString, "application/json", &ResponseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
json::Document AuthResponse;
|
rapidjson::Document AuthResponse;
|
||||||
AuthResponse.Parse(Rc.c_str());
|
AuthResponse.Parse(Rc.c_str());
|
||||||
if (Rc == Http::ErrorString || AuthResponse.HasParseError()) {
|
if (Rc == Http::ErrorString || AuthResponse.HasParseError()) {
|
||||||
ClientKick(*Client, "Invalid key! Please restart your game.");
|
ClientKick(*Client, "Invalid key! Please restart your game.");
|
||||||
@@ -477,7 +484,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
|
|||||||
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
||||||
beammp_info("Client kicked: " + R);
|
beammp_info("Client kicked: " + R);
|
||||||
if (!TCPSend(c, "K" + R)) {
|
if (!TCPSend(c, "K" + R)) {
|
||||||
// TODO handle
|
beammp_warn("tried to kick player '" + c.GetName() + "' (id " + std::to_string(c.GetID()) + "), but was already disconnected");
|
||||||
}
|
}
|
||||||
c.SetStatus(-2);
|
c.SetStatus(-2);
|
||||||
|
|
||||||
@@ -755,12 +762,12 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
|
|
||||||
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
||||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
std::ifstream f(Name.c_str(), std::ios::binary);
|
||||||
uint32_t Split = 0x7735940; // 125MB
|
uint32_t Split = 125 * MB;
|
||||||
std::vector<char> Data;
|
char* Data;
|
||||||
if (Size > Split)
|
if (Size > Split)
|
||||||
Data.resize(Split);
|
Data = new char[Split];
|
||||||
else
|
else
|
||||||
Data.resize(Size);
|
Data = new char[Size];
|
||||||
SOCKET TCPSock;
|
SOCKET TCPSock;
|
||||||
if (D)
|
if (D)
|
||||||
TCPSock = c.GetDownSock();
|
TCPSock = c.GetDownSock();
|
||||||
@@ -771,8 +778,8 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
|
|||||||
size_t Diff = Size - Sent;
|
size_t Diff = Size - Sent;
|
||||||
if (Diff > Split) {
|
if (Diff > Split) {
|
||||||
f.seekg(Sent, std::ios_base::beg);
|
f.seekg(Sent, std::ios_base::beg);
|
||||||
f.read(Data.data(), Split);
|
f.read(Data, Split);
|
||||||
if (!TCPSendRaw(c, TCPSock, Data.data(), Split)) {
|
if (!TCPSendRaw(c, TCPSock, Data, Split)) {
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
break;
|
break;
|
||||||
@@ -780,8 +787,8 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
|
|||||||
Sent += Split;
|
Sent += Split;
|
||||||
} else {
|
} else {
|
||||||
f.seekg(Sent, std::ios_base::beg);
|
f.seekg(Sent, std::ios_base::beg);
|
||||||
f.read(Data.data(), Diff);
|
f.read(Data, Diff);
|
||||||
if (!TCPSendRaw(c, TCPSock, Data.data(), int32_t(Diff))) {
|
if (!TCPSendRaw(c, TCPSock, Data, int32_t(Diff))) {
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
break;
|
break;
|
||||||
@@ -789,6 +796,8 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
|
|||||||
Sent += Diff;
|
Sent += Diff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
delete[] Data;
|
||||||
|
f.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
|
bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
|
||||||
|
|||||||
+1
-1
@@ -72,7 +72,7 @@ void TSentry::Log(SentryLevel level, const std::string& logger, const std::strin
|
|||||||
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
||||||
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
||||||
sentry_capture_event(Msg);
|
sentry_capture_event(Msg);
|
||||||
sentry_remove_transaction();
|
sentry_set_transaction(nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
||||||
|
|||||||
+11
-19
@@ -125,7 +125,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
break;
|
break;
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
||||||
TLuaEngine::WaitForAll(Futures);
|
TLuaEngine::WaitForAll(Futures);
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1)); // FIXME: this needs to be adjusted once lua is merged
|
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
|
||||||
@@ -150,26 +150,18 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::HandleEvent(TClient& c, const std::string& Data) {
|
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||||
std::stringstream ss(Data);
|
// E:Name:Data
|
||||||
std::string t, Name;
|
// Data is allowed to have ':'
|
||||||
int a = 0;
|
auto NameDataSep = RawData.find(':', 2);
|
||||||
while (std::getline(ss, t, ':')) {
|
if (NameDataSep == std::string::npos) {
|
||||||
switch (a) {
|
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||||
case 1:
|
|
||||||
Name = t;
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), t));
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (a == 2)
|
|
||||||
break;
|
|
||||||
a++;
|
|
||||||
}
|
}
|
||||||
|
std::string Name = RawData.substr(2, NameDataSep - 2);
|
||||||
|
std::string Data = RawData.substr(NameDataSep + 1);
|
||||||
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
||||||
try {
|
try {
|
||||||
auto Car = nlohmann::json::parse(CarJson);
|
auto Car = nlohmann::json::parse(CarJson);
|
||||||
|
|||||||
+18
-2
@@ -1,14 +1,30 @@
|
|||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
#include <regex>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
TVehicleData::TVehicleData(int ID, std::string Data)
|
TVehicleData::TVehicleData(int ID, const std::string& Data)
|
||||||
: mID(ID)
|
: mID(ID)
|
||||||
, mData(std::move(Data)) {
|
, mData(Data) {
|
||||||
|
try {
|
||||||
|
std::regex Reg(R"(^[a-zA-Z0-9_\-.]+:[a-zA-Z0-9_\-.]+:[a-zA-Z0-9_\-.]+:\d+\-\d+:(\{.+\}))", std::regex::ECMAScript);
|
||||||
|
std::smatch Match;
|
||||||
|
std::string Result;
|
||||||
|
if (std::regex_search(Data, Match, Reg) && Match.size() > 1) {
|
||||||
|
Result = Match.str(1);
|
||||||
|
mJson = json::parse(Result);
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_debugf("Failed to parse vehicle data for vehicle {} as json, this isn't expected: {}", ID, e.what());
|
||||||
|
}
|
||||||
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
|
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
|
||||||
}
|
}
|
||||||
|
|
||||||
TVehicleData::~TVehicleData() {
|
TVehicleData::~TVehicleData() {
|
||||||
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
|
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const json& TVehicleData::Json() const {
|
||||||
|
return mJson;
|
||||||
|
}
|
||||||
|
|||||||
+6
-3
@@ -113,7 +113,7 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
try {
|
try {
|
||||||
fs::current_path(fs::path(MaybeWorkingDirectory.value()));
|
fs::current_path(fs::path(MaybeWorkingDirectory.value()));
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("Could not set working directory to '" + MaybeWorkingDirectory.value() + "': " + e.what());
|
beammp_errorf("Could not set working directory to '{}': {}", MaybeWorkingDirectory.value(), e.what());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,9 +163,12 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
PPSMonitor.SetNetwork(Network);
|
PPSMonitor.SetNetwork(Network);
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
|
std::unique_ptr<Http::Server::THttpServerInstance> HttpServer;
|
||||||
if (Application::Settings.HTTPServerEnabled) {
|
if (Application::Settings.HTTPServerEnabled) {
|
||||||
Http::Server::SetupEnvironment();
|
HttpServer = std::make_unique<Http::Server::THttpServerInstance>(
|
||||||
Http::Server::THttpServerInstance HttpServerInstance {};
|
Server,
|
||||||
|
Network,
|
||||||
|
ResourceManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||||
|
|||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
include(FetchContent)
|
||||||
|
|
||||||
|
message(STATUS "Getting, checking and running vcpkg, this may take a while")
|
||||||
|
|
||||||
|
FetchContent_Declare(
|
||||||
|
vcpkg
|
||||||
|
GIT_REPOSITORY https://github.com/microsoft/vcpkg.git
|
||||||
|
)
|
||||||
|
|
||||||
|
FetchContent_GetProperties(vcpkg)
|
||||||
|
|
||||||
|
if(NOT vcpkg_POPULATED)
|
||||||
|
FetchContent_Populate(vcpkg)
|
||||||
|
execute_process(COMMAND ./${vcpkg_SOURCE_DIR}/bootstrap-vcpkg.sh)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_TOOLCHAIN_FILE ${vcpkg_SOURCE_DIR}/scripts/buildsystems/vcpkg.cmake
|
||||||
|
CACHE STRING "Vcpkg toolchain file")
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"name": "beammp-server",
|
||||||
|
"version-string": "3.0.2",
|
||||||
|
"homepage": "https://beammp.com",
|
||||||
|
"dependencies": [
|
||||||
|
"sentry-native",
|
||||||
|
"lua",
|
||||||
|
"zlib",
|
||||||
|
"rapidjson",
|
||||||
|
"nlohmann-json",
|
||||||
|
"openssl",
|
||||||
|
"curl",
|
||||||
|
"sol2",
|
||||||
|
"cpp-httplib",
|
||||||
|
"toml11"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user