mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0d560405c | |||
| 98c69561b5 | |||
| d0cc23333c | |||
| c173ffdbdc | |||
| 7d813f7562 | |||
| ee74d6291b | |||
| 8654beb706 | |||
| 630d5f1cfa | |||
| bde689d31a | |||
| 303a619ece | |||
| 24723c01da | |||
| b06991aaca | |||
| e0fe6693e0 | |||
| b882174ae7 | |||
| 3de142a6d0 | |||
| 9502048525 | |||
| 9e99177fcb | |||
| dbab9eb894 | |||
| 9ea0931e13 | |||
| e9805c3679 | |||
| ff33f1d42f | |||
| 65d2ba3556 | |||
| 6a411171f9 | |||
| 05dfb4e0c3 | |||
| 4aca87d3e6 | |||
| 7e9bb0cbf2 | |||
| 443871ec0f | |||
| 130e1acdb3 | |||
| aa29d04b60 | |||
| b9f73f77c3 |
@@ -1 +0,0 @@
|
|||||||
patreon: BeamMP
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
Please replace this text <-> with your PR description and leave the below declarations intact.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
By creating this pull request, I understand that code that is AI generated or otherwise automatically generated may be rejected without further discussion.
|
|
||||||
I declare that I fully understand all code I pushed into this PR, and wrote all this code myself and own the rights to this code.
|
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
name: Linux
|
name: Linux
|
||||||
|
|
||||||
on:
|
on: [push]
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- 'develop'
|
|
||||||
- 'minor'
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
@@ -26,7 +22,7 @@ jobs:
|
|||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 22.04
|
version: 22.04
|
||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 24.04
|
version: 20.04
|
||||||
container:
|
container:
|
||||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
steps:
|
steps:
|
||||||
@@ -63,13 +59,13 @@ jobs:
|
|||||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
- name: Archive server artifact
|
- name: Archive server artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||||
path: ./bin/BeamMP-Server
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
- name: Archive server debug info artifact
|
- name: Archive server debug info artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||||
path: ./bin/BeamMP-Server.debug
|
path: ./bin/BeamMP-Server.debug
|
||||||
@@ -97,7 +93,7 @@ jobs:
|
|||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 22.04
|
version: 22.04
|
||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 24.04
|
version: 20.04
|
||||||
container:
|
container:
|
||||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
steps:
|
steps:
|
||||||
@@ -134,13 +130,13 @@ jobs:
|
|||||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
- name: Archive server artifact
|
- name: Archive server artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||||
path: ./bin/BeamMP-Server
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
- name: Archive server debug info artifact
|
- name: Archive server debug info artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||||
path: ./bin/BeamMP-Server.debug
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ jobs:
|
|||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 22.04
|
version: 22.04
|
||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 24.04
|
version: 20.04
|
||||||
container:
|
container:
|
||||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
steps:
|
steps:
|
||||||
@@ -116,10 +116,9 @@ jobs:
|
|||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 22.04
|
version: 22.04
|
||||||
- distro: ubuntu
|
- distro: ubuntu
|
||||||
version: 24.04
|
version: 20.04
|
||||||
env:
|
env:
|
||||||
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
|
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
|
||||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
|
||||||
container:
|
container:
|
||||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
name: Windows
|
name: Windows
|
||||||
|
|
||||||
on:
|
on: [push]
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- 'develop'
|
|
||||||
- 'minor'
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||||
@@ -41,7 +36,7 @@ jobs:
|
|||||||
run: bash ./scripts/windows/2-build.sh
|
run: bash ./scripts/windows/2-build.sh
|
||||||
|
|
||||||
- name: Archive server artifact
|
- name: Archive server artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server-windows
|
name: BeamMP-Server-windows
|
||||||
path: ./bin/Release/BeamMP-Server.exe
|
path: ./bin/Release/BeamMP-Server.exe
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
.idea/
|
.idea/
|
||||||
|
.sentry-native/
|
||||||
*.orig
|
*.orig
|
||||||
*.toml
|
*.toml
|
||||||
boost_*
|
boost_*
|
||||||
|
|||||||
+3
-3
@@ -4,6 +4,6 @@
|
|||||||
[submodule "vcpkg"]
|
[submodule "vcpkg"]
|
||||||
path = vcpkg
|
path = vcpkg
|
||||||
url = https://github.com/Microsoft/vcpkg.git
|
url = https://github.com/Microsoft/vcpkg.git
|
||||||
[submodule "deps/toml11"]
|
[submodule "deps/BeamMP-Protocol"]
|
||||||
path = deps/toml11
|
path = deps/BeamMP-Protocol
|
||||||
url = https://github.com/ToruNiina/toml11
|
url = https://github.com/BeamMP/BeamMP-Protocol
|
||||||
|
|||||||
+17
-31
@@ -15,15 +15,16 @@ include(cmake/StandardSettings.cmake)
|
|||||||
include(cmake/StaticAnalyzers.cmake)
|
include(cmake/StaticAnalyzers.cmake)
|
||||||
include(cmake/Git.cmake)
|
include(cmake/Git.cmake)
|
||||||
|
|
||||||
|
add_subdirectory(deps/BeamMP-Protocol)
|
||||||
|
|
||||||
# below are options which should be changed
|
# below are options which should be changed
|
||||||
|
|
||||||
### SETTINGS ###
|
### SETTINGS ###
|
||||||
|
|
||||||
# add all headers (.h, .hpp) to this
|
# add all headers (.h, .hpp) to this
|
||||||
set(PRJ_HEADERS
|
set(PRJ_HEADERS
|
||||||
include/ArgsParser.h
|
include/ArgsParser.h
|
||||||
include/BoostAliases.h
|
include/BoostAliases.h
|
||||||
include/Client.h
|
|
||||||
include/Common.h
|
include/Common.h
|
||||||
include/Compat.h
|
include/Compat.h
|
||||||
include/Cryptography.h
|
include/Cryptography.h
|
||||||
@@ -41,22 +42,15 @@ set(PRJ_HEADERS
|
|||||||
include/THeartbeatThread.h
|
include/THeartbeatThread.h
|
||||||
include/TLuaEngine.h
|
include/TLuaEngine.h
|
||||||
include/TLuaPlugin.h
|
include/TLuaPlugin.h
|
||||||
include/TNetwork.h
|
|
||||||
include/TPluginMonitor.h
|
include/TPluginMonitor.h
|
||||||
include/TPPSMonitor.h
|
|
||||||
include/TResourceManager.h
|
|
||||||
include/TScopedTimer.h
|
include/TScopedTimer.h
|
||||||
include/TServer.h
|
|
||||||
include/VehicleData.h
|
include/VehicleData.h
|
||||||
include/Env.h
|
include/Env.h
|
||||||
include/Settings.h
|
include/Network.h
|
||||||
include/Profiling.h
|
|
||||||
include/ChronoWrapper.h
|
|
||||||
)
|
)
|
||||||
# add all source files (.cpp) to this, except the one with main()
|
# add all source files (.cpp) to this, except the one with main()
|
||||||
set(PRJ_SOURCES
|
set(PRJ_SOURCES
|
||||||
src/ArgsParser.cpp
|
src/ArgsParser.cpp
|
||||||
src/Client.cpp
|
|
||||||
src/Common.cpp
|
src/Common.cpp
|
||||||
src/Compat.cpp
|
src/Compat.cpp
|
||||||
src/Http.cpp
|
src/Http.cpp
|
||||||
@@ -67,17 +61,11 @@ set(PRJ_SOURCES
|
|||||||
src/THeartbeatThread.cpp
|
src/THeartbeatThread.cpp
|
||||||
src/TLuaEngine.cpp
|
src/TLuaEngine.cpp
|
||||||
src/TLuaPlugin.cpp
|
src/TLuaPlugin.cpp
|
||||||
src/TNetwork.cpp
|
|
||||||
src/TPluginMonitor.cpp
|
src/TPluginMonitor.cpp
|
||||||
src/TPPSMonitor.cpp
|
|
||||||
src/TResourceManager.cpp
|
|
||||||
src/TScopedTimer.cpp
|
src/TScopedTimer.cpp
|
||||||
src/TServer.cpp
|
|
||||||
src/VehicleData.cpp
|
src/VehicleData.cpp
|
||||||
src/Env.cpp
|
src/Env.cpp
|
||||||
src/Settings.cpp
|
src/Network.cpp
|
||||||
src/Profiling.cpp
|
|
||||||
src/ChronoWrapper.cpp
|
|
||||||
)
|
)
|
||||||
|
|
||||||
find_package(Lua REQUIRED)
|
find_package(Lua REQUIRED)
|
||||||
@@ -93,7 +81,7 @@ set(PRJ_COMPILE_FEATURES cxx_std_20)
|
|||||||
# set #defines (test enable/disable not included here)
|
# set #defines (test enable/disable not included here)
|
||||||
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
|
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||||
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||||
set(PRJ_LIBRARIES
|
set(PRJ_LIBRARIES
|
||||||
fmt::fmt
|
fmt::fmt
|
||||||
doctest::doctest
|
doctest::doctest
|
||||||
Threads::Threads
|
Threads::Threads
|
||||||
@@ -104,21 +92,25 @@ set(PRJ_LIBRARIES
|
|||||||
httplib::httplib
|
httplib::httplib
|
||||||
libzip::zip
|
libzip::zip
|
||||||
OpenSSL::SSL OpenSSL::Crypto
|
OpenSSL::SSL OpenSSL::Crypto
|
||||||
CURL::libcurl
|
protocol
|
||||||
${LUA_LIBRARIES}
|
${LUA_LIBRARIES}
|
||||||
|
zstd::libzstd_static
|
||||||
|
Boost::thread
|
||||||
|
glm::glm
|
||||||
)
|
)
|
||||||
|
|
||||||
# add dependency find_package calls and similar here
|
# add dependency find_package calls and similar here
|
||||||
find_package(fmt CONFIG REQUIRED)
|
find_package(fmt CONFIG REQUIRED)
|
||||||
find_package(OpenSSL REQUIRED)
|
find_package(OpenSSL REQUIRED)
|
||||||
find_package(doctest CONFIG REQUIRED)
|
find_package(doctest CONFIG REQUIRED)
|
||||||
find_package(Boost REQUIRED)
|
find_package(Boost REQUIRED COMPONENTS thread)
|
||||||
find_package(httplib CONFIG REQUIRED)
|
find_package(httplib CONFIG REQUIRED)
|
||||||
find_package(libzip CONFIG REQUIRED)
|
find_package(libzip CONFIG REQUIRED)
|
||||||
find_package(RapidJSON CONFIG REQUIRED)
|
find_package(RapidJSON CONFIG REQUIRED)
|
||||||
find_package(sol2 CONFIG REQUIRED)
|
find_package(sol2 CONFIG REQUIRED)
|
||||||
find_package(CURL CONFIG REQUIRED)
|
find_package(toml11 CONFIG REQUIRED)
|
||||||
add_subdirectory("deps/toml11")
|
find_package(zstd CONFIG REQUIRED)
|
||||||
|
find_package(glm CONFIG REQUIRED)
|
||||||
|
|
||||||
include_directories(include)
|
include_directories(include)
|
||||||
|
|
||||||
@@ -127,7 +119,7 @@ include(FindThreads)
|
|||||||
|
|
||||||
### END SETTINGS ###
|
### END SETTINGS ###
|
||||||
|
|
||||||
# DONT change anything beyond this point unless you've read the cmake bible and
|
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||||
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
||||||
|
|
||||||
####################
|
####################
|
||||||
@@ -149,7 +141,6 @@ endif(UNIX)
|
|||||||
|
|
||||||
if (WIN32)
|
if (WIN32)
|
||||||
add_compile_options("-D_WIN32_WINNT=0x0601")
|
add_compile_options("-D_WIN32_WINNT=0x0601")
|
||||||
add_compile_options("/bigobj")
|
|
||||||
endif(WIN32)
|
endif(WIN32)
|
||||||
|
|
||||||
|
|
||||||
@@ -166,7 +157,7 @@ set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
|||||||
)
|
)
|
||||||
|
|
||||||
# build commandline manually for funky windows flags to carry over without a custom toolchain file
|
# build commandline manually for funky windows flags to carry over without a custom toolchain file
|
||||||
add_library(commandline_static
|
add_library(commandline_static
|
||||||
deps/commandline/src/impls.h
|
deps/commandline/src/impls.h
|
||||||
deps/commandline/src/windows_impl.cpp
|
deps/commandline/src/windows_impl.cpp
|
||||||
deps/commandline/src/linux_impl.cpp
|
deps/commandline/src/linux_impl.cpp
|
||||||
@@ -179,11 +170,6 @@ add_library(commandline_static
|
|||||||
deps/commandline/src/backends/BufferedBackend.cpp
|
deps/commandline/src/backends/BufferedBackend.cpp
|
||||||
deps/commandline/src/backends/BufferedBackend.h
|
deps/commandline/src/backends/BufferedBackend.h
|
||||||
)
|
)
|
||||||
|
|
||||||
# Ensure the commandline library uses C++11
|
|
||||||
set_target_properties(commandline_static PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED YES)
|
|
||||||
|
|
||||||
|
|
||||||
if (WIN32)
|
if (WIN32)
|
||||||
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
|
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
|
||||||
else ()
|
else ()
|
||||||
@@ -208,7 +194,6 @@ target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARN
|
|||||||
)
|
)
|
||||||
|
|
||||||
if(MSVC)
|
if(MSVC)
|
||||||
target_compile_options(${PROJECT_NAME} PUBLIC "/bigobj")
|
|
||||||
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
|
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
endif(MSVC)
|
endif(MSVC)
|
||||||
|
|
||||||
@@ -227,3 +212,4 @@ if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
|
|||||||
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
|
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
endif(MSVC)
|
endif(MSVC)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|||||||
+5
-22
@@ -53,28 +53,11 @@ Do **NOT** pull with merge. This is the default git behavior for `git pull`, but
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
## Workflow
|
|
||||||
|
|
||||||
### Making an issue and fixing it
|
|
||||||
|
|
||||||
1. Create an issue detailing the feature or bug.
|
|
||||||
2. Assign a milestone to the issue, or wait for a maintainer to add a milestone to your issue.
|
|
||||||
3. Fork the repository and base your work on the branch mentioned in the milestone attached to your issue (e.g. `v3.0.0 (develop)` -> `develop`).
|
|
||||||
4. Program your feature or bug fix.
|
|
||||||
5. Open a PR that references the issue by number in the format: `#12345`.
|
|
||||||
6. Someone will review your PR and merge it, or ask for changes.
|
|
||||||
|
|
||||||
### Fixing an existing issue
|
|
||||||
|
|
||||||
1. Fork the repository and base your work on the branch mentioned in the milestone attached to your issue (e.g. `v3.0.0 (develop)` -> `develop`).
|
|
||||||
2. Program your feature or bug fix.
|
|
||||||
3. Open a PR that references the issue by number in the format: `#12345`.
|
|
||||||
4. Someone will review your PR and merge it, or ask for changes.
|
|
||||||
|
|
||||||
## Branches
|
## Branches
|
||||||
|
|
||||||
- `minor`: Minor releases, like `v1.2.3` -> `v1.3.0` or `v1.2.3` -> `v1.2.4`.
|
### Which branch should I base my work on?
|
||||||
- `develop`: Major releases, like `v1.2.3` -> `v2.0.0`, and larger feature/minor releases.
|
|
||||||
|
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
|
## Unit tests & CI/CD
|
||||||
|
|
||||||
@@ -108,8 +91,8 @@ A BeamMP-Developer must review your code in detail, and leave a review. If this
|
|||||||
5. Run `git submodule update --init --recursive`.
|
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.
|
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`).
|
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`. An example invocation on Linux with GNU make would be
|
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` .
|
`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.
|
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.
|
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`).
|
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`).
|
||||||
|
|||||||
@@ -1,661 +1,2 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor). BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||||
Version 3, 19 November 2007
|
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||||
|
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
||||||
Everyone is permitted to copy and distribute verbatim copies
|
|
||||||
of this license document, but changing it is not allowed.
|
|
||||||
|
|
||||||
Preamble
|
|
||||||
|
|
||||||
The GNU Affero General Public License is a free, copyleft license for
|
|
||||||
software and other kinds of works, specifically designed to ensure
|
|
||||||
cooperation with the community in the case of network server software.
|
|
||||||
|
|
||||||
The licenses for most software and other practical works are designed
|
|
||||||
to take away your freedom to share and change the works. By contrast,
|
|
||||||
our General Public Licenses are intended to guarantee your freedom to
|
|
||||||
share and change all versions of a program--to make sure it remains free
|
|
||||||
software for all its users.
|
|
||||||
|
|
||||||
When we speak of free software, we are referring to freedom, not
|
|
||||||
price. Our General Public Licenses are designed to make sure that you
|
|
||||||
have the freedom to distribute copies of free software (and charge for
|
|
||||||
them if you wish), that you receive source code or can get it if you
|
|
||||||
want it, that you can change the software or use pieces of it in new
|
|
||||||
free programs, and that you know you can do these things.
|
|
||||||
|
|
||||||
Developers that use our General Public Licenses protect your rights
|
|
||||||
with two steps: (1) assert copyright on the software, and (2) offer
|
|
||||||
you this License which gives you legal permission to copy, distribute
|
|
||||||
and/or modify the software.
|
|
||||||
|
|
||||||
A secondary benefit of defending all users' freedom is that
|
|
||||||
improvements made in alternate versions of the program, if they
|
|
||||||
receive widespread use, become available for other developers to
|
|
||||||
incorporate. Many developers of free software are heartened and
|
|
||||||
encouraged by the resulting cooperation. However, in the case of
|
|
||||||
software used on network servers, this result may fail to come about.
|
|
||||||
The GNU General Public License permits making a modified version and
|
|
||||||
letting the public access it on a server without ever releasing its
|
|
||||||
source code to the public.
|
|
||||||
|
|
||||||
The GNU Affero General Public License is designed specifically to
|
|
||||||
ensure that, in such cases, the modified source code becomes available
|
|
||||||
to the community. It requires the operator of a network server to
|
|
||||||
provide the source code of the modified version running there to the
|
|
||||||
users of that server. Therefore, public use of a modified version, on
|
|
||||||
a publicly accessible server, gives the public access to the source
|
|
||||||
code of the modified version.
|
|
||||||
|
|
||||||
An older license, called the Affero General Public License and
|
|
||||||
published by Affero, was designed to accomplish similar goals. This is
|
|
||||||
a different license, not a version of the Affero GPL, but Affero has
|
|
||||||
released a new version of the Affero GPL which permits relicensing under
|
|
||||||
this license.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and
|
|
||||||
modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
0. Definitions.
|
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
|
||||||
works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this
|
|
||||||
License. Each licensee is addressed as "you". "Licensees" and
|
|
||||||
"recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work
|
|
||||||
in a fashion requiring copyright permission, other than the making of an
|
|
||||||
exact copy. The resulting work is called a "modified version" of the
|
|
||||||
earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based
|
|
||||||
on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without
|
|
||||||
permission, would make you directly or secondarily liable for
|
|
||||||
infringement under applicable copyright law, except executing it on a
|
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
|
||||||
distribution (with or without modification), making available to the
|
|
||||||
public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other
|
|
||||||
parties to make or receive copies. Mere interaction with a user through
|
|
||||||
a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices"
|
|
||||||
to the extent that it includes a convenient and prominently visible
|
|
||||||
feature that (1) displays an appropriate copyright notice, and (2)
|
|
||||||
tells the user that there is no warranty for the work (except to the
|
|
||||||
extent that warranties are provided), that licensees may convey the
|
|
||||||
work under this License, and how to view a copy of this License. If
|
|
||||||
the interface presents a list of user commands or options, such as a
|
|
||||||
menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
|
||||||
|
|
||||||
The "source code" for a work means the preferred form of the work
|
|
||||||
for making modifications to it. "Object code" means any non-source
|
|
||||||
form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official
|
|
||||||
standard defined by a recognized standards body, or, in the case of
|
|
||||||
interfaces specified for a particular programming language, one that
|
|
||||||
is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other
|
|
||||||
than the work as a whole, that (a) is included in the normal form of
|
|
||||||
packaging a Major Component, but which is not part of that Major
|
|
||||||
Component, and (b) serves only to enable use of the work with that
|
|
||||||
Major Component, or to implement a Standard Interface for which an
|
|
||||||
implementation is available to the public in source code form. A
|
|
||||||
"Major Component", in this context, means a major essential component
|
|
||||||
(kernel, window system, and so on) of the specific operating system
|
|
||||||
(if any) on which the executable work runs, or a compiler used to
|
|
||||||
produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all
|
|
||||||
the source code needed to generate, install, and (for an executable
|
|
||||||
work) run the object code and to modify the work, including scripts to
|
|
||||||
control those activities. However, it does not include the work's
|
|
||||||
System Libraries, or general-purpose tools or generally available free
|
|
||||||
programs which are used unmodified in performing those activities but
|
|
||||||
which are not part of the work. For example, Corresponding Source
|
|
||||||
includes interface definition files associated with source files for
|
|
||||||
the work, and the source code for shared libraries and dynamically
|
|
||||||
linked subprograms that the work is specifically designed to require,
|
|
||||||
such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users
|
|
||||||
can regenerate automatically from other parts of the Corresponding
|
|
||||||
Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that
|
|
||||||
same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
|
||||||
|
|
||||||
All rights granted under this License are granted for the term of
|
|
||||||
copyright on the Program, and are irrevocable provided the stated
|
|
||||||
conditions are met. This License explicitly affirms your unlimited
|
|
||||||
permission to run the unmodified Program. The output from running a
|
|
||||||
covered work is covered by this License only if the output, given its
|
|
||||||
content, constitutes a covered work. This License acknowledges your
|
|
||||||
rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not
|
|
||||||
convey, without conditions so long as your license otherwise remains
|
|
||||||
in force. You may convey covered works to others for the sole purpose
|
|
||||||
of having them make modifications exclusively for you, or provide you
|
|
||||||
with facilities for running those works, provided that you comply with
|
|
||||||
the terms of this License in conveying all material for which you do
|
|
||||||
not control copyright. Those thus making or running the covered works
|
|
||||||
for you must do so exclusively on your behalf, under your direction
|
|
||||||
and control, on terms that prohibit them from making any copies of
|
|
||||||
your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under
|
|
||||||
the conditions stated below. Sublicensing is not allowed; section 10
|
|
||||||
makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
|
||||||
|
|
||||||
No covered work shall be deemed part of an effective technological
|
|
||||||
measure under any applicable law fulfilling obligations under article
|
|
||||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
|
||||||
similar laws prohibiting or restricting circumvention of such
|
|
||||||
measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid
|
|
||||||
circumvention of technological measures to the extent such circumvention
|
|
||||||
is effected by exercising rights under this License with respect to
|
|
||||||
the covered work, and you disclaim any intention to limit operation or
|
|
||||||
modification of the work as a means of enforcing, against the work's
|
|
||||||
users, your or third parties' legal rights to forbid circumvention of
|
|
||||||
technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
|
|
||||||
You may convey verbatim copies of the Program's source code as you
|
|
||||||
receive it, in any medium, provided that you conspicuously and
|
|
||||||
appropriately publish on each copy an appropriate copyright notice;
|
|
||||||
keep intact all notices stating that this License and any
|
|
||||||
non-permissive terms added in accord with section 7 apply to the code;
|
|
||||||
keep intact all notices of the absence of any warranty; and give all
|
|
||||||
recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey,
|
|
||||||
and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
|
||||||
|
|
||||||
You may convey a work based on the Program, or the modifications to
|
|
||||||
produce it from the Program, in the form of source code under the
|
|
||||||
terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified
|
|
||||||
it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is
|
|
||||||
released under this License and any conditions added under section
|
|
||||||
7. This requirement modifies the requirement in section 4 to
|
|
||||||
"keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this
|
|
||||||
License to anyone who comes into possession of a copy. This
|
|
||||||
License will therefore apply, along with any applicable section 7
|
|
||||||
additional terms, to the whole of the work, and all its parts,
|
|
||||||
regardless of how they are packaged. This License gives no
|
|
||||||
permission to license the work in any other way, but it does not
|
|
||||||
invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display
|
|
||||||
Appropriate Legal Notices; however, if the Program has interactive
|
|
||||||
interfaces that do not display Appropriate Legal Notices, your
|
|
||||||
work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent
|
|
||||||
works, which are not by their nature extensions of the covered work,
|
|
||||||
and which are not combined with it such as to form a larger program,
|
|
||||||
in or on a volume of a storage or distribution medium, is called an
|
|
||||||
"aggregate" if the compilation and its resulting copyright are not
|
|
||||||
used to limit the access or legal rights of the compilation's users
|
|
||||||
beyond what the individual works permit. Inclusion of a covered work
|
|
||||||
in an aggregate does not cause this License to apply to the other
|
|
||||||
parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
|
||||||
|
|
||||||
You may convey a covered work in object code form under the terms
|
|
||||||
of sections 4 and 5, provided that you also convey the
|
|
||||||
machine-readable Corresponding Source under the terms of this License,
|
|
||||||
in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by the
|
|
||||||
Corresponding Source fixed on a durable physical medium
|
|
||||||
customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product
|
|
||||||
(including a physical distribution medium), accompanied by a
|
|
||||||
written offer, valid for at least three years and valid for as
|
|
||||||
long as you offer spare parts or customer support for that product
|
|
||||||
model, to give anyone who possesses the object code either (1) a
|
|
||||||
copy of the Corresponding Source for all the software in the
|
|
||||||
product that is covered by this License, on a durable physical
|
|
||||||
medium customarily used for software interchange, for a price no
|
|
||||||
more than your reasonable cost of physically performing this
|
|
||||||
conveying of source, or (2) access to copy the
|
|
||||||
Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the
|
|
||||||
written offer to provide the Corresponding Source. This
|
|
||||||
alternative is allowed only occasionally and noncommercially, and
|
|
||||||
only if you received the object code with such an offer, in accord
|
|
||||||
with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated
|
|
||||||
place (gratis or for a charge), and offer equivalent access to the
|
|
||||||
Corresponding Source in the same way through the same place at no
|
|
||||||
further charge. You need not require recipients to copy the
|
|
||||||
Corresponding Source along with the object code. If the place to
|
|
||||||
copy the object code is a network server, the Corresponding Source
|
|
||||||
may be on a different server (operated by you or a third party)
|
|
||||||
that supports equivalent copying facilities, provided you maintain
|
|
||||||
clear directions next to the object code saying where to find the
|
|
||||||
Corresponding Source. Regardless of what server hosts the
|
|
||||||
Corresponding Source, you remain obligated to ensure that it is
|
|
||||||
available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided
|
|
||||||
you inform other peers where the object code and Corresponding
|
|
||||||
Source of the work are being offered to the general public at no
|
|
||||||
charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded
|
|
||||||
from the Corresponding Source as a System Library, need not be
|
|
||||||
included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any
|
|
||||||
tangible personal property which is normally used for personal, family,
|
|
||||||
or household purposes, or (2) anything designed or sold for incorporation
|
|
||||||
into a dwelling. In determining whether a product is a consumer product,
|
|
||||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
|
||||||
product received by a particular user, "normally used" refers to a
|
|
||||||
typical or common use of that class of product, regardless of the status
|
|
||||||
of the particular user or of the way in which the particular user
|
|
||||||
actually uses, or expects or is expected to use, the product. A product
|
|
||||||
is a consumer product regardless of whether the product has substantial
|
|
||||||
commercial, industrial or non-consumer uses, unless such uses represent
|
|
||||||
the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods,
|
|
||||||
procedures, authorization keys, or other information required to install
|
|
||||||
and execute modified versions of a covered work in that User Product from
|
|
||||||
a modified version of its Corresponding Source. The information must
|
|
||||||
suffice to ensure that the continued functioning of the modified object
|
|
||||||
code is in no case prevented or interfered with solely because
|
|
||||||
modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or
|
|
||||||
specifically for use in, a User Product, and the conveying occurs as
|
|
||||||
part of a transaction in which the right of possession and use of the
|
|
||||||
User Product is transferred to the recipient in perpetuity or for a
|
|
||||||
fixed term (regardless of how the transaction is characterized), the
|
|
||||||
Corresponding Source conveyed under this section must be accompanied
|
|
||||||
by the Installation Information. But this requirement does not apply
|
|
||||||
if neither you nor any third party retains the ability to install
|
|
||||||
modified object code on the User Product (for example, the work has
|
|
||||||
been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a
|
|
||||||
requirement to continue to provide support service, warranty, or updates
|
|
||||||
for a work that has been modified or installed by the recipient, or for
|
|
||||||
the User Product in which it has been modified or installed. Access to a
|
|
||||||
network may be denied when the modification itself materially and
|
|
||||||
adversely affects the operation of the network or violates the rules and
|
|
||||||
protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided,
|
|
||||||
in accord with this section must be in a format that is publicly
|
|
||||||
documented (and with an implementation available to the public in
|
|
||||||
source code form), and must require no special password or key for
|
|
||||||
unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
|
||||||
|
|
||||||
"Additional permissions" are terms that supplement the terms of this
|
|
||||||
License by making exceptions from one or more of its conditions.
|
|
||||||
Additional permissions that are applicable to the entire Program shall
|
|
||||||
be treated as though they were included in this License, to the extent
|
|
||||||
that they are valid under applicable law. If additional permissions
|
|
||||||
apply only to part of the Program, that part may be used separately
|
|
||||||
under those permissions, but the entire Program remains governed by
|
|
||||||
this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option
|
|
||||||
remove any additional permissions from that copy, or from any part of
|
|
||||||
it. (Additional permissions may be written to require their own
|
|
||||||
removal in certain cases when you modify the work.) You may place
|
|
||||||
additional permissions on material, added by you to a covered work,
|
|
||||||
for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you
|
|
||||||
add to a covered work, you may (if authorized by the copyright holders of
|
|
||||||
that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the
|
|
||||||
terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or
|
|
||||||
author attributions in that material or in the Appropriate Legal
|
|
||||||
Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or
|
|
||||||
requiring that modified versions of such material be marked in
|
|
||||||
reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or
|
|
||||||
authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some
|
|
||||||
trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that
|
|
||||||
material by anyone who conveys the material (or modified versions of
|
|
||||||
it) with contractual assumptions of liability to the recipient, for
|
|
||||||
any liability that these contractual assumptions directly impose on
|
|
||||||
those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further
|
|
||||||
restrictions" within the meaning of section 10. If the Program as you
|
|
||||||
received it, or any part of it, contains a notice stating that it is
|
|
||||||
governed by this License along with a term that is a further
|
|
||||||
restriction, you may remove that term. If a license document contains
|
|
||||||
a further restriction but permits relicensing or conveying under this
|
|
||||||
License, you may add to a covered work material governed by the terms
|
|
||||||
of that license document, provided that the further restriction does
|
|
||||||
not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you
|
|
||||||
must place, in the relevant source files, a statement of the
|
|
||||||
additional terms that apply to those files, or a notice indicating
|
|
||||||
where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the
|
|
||||||
form of a separately written license, or stated as exceptions;
|
|
||||||
the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly
|
|
||||||
provided under this License. Any attempt otherwise to propagate or
|
|
||||||
modify it is void, and will automatically terminate your rights under
|
|
||||||
this License (including any patent licenses granted under the third
|
|
||||||
paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your
|
|
||||||
license from a particular copyright holder is reinstated (a)
|
|
||||||
provisionally, unless and until the copyright holder explicitly and
|
|
||||||
finally terminates your license, and (b) permanently, if the copyright
|
|
||||||
holder fails to notify you of the violation by some reasonable means
|
|
||||||
prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is
|
|
||||||
reinstated permanently if the copyright holder notifies you of the
|
|
||||||
violation by some reasonable means, this is the first time you have
|
|
||||||
received notice of violation of this License (for any work) from that
|
|
||||||
copyright holder, and you cure the violation prior to 30 days after
|
|
||||||
your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the
|
|
||||||
licenses of parties who have received copies or rights from you under
|
|
||||||
this License. If your rights have been terminated and not permanently
|
|
||||||
reinstated, you do not qualify to receive new licenses for the same
|
|
||||||
material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or
|
|
||||||
run a copy of the Program. Ancillary propagation of a covered work
|
|
||||||
occurring solely as a consequence of using peer-to-peer transmission
|
|
||||||
to receive a copy likewise does not require acceptance. However,
|
|
||||||
nothing other than this License grants you permission to propagate or
|
|
||||||
modify any covered work. These actions infringe copyright if you do
|
|
||||||
not accept this License. Therefore, by modifying or propagating a
|
|
||||||
covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically
|
|
||||||
receives a license from the original licensors, to run, modify and
|
|
||||||
propagate that work, subject to this License. You are not responsible
|
|
||||||
for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an
|
|
||||||
organization, or substantially all assets of one, or subdividing an
|
|
||||||
organization, or merging organizations. If propagation of a covered
|
|
||||||
work results from an entity transaction, each party to that
|
|
||||||
transaction who receives a copy of the work also receives whatever
|
|
||||||
licenses to the work the party's predecessor in interest had or could
|
|
||||||
give under the previous paragraph, plus a right to possession of the
|
|
||||||
Corresponding Source of the work from the predecessor in interest, if
|
|
||||||
the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the
|
|
||||||
rights granted or affirmed under this License. For example, you may
|
|
||||||
not impose a license fee, royalty, or other charge for exercise of
|
|
||||||
rights granted under this License, and you may not initiate litigation
|
|
||||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
|
||||||
any patent claim is infringed by making, using, selling, offering for
|
|
||||||
sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this
|
|
||||||
License of the Program or a work on which the Program is based. The
|
|
||||||
work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims
|
|
||||||
owned or controlled by the contributor, whether already acquired or
|
|
||||||
hereafter acquired, that would be infringed by some manner, permitted
|
|
||||||
by this License, of making, using, or selling its contributor version,
|
|
||||||
but do not include claims that would be infringed only as a
|
|
||||||
consequence of further modification of the contributor version. For
|
|
||||||
purposes of this definition, "control" includes the right to grant
|
|
||||||
patent sublicenses in a manner consistent with the requirements of
|
|
||||||
this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
|
||||||
patent license under the contributor's essential patent claims, to
|
|
||||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
|
||||||
propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express
|
|
||||||
agreement or commitment, however denominated, not to enforce a patent
|
|
||||||
(such as an express permission to practice a patent or covenant not to
|
|
||||||
sue for patent infringement). To "grant" such a patent license to a
|
|
||||||
party means to make such an agreement or commitment not to enforce a
|
|
||||||
patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license,
|
|
||||||
and the Corresponding Source of the work is not available for anyone
|
|
||||||
to copy, free of charge and under the terms of this License, through a
|
|
||||||
publicly available network server or other readily accessible means,
|
|
||||||
then you must either (1) cause the Corresponding Source to be so
|
|
||||||
available, or (2) arrange to deprive yourself of the benefit of the
|
|
||||||
patent license for this particular work, or (3) arrange, in a manner
|
|
||||||
consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have
|
|
||||||
actual knowledge that, but for the patent license, your conveying the
|
|
||||||
covered work in a country, or your recipient's use of the covered work
|
|
||||||
in a country, would infringe one or more identifiable patents in that
|
|
||||||
country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or
|
|
||||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
|
||||||
covered work, and grant a patent license to some of the parties
|
|
||||||
receiving the covered work authorizing them to use, propagate, modify
|
|
||||||
or convey a specific copy of the covered work, then the patent license
|
|
||||||
you grant is automatically extended to all recipients of the covered
|
|
||||||
work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within
|
|
||||||
the scope of its coverage, prohibits the exercise of, or is
|
|
||||||
conditioned on the non-exercise of one or more of the rights that are
|
|
||||||
specifically granted under this License. You may not convey a covered
|
|
||||||
work if you are a party to an arrangement with a third party that is
|
|
||||||
in the business of distributing software, under which you make payment
|
|
||||||
to the third party based on the extent of your activity of conveying
|
|
||||||
the work, and under which the third party grants, to any of the
|
|
||||||
parties who would receive the covered work from you, a discriminatory
|
|
||||||
patent license (a) in connection with copies of the covered work
|
|
||||||
conveyed by you (or copies made from those copies), or (b) primarily
|
|
||||||
for and in connection with specific products or compilations that
|
|
||||||
contain the covered work, unless you entered into that arrangement,
|
|
||||||
or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting
|
|
||||||
any implied license or other defenses to infringement that may
|
|
||||||
otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or
|
|
||||||
otherwise) that contradict the conditions of this License, they do not
|
|
||||||
excuse you from the conditions of this License. If you cannot convey a
|
|
||||||
covered work so as to satisfy simultaneously your obligations under this
|
|
||||||
License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you
|
|
||||||
to collect a royalty for further conveying from those to whom you convey
|
|
||||||
the Program, the only way you could satisfy both those terms and this
|
|
||||||
License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, if you modify the
|
|
||||||
Program, your modified version must prominently offer all users
|
|
||||||
interacting with it remotely through a computer network (if your version
|
|
||||||
supports such interaction) an opportunity to receive the Corresponding
|
|
||||||
Source of your version by providing access to the Corresponding Source
|
|
||||||
from a network server at no charge, through some standard or customary
|
|
||||||
means of facilitating copying of software. This Corresponding Source
|
|
||||||
shall include the Corresponding Source for any work covered by version 3
|
|
||||||
of the GNU General Public License that is incorporated pursuant to the
|
|
||||||
following paragraph.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have
|
|
||||||
permission to link or combine any covered work with a work licensed
|
|
||||||
under version 3 of the GNU General Public License into a single
|
|
||||||
combined work, and to convey the resulting work. The terms of this
|
|
||||||
License will continue to apply to the part which is the covered work,
|
|
||||||
but the work with which it is combined will remain governed by version
|
|
||||||
3 of the GNU General Public License.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of
|
|
||||||
the GNU Affero General Public License from time to time. Such new versions
|
|
||||||
will be similar in spirit to the present version, but may differ in detail to
|
|
||||||
address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the
|
|
||||||
Program specifies that a certain numbered version of the GNU Affero General
|
|
||||||
Public License "or any later version" applies to it, you have the
|
|
||||||
option of following the terms and conditions either of that numbered
|
|
||||||
version or of any later version published by the Free Software
|
|
||||||
Foundation. If the Program does not specify a version number of the
|
|
||||||
GNU Affero General Public License, you may choose any version ever published
|
|
||||||
by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future
|
|
||||||
versions of the GNU Affero General Public License can be used, that proxy's
|
|
||||||
public statement of acceptance of a version permanently authorizes you
|
|
||||||
to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different
|
|
||||||
permissions. However, no additional obligations are imposed on any
|
|
||||||
author or copyright holder as a result of your choosing to follow a
|
|
||||||
later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
|
||||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
|
||||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
|
||||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
|
||||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
|
||||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
|
||||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
|
||||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
|
||||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
|
||||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
|
||||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
|
||||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
|
||||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
|
||||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
|
||||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
|
||||||
SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided
|
|
||||||
above cannot be given local legal effect according to their terms,
|
|
||||||
reviewing courts shall apply local law that most closely approximates
|
|
||||||
an absolute waiver of all civil liability in connection with the
|
|
||||||
Program, unless a warranty or assumption of liability accompanies a
|
|
||||||
copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest
|
|
||||||
possible use to the public, the best way to achieve this is to make it
|
|
||||||
free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest
|
|
||||||
to attach them to the start of each source file to most effectively
|
|
||||||
state the exclusion of warranty; and each file should have at least
|
|
||||||
the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
|
||||||
Copyright (C) <year> <name of author>
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU Affero General Public License as published
|
|
||||||
by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If your software can interact with users remotely through a computer
|
|
||||||
network, you should also make sure that it provides a way for users to
|
|
||||||
get its source. For example, if your program is a web application, its
|
|
||||||
interface could display a "Source" link that leads users to an archive
|
|
||||||
of the code. There are many ways you could offer source, and different
|
|
||||||
solutions will be better for different programs; see section 13 for the
|
|
||||||
specific requirements.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school,
|
|
||||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
|
||||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
|
||||||
<https://www.gnu.org/licenses/>.
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ Feel free to ask any questions via the following channels:
|
|||||||
|
|
||||||
These values are guesstimated and are subject to change with each release.
|
These values are guesstimated and are subject to change with each release.
|
||||||
|
|
||||||
* RAM: 30-100 MiB usable (not counting OS overhead)
|
* RAM: 50+ MiB usable (not counting OS overhead)
|
||||||
* CPU: >1GHz, preferably multicore
|
* CPU: >1GHz, preferably multicore
|
||||||
* OS: Windows, Linux (theoretically any POSIX)
|
* OS: Windows, Linux (theoretically any POSIX)
|
||||||
* GPU: None
|
* GPU: None
|
||||||
@@ -38,11 +38,11 @@ If you need support with understanding the codebase, please write us in the Disc
|
|||||||
|
|
||||||
## About Building from Source
|
## About Building from Source
|
||||||
|
|
||||||
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.4.1`. See [the tags](https://github.com/BeamMP/BeamMP-Server/tags) for possible versions/tags, as well as [the releases](https://github.com/BeamMP/BeamMP-Server/releases) to check which version is marked as a release/prerelease. We recommend using the [latest release](https://github.com/BeamMP/BeamMP-Server/releases/latest).
|
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.1.0`.
|
||||||
|
|
||||||
## Supported Operating Systems
|
## Supported Operating Systems
|
||||||
|
|
||||||
The code itself supports (latest stable) Linux, Windows and FreeBSD. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
|
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
|
||||||
|
|
||||||
Recommended compilers: MSVC, GCC, CLANG.
|
Recommended compilers: MSVC, GCC, CLANG.
|
||||||
|
|
||||||
@@ -66,20 +66,11 @@ You can build on **Windows, Linux** or other platforms by following these steps:
|
|||||||
|
|
||||||
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
||||||
2. Go into the directory `cd BeamMP-Server`.
|
2. Go into the directory `cd BeamMP-Server`.
|
||||||
3. Specify the server version to build by checking out a tag: `git checkout tags/v3.4.1` - [Possible versions/tags](https://github.com/BeamMP/BeamMP-Server/tags)
|
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
|
||||||
4. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
|
4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
|
||||||
5. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
|
5. Your executable can be found in `bin/`.
|
||||||
6. Your executable can be found in `bin/`.
|
|
||||||
|
|
||||||
When you make changes to the code, you only have to run step 4 again.
|
When you make changes to the code, you only have to run step 4 again.
|
||||||
### Building for FreeBSD
|
|
||||||
Building is only supported for major release branches of FreeBSD that are currently not EOL. The build process is the same as on Linux, although build dependencies can be universally installed from ports via pkg:
|
|
||||||
```
|
|
||||||
pkg install git cmake-core zip bash devel/ninja devel/pkgconf lua53
|
|
||||||
```
|
|
||||||
After installing the necessary build dependencies, follow the Linux build instructions beginning from step 3. Beware that running the initial cmake command will compile vcpkg from source, as vcpkg has no native FreeBSD port - this may take some time.
|
|
||||||
|
|
||||||
On systems with a single logical CPU core, `make` may fail to build the server when using the `--parallel` option when calling CMake. If you see error messages related to make, simply omit the `--parallel` from the command: `cmake --build bin --config Release -t BeamMP-Server`.
|
|
||||||
|
|
||||||
### Runtime Dependencies
|
### Runtime Dependencies
|
||||||
|
|
||||||
@@ -93,3 +84,9 @@ Windows: No libraries.
|
|||||||
|
|
||||||
## Support
|
## 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.
|
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 (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
|
||||||
|
BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||||
|
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
||||||
# Courtesy of Jason Turner
|
# Courtesy of Jason Turner
|
||||||
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
||||||
#
|
#
|
||||||
# This version has been modified by the owners of the current respository.
|
# This version has been modified by the owners of the current respository.
|
||||||
# Modifications have mostly been marked with "modified" or similar, though this is not
|
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||||
# strictly required.
|
# strictly required.
|
||||||
|
|
||||||
function(set_project_warnings project_name)
|
function(set_project_warnings project_name)
|
||||||
@@ -71,8 +71,8 @@ function(set_project_warnings project_name)
|
|||||||
-Werror=write-strings
|
-Werror=write-strings
|
||||||
-Werror=strict-aliasing -fstrict-aliasing
|
-Werror=strict-aliasing -fstrict-aliasing
|
||||||
-Werror=missing-declarations
|
-Werror=missing-declarations
|
||||||
-Werror=missing-field-initializers
|
|
||||||
-Werror=ctor-dtor-privacy
|
-Werror=ctor-dtor-privacy
|
||||||
|
-Wno-missing-field-initializers
|
||||||
-Wswitch-default
|
-Wswitch-default
|
||||||
-Werror=unused-result
|
-Werror=unused-result
|
||||||
-Werror=implicit-fallthrough
|
-Werror=implicit-fallthrough
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ find_package(Git)
|
|||||||
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
|
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
|
||||||
if(Git_FOUND)
|
if(Git_FOUND)
|
||||||
message(STATUS "Git found, submodule update and init")
|
message(STATUS "Git found, submodule update and init")
|
||||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
|||||||
+1
Submodule deps/BeamMP-Protocol added at 8eda5714c0
Vendored
+1
-1
Submodule deps/commandline updated: 04952e4811...b2a29733f9
Vendored
-1
Submodule deps/toml11 deleted from f33ca743fb
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <initializer_list>
|
#include <initializer_list>
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <boost/asio.hpp>
|
#include <boost/asio.hpp>
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace ChronoWrapper {
|
|
||||||
std::chrono::high_resolution_clock::duration TimeFromStringWithLiteral(const std::string& time_str);
|
|
||||||
}
|
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <memory>
|
|
||||||
#include <optional>
|
|
||||||
#include <queue>
|
|
||||||
#include <string>
|
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "Compat.h"
|
|
||||||
#include "VehicleData.h"
|
|
||||||
|
|
||||||
class TServer;
|
|
||||||
|
|
||||||
#ifdef BEAMMP_WINDOWS
|
|
||||||
// for socklen_t
|
|
||||||
#include <WS2tcpip.h>
|
|
||||||
#endif // WINDOWS
|
|
||||||
|
|
||||||
struct TConnection final {
|
|
||||||
ip::tcp::socket Socket;
|
|
||||||
ip::tcp::endpoint SockAddr;
|
|
||||||
};
|
|
||||||
|
|
||||||
class TClient final {
|
|
||||||
public:
|
|
||||||
using TSetOfVehicleData = std::vector<TVehicleData>;
|
|
||||||
|
|
||||||
struct TVehicleDataLockPair {
|
|
||||||
TSetOfVehicleData* VehicleData;
|
|
||||||
std::unique_lock<std::mutex> Lock;
|
|
||||||
};
|
|
||||||
|
|
||||||
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
|
||||||
TClient(const TClient&) = delete;
|
|
||||||
~TClient();
|
|
||||||
TClient& operator=(const TClient&) = delete;
|
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
|
||||||
void SetCarData(int Ident, const std::string& Data);
|
|
||||||
void SetCarPosition(int Ident, const std::string& Data);
|
|
||||||
TVehicleDataLockPair GetAllCars();
|
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
|
||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
|
||||||
std::string GetCarData(int Ident);
|
|
||||||
std::string GetCarPositionRaw(int Ident);
|
|
||||||
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
|
||||||
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
|
||||||
void Disconnect(std::string_view Reason);
|
|
||||||
bool IsDisconnected() const { return !mSocket.is_open(); }
|
|
||||||
// locks
|
|
||||||
void DeleteCar(int Ident);
|
|
||||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
|
||||||
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
|
||||||
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
|
||||||
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
|
||||||
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
|
||||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
|
||||||
[[nodiscard]] std::string GetName() const { return mName; }
|
|
||||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
|
||||||
void SetID(int ID) { mID = ID; }
|
|
||||||
[[nodiscard]] int GetOpenCarID() const;
|
|
||||||
[[nodiscard]] int GetCarCount() const;
|
|
||||||
void ClearCars();
|
|
||||||
[[nodiscard]] int GetID() const { return mID; }
|
|
||||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
|
||||||
[[nodiscard]] bool IsUDPConnected() const { return mIsUDPConnected; }
|
|
||||||
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
|
|
||||||
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
|
|
||||||
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
|
|
||||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
|
||||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
|
||||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
|
||||||
void EnqueuePacket(const std::vector<uint8_t>& Packet);
|
|
||||||
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
|
||||||
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
|
||||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
|
||||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
|
||||||
void SetIsUDPConnected(bool NewIsConnected) { mIsUDPConnected = NewIsConnected; }
|
|
||||||
[[nodiscard]] TServer& Server() const;
|
|
||||||
void UpdatePingTime();
|
|
||||||
int SecondsSinceLastPing();
|
|
||||||
|
|
||||||
private:
|
|
||||||
void InsertVehicle(int ID, const std::string& Data);
|
|
||||||
|
|
||||||
TServer& mServer;
|
|
||||||
bool mIsUDPConnected = false;
|
|
||||||
bool mIsSynced = false;
|
|
||||||
bool mIsSyncing = false;
|
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
|
||||||
std::queue<std::vector<uint8_t>> mPacketsSync;
|
|
||||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
|
||||||
bool mIsGuest = false;
|
|
||||||
mutable std::mutex mVehicleDataMutex;
|
|
||||||
mutable std::mutex mVehiclePositionMutex;
|
|
||||||
TSetOfVehicleData mVehicleData;
|
|
||||||
SparseArray<std::string> mVehiclePosition;
|
|
||||||
std::string mName = "Unknown Client";
|
|
||||||
ip::tcp::socket mSocket;
|
|
||||||
ip::udp::endpoint mUDPAddress {};
|
|
||||||
int mUnicycleID = -1;
|
|
||||||
std::string mRole;
|
|
||||||
std::string mDID;
|
|
||||||
int mID = -1;
|
|
||||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime = std::chrono::high_resolution_clock::now();
|
|
||||||
};
|
|
||||||
|
|
||||||
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
|
||||||
+42
-48
@@ -1,24 +1,5 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -29,7 +10,6 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <shared_mutex>
|
#include <shared_mutex>
|
||||||
#include <span>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <zlib.h>
|
#include <zlib.h>
|
||||||
@@ -38,7 +18,6 @@
|
|||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
#include "Settings.h"
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
struct Version {
|
struct Version {
|
||||||
@@ -61,6 +40,32 @@ using SparseArray = std::unordered_map<size_t, T>;
|
|||||||
class Application final {
|
class Application final {
|
||||||
public:
|
public:
|
||||||
// types
|
// types
|
||||||
|
struct TSettings {
|
||||||
|
std::string ServerName { "BeamMP Server" };
|
||||||
|
std::string ServerDesc { "BeamMP Default Description" };
|
||||||
|
std::string ServerTags { "Freeroam" };
|
||||||
|
std::string Resource { "Resources" };
|
||||||
|
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||||
|
std::string Key {};
|
||||||
|
std::string Password{};
|
||||||
|
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||||
|
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||||
|
bool HTTPServerEnabled { false };
|
||||||
|
int MaxPlayers { 8 };
|
||||||
|
bool Private { true };
|
||||||
|
int MaxCars { 1 };
|
||||||
|
bool DebugModeEnabled { false };
|
||||||
|
int Port { 30814 };
|
||||||
|
std::string CustomIP {};
|
||||||
|
bool LogChat { true };
|
||||||
|
bool SendErrors { true };
|
||||||
|
bool SendErrorsMessageEnabled { true };
|
||||||
|
int HTTPServerPort { 8080 };
|
||||||
|
std::string HTTPServerIP { "127.0.0.1" };
|
||||||
|
bool HTTPServerUseSSL { false };
|
||||||
|
bool HideUpdateMessages { false };
|
||||||
|
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||||
|
};
|
||||||
|
|
||||||
using TShutdownHandler = std::function<void()>;
|
using TShutdownHandler = std::function<void()>;
|
||||||
|
|
||||||
@@ -74,19 +79,21 @@ public:
|
|||||||
static TConsole& Console() { return mConsole; }
|
static TConsole& Console() { return mConsole; }
|
||||||
static std::string ServerVersionString();
|
static std::string ServerVersionString();
|
||||||
static const Version& ServerVersion() { return mVersion; }
|
static const Version& ServerVersion() { return mVersion; }
|
||||||
static Version ClientMinimumVersion() { return Version { 2, 2, 0 }; }
|
static uint8_t ClientMajorVersion() { return 2; }
|
||||||
static std::string PPS() { return mPPS; }
|
static std::string PPS() { return mPPS; }
|
||||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||||
|
|
||||||
static inline struct Settings Settings { };
|
static TSettings Settings;
|
||||||
|
|
||||||
static std::vector<std::string> GetBackendUrlsInOrder() {
|
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||||
return {
|
return {
|
||||||
"https://backend.beammp.com",
|
"backend.beammp.com",
|
||||||
|
"backup1.beammp.com",
|
||||||
|
"backup2.beammp.com"
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
static std::string GetBackendUrlForAuth() { return "https://auth.beammp.com"; }
|
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
||||||
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
||||||
static void CheckForUpdates();
|
static void CheckForUpdates();
|
||||||
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
||||||
@@ -127,7 +134,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, 8, 0 };
|
static inline Version mVersion { 3, 2, 2 };
|
||||||
};
|
};
|
||||||
|
|
||||||
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
|
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
|
||||||
@@ -139,6 +146,7 @@ void RegisterThread(const std::string& str);
|
|||||||
#define KB 1024llu
|
#define KB 1024llu
|
||||||
#define MB (KB * 1024llu)
|
#define MB (KB * 1024llu)
|
||||||
#define GB (MB * 1024llu)
|
#define GB (MB * 1024llu)
|
||||||
|
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||||
|
|
||||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||||
#define _line std::to_string(__LINE__)
|
#define _line std::to_string(__LINE__)
|
||||||
@@ -161,13 +169,13 @@ void RegisterThread(const std::string& str);
|
|||||||
#else
|
#else
|
||||||
#define _function_name std::string(__func__)
|
#define _function_name std::string(__func__)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
#define DEBUG
|
#define DEBUG
|
||||||
#endif
|
#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
|
||||||
// each info/debug/warn... call instead of the 'filename:line' format.
|
// each info/debug/warn... call instead of the 'filename:line' format.
|
||||||
#if defined(BMP_FULL_FUNCTION_NAMES)
|
#if defined(BMP_FULL_FUNCTION_NAMES)
|
||||||
@@ -177,7 +185,7 @@ void RegisterThread(const std::string& str);
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
#endif // defined(DEBUG)
|
#endif // defined(DEBUG)
|
||||||
|
|
||||||
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
||||||
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
||||||
#define beammp_error(x) \
|
#define beammp_error(x) \
|
||||||
@@ -188,10 +196,6 @@ void RegisterThread(const std::string& str);
|
|||||||
do { \
|
do { \
|
||||||
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_lua_log(level, plugin, x) \
|
|
||||||
do { \
|
|
||||||
Application::Console().Write(_this_location + fmt::format("[{}] [{}] ", plugin, level) + (x)); \
|
|
||||||
} while (false)
|
|
||||||
#define beammp_lua_warn(x) \
|
#define beammp_lua_warn(x) \
|
||||||
do { \
|
do { \
|
||||||
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||||
@@ -199,13 +203,13 @@ void RegisterThread(const std::string& str);
|
|||||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||||
#define beammp_debug(x) \
|
#define beammp_debug(x) \
|
||||||
do { \
|
do { \
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_event(x) \
|
#define beammp_event(x) \
|
||||||
do { \
|
do { \
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
@@ -213,14 +217,14 @@ void RegisterThread(const std::string& str);
|
|||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
#define beammp_trace(x) \
|
#define beammp_trace(x) \
|
||||||
do { \
|
do { \
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#else
|
#else
|
||||||
#define beammp_trace(x)
|
#define beammp_trace(x)
|
||||||
#endif // defined(DEBUG)
|
#endif // defined(DEBUG)
|
||||||
|
|
||||||
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||||
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||||
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||||
@@ -247,7 +251,6 @@ void RegisterThread(const std::string& str);
|
|||||||
#define beammp_tracef(...) beammp_trace(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_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||||
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||||
#define beammp_lua_log(level, plugin, x) /* x */
|
|
||||||
|
|
||||||
#endif // DOCTEST_CONFIG_DISABLE
|
#endif // DOCTEST_CONFIG_DISABLE
|
||||||
|
|
||||||
@@ -262,14 +265,5 @@ void RegisterThread(const std::string& 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::vector<uint8_t> Comp(std::span<const uint8_t> input);
|
|
||||||
std::vector<uint8_t> DeComp(std::span<const uint8_t> input);
|
|
||||||
|
|
||||||
std::string GetPlatformAgnosticErrorString();
|
std::string GetPlatformAgnosticErrorString();
|
||||||
#define S_DSN SU_RAW
|
#define S_DSN SU_RAW
|
||||||
|
|
||||||
class InvalidDataError : std::runtime_error {
|
|
||||||
public:
|
|
||||||
InvalidDataError() : std::runtime_error("Invalid data") {
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
+1
-29
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Environment.h"
|
#include "Environment.h"
|
||||||
@@ -27,17 +9,7 @@
|
|||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
char _getch();
|
char _getch();
|
||||||
#endif // linux
|
#endif // unix
|
||||||
|
|
||||||
#ifdef BEAMMP_FREEBSD
|
|
||||||
#include <errno.h>
|
|
||||||
#include <termios.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
char _getch();
|
|
||||||
// macros 'major' and 'minor' need to be undefined on FreeBSD to avoid naming collision with system headers
|
|
||||||
#undef major
|
|
||||||
#undef minor
|
|
||||||
#endif // freebsd
|
|
||||||
|
|
||||||
// ======================= APPLE ========================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
|
|||||||
+1
-17
@@ -1,20 +1,4 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
// Copyright Anonymous275 8/11/2020
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include <array>
|
#include <array>
|
||||||
|
|||||||
+4
-21
@@ -1,20 +1,4 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
// Author: lionkor
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Asserts are to be used anywhere where assumptions about state are made
|
* Asserts are to be used anywhere where assumptions about state are made
|
||||||
@@ -32,7 +16,6 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
|
||||||
|
|
||||||
static const char* const ANSI_RESET = "\u001b[0m";
|
static const char* const ANSI_RESET = "\u001b[0m";
|
||||||
|
|
||||||
@@ -57,7 +40,7 @@ static const char* const ANSI_WHITE_BOLD = "\u001b[37;1m";
|
|||||||
static const char* const ANSI_BOLD = "\u001b[1m";
|
static const char* const ANSI_BOLD = "\u001b[1m";
|
||||||
static const char* const ANSI_UNDERLINE = "\u001b[4m";
|
static const char* const ANSI_UNDERLINE = "\u001b[4m";
|
||||||
|
|
||||||
#if defined(DEBUG) && !defined(BEAMMP_FREEBSD)
|
#ifdef DEBUG
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
|
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
|
||||||
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
|
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
|
||||||
@@ -82,8 +65,8 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_assert_not_reachable() \
|
#define beammp_assert_not_reachable() \
|
||||||
do { \
|
do { \
|
||||||
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||||
} while (false)
|
} while (false)
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <optional>
|
#include <optional>
|
||||||
@@ -25,8 +7,6 @@ namespace Env {
|
|||||||
enum class Key {
|
enum class Key {
|
||||||
// provider settings
|
// provider settings
|
||||||
PROVIDER_UPDATE_MESSAGE,
|
PROVIDER_UPDATE_MESSAGE,
|
||||||
PROVIDER_DISABLE_CONFIG,
|
|
||||||
PROVIDER_PORT_ENV,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
std::optional<std::string> Get(Key key);
|
std::optional<std::string> Get(Key key);
|
||||||
|
|||||||
+2
-22
@@ -1,33 +1,13 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
|
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE) && !defined(BEAMMP_FREEBSD)
|
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE)
|
||||||
#if defined(_WIN32) || defined(__CYGWIN__)
|
#if defined(_WIN32) || defined(__CYGWIN__)
|
||||||
#define BEAMMP_WINDOWS
|
#define BEAMMP_WINDOWS
|
||||||
#elif defined(__linux__) || defined(__linux) || defined(linux)
|
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__unix__) || defined(__unix) || defined(unix)
|
||||||
#define BEAMMP_LINUX
|
#define BEAMMP_LINUX
|
||||||
#elif defined(__FreeBSD__)
|
|
||||||
#define BEAMMP_FREEBSD
|
|
||||||
#elif defined(__APPLE__) || defined(__MACH__)
|
#elif defined(__APPLE__) || defined(__MACH__)
|
||||||
#define BEAMMP_APPLE
|
#define BEAMMP_APPLE
|
||||||
#else
|
#else
|
||||||
|
|||||||
+2
-21
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <Common.h>
|
#include <Common.h>
|
||||||
@@ -23,7 +5,6 @@
|
|||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <curl/curl.h>
|
|
||||||
|
|
||||||
#if defined(BEAMMP_LINUX)
|
#if defined(BEAMMP_LINUX)
|
||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
@@ -39,8 +20,8 @@
|
|||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
namespace Http {
|
namespace Http {
|
||||||
std::string GET(const std::string& url, unsigned int* status = nullptr);
|
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
||||||
std::string POST(const std::string& url, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const std::map<std::string, std::string>& headers = {});
|
std::string POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const httplib::Headers& headers = {});
|
||||||
namespace Status {
|
namespace Status {
|
||||||
std::string ToString(int code);
|
std::string ToString(int code);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-23
@@ -1,23 +1,6 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
// pure virtual class to be inherited from by classes which intend to be threaded
|
// pure virtual class to be inherited from by classes which intend to be threaded
|
||||||
@@ -27,16 +10,14 @@ public:
|
|||||||
// invokes operator() on this object
|
// invokes operator() on this object
|
||||||
: mThread() { }
|
: mThread() { }
|
||||||
virtual ~IThreaded() noexcept {
|
virtual ~IThreaded() noexcept {
|
||||||
if (mThread.joinable()) {
|
mThread.interrupt();
|
||||||
mThread.join();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
virtual void Start() final {
|
virtual void Start() final {
|
||||||
mThread = std::thread([this] { (*this)(); });
|
mThread = boost::scoped_thread<>([this] { (*this)(); });
|
||||||
}
|
}
|
||||||
virtual void operator()() = 0;
|
virtual void operator()() = 0;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
std::thread mThread;
|
boost::scoped_thread<> mThread {};
|
||||||
};
|
};
|
||||||
|
|||||||
+3
-17
@@ -1,23 +1,9 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
//
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
// Created by anon on 4/21/21.
|
||||||
//
|
//
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include "rapidjson/document.h"
|
|
||||||
#include "rapidjson/prettywriter.h"
|
|
||||||
#include "rapidjson/stringbuffer.h"
|
#include "rapidjson/stringbuffer.h"
|
||||||
|
#include "rapidjson/prettywriter.h"
|
||||||
|
#include "rapidjson/document.h"
|
||||||
#include "rapidjson/writer.h"
|
#include "rapidjson/writer.h"
|
||||||
|
|||||||
+1
-21
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
@@ -32,13 +14,11 @@ namespace MP {
|
|||||||
std::tuple<int, int, int> GetServerVersion();
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
std::pair<bool, std::string> 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->Network()->authenticated_client_count(); }
|
||||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||||
std::pair<bool, std::string> SendNotification(int ID, const std::string& Message, const std::string& Icon, const std::string& Category);
|
|
||||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||||
void Set(int ConfigID, sol::object NewValue);
|
void Set(int ConfigID, sol::object NewValue);
|
||||||
TLuaValue Get(int ConfigID);
|
|
||||||
bool IsPlayerGuest(int ID);
|
bool IsPlayerGuest(int ID);
|
||||||
bool IsPlayerConnected(int ID);
|
bool IsPlayerConnected(int ID);
|
||||||
void Sleep(size_t Ms);
|
void Sleep(size_t Ms);
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Common.h"
|
||||||
|
#include "Packet.h"
|
||||||
|
#include "State.h"
|
||||||
|
#include "Sync.h"
|
||||||
|
#include "Transport.h"
|
||||||
|
#include "Util.h"
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/asio/execution_context.hpp>
|
||||||
|
#include <boost/asio/thread_pool.hpp>
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
|
#include <boost/thread/synchronized_value.hpp>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <glm/detail/qualifier.hpp>
|
||||||
|
#include <glm/vec3.hpp>
|
||||||
|
#include <glm/vec4.hpp>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
#include <optional>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using ClientID = uint32_t;
|
||||||
|
using VehicleID = uint16_t;
|
||||||
|
|
||||||
|
using namespace boost::asio;
|
||||||
|
|
||||||
|
struct Client : std::enable_shared_from_this<Client> {
|
||||||
|
using StrandPtr = std::shared_ptr<boost::asio::strand<ip::tcp::socket::executor_type>>;
|
||||||
|
using Ptr = std::shared_ptr<Client>;
|
||||||
|
|
||||||
|
ClientID id;
|
||||||
|
Sync<bmp::State> state { bmp::State::None };
|
||||||
|
|
||||||
|
Sync<std::string> name;
|
||||||
|
Sync<std::string> role;
|
||||||
|
Sync<bool> is_guest;
|
||||||
|
Sync<std::unordered_map<std::string /* identifier */, std::string /* value */>> identifiers;
|
||||||
|
/// Writes the packet to the TCP stream. Blocks all other writes.
|
||||||
|
void tcp_write(bmp::Packet& packet);
|
||||||
|
/// Writes the specified to the TCP stream without a header or any metadata - use in
|
||||||
|
/// conjunction with something else. Blocks other writes.
|
||||||
|
void tcp_write_file_raw(const std::filesystem::path& path);
|
||||||
|
|
||||||
|
/// Ensures no client is ever created as a non-shared-ptr, so that enable_shared_from_this works.
|
||||||
|
static Client::Ptr make_ptr(ClientID new_id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||||
|
~Client();
|
||||||
|
|
||||||
|
ip::tcp::socket& tcp_socket() { return m_tcp_socket; }
|
||||||
|
|
||||||
|
void start_tcp();
|
||||||
|
|
||||||
|
/// Used to associate the udp socket with this client.
|
||||||
|
/// This isn't very secure and still allows spoofing of the UDP connection (technically),
|
||||||
|
/// but better than simply using the ID like the old protocol.
|
||||||
|
const uint64_t udp_magic;
|
||||||
|
|
||||||
|
const ip::udp::endpoint& udp_endpoint() const { return m_udp_endpoint; }
|
||||||
|
void set_udp_endpoint(const ip::udp::endpoint& ep) { m_udp_endpoint = ep; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
/// Ctor must be private to ensure all clients are constructed as shared_ptr to enable_shared_from_this.
|
||||||
|
Client(ClientID id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||||
|
/// Call this when the client seems to have timed out. Will send a ping and set a flag.
|
||||||
|
/// Returns true if try-again, false if the connection was closed.
|
||||||
|
[[nodiscard]] bool handle_timeout();
|
||||||
|
bool m_timed_out { false };
|
||||||
|
|
||||||
|
/// Timeout used for typical tcp reads.
|
||||||
|
boost::posix_time::milliseconds m_read_timeout { 5000 };
|
||||||
|
/// Timeout used for typical tcp writes. Specified in milliseconds per byte.
|
||||||
|
/// For example, 10 mbit/s works out to 1250 B/ms, so a value of 1250 here would
|
||||||
|
/// cause clients with >10 mbit/s download speed to usually not time out.
|
||||||
|
/// This is done because a write is considered completed when all data is written,
|
||||||
|
/// and worst-case this could mean that we're limited by their download speed.
|
||||||
|
/// We're setting it to 50, which will drop clients who are below a download speed + ping
|
||||||
|
/// combination of 0.4 mbit/s.
|
||||||
|
double m_write_byte_timeout { 0.01 };
|
||||||
|
/// Timeout used for mod download tcp writes.
|
||||||
|
/// This is typically orders of magnitude larger
|
||||||
|
/// to allow for slow downloads.
|
||||||
|
boost::posix_time::milliseconds m_download_write_timeout { 60000 };
|
||||||
|
|
||||||
|
std::mutex m_tcp_read_mtx;
|
||||||
|
std::mutex m_tcp_write_mtx;
|
||||||
|
std::mutex m_udp_read_mtx;
|
||||||
|
|
||||||
|
ip::tcp::socket m_tcp_socket;
|
||||||
|
|
||||||
|
boost::scoped_thread<> m_tcp_thread;
|
||||||
|
|
||||||
|
std::vector<uint8_t> m_header { bmp::Header::SERIALIZED_SIZE };
|
||||||
|
bmp::Packet m_packet {};
|
||||||
|
|
||||||
|
ip::udp::endpoint m_udp_endpoint;
|
||||||
|
|
||||||
|
class Network& m_network;
|
||||||
|
|
||||||
|
StrandPtr m_tcp_strand;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Vehicle {
|
||||||
|
using Ptr = std::shared_ptr<Vehicle>;
|
||||||
|
Sync<ClientID> owner;
|
||||||
|
Sync<std::vector<uint8_t>> data;
|
||||||
|
|
||||||
|
Vehicle(std::span<uint8_t> raw_data)
|
||||||
|
: data(std::vector<uint8_t>(raw_data.begin(), raw_data.end())) {
|
||||||
|
reset_status(data.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets all status fields to zero and reads any statuses present in the data into the fields.
|
||||||
|
void reset_status(std::span<const uint8_t> status_data);
|
||||||
|
|
||||||
|
struct Status {
|
||||||
|
glm::vec3 rvel {};
|
||||||
|
glm::vec4 rot {};
|
||||||
|
glm::vec3 vel {};
|
||||||
|
glm::vec3 pos {};
|
||||||
|
float time {};
|
||||||
|
};
|
||||||
|
|
||||||
|
Status get_status();
|
||||||
|
|
||||||
|
void update_status(std::span<const uint8_t> raw_packet);
|
||||||
|
|
||||||
|
const std::vector<uint8_t>& get_raw_status() const { return m_status_data; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::recursive_mutex m_mtx;
|
||||||
|
|
||||||
|
/// Holds pos, rvel, vel, etc. raw, updated every time
|
||||||
|
/// such a packet arrives.
|
||||||
|
std::vector<uint8_t> m_status_data;
|
||||||
|
|
||||||
|
/// Parses the status_data on request sets needs_refresh = false.
|
||||||
|
void refresh_cache(std::unique_lock<std::recursive_mutex>& lock);
|
||||||
|
|
||||||
|
bool m_needs_refresh = false;
|
||||||
|
glm::vec3 m_rvel {};
|
||||||
|
glm::vec4 m_rot {};
|
||||||
|
glm::vec3 m_vel {};
|
||||||
|
glm::vec3 m_pos {};
|
||||||
|
float m_time {};
|
||||||
|
};
|
||||||
|
|
||||||
|
class Network {
|
||||||
|
public:
|
||||||
|
Network();
|
||||||
|
~Network();
|
||||||
|
|
||||||
|
friend Client;
|
||||||
|
|
||||||
|
void disconnect(ClientID id, const std::string& msg);
|
||||||
|
|
||||||
|
void send_to(ClientID id, bmp::Packet& packet);
|
||||||
|
|
||||||
|
/// Returns a map of <id, client> containing only clients which are
|
||||||
|
/// fully connected, i.e. who have mods downloaded and everything spawned in.
|
||||||
|
/// If you're unsure which to use, use this one.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> playing_clients() const;
|
||||||
|
/// Returns a map of <id, client> containing only clients who are authenticated.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> authenticated_clients() const;
|
||||||
|
/// Returns all clients, including non-authenticated clients. Use only for debugging,
|
||||||
|
/// information, stats, status.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> all_clients() const;
|
||||||
|
|
||||||
|
std::optional<Client::Ptr> get_client(ClientID id, bmp::State min_state) const;
|
||||||
|
|
||||||
|
std::unordered_map<VehicleID, Vehicle::Ptr> get_vehicles_owned_by(ClientID id);
|
||||||
|
|
||||||
|
std::optional<Vehicle::Ptr> get_vehicle(VehicleID id);
|
||||||
|
|
||||||
|
/// Builds the SessionSetup.PlayersInfo json which contains all player info and all vehicles.
|
||||||
|
nlohmann::json build_players_info();
|
||||||
|
|
||||||
|
size_t authenticated_client_count() const;
|
||||||
|
|
||||||
|
size_t clients_in_state_count(bmp::State state) const;
|
||||||
|
|
||||||
|
size_t guest_count() const;
|
||||||
|
|
||||||
|
size_t vehicle_count() const;
|
||||||
|
|
||||||
|
/// Creates a Playing state packet from uncompressed data.
|
||||||
|
bmp::Packet make_playing_packet(bmp::Purpose purpose, ClientID from_id, VehicleID veh_id, const std::vector<uint8_t>& data);
|
||||||
|
|
||||||
|
/// Sends a <System> or <Server> chat message to all or only one client(s).
|
||||||
|
void send_system_chat_message(const std::string& msg, ClientID to = 0xffffffff);
|
||||||
|
|
||||||
|
/// To be called by accept() async handler once an accept() is completed.
|
||||||
|
void accept();
|
||||||
|
|
||||||
|
/// Gets the async i/o context of the network - can be used to "schedule" tasks on it.
|
||||||
|
boost::asio::thread_pool& context() {
|
||||||
|
return m_threadpool;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void handle_packet(ClientID id, const bmp::Packet& packet);
|
||||||
|
|
||||||
|
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
|
||||||
|
bmp::Packet udp_read(ip::udp::endpoint& out_ep);
|
||||||
|
/// Sends a packet to the specified UDP endpoint via the UDP socket.
|
||||||
|
void udp_write(bmp::Packet& packet, const ip::udp::endpoint& ep);
|
||||||
|
|
||||||
|
void udp_read_main();
|
||||||
|
void tcp_listen_main();
|
||||||
|
|
||||||
|
/// Handles all packets which are allowed during the Identification state.
|
||||||
|
void handle_identification(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the Authentication state.
|
||||||
|
void handle_authentication(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the ModDownload state.
|
||||||
|
void handle_mod_download(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the SessionSetup state.
|
||||||
|
void handle_session_setup(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the Playing state.
|
||||||
|
void handle_playing(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
|
||||||
|
/// On failure, throws an exception with the error for the client.
|
||||||
|
static void authenticate_user(const std::string& public_key, std::shared_ptr<Client>& client);
|
||||||
|
|
||||||
|
/// Called by accept() once completed (completion handler).
|
||||||
|
void handle_accept(const boost::system::error_code& ec);
|
||||||
|
|
||||||
|
Sync<std::unordered_map<ClientID, Client::Ptr>> m_clients {};
|
||||||
|
Sync<std::unordered_map<VehicleID, Vehicle::Ptr>> m_vehicles {};
|
||||||
|
Sync<std::unordered_map<uint64_t, ClientID>> m_client_magics {};
|
||||||
|
Sync<std::unordered_map<ip::udp::endpoint, ClientID>> m_udp_endpoints {};
|
||||||
|
|
||||||
|
ClientID new_client_id();
|
||||||
|
VehicleID new_vehicle_id();
|
||||||
|
|
||||||
|
thread_pool m_threadpool { std::thread::hardware_concurrency() };
|
||||||
|
Sync<bool> m_shutdown { false };
|
||||||
|
|
||||||
|
ip::udp::socket m_udp_socket { m_threadpool };
|
||||||
|
|
||||||
|
ip::tcp::socket m_tcp_listener { m_threadpool };
|
||||||
|
ip::tcp::acceptor m_tcp_acceptor { m_threadpool };
|
||||||
|
/// This socket gets accepted into, and is then moved.
|
||||||
|
ip::tcp::socket m_temp_socket { m_threadpool };
|
||||||
|
|
||||||
|
boost::scoped_thread<> m_tcp_listen_thread;
|
||||||
|
boost::scoped_thread<> m_udp_read_thread;
|
||||||
|
};
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <boost/thread/synchronized_value.hpp>
|
|
||||||
#include <chrono>
|
|
||||||
#include <cstddef>
|
|
||||||
#include <limits>
|
|
||||||
#include <unordered_map>
|
|
||||||
|
|
||||||
#undef max
|
|
||||||
#undef min
|
|
||||||
|
|
||||||
namespace prof {
|
|
||||||
|
|
||||||
using Duration = std::chrono::duration<double, std::milli>;
|
|
||||||
using TimePoint = std::chrono::high_resolution_clock::time_point;
|
|
||||||
|
|
||||||
/// Returns the current time.
|
|
||||||
TimePoint now();
|
|
||||||
|
|
||||||
/// Returns a sub-millisecond resolution duration between start and end.
|
|
||||||
Duration duration(const TimePoint& start, const TimePoint& end);
|
|
||||||
|
|
||||||
struct Stats {
|
|
||||||
double mean;
|
|
||||||
double stdev;
|
|
||||||
double min;
|
|
||||||
double max;
|
|
||||||
size_t n;
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Calculates and stores the moving average over K samples of execution time data
|
|
||||||
/// for some single unit of code. Threadsafe.
|
|
||||||
struct UnitExecutionTime {
|
|
||||||
UnitExecutionTime();
|
|
||||||
|
|
||||||
/// Adds a sample to the collection, overriding the oldest sample if needed.
|
|
||||||
void add_sample(const Duration& dur);
|
|
||||||
|
|
||||||
/// Calculates the mean duration over the `measurement_count()` measurements,
|
|
||||||
/// as well as the standard deviation.
|
|
||||||
Stats stats() const;
|
|
||||||
|
|
||||||
/// Returns the number of elements the moving average is calculated over.
|
|
||||||
size_t measurement_count() const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
mutable std::mutex m_mtx {};
|
|
||||||
size_t m_total_calls {};
|
|
||||||
double m_sum {};
|
|
||||||
// sum of measurements squared (for running stdev)
|
|
||||||
double m_measurement_sqr_sum {};
|
|
||||||
double m_min { std::numeric_limits<double>::max() };
|
|
||||||
double m_max { std::numeric_limits<double>::min() };
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Holds profiles for multiple units by name. Threadsafe.
|
|
||||||
struct UnitProfileCollection {
|
|
||||||
/// Adds a sample to the collection, overriding the oldest sample if needed.
|
|
||||||
void add_sample(const std::string& unit, const Duration& duration);
|
|
||||||
|
|
||||||
/// Calculates the mean duration over the `measurement_count()` measurements,
|
|
||||||
/// as well as the standard deviation.
|
|
||||||
Stats stats(const std::string& unit);
|
|
||||||
|
|
||||||
/// Returns the number of elements the moving average is calculated over.
|
|
||||||
size_t measurement_count(const std::string& unit);
|
|
||||||
|
|
||||||
/// Returns the stats for all stored units.
|
|
||||||
std::unordered_map<std::string, Stats> all_stats();
|
|
||||||
|
|
||||||
private:
|
|
||||||
boost::synchronized_value<std::unordered_map<std::string, UnitExecutionTime>> m_map;
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
+2
-19
@@ -1,21 +1,4 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
// Author: lionkor
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -23,8 +6,8 @@
|
|||||||
* and write locks and read locks are mutually exclusive.
|
* and write locks and read locks are mutually exclusive.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <mutex>
|
|
||||||
#include <shared_mutex>
|
#include <shared_mutex>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
// Use ReadLock(m) and WriteLock(m) to lock it.
|
// Use ReadLock(m) and WriteLock(m) to lock it.
|
||||||
using RWMutex = std::shared_mutex;
|
using RWMutex = std::shared_mutex;
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include "Sync.h"
|
|
||||||
#include <concepts>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <doctest/doctest.h>
|
|
||||||
#include <fmt/core.h>
|
|
||||||
#include <fmt/format.h>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <variant>
|
|
||||||
|
|
||||||
struct ComposedKey {
|
|
||||||
std::string Category;
|
|
||||||
std::string Key;
|
|
||||||
|
|
||||||
bool operator==(const ComposedKey& rhs) const {
|
|
||||||
return (this->Category == rhs.Category && this->Key == rhs.Key);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template <>
|
|
||||||
struct fmt::formatter<ComposedKey> : formatter<std::string> {
|
|
||||||
auto format(ComposedKey key, format_context& ctx) const;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline auto fmt::formatter<ComposedKey>::format(ComposedKey key, fmt::format_context& ctx) const {
|
|
||||||
std::string key_metadata = fmt::format("{}::{}", key.Category, key.Key);
|
|
||||||
return formatter<std::string>::format(key_metadata, ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace std {
|
|
||||||
template <>
|
|
||||||
class hash<ComposedKey> {
|
|
||||||
public:
|
|
||||||
std::uint64_t operator()(const ComposedKey& key) const {
|
|
||||||
std::hash<std::string> hash_fn;
|
|
||||||
return hash_fn(key.Category + key.Key);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Settings {
|
|
||||||
using SettingsTypeVariant = std::variant<std::string, bool, int>;
|
|
||||||
|
|
||||||
Settings();
|
|
||||||
|
|
||||||
enum Key {
|
|
||||||
// Keys that correspond to the keys set in TOML
|
|
||||||
// Keys have their TOML section name as prefix
|
|
||||||
|
|
||||||
// [Misc]
|
|
||||||
Misc_ImScaredOfUpdates,
|
|
||||||
Misc_UpdateReminderTime,
|
|
||||||
|
|
||||||
// [General]
|
|
||||||
General_Description,
|
|
||||||
General_Tags,
|
|
||||||
General_MaxPlayers,
|
|
||||||
General_Name,
|
|
||||||
General_Map,
|
|
||||||
General_AuthKey,
|
|
||||||
General_Private,
|
|
||||||
General_Port,
|
|
||||||
General_MaxCars,
|
|
||||||
General_LogChat,
|
|
||||||
General_ResourceFolder,
|
|
||||||
General_Debug,
|
|
||||||
General_AllowGuests,
|
|
||||||
General_InformationPacket,
|
|
||||||
};
|
|
||||||
|
|
||||||
Sync<std::unordered_map<Key, SettingsTypeVariant>> SettingsMap;
|
|
||||||
enum SettingsAccessMask {
|
|
||||||
READ_ONLY, // Value can be read from console
|
|
||||||
READ_WRITE, // Value can be read and written to from console
|
|
||||||
NO_ACCESS // Value is inaccessible from console (no read OR write)
|
|
||||||
};
|
|
||||||
|
|
||||||
using SettingsAccessControl = std::pair<
|
|
||||||
Key, // The Key's corresponding enum encoding
|
|
||||||
SettingsAccessMask // Console read/write permissions
|
|
||||||
>;
|
|
||||||
|
|
||||||
Sync<std::unordered_map<ComposedKey, SettingsAccessControl>> InputAccessMapping;
|
|
||||||
std::string getAsString(Key key);
|
|
||||||
|
|
||||||
int getAsInt(Key key);
|
|
||||||
|
|
||||||
bool getAsBool(Key key);
|
|
||||||
|
|
||||||
SettingsTypeVariant get(Key key);
|
|
||||||
|
|
||||||
void set(Key key, const std::string& value);
|
|
||||||
|
|
||||||
template <typename Integer, std::enable_if_t<std::is_same_v<Integer, int>, bool> = true>
|
|
||||||
void set(Key key, Integer value) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(int)" };
|
|
||||||
}
|
|
||||||
if (!std::holds_alternative<int>(map->at(key))) {
|
|
||||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(int): index {}", map->at(key).index()) };
|
|
||||||
}
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
template <typename Boolean, std::enable_if_t<std::is_same_v<bool, Boolean>, bool> = true>
|
|
||||||
void set(Key key, Boolean value) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(bool)" };
|
|
||||||
}
|
|
||||||
if (!std::holds_alternative<bool>(map->at(key))) {
|
|
||||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(bool): index {}", map->at(key).index()) };
|
|
||||||
}
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::unordered_map<ComposedKey, SettingsAccessControl> getAccessControlMap() const;
|
|
||||||
SettingsAccessControl getConsoleInputAccessMapping(const ComposedKey& keyName);
|
|
||||||
|
|
||||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, const std::string& value);
|
|
||||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, int value);
|
|
||||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, bool value);
|
|
||||||
};
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
void SetupSignalHandlers();
|
void SetupSignalHandlers();
|
||||||
|
|||||||
+2
-1
@@ -5,5 +5,6 @@
|
|||||||
|
|
||||||
/// This header provides convenience aliases for synchronization primitives.
|
/// This header provides convenience aliases for synchronization primitives.
|
||||||
|
|
||||||
template <typename T>
|
template<typename T>
|
||||||
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
||||||
|
|
||||||
|
|||||||
+4
-22
@@ -1,25 +1,6 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Settings.h"
|
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
@@ -36,17 +17,18 @@ public:
|
|||||||
[[nodiscard]] bool Failed() const { return mFailed; }
|
[[nodiscard]] bool Failed() const { return mFailed; }
|
||||||
|
|
||||||
void FlushToFile();
|
void FlushToFile();
|
||||||
void PrintDebug();
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void CreateConfigFile();
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, Settings::Key key);
|
void PrintDebug();
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
std::string TagsAsPrettyArray() const;
|
std::string TagsAsPrettyArray() const;
|
||||||
bool IsDefault();
|
bool IsDefault();
|
||||||
bool mFailed { false };
|
bool mFailed { false };
|
||||||
bool mDisableConfig { false };
|
|
||||||
std::string mConfigFileName;
|
std::string mConfigFileName;
|
||||||
};
|
};
|
||||||
|
|||||||
+26
-20
@@ -1,24 +1,7 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Cryptography.h"
|
#include "Cryptography.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include "commandline.h"
|
#include "commandline.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
@@ -28,6 +11,30 @@
|
|||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#include <boost/container/deque.hpp>
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
|
#include <boost/thread/synchronized_value.hpp>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
|
#include <spdlog/details/null_mutex.h>
|
||||||
|
#include <spdlog/sinks/base_sink.h>
|
||||||
|
#include <spdlog/sinks/sink.h>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
class TConsole;
|
||||||
|
|
||||||
|
class ConsoleSink : public spdlog::sinks::base_sink<spdlog::details::null_mutex> {
|
||||||
|
public:
|
||||||
|
ConsoleSink(TConsole& console);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void sink_it_(const spdlog::details::log_msg& msg) override;
|
||||||
|
void flush_() override;
|
||||||
|
|
||||||
|
TConsole* m_console;
|
||||||
|
};
|
||||||
|
|
||||||
class TLuaEngine;
|
class TLuaEngine;
|
||||||
|
|
||||||
@@ -58,7 +65,6 @@ private:
|
|||||||
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
||||||
void Command_Version(const std::string& cmd, const std::vector<std::string>& args);
|
|
||||||
|
|
||||||
void Command_Say(const std::string& FullCommand);
|
void Command_Say(const std::string& FullCommand);
|
||||||
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
||||||
@@ -76,7 +82,6 @@ private:
|
|||||||
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
||||||
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
||||||
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||||
{ "version", [this](const auto& a, const auto& b) { Command_Version(a, b); } },
|
|
||||||
};
|
};
|
||||||
|
|
||||||
std::unique_ptr<Commandline> mCommandline { nullptr };
|
std::unique_ptr<Commandline> mCommandline { nullptr };
|
||||||
@@ -89,4 +94,5 @@ private:
|
|||||||
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
||||||
std::ofstream mLogFileStream;
|
std::ofstream mLogFileStream;
|
||||||
std::mutex mLogFileStreamMtx;
|
std::mutex mLogFileStreamMtx;
|
||||||
|
TScopedTimer mUptimeTimer{};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,39 +1,18 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "IThreaded.h"
|
#include "IThreaded.h"
|
||||||
#include "TResourceManager.h"
|
#include "Network.h"
|
||||||
#include "TServer.h"
|
|
||||||
|
|
||||||
class THeartbeatThread : public IThreaded {
|
class THeartbeatThread : public IThreaded {
|
||||||
public:
|
public:
|
||||||
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server);
|
THeartbeatThread(std::shared_ptr<Network> network);
|
||||||
//~THeartbeatThread();
|
//~THeartbeatThread();
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
static inline std::string lastCall = "";
|
|
||||||
private:
|
private:
|
||||||
std::string GenerateCall();
|
std::string GenerateCall();
|
||||||
std::string GetPlayers();
|
std::string GetPlayers();
|
||||||
|
|
||||||
TResourceManager& mResourceManager;
|
std::shared_ptr<Network> m_network;
|
||||||
TServer& mServer;
|
|
||||||
};
|
};
|
||||||
|
|||||||
+30
-72
@@ -1,28 +1,10 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Profiling.h"
|
#include "Common.h"
|
||||||
#include "TNetwork.h"
|
#include "IThreaded.h"
|
||||||
#include "TServer.h"
|
#include "Network.h"
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <chrono>
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <initializer_list>
|
#include <initializer_list>
|
||||||
@@ -30,7 +12,6 @@
|
|||||||
#include <lua.hpp>
|
#include <lua.hpp>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
@@ -39,34 +20,19 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#define SOL_ALL_SAFETIES_ON 1
|
#define SOL_ALL_SAFETIES_ON 1
|
||||||
#define SOL_USER_C_ASSERT SOL_ON
|
|
||||||
#define SOL_C_ASSERT(...) \
|
|
||||||
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__)
|
|
||||||
#include <sol/sol.hpp>
|
#include <sol/sol.hpp>
|
||||||
|
|
||||||
struct JsonString {
|
|
||||||
std::string value;
|
|
||||||
};
|
|
||||||
|
|
||||||
// value used to keep nils in a table or array, across serialization boundaries like
|
|
||||||
// JsonEncode, so that the nil stays at the same index and isn't treated like a special
|
|
||||||
// value (e.g. one that can be ignored or discarded).
|
|
||||||
const inline std::string BEAMMP_INTERNAL_NIL = "BEAMMP_SERVER_INTERNAL_NIL_VALUE";
|
|
||||||
|
|
||||||
using TLuaStateId = std::string;
|
using TLuaStateId = std::string;
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
/**
|
/**
|
||||||
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
||||||
*/
|
*/
|
||||||
using TLuaValue = std::variant<std::string, int, JsonString, bool, std::unordered_map<std::string, std::string>, float>;
|
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
|
||||||
enum TLuaType {
|
static constexpr size_t TLuaArgTypes_String = 0;
|
||||||
String = 0,
|
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||||
Int = 1,
|
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||||
Json = 2,
|
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||||
Bool = 3,
|
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||||
StringStringMap = 4,
|
|
||||||
Float = 5,
|
|
||||||
};
|
|
||||||
|
|
||||||
class TLuaPlugin;
|
class TLuaPlugin;
|
||||||
|
|
||||||
@@ -104,7 +70,7 @@ struct TLuaChunk {
|
|||||||
std::string PluginPath;
|
std::string PluginPath;
|
||||||
};
|
};
|
||||||
|
|
||||||
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
|
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine> {
|
||||||
public:
|
public:
|
||||||
enum CallStrategy : int {
|
enum CallStrategy : int {
|
||||||
BestEffort,
|
BestEffort,
|
||||||
@@ -114,7 +80,7 @@ public:
|
|||||||
struct QueuedFunction {
|
struct QueuedFunction {
|
||||||
std::string FunctionName;
|
std::string FunctionName;
|
||||||
std::shared_ptr<TLuaResult> Result;
|
std::shared_ptr<TLuaResult> Result;
|
||||||
std::vector<TLuaValue> Args;
|
std::vector<TLuaArgTypes> Args;
|
||||||
std::string EventName; // optional, may be empty
|
std::string EventName; // optional, may be empty
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -123,13 +89,11 @@ public:
|
|||||||
beammp_debug("Lua Engine terminated");
|
beammp_debug("Lua Engine terminated");
|
||||||
}
|
}
|
||||||
|
|
||||||
void operator()() override;
|
void Start();
|
||||||
|
|
||||||
TNetwork& Network() { return *mNetwork; }
|
std::shared_ptr<::Network> Network() { return mNetwork; }
|
||||||
TServer& Server() { return *mServer; }
|
|
||||||
|
|
||||||
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
|
void SetNetwork(const std::shared_ptr<::Network>& network) { mNetwork = network; }
|
||||||
void SetServer(TServer* Server) { mServer = Server; }
|
|
||||||
|
|
||||||
size_t GetResultsToCheckSize() {
|
size_t GetResultsToCheckSize() {
|
||||||
std::unique_lock Lock(mResultsToCheckMutex);
|
std::unique_lock Lock(mResultsToCheckMutex);
|
||||||
@@ -167,7 +131,7 @@ public:
|
|||||||
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
||||||
bool HasState(TLuaStateId StateId);
|
bool HasState(TLuaStateId StateId);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||||
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||||
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||||
/**
|
/**
|
||||||
@@ -187,14 +151,12 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||||
|
|
||||||
for (const auto& Event : mLuaEvents.at(EventName)) {
|
for (const auto& Event : mLuaEvents.at(EventName)) {
|
||||||
for (const auto& Function : Event.second) {
|
for (const auto& Function : Event.second) {
|
||||||
if (Event.first != IgnoreId) {
|
if (Event.first != IgnoreId) {
|
||||||
auto Result = EnqueueFunctionCall(Event.first, Function, Arguments, EventName);
|
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments));
|
||||||
Results.push_back(Result);
|
|
||||||
AddResultToCheck(Result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,10 +170,10 @@ public:
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||||
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||||
for (const auto& Handler : Handlers) {
|
for (const auto& Handler : Handlers) {
|
||||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments, EventName));
|
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||||
}
|
}
|
||||||
return Results;
|
return Results;
|
||||||
}
|
}
|
||||||
@@ -239,17 +201,17 @@ private:
|
|||||||
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||||
size_t CalculateMemoryUsage();
|
size_t CalculateMemoryUsage();
|
||||||
|
|
||||||
class StateThreadData : IThreaded {
|
class StateThreadData {
|
||||||
public:
|
public:
|
||||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||||
StateThreadData(const StateThreadData&) = delete;
|
StateThreadData(const StateThreadData&) = delete;
|
||||||
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||||
void operator()() override;
|
void Start();
|
||||||
sol::state_view State() { return sol::state_view(mState); }
|
sol::state_view State() { return sol::state_view(mState); }
|
||||||
|
|
||||||
std::vector<std::string> GetStateGlobalKeys();
|
std::vector<std::string> GetStateGlobalKeys();
|
||||||
@@ -259,28 +221,24 @@ private:
|
|||||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||||
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
||||||
|
|
||||||
|
sol::table Lua_JsonDecode(const std::string& str);
|
||||||
|
|
||||||
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);
|
||||||
sol::table Lua_GetPlayerIdentifiers(int ID);
|
sol::table Lua_GetPlayerIdentifiers(int ID);
|
||||||
std::variant<std::string, sol::nil_t> Lua_GetPlayerRole(int ID);
|
|
||||||
sol::table Lua_GetPlayers();
|
sol::table Lua_GetPlayers();
|
||||||
std::string Lua_GetPlayerName(int ID);
|
std::string Lua_GetPlayerName(int ID);
|
||||||
sol::table Lua_GetPlayerVehicles(int ID);
|
sol::table Lua_GetPlayerVehicles(int ID);
|
||||||
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
|
std::pair<sol::table, std::string> Lua_GetVehicleStatus(int VID);
|
||||||
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
||||||
sol::table Lua_JsonDecode(const std::string& str);
|
|
||||||
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_ListFiles(const std::string& Path);
|
||||||
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||||
|
|
||||||
prof::UnitProfileCollection mProfile {};
|
|
||||||
std::unordered_map<std::string, prof::TimePoint> mProfileStarts;
|
|
||||||
|
|
||||||
std::string mName;
|
std::string mName;
|
||||||
TLuaStateId mStateId;
|
TLuaStateId mStateId;
|
||||||
lua_State* mState;
|
lua_State* mState;
|
||||||
std::thread mThread;
|
|
||||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||||
std::recursive_mutex mStateExecuteQueueMutex;
|
std::recursive_mutex mStateExecuteQueueMutex;
|
||||||
std::vector<QueuedFunction> mStateFunctionQueue;
|
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||||
@@ -292,7 +250,7 @@ private:
|
|||||||
std::recursive_mutex mPathsMutex;
|
std::recursive_mutex mPathsMutex;
|
||||||
std::mt19937 mMersenneTwister;
|
std::mt19937 mMersenneTwister;
|
||||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||||
std::vector<sol::object> JsonStringToArray(JsonString Str);
|
boost::scoped_thread<> mThread;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct TimedEvent {
|
struct TimedEvent {
|
||||||
@@ -305,8 +263,7 @@ private:
|
|||||||
void Reset();
|
void Reset();
|
||||||
};
|
};
|
||||||
|
|
||||||
TNetwork* mNetwork;
|
std::shared_ptr<::Network> mNetwork;
|
||||||
TServer* mServer;
|
|
||||||
const fs::path mResourceServerPath;
|
const fs::path mResourceServerPath;
|
||||||
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
||||||
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
||||||
@@ -318,6 +275,7 @@ private:
|
|||||||
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
||||||
std::mutex mResultsToCheckMutex;
|
std::mutex mResultsToCheckMutex;
|
||||||
std::condition_variable mResultsToCheckCond;
|
std::condition_variable mResultsToCheckCond;
|
||||||
|
boost::scoped_thread<> mThread;
|
||||||
};
|
};
|
||||||
|
|
||||||
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
class TLuaPlugin {
|
class TLuaPlugin {
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Compat.h"
|
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <boost/asio/io_context.hpp>
|
|
||||||
#include <boost/asio/ip/udp.hpp>
|
|
||||||
|
|
||||||
struct TConnection;
|
|
||||||
|
|
||||||
class TNetwork {
|
|
||||||
public:
|
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
|
||||||
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
|
||||||
std::vector<uint8_t> TCPRcv(TClient& c);
|
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
|
||||||
void Identify(TConnection&& client);
|
|
||||||
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
|
||||||
void SyncResources(TClient& c);
|
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
|
||||||
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
|
||||||
void UpdatePlayer(TClient& Client);
|
|
||||||
|
|
||||||
private:
|
|
||||||
void UDPServerMain();
|
|
||||||
void TCPServerMain();
|
|
||||||
|
|
||||||
TServer& mServer;
|
|
||||||
TPPSMonitor& mPPSMonitor;
|
|
||||||
ip::udp::socket mUDPSock;
|
|
||||||
TResourceManager& mResourceManager;
|
|
||||||
std::thread mUDPThread;
|
|
||||||
std::thread mTCPThread;
|
|
||||||
std::mutex mOpenIDMutex;
|
|
||||||
|
|
||||||
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
|
||||||
int OpenID();
|
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
|
||||||
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
|
||||||
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
|
||||||
static void SendFileToClient(TClient& c, size_t Size, const std::string& Name);
|
|
||||||
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
|
||||||
};
|
|
||||||
|
|
||||||
std::string HashPassword(const std::string& str);
|
|
||||||
std::vector<uint8_t> StringToVector(const std::string& Str);
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "Common.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
class TNetwork;
|
|
||||||
|
|
||||||
class TPPSMonitor : public IThreaded {
|
|
||||||
public:
|
|
||||||
explicit TPPSMonitor(TServer& Server);
|
|
||||||
virtual ~TPPSMonitor() { }
|
|
||||||
|
|
||||||
void operator()() override;
|
|
||||||
|
|
||||||
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
|
|
||||||
void IncrementInternalPPS() { ++mInternalPPS; }
|
|
||||||
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
|
|
||||||
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
|
|
||||||
|
|
||||||
private:
|
|
||||||
TNetwork& Network() { return mNetwork->get(); }
|
|
||||||
|
|
||||||
TServer& mServer;
|
|
||||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
|
||||||
int mInternalPPS { 0 };
|
|
||||||
};
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "Common.h"
|
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
|
|
||||||
class TResourceManager {
|
|
||||||
public:
|
|
||||||
TResourceManager();
|
|
||||||
|
|
||||||
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
|
|
||||||
[[nodiscard]] std::string FileList() const { return mFileList; }
|
|
||||||
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
|
||||||
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
|
||||||
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
|
||||||
|
|
||||||
[[nodiscard]] std::string NewFileList() const;
|
|
||||||
|
|
||||||
void RefreshFiles();
|
|
||||||
|
|
||||||
private:
|
|
||||||
size_t mMaxModSize = 0;
|
|
||||||
std::string mFileSizes;
|
|
||||||
std::string mFileList;
|
|
||||||
std::string mTrimmedList;
|
|
||||||
int mModsLoaded = 0;
|
|
||||||
|
|
||||||
std::mutex mModsMutex;
|
|
||||||
nlohmann::json mMods = nlohmann::json::array();
|
|
||||||
};
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "IThreaded.h"
|
|
||||||
#include "RWMutex.h"
|
|
||||||
#include "TScopedTimer.h"
|
|
||||||
#include <functional>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
|
|
||||||
class TClient;
|
|
||||||
class TNetwork;
|
|
||||||
class TPPSMonitor;
|
|
||||||
|
|
||||||
class TServer final {
|
|
||||||
public:
|
|
||||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
|
||||||
|
|
||||||
TServer(const std::vector<std::string_view>& Arguments);
|
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
|
||||||
// in Fn, return true to continue, return false to break
|
|
||||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
|
||||||
size_t ClientCount() const;
|
|
||||||
|
|
||||||
void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
|
||||||
static void HandleEvent(TClient& c, const std::string& Data);
|
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
|
||||||
|
|
||||||
const TScopedTimer UptimeTimer;
|
|
||||||
|
|
||||||
// asio io context
|
|
||||||
io_context& IoCtx() { return mIoCtx; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
io_context mIoCtx {};
|
|
||||||
TClientSet mClients;
|
|
||||||
mutable RWMutex mClientsMutex;
|
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
|
||||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
|
||||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
|
||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
|
||||||
void HandlePosition(TClient& c, const std::string& Packet);
|
|
||||||
};
|
|
||||||
|
|
||||||
struct BufferView {
|
|
||||||
uint8_t* Data { nullptr };
|
|
||||||
size_t Size { 0 };
|
|
||||||
const uint8_t* data() const { return Data; }
|
|
||||||
uint8_t* data() { return Data; }
|
|
||||||
size_t size() const { return Size; }
|
|
||||||
};
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|||||||
@@ -4,4 +4,4 @@ set -ex
|
|||||||
|
|
||||||
./vcpkg/bootstrap-vcpkg.sh
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
|
|||||||
@@ -4,4 +4,4 @@ set -ex
|
|||||||
|
|
||||||
./vcpkg/bootstrap-vcpkg.sh
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
|
|||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
@@ -4,4 +4,4 @@ set -ex
|
|||||||
|
|
||||||
./vcpkg/bootstrap-vcpkg.sh
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
set -ex
|
|
||||||
|
|
||||||
./vcpkg/bootstrap-vcpkg.sh
|
|
||||||
|
|
||||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
|
||||||
@@ -2,6 +2,6 @@
|
|||||||
|
|
||||||
set -ex
|
set -ex
|
||||||
|
|
||||||
vcpkg add port lua
|
./vcpkg/vcpkg add port lua
|
||||||
|
|
||||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "ArgsParser.h"
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
#include "ChronoWrapper.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include <regex>
|
|
||||||
|
|
||||||
std::chrono::high_resolution_clock::duration ChronoWrapper::TimeFromStringWithLiteral(const std::string& time_str) {
|
|
||||||
// const std::regex time_regex(R"((\d+\.{0,1}\d*)(min|ms|us|ns|[dhs]))"); //i.e one of: "25ns, 6us, 256ms, 2s, 13min, 69h, 356d" will get matched (only available in newer C++ versions)
|
|
||||||
const std::regex time_regex(R"((\d+\.{0,1}\d*)(min|[dhs]))"); // i.e one of: "2.01s, 13min, 69h, 356.69d" will get matched
|
|
||||||
std::smatch match;
|
|
||||||
float time_value;
|
|
||||||
if (!std::regex_search(time_str, match, time_regex))
|
|
||||||
return std::chrono::nanoseconds(0);
|
|
||||||
time_value = stof(match.str(1));
|
|
||||||
if (match.str(2) == "d") {
|
|
||||||
return std::chrono::seconds((uint64_t)(time_value * 86400)); // 86400 seconds in a day
|
|
||||||
} else if (match.str(2) == "h") {
|
|
||||||
return std::chrono::seconds((uint64_t)(time_value * 3600)); // 3600 seconds in an hour
|
|
||||||
} else if (match.str(2) == "min") {
|
|
||||||
return std::chrono::seconds((uint64_t)(time_value * 60));
|
|
||||||
} else if (match.str(2) == "s") {
|
|
||||||
return std::chrono::seconds((uint64_t)time_value);
|
|
||||||
}
|
|
||||||
return std::chrono::nanoseconds(0);
|
|
||||||
}
|
|
||||||
-184
@@ -1,184 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <memory>
|
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
|
||||||
// TODO: Send delete packets
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
|
||||||
return Ident == elem.ID();
|
|
||||||
});
|
|
||||||
if (iter != mVehicleData.end()) {
|
|
||||||
mVehicleData.erase(iter);
|
|
||||||
} else {
|
|
||||||
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::ClearCars() {
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
mVehicleData.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
int TClient::GetOpenCarID() const {
|
|
||||||
int OpenID = 0;
|
|
||||||
bool found;
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
do {
|
|
||||||
found = true;
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == OpenID) {
|
|
||||||
OpenID++;
|
|
||||||
found = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} while (!found);
|
|
||||||
return OpenID;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::AddNewCar(int Ident, const std::string& Data) {
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
mVehicleData.emplace_back(Ident, Data);
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|
||||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
try {
|
|
||||||
return mVehiclePosition.at(size_t(Ident));
|
|
||||||
} catch (const std::out_of_range& oor) {
|
|
||||||
beammp_debugf("Failed to get vehicle position for {}: {}", Ident, oor.what());
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::Disconnect(std::string_view Reason) {
|
|
||||||
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
|
||||||
boost::system::error_code ec;
|
|
||||||
if (mSocket.is_open()) {
|
|
||||||
mSocket.shutdown(socket_base::shutdown_both, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
mSocket.close(ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to close client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
beammp_debug("Socket is already closed.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
mVehiclePosition[size_t(Ident)] = Data;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TClient::GetCarData(int Ident) {
|
|
||||||
{ // lock
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == Ident) {
|
|
||||||
return v.Data();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // unlock
|
|
||||||
DeleteCar(Ident);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::SetCarData(int Ident, const std::string& Data) {
|
|
||||||
{ // lock
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == Ident) {
|
|
||||||
v.SetData(Data);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // unlock
|
|
||||||
DeleteCar(Ident);
|
|
||||||
}
|
|
||||||
|
|
||||||
int TClient::GetCarCount() const {
|
|
||||||
// mVechileData holds both unicycle and cars which both count towards the maximum car count
|
|
||||||
// spawning a unicycle meant reaching the max, hence being unable to spawn car. this dirty fixes the problem for now.
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == mUnicycleID) {
|
|
||||||
return int(mVehicleData.size() - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return int(mVehicleData.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
TServer& TClient::Server() const {
|
|
||||||
return mServer;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
|
||||||
mPacketsSync.push(Packet);
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
|
||||||
: mServer(Server)
|
|
||||||
, mSocket(std::move(Socket))
|
|
||||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::~TClient() {
|
|
||||||
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
|
||||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
|
||||||
}
|
|
||||||
int TClient::SecondsSinceLastPing() {
|
|
||||||
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
|
||||||
std::chrono::high_resolution_clock::now() - mLastPingTime)
|
|
||||||
.count();
|
|
||||||
return int(seconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
|
||||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
|
||||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
|
||||||
ReadLock Lock(Server.GetClientMutex());
|
|
||||||
if (!CPtr.expired()) {
|
|
||||||
auto C = CPtr.lock();
|
|
||||||
if (C->GetID() == ID) {
|
|
||||||
MaybeClient = CPtr;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
beammp_debugf("Found an expired client while looking for id {}", ID);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return MaybeClient;
|
|
||||||
}
|
|
||||||
+11
-95
@@ -1,30 +1,10 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include "Env.h"
|
#include "Env.h"
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <charconv>
|
#include <charconv>
|
||||||
#include <chrono>
|
|
||||||
#include <fmt/core.h>
|
#include <fmt/core.h>
|
||||||
#include <fstream>
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <regex>
|
#include <regex>
|
||||||
@@ -35,6 +15,8 @@
|
|||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
|
Application::TSettings Application::Settings = {};
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
if (Handler) {
|
if (Handler) {
|
||||||
@@ -215,14 +197,14 @@ void Application::CheckForUpdates() {
|
|||||||
// checks current version against latest version
|
// checks current version against latest version
|
||||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||||
auto Response = Http::GET(url + "/v/s");
|
auto Response = Http::GET(url, 443, "/v/s");
|
||||||
bool Matches = std::regex_match(Response, VersionRegex);
|
bool Matches = std::regex_match(Response, VersionRegex);
|
||||||
if (Matches) {
|
if (Matches) {
|
||||||
auto MyVersion = ServerVersion();
|
auto MyVersion = ServerVersion();
|
||||||
auto RemoteVersion = Version(VersionStrToInts(Response));
|
auto RemoteVersion = Version(VersionStrToInts(Response));
|
||||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
if (IsOutdated(MyVersion, RemoteVersion)) {
|
||||||
std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
|
std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
|
||||||
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://docs.beammp.com/server/server-maintenance/#updating-the-server";
|
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
|
||||||
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
|
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
|
||||||
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
|
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
|
||||||
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
|
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
|
||||||
@@ -256,7 +238,7 @@ static std::mutex ThreadNameMapMutex {};
|
|||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride) {
|
std::string ThreadName(bool DebugModeOverride) {
|
||||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||||
if (DebugModeOverride || Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
|
||||||
auto id = std::this_thread::get_id();
|
auto id = std::this_thread::get_id();
|
||||||
if (threadNameMap.find(id) != threadNameMap.end()) {
|
if (threadNameMap.find(id) != threadNameMap.end()) {
|
||||||
// found
|
// found
|
||||||
@@ -268,21 +250,21 @@ std::string ThreadName(bool DebugModeOverride) {
|
|||||||
|
|
||||||
TEST_CASE("ThreadName") {
|
TEST_CASE("ThreadName") {
|
||||||
RegisterThread("MyThread");
|
RegisterThread("MyThread");
|
||||||
auto OrigDebug = Application::Settings.getAsBool(Settings::Key::General_Debug);
|
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
||||||
|
|
||||||
// ThreadName adds a space at the end, legacy but we need it still
|
// ThreadName adds a space at the end, legacy but we need it still
|
||||||
SUBCASE("Debug mode enabled") {
|
SUBCASE("Debug mode enabled") {
|
||||||
Application::Settings.set(Settings::Key::General_Debug, true);
|
Application::Settings.DebugModeEnabled = true;
|
||||||
CHECK(ThreadName(true) == "MyThread ");
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
CHECK(ThreadName(false) == "MyThread ");
|
CHECK(ThreadName(false) == "MyThread ");
|
||||||
}
|
}
|
||||||
SUBCASE("Debug mode disabled") {
|
SUBCASE("Debug mode disabled") {
|
||||||
Application::Settings.set(Settings::Key::General_Debug, false);
|
Application::Settings.DebugModeEnabled = false;
|
||||||
CHECK(ThreadName(true) == "MyThread ");
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
CHECK(ThreadName(false) == "");
|
CHECK(ThreadName(false) == "");
|
||||||
}
|
}
|
||||||
// cleanup
|
// cleanup
|
||||||
Application::Settings.set(Settings::Key::General_Debug, OrigDebug);
|
Application::Settings.DebugModeEnabled = OrigDebug;
|
||||||
}
|
}
|
||||||
|
|
||||||
void RegisterThread(const std::string& str) {
|
void RegisterThread(const std::string& str) {
|
||||||
@@ -293,10 +275,8 @@ void RegisterThread(const std::string& str) {
|
|||||||
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
|
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
|
||||||
#elif defined(BEAMMP_LINUX)
|
#elif defined(BEAMMP_LINUX)
|
||||||
ThreadId = std::to_string(gettid());
|
ThreadId = std::to_string(gettid());
|
||||||
#elif defined(BEAMMP_FREEBSD)
|
|
||||||
ThreadId = std::to_string(getpid());
|
|
||||||
#endif
|
#endif
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
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;
|
||||||
}
|
}
|
||||||
@@ -329,7 +309,7 @@ TEST_CASE("Version::AsString") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_LogChat)) {
|
if (Application::Settings.LogChat) {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << ThreadName();
|
ss << ThreadName();
|
||||||
ss << "[CHAT] ";
|
ss << "[CHAT] ";
|
||||||
@@ -384,67 +364,3 @@ void SplitString(const std::string& str, const char delim, std::vector<std::stri
|
|||||||
out.push_back(str.substr(start, end - start));
|
out.push_back(str.substr(start, end - start));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
static constexpr size_t STARTING_MAX_DECOMPRESSION_BUFFER_SIZE = 15 * 1024 * 1024;
|
|
||||||
static constexpr size_t MAX_DECOMPRESSION_BUFFER_SIZE = 30 * 1024 * 1024;
|
|
||||||
|
|
||||||
std::vector<uint8_t> DeComp(std::span<const uint8_t> input) {
|
|
||||||
beammp_debugf("got {} bytes of input data", input.size());
|
|
||||||
|
|
||||||
// start with a decompression buffer of 5x the input size, clamped to a maximum of 15 MB.
|
|
||||||
// this buffer can and will grow, but we don't want to start it too large. A 5x compression ratio
|
|
||||||
// is pretty optimistic.
|
|
||||||
std::vector<uint8_t> output_buffer(std::min<size_t>(input.size() * 5, STARTING_MAX_DECOMPRESSION_BUFFER_SIZE));
|
|
||||||
|
|
||||||
uLongf output_size = output_buffer.size();
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
int res = uncompress(
|
|
||||||
reinterpret_cast<Bytef*>(output_buffer.data()),
|
|
||||||
&output_size,
|
|
||||||
reinterpret_cast<const Bytef*>(input.data()),
|
|
||||||
static_cast<uLongf>(input.size()));
|
|
||||||
if (res == Z_BUF_ERROR) {
|
|
||||||
// We assume that a reasonable maximum size for decompressed packets exists. We want to avoid
|
|
||||||
// a client effectively "zip bombing" us by sending a lot of small packets which decompress
|
|
||||||
// into huge data.
|
|
||||||
// If this limit were to be an issue, this could be made configurable, however clients have a similar
|
|
||||||
// limit. For that reason, we just reject packets which decompress into too much data.
|
|
||||||
if (output_buffer.size() >= MAX_DECOMPRESSION_BUFFER_SIZE) {
|
|
||||||
throw std::runtime_error(fmt::format("decompressed packet size of {} bytes exceeded", MAX_DECOMPRESSION_BUFFER_SIZE));
|
|
||||||
}
|
|
||||||
// if decompression fails, we double the buffer size (up to the allowed limit) and try again
|
|
||||||
output_buffer.resize(std::max<size_t>(output_buffer.size() * 2, MAX_DECOMPRESSION_BUFFER_SIZE));
|
|
||||||
beammp_warnf("zlib uncompress() failed, trying with a larger buffer size of {}", output_buffer.size());
|
|
||||||
output_size = output_buffer.size();
|
|
||||||
} else if (res != Z_OK) {
|
|
||||||
beammp_error("zlib uncompress() failed: " + std::to_string(res));
|
|
||||||
if (res == Z_DATA_ERROR) {
|
|
||||||
throw InvalidDataError {};
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error("zlib uncompress() failed");
|
|
||||||
}
|
|
||||||
} else if (res == Z_OK) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
output_buffer.resize(output_size);
|
|
||||||
return output_buffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<uint8_t> Comp(std::span<const uint8_t> input) {
|
|
||||||
auto max_size = compressBound(input.size());
|
|
||||||
std::vector<uint8_t> output(max_size);
|
|
||||||
uLongf output_size = output.size();
|
|
||||||
int res = compress(
|
|
||||||
reinterpret_cast<Bytef*>(output.data()),
|
|
||||||
&output_size,
|
|
||||||
reinterpret_cast<const Bytef*>(input.data()),
|
|
||||||
static_cast<uLongf>(input.size()));
|
|
||||||
if (res != Z_OK) {
|
|
||||||
beammp_error("zlib compress() failed: " + std::to_string(res));
|
|
||||||
throw std::runtime_error("zlib compress() failed");
|
|
||||||
}
|
|
||||||
beammp_debug("zlib compressed " + std::to_string(input.size()) + " B to " + std::to_string(output_size) + " B");
|
|
||||||
output.resize(output_size);
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -59,9 +41,7 @@ TEST_CASE("init and reset termios") {
|
|||||||
CHECK_EQ(current.c_iflag, original.c_iflag);
|
CHECK_EQ(current.c_iflag, original.c_iflag);
|
||||||
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
||||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||||
#ifndef BEAMMP_FREEBSD // The 'c_line' attribute seems to only exist on Linux, so we need to omit it on other platforms
|
|
||||||
CHECK_EQ(current.c_line, original.c_line);
|
CHECK_EQ(current.c_line, original.c_line);
|
||||||
#endif
|
|
||||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||||
}
|
}
|
||||||
|
|||||||
-24
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Env.h"
|
#include "Env.h"
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
@@ -33,12 +15,6 @@ std::string_view Env::ToString(Env::Key key) {
|
|||||||
case Key::PROVIDER_UPDATE_MESSAGE:
|
case Key::PROVIDER_UPDATE_MESSAGE:
|
||||||
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
|
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
|
||||||
break;
|
break;
|
||||||
case Key::PROVIDER_DISABLE_CONFIG:
|
|
||||||
return "BEAMMP_PROVIDER_DISABLE_CONFIG";
|
|
||||||
break;
|
|
||||||
case Key::PROVIDER_PORT_ENV:
|
|
||||||
return "BEAMMP_PROVIDER_PORT_ENV";
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-87
@@ -1,24 +1,5 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
@@ -28,87 +9,41 @@
|
|||||||
#include <random>
|
#include <random>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
|
// TODO: Add sentry error handling back
|
||||||
|
|
||||||
using json = nlohmann::json;
|
using json = nlohmann::json;
|
||||||
|
|
||||||
static size_t CurlWriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
|
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||||
std::string* Result = reinterpret_cast<std::string*>(userp);
|
static thread_local httplib::SSLClient client(host, port);
|
||||||
std::string NewContents(reinterpret_cast<char*>(contents), size * nmemb);
|
client.enable_server_certificate_verification(false);
|
||||||
*Result += NewContents;
|
client.set_address_family(AF_INET);
|
||||||
return size * nmemb;
|
auto res = client.Get(target.c_str());
|
||||||
}
|
if (res) {
|
||||||
|
|
||||||
std::string Http::GET(const std::string& url, unsigned int* status) {
|
|
||||||
std::string Ret;
|
|
||||||
static thread_local CURL* curl = curl_easy_init();
|
|
||||||
if (curl) {
|
|
||||||
CURLcode res;
|
|
||||||
char errbuf[CURL_ERROR_SIZE];
|
|
||||||
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
|
||||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&Ret);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); // seconds
|
|
||||||
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
|
|
||||||
errbuf[0] = 0;
|
|
||||||
res = curl_easy_perform(curl);
|
|
||||||
if (res != CURLE_OK) {
|
|
||||||
beammp_error("GET to " + url + " failed: " + std::string(curl_easy_strerror(res)));
|
|
||||||
beammp_error("Curl error: " + std::string(errbuf));
|
|
||||||
return Http::ErrorString;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status) {
|
if (status) {
|
||||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, status);
|
*status = res->status;
|
||||||
}
|
}
|
||||||
|
return res->body;
|
||||||
} else {
|
} else {
|
||||||
beammp_error("Curl easy init failed");
|
|
||||||
return Http::ErrorString;
|
return Http::ErrorString;
|
||||||
}
|
}
|
||||||
return Ret;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Http::POST(const std::string& url, const std::string& body, const std::string& ContentType, unsigned int* status, const std::map<std::string, std::string>& headers) {
|
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
||||||
std::string Ret;
|
static thread_local httplib::SSLClient client(host, port);
|
||||||
static thread_local CURL* curl = curl_easy_init();
|
client.set_read_timeout(std::chrono::seconds(10));
|
||||||
if (curl) {
|
beammp_assert(client.is_valid());
|
||||||
CURLcode res;
|
client.enable_server_certificate_verification(false);
|
||||||
char errbuf[CURL_ERROR_SIZE];
|
client.set_address_family(AF_INET);
|
||||||
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
auto res = client.Post(target.c_str(), headers, body.c_str(), body.size(), ContentType.c_str());
|
||||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
|
if (res) {
|
||||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&Ret);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_POST, 1);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
|
|
||||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, body.size());
|
|
||||||
struct curl_slist* list = nullptr;
|
|
||||||
list = curl_slist_append(list, ("Content-Type: " + ContentType).c_str());
|
|
||||||
|
|
||||||
for (auto [header, value] : headers) {
|
|
||||||
list = curl_slist_append(list, (header + ": " + value).c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); // seconds
|
|
||||||
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
|
|
||||||
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
|
|
||||||
errbuf[0] = 0;
|
|
||||||
res = curl_easy_perform(curl);
|
|
||||||
curl_slist_free_all(list);
|
|
||||||
if (res != CURLE_OK) {
|
|
||||||
beammp_error("POST to " + url + " failed: " + std::string(curl_easy_strerror(res)));
|
|
||||||
beammp_error("Curl error: " + std::string(errbuf));
|
|
||||||
return Http::ErrorString;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status) {
|
if (status) {
|
||||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, status);
|
*status = res->status;
|
||||||
}
|
}
|
||||||
|
return res->body;
|
||||||
} else {
|
} else {
|
||||||
beammp_error("Curl easy init failed");
|
beammp_debug("POST failed: " + httplib::to_string(res.error()));
|
||||||
return Http::ErrorString;
|
return Http::ErrorString;
|
||||||
}
|
}
|
||||||
return Ret;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RFC 2616, RFC 7231
|
// RFC 2616, RFC 7231
|
||||||
@@ -218,6 +153,7 @@ Http::Server::THttpServerInstance::THttpServerInstance() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Http::Server::THttpServerInstance::operator()() try {
|
void Http::Server::THttpServerInstance::operator()() try {
|
||||||
|
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
|
||||||
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
||||||
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
||||||
// todo: make this IP agnostic so people can set their own IP
|
// todo: make this IP agnostic so people can set their own IP
|
||||||
@@ -244,7 +180,7 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.set_content(
|
res.set_content(
|
||||||
json {
|
nlohmann::json {
|
||||||
{ "ok", SystemsBad == 0 },
|
{ "ok", SystemsBad == 0 },
|
||||||
}
|
}
|
||||||
.dump(),
|
.dump(),
|
||||||
@@ -259,6 +195,10 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
||||||
});
|
});
|
||||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||||
|
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
||||||
|
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.");
|
||||||
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("Failed to start http server. Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it. Error: " + std::string(e.what()));
|
beammp_error("Failed to start http server. Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it. Error: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-169
@@ -1,26 +1,6 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Settings.h"
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
@@ -61,11 +41,7 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
|
|||||||
}
|
}
|
||||||
case sol::type::number: {
|
case sol::type::number: {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
if (Value.is<int>()) {
|
ss << Value.as<float>();
|
||||||
ss << Value.as<int>();
|
|
||||||
} else {
|
|
||||||
ss << Value.as<float>();
|
|
||||||
}
|
|
||||||
return ss.str();
|
return ss.str();
|
||||||
}
|
}
|
||||||
case sol::type::lua_nil:
|
case sol::type::lua_nil:
|
||||||
@@ -137,24 +113,26 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||||
std::string Packet = "E:" + EventName + ":" + Data;
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
if (PlayerID == -1) {
|
/*
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
return { true, "" };
|
if (PlayerID == -1) {
|
||||||
} else {
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
return { true, "" };
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
} else {
|
||||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
return { false, "Invalid Player ID" };
|
if (!MaybeClient) {
|
||||||
}
|
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||||
auto c = MaybeClient.value().lock();
|
return { false, "Invalid Player ID" };
|
||||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
}
|
||||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
auto c = MaybeClient.value();
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
return { false, "Respond failed, dropping client" };
|
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||||
}
|
LuaAPI::MP::Engine->Network().Disconnect(*c);
|
||||||
return { true, "" };
|
return { false, "Respond failed, dropping client" };
|
||||||
}
|
}
|
||||||
|
return { true, "" };
|
||||||
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||||
@@ -163,17 +141,22 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient) {
|
||||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||||
return { false, "Player does not exist" };
|
return { false, "Player does not exist" };
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||||
return { true, "" };
|
return { true, "" };
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
std::pair<bool, std::string> Result;
|
std::pair<bool, std::string> Result;
|
||||||
std::string Packet = "C:Server: " + Message;
|
std::string Packet = "C:Server: " + Message;
|
||||||
if (ID == -1) {
|
if (ID == -1) {
|
||||||
@@ -182,17 +165,18 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
if (!c->IsSynced()) {
|
if (!c->IsSynced) {
|
||||||
Result.first = false;
|
Result.first = false;
|
||||||
Result.second = "Player still syncing data";
|
Result.second = "Player still syncing data";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message);
|
||||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||||
// TODO: should we return an error here?
|
beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get());
|
||||||
|
Engine->Network().Disconnect(c);
|
||||||
}
|
}
|
||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
@@ -203,52 +187,23 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
}
|
*/
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::SendNotification(int ID, const std::string& Message, const std::string& Icon, const std::string& Category) {
|
|
||||||
std::pair<bool, std::string> Result;
|
|
||||||
std::string Packet = "n" + Category + ":" + Icon + ":" + Message;
|
|
||||||
if (ID == -1) {
|
|
||||||
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
|
||||||
Result.first = true;
|
|
||||||
} else {
|
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
|
||||||
if (MaybeClient) {
|
|
||||||
auto c = MaybeClient.value().lock();
|
|
||||||
if (!c->IsSynced()) {
|
|
||||||
Result.first = false;
|
|
||||||
Result.second = "Player is not synced yet";
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
|
||||||
beammp_errorf("Failed to send notification to player (id {}) - did the player disconnect?", ID);
|
|
||||||
Result.first = false;
|
|
||||||
Result.second = "Failed to send packet";
|
|
||||||
}
|
|
||||||
Result.first = true;
|
|
||||||
} else {
|
|
||||||
beammp_lua_error("SendNotification invalid argument [1] invalid ID");
|
|
||||||
Result.first = false;
|
|
||||||
Result.second = "Invalid Player ID";
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
std::pair<bool, std::string> Result;
|
std::pair<bool, std::string> Result;
|
||||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient) {
|
||||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||||
Result.first = false;
|
Result.first = false;
|
||||||
Result.second = "Invalid Player ID";
|
Result.second = "Invalid Player ID";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
if (!c->GetCarData(VID).empty()) {
|
if (!c->GetCarData(VID).empty()) {
|
||||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", PID, VID));
|
|
||||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
c->DeleteCar(VID);
|
c->DeleteCar(VID);
|
||||||
Result.first = true;
|
Result.first = true;
|
||||||
@@ -257,124 +212,98 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
|||||||
Result.second = "Vehicle does not exist";
|
Result.second = "Vehicle does not exist";
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||||
switch (ConfigID) {
|
switch (ConfigID) {
|
||||||
case 0: // debug
|
case 0: // debug
|
||||||
if (NewValue.is<bool>()) {
|
if (NewValue.is<bool>()) {
|
||||||
Application::Settings.set(Settings::Key::General_Debug, NewValue.as<bool>());
|
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
|
||||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.getAsBool(Settings::Key::General_Debug) ? "true" : "false"));
|
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 1: // private
|
case 1: // private
|
||||||
if (NewValue.is<bool>()) {
|
if (NewValue.is<bool>()) {
|
||||||
Application::Settings.set(Settings::Key::General_Private, NewValue.as<bool>());
|
Application::Settings.Private = NewValue.as<bool>();
|
||||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false"));
|
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 2: // max cars
|
case 2: // max cars
|
||||||
if (NewValue.is<int>()) {
|
if (NewValue.is<int>()) {
|
||||||
Application::Settings.set(Settings::Key::General_MaxCars, NewValue.as<int>());
|
Application::Settings.MaxCars = NewValue.as<int>();
|
||||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxCars)));
|
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected integer");
|
beammp_lua_error("set invalid argument [2] expected integer");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 3: // max players
|
case 3: // max players
|
||||||
if (NewValue.is<int>()) {
|
if (NewValue.is<int>()) {
|
||||||
Application::Settings.set(Settings::Key::General_MaxPlayers, NewValue.as<int>());
|
Application::Settings.MaxPlayers = NewValue.as<int>();
|
||||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)));
|
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected integer");
|
beammp_lua_error("set invalid argument [2] expected integer");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 4: // Map
|
case 4: // Map
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::Settings.set(Settings::Key::General_Map, NewValue.as<std::string>());
|
Application::Settings.MapName = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.getAsString(Settings::Key::General_Map));
|
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 5: // Name
|
case 5: // Name
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::Settings.set(Settings::Key::General_Name, NewValue.as<std::string>());
|
Application::Settings.ServerName = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.getAsString(Settings::Key::General_Name));
|
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 6: // Desc
|
case 6: // Desc
|
||||||
if (NewValue.is<std::string>()) {
|
if (NewValue.is<std::string>()) {
|
||||||
Application::Settings.set(Settings::Key::General_Description, NewValue.as<std::string>());
|
Application::Settings.ServerDesc = NewValue.as<std::string>();
|
||||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.getAsString(Settings::Key::General_Description));
|
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 7: // Information packet
|
|
||||||
if (NewValue.is<bool>()) {
|
|
||||||
Application::Settings.set(Settings::Key::General_InformationPacket, NewValue.as<bool>());
|
|
||||||
beammp_info(std::string("Set `InformationPacket` to ") + (Application::Settings.getAsBool(Settings::Key::General_InformationPacket) ? "true" : "false"));
|
|
||||||
} else {
|
|
||||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
TLuaValue LuaAPI::MP::Get(int ConfigID) {
|
|
||||||
switch (ConfigID) {
|
|
||||||
case 0: // debug
|
|
||||||
return Application::Settings.getAsBool(Settings::Key::General_Debug);
|
|
||||||
case 1: // private
|
|
||||||
return Application::Settings.getAsBool(Settings::Key::General_Private);
|
|
||||||
case 2: // max cars
|
|
||||||
return Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
|
||||||
case 3: // max players
|
|
||||||
return Application::Settings.getAsInt(Settings::Key::General_MaxPlayers);
|
|
||||||
case 4: // Map
|
|
||||||
return Application::Settings.getAsString(Settings::Key::General_Map);
|
|
||||||
case 5: // Name
|
|
||||||
return Application::Settings.getAsString(Settings::Key::General_Name);
|
|
||||||
case 6: // Desc
|
|
||||||
return Application::Settings.getAsString(Settings::Key::General_Description);
|
|
||||||
case 7: // Information packet
|
|
||||||
return Application::Settings.getAsBool(Settings::Key::General_InformationPacket);
|
|
||||||
default:
|
|
||||||
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void LuaAPI::MP::Sleep(size_t Ms) {
|
void LuaAPI::MP::Sleep(size_t Ms) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
|
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
return MaybeClient.value().lock()->IsUDPConnected();
|
return MaybeClient.value()->IsConnected.get();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
return MaybeClient.value().lock()->IsGuest();
|
return MaybeClient.value()->IsGuest.get();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||||
@@ -630,11 +559,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
key = left.as<std::string>();
|
key = left.as<std::string>();
|
||||||
break;
|
break;
|
||||||
case sol::type::number:
|
case sol::type::number:
|
||||||
if (left.is<int>()) {
|
key = std::to_string(left.as<double>());
|
||||||
key = std::to_string(left.as<int>());
|
|
||||||
} else {
|
|
||||||
key = std::to_string(left.as<double>());
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
beammp_assert_not_reachable();
|
beammp_assert_not_reachable();
|
||||||
@@ -662,31 +587,22 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
case sol::type::string:
|
case sol::type::string:
|
||||||
value = right.as<std::string>();
|
value = right.as<std::string>();
|
||||||
break;
|
break;
|
||||||
case sol::type::number: {
|
case sol::type::number:
|
||||||
if (right.is<int>()) {
|
value = right.as<double>();
|
||||||
value = right.as<int>();
|
|
||||||
} else {
|
|
||||||
value = right.as<double>();
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
case sol::type::function:
|
case sol::type::function:
|
||||||
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
||||||
return;
|
return;
|
||||||
case sol::type::table: {
|
case sol::type::table: {
|
||||||
if (right.as<sol::table>().empty()) {
|
bool local_is_array = true;
|
||||||
value = nlohmann::json::object();
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
} else {
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
bool local_is_array = true;
|
local_is_array = false;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
|
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -702,19 +618,15 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
||||||
nlohmann::json json;
|
nlohmann::json json;
|
||||||
// table
|
// table
|
||||||
if (object.as<sol::table>().empty()) {
|
bool is_array = true;
|
||||||
json = nlohmann::json::object();
|
for (const auto& pair : object.as<sol::table>()) {
|
||||||
} else {
|
if (pair.first.get_type() != sol::type::number) {
|
||||||
bool is_array = true;
|
is_array = false;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const auto& entry : object) {
|
||||||
|
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||||
|
}
|
||||||
return json.dump();
|
return json.dump();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1251
File diff suppressed because it is too large
Load Diff
@@ -1,59 +0,0 @@
|
|||||||
#include "Profiling.h"
|
|
||||||
#include <limits>
|
|
||||||
|
|
||||||
prof::Duration prof::duration(const TimePoint& start, const TimePoint& end) {
|
|
||||||
return end - start;
|
|
||||||
}
|
|
||||||
prof::TimePoint prof::now() {
|
|
||||||
return std::chrono::high_resolution_clock::now();
|
|
||||||
}
|
|
||||||
prof::Stats prof::UnitProfileCollection::stats(const std::string& unit) {
|
|
||||||
return m_map->operator[](unit).stats();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t prof::UnitProfileCollection::measurement_count(const std::string& unit) {
|
|
||||||
return m_map->operator[](unit).measurement_count();
|
|
||||||
}
|
|
||||||
|
|
||||||
void prof::UnitProfileCollection::add_sample(const std::string& unit, const Duration& duration) {
|
|
||||||
m_map->operator[](unit).add_sample(duration);
|
|
||||||
}
|
|
||||||
|
|
||||||
prof::Stats prof::UnitExecutionTime::stats() const {
|
|
||||||
std::unique_lock lock(m_mtx);
|
|
||||||
Stats result {};
|
|
||||||
// calculate sum
|
|
||||||
result.n = m_total_calls;
|
|
||||||
result.max = m_min;
|
|
||||||
result.min = m_max;
|
|
||||||
// calculate mean: mean = sum_x / n
|
|
||||||
result.mean = m_sum / double(m_total_calls);
|
|
||||||
// calculate stdev: stdev = sqrt((sum_x2 / n) - (mean * mean))
|
|
||||||
result.stdev = std::sqrt((m_measurement_sqr_sum / double(result.n)) - (result.mean * result.mean));
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
void prof::UnitExecutionTime::add_sample(const Duration& dur) {
|
|
||||||
std::unique_lock lock(m_mtx);
|
|
||||||
m_sum += dur.count();
|
|
||||||
m_measurement_sqr_sum += dur.count() * dur.count();
|
|
||||||
m_min = std::min(dur.count(), m_min);
|
|
||||||
m_max = std::max(dur.count(), m_max);
|
|
||||||
++m_total_calls;
|
|
||||||
}
|
|
||||||
|
|
||||||
prof::UnitExecutionTime::UnitExecutionTime() {
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unordered_map<std::string, prof::Stats> prof::UnitProfileCollection::all_stats() {
|
|
||||||
auto map = m_map.synchronize();
|
|
||||||
std::unordered_map<std::string, Stats> result {};
|
|
||||||
for (const auto& [name, time] : *map) {
|
|
||||||
result[name] = time.stats();
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
size_t prof::UnitExecutionTime::measurement_count() const {
|
|
||||||
std::unique_lock lock(m_mtx);
|
|
||||||
return m_total_calls;
|
|
||||||
}
|
|
||||||
@@ -1,189 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Settings.h"
|
|
||||||
|
|
||||||
Settings::Settings() {
|
|
||||||
SettingsMap = std::unordered_map<Key, SettingsTypeVariant> {
|
|
||||||
// All entries which contain std::strings must be explicitly constructed, otherwise they become 'bool'
|
|
||||||
{ General_Description, std::string("BeamMP Default Description") },
|
|
||||||
{ General_Tags, std::string("Freeroam") },
|
|
||||||
{ General_MaxPlayers, 8 },
|
|
||||||
{ General_Name, std::string("BeamMP Server") },
|
|
||||||
{ General_Map, std::string("/levels/gridmap_v2/info.json") },
|
|
||||||
{ General_AuthKey, std::string("") },
|
|
||||||
{ General_Private, true },
|
|
||||||
{ General_Port, 30814 },
|
|
||||||
{ General_MaxCars, 1 },
|
|
||||||
{ General_LogChat, true },
|
|
||||||
{ General_ResourceFolder, std::string("Resources") },
|
|
||||||
{ General_Debug, false },
|
|
||||||
{ General_AllowGuests, true },
|
|
||||||
{ General_InformationPacket, true },
|
|
||||||
{ Misc_ImScaredOfUpdates, true },
|
|
||||||
{ Misc_UpdateReminderTime, "30s" }
|
|
||||||
};
|
|
||||||
|
|
||||||
InputAccessMapping = std::unordered_map<ComposedKey, SettingsAccessControl> {
|
|
||||||
{ { "General", "Description" }, { General_Description, READ_WRITE } },
|
|
||||||
{ { "General", "Tags" }, { General_Tags, READ_WRITE } },
|
|
||||||
{ { "General", "MaxPlayers" }, { General_MaxPlayers, READ_WRITE } },
|
|
||||||
{ { "General", "Name" }, { General_Name, READ_WRITE } },
|
|
||||||
{ { "General", "Map" }, { General_Map, READ_WRITE } },
|
|
||||||
{ { "General", "AuthKey" }, { General_AuthKey, NO_ACCESS } },
|
|
||||||
{ { "General", "Private" }, { General_Private, READ_ONLY } },
|
|
||||||
{ { "General", "Port" }, { General_Port, READ_ONLY } },
|
|
||||||
{ { "General", "MaxCars" }, { General_MaxCars, READ_WRITE } },
|
|
||||||
{ { "General", "LogChat" }, { General_LogChat, READ_ONLY } },
|
|
||||||
{ { "General", "ResourceFolder" }, { General_ResourceFolder, READ_ONLY } },
|
|
||||||
{ { "General", "Debug" }, { General_Debug, READ_WRITE } },
|
|
||||||
{ { "General", "AllowGuests" }, { General_AllowGuests, READ_WRITE } },
|
|
||||||
{ { "General", "InformationPacket" }, { General_InformationPacket, READ_WRITE } },
|
|
||||||
{ { "Misc", "ImScaredOfUpdates" }, { Misc_ImScaredOfUpdates, READ_WRITE } },
|
|
||||||
{ { "Misc", "UpdateReminderTime" }, { Misc_UpdateReminderTime, READ_WRITE } }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Settings::getAsString(Key key) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined key accessed in Settings::getAsString" };
|
|
||||||
}
|
|
||||||
return std::get<std::string>(map->at(key));
|
|
||||||
}
|
|
||||||
int Settings::getAsInt(Key key) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined key accessed in Settings::getAsInt" };
|
|
||||||
}
|
|
||||||
return std::get<int>(map->at(key));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Settings::getAsBool(Key key) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined key accessed in Settings::getAsBool" };
|
|
||||||
}
|
|
||||||
return std::get<bool>(map->at(key));
|
|
||||||
}
|
|
||||||
|
|
||||||
Settings::SettingsTypeVariant Settings::get(Key key) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined setting key accessed in Settings::get" };
|
|
||||||
}
|
|
||||||
return map->at(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Settings::set(Key key, const std::string& value) {
|
|
||||||
auto map = SettingsMap.synchronize();
|
|
||||||
if (!map->contains(key)) {
|
|
||||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(std::string)" };
|
|
||||||
}
|
|
||||||
if (!std::holds_alternative<std::string>(map->at(key))) {
|
|
||||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(std::string): index {}", map->at(key).index()) };
|
|
||||||
}
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::unordered_map<ComposedKey, Settings::SettingsAccessControl> Settings::getAccessControlMap() const {
|
|
||||||
return *InputAccessMapping;
|
|
||||||
}
|
|
||||||
|
|
||||||
Settings::SettingsAccessControl Settings::getConsoleInputAccessMapping(const ComposedKey& keyName) {
|
|
||||||
auto acl_map = InputAccessMapping.synchronize();
|
|
||||||
if (!acl_map->contains(keyName)) {
|
|
||||||
throw std::logic_error { "Unknown key name accessed in Settings::getConsoleInputAccessMapping" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
|
||||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
|
||||||
}
|
|
||||||
return acl_map->at(keyName);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, const std::string& value) {
|
|
||||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
|
||||||
if (!acl_map->contains(keyName)) {
|
|
||||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
|
||||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
|
||||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
|
||||||
}
|
|
||||||
|
|
||||||
Key key = acl_map->at(keyName).first;
|
|
||||||
|
|
||||||
if (!std::holds_alternative<std::string>(map->at(key))) {
|
|
||||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected std::string" };
|
|
||||||
}
|
|
||||||
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, int value) {
|
|
||||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
|
||||||
if (!acl_map->contains(keyName)) {
|
|
||||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
|
||||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
|
||||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
|
||||||
}
|
|
||||||
|
|
||||||
Key key = acl_map->at(keyName).first;
|
|
||||||
|
|
||||||
if (!std::holds_alternative<int>(map->at(key))) {
|
|
||||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected int" };
|
|
||||||
}
|
|
||||||
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, bool value) {
|
|
||||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
|
||||||
if (!acl_map->contains(keyName)) {
|
|
||||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
|
||||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
|
||||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
|
||||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
|
||||||
}
|
|
||||||
|
|
||||||
Key key = acl_map->at(keyName).first;
|
|
||||||
|
|
||||||
if (!std::holds_alternative<bool>(map->at(key))) {
|
|
||||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected bool" };
|
|
||||||
}
|
|
||||||
|
|
||||||
map->at(key) = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("settings get/set") {
|
|
||||||
Settings settings;
|
|
||||||
settings.set(Settings::General_Name, "hello, world");
|
|
||||||
CHECK_EQ(settings.getAsString(Settings::General_Name), "hello, world");
|
|
||||||
settings.set(Settings::General_Name, std::string("hello, world"));
|
|
||||||
CHECK_EQ(settings.getAsString(Settings::General_Name), "hello, world");
|
|
||||||
settings.set(Settings::General_MaxPlayers, 12);
|
|
||||||
CHECK_EQ(settings.getAsInt(Settings::General_MaxPlayers), 12);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("settings check for exception on wrong input type") {
|
|
||||||
Settings settings;
|
|
||||||
CHECK_THROWS(settings.set(Settings::General_Debug, "hello, world"));
|
|
||||||
CHECK_NOTHROW(settings.set(Settings::General_Debug, false));
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
|
|||||||
+147
-156
@@ -1,33 +1,11 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include "Env.h"
|
|
||||||
#include "Settings.h"
|
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <exception>
|
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <istream>
|
#include <istream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
// General
|
// General
|
||||||
static constexpr std::string_view StrDebug = "Debug";
|
static constexpr std::string_view StrDebug = "Debug";
|
||||||
@@ -54,15 +32,12 @@ static constexpr std::string_view StrAuthKey = "AuthKey";
|
|||||||
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
|
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
|
||||||
static constexpr std::string_view StrLogChat = "LogChat";
|
static constexpr std::string_view StrLogChat = "LogChat";
|
||||||
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
|
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
|
||||||
static constexpr std::string_view StrAllowGuests = "AllowGuests";
|
|
||||||
static constexpr std::string_view EnvStrAllowGuests = "BEAMMP_ALLOW_GUESTS";
|
|
||||||
static constexpr std::string_view StrInformationPacket = "InformationPacket";
|
|
||||||
static constexpr std::string_view EnvStrInformationPacket = "BEAMMP_INFORMATION_PACKET";
|
|
||||||
static constexpr std::string_view StrPassword = "Password";
|
static constexpr std::string_view StrPassword = "Password";
|
||||||
|
|
||||||
// Misc
|
// Misc
|
||||||
|
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
|
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||||
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||||
static constexpr std::string_view StrUpdateReminderTime = "UpdateReminderTime";
|
|
||||||
|
|
||||||
TEST_CASE("TConfig::TConfig") {
|
TEST_CASE("TConfig::TConfig") {
|
||||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||||
@@ -94,9 +69,7 @@ TEST_CASE("TConfig::TConfig") {
|
|||||||
TConfig::TConfig(const std::string& ConfigFileName)
|
TConfig::TConfig(const std::string& ConfigFileName)
|
||||||
: mConfigFileName(ConfigFileName) {
|
: mConfigFileName(ConfigFileName) {
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Starting);
|
Application::SetSubsystemStatus("Config", Application::Status::Starting);
|
||||||
auto DisableConfig = Env::Get(Env::Key::PROVIDER_DISABLE_CONFIG).value_or("false");
|
if (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName)) {
|
||||||
mDisableConfig = DisableConfig == "true" || DisableConfig == "1";
|
|
||||||
if (!mDisableConfig && (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName))) {
|
|
||||||
beammp_info("No config file found! Generating one...");
|
beammp_info("No config file found! Generating one...");
|
||||||
CreateConfigFile();
|
CreateConfigFile();
|
||||||
}
|
}
|
||||||
@@ -126,37 +99,35 @@ void SetComment(CommentsT& Comments, const std::string& Comment) {
|
|||||||
void TConfig::FlushToFile() {
|
void TConfig::FlushToFile() {
|
||||||
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||||
auto data = toml::value {};
|
auto data = toml::value {};
|
||||||
data["General"][StrAuthKey.data()] = Application::Settings.getAsString(Settings::Key::General_AuthKey);
|
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.getAsBool(Settings::Key::General_LogChat);
|
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
|
||||||
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
||||||
data["General"][StrDebug.data()] = Application::Settings.getAsBool(Settings::Key::General_Debug);
|
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||||
data["General"][StrPrivate.data()] = Application::Settings.getAsBool(Settings::Key::General_Private);
|
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||||
SetComment(data["General"][StrInformationPacket.data()].comments(), " Whether to allow unconnected clients to get the public server information without joining");
|
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||||
data["General"][StrInformationPacket.data()] = Application::Settings.getAsBool(Settings::Key::General_InformationPacket);
|
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||||
data["General"][StrAllowGuests.data()] = Application::Settings.getAsBool(Settings::Key::General_AllowGuests);
|
|
||||||
SetComment(data["General"][StrAllowGuests.data()].comments(), " Whether to allow guests");
|
|
||||||
data["General"][StrPort.data()] = Application::Settings.getAsInt(Settings::Key::General_Port);
|
|
||||||
data["General"][StrName.data()] = Application::Settings.getAsString(Settings::Key::General_Name);
|
|
||||||
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
|
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
|
||||||
data["General"][StrTags.data()] = Application::Settings.getAsString(Settings::Key::General_Tags);
|
data["General"][StrTags.data()] = Application::Settings.ServerTags;
|
||||||
data["General"][StrMaxCars.data()] = Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
||||||
data["General"][StrMaxPlayers.data()] = Application::Settings.getAsInt(Settings::Key::General_MaxPlayers);
|
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||||
data["General"][StrMap.data()] = Application::Settings.getAsString(Settings::Key::General_Map);
|
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||||
data["General"][StrDescription.data()] = Application::Settings.getAsString(Settings::Key::General_Description);
|
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||||
data["General"][StrResourceFolder.data()] = Application::Settings.getAsString(Settings::Key::General_ResourceFolder);
|
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||||
// data["General"][StrPassword.data()] = Application::Settings.Password;
|
// data["General"][StrPassword.data()] = Application::Settings.Password;
|
||||||
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
|
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
|
||||||
// Misc
|
// Misc
|
||||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.getAsBool(Settings::Key::Misc_ImScaredOfUpdates);
|
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||||
data["Misc"][StrUpdateReminderTime.data()] = Application::Settings.getAsString(Settings::Key::Misc_UpdateReminderTime);
|
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||||
SetComment(data["Misc"][StrUpdateReminderTime.data()].comments(), " Specifies the time between update reminders. You can use any of \"s, min, h, d\" at the end to specify the units seconds, minutes, hours or days. So 30d or 0.5min will print the update message every 30 days or half a minute.");
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||||
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
std::stringstream Ss;
|
std::stringstream Ss;
|
||||||
Ss << "# This is the BeamMP-Server config file.\n"
|
Ss << "# This is the BeamMP-Server config file.\n"
|
||||||
"# Help & Documentation: `https://docs.beammp.com/server/server-maintenance/`\n"
|
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
|
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
|
||||||
<< toml::format(data);
|
<< data;
|
||||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||||
if (!File) {
|
if (!File) {
|
||||||
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
||||||
@@ -172,152 +143,172 @@ void TConfig::FlushToFile() {
|
|||||||
|
|
||||||
void TConfig::CreateConfigFile() {
|
void TConfig::CreateConfigFile() {
|
||||||
// build from old config Server.cfg
|
// build from old config Server.cfg
|
||||||
if (mDisableConfig) {
|
|
||||||
return;
|
try {
|
||||||
|
if (fs::exists("Server.cfg")) {
|
||||||
|
// parse it (this is weird and bad and should be removed in some future version)
|
||||||
|
ParseOldFormat();
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|
||||||
FlushToFile();
|
FlushToFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
// This arcane template magic is needed for using lambdas as overloaded visitors
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) {
|
||||||
// See https://en.cppreference.com/w/cpp/utility/variant/visit for reference
|
|
||||||
template <class... Ts>
|
|
||||||
struct overloaded : Ts... {
|
|
||||||
using Ts::operator()...;
|
|
||||||
};
|
|
||||||
template <class... Ts>
|
|
||||||
overloaded(Ts...) -> overloaded<Ts...>;
|
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, Settings::Key key) {
|
|
||||||
if (!Env.empty()) {
|
if (!Env.empty()) {
|
||||||
if (const char* envp = std::getenv(Env.data());
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
envp != nullptr && std::strcmp(envp, "") != 0) {
|
OutValue = std::string(envp);
|
||||||
|
|
||||||
std::visit(
|
|
||||||
overloaded {
|
|
||||||
[&envp, &key](std::string) {
|
|
||||||
Application::Settings.set(key, std::string(envp));
|
|
||||||
},
|
|
||||||
[&envp, &key](int) {
|
|
||||||
Application::Settings.set(key, int(std::strtol(envp, nullptr, 10)));
|
|
||||||
},
|
|
||||||
[&envp, &key](bool) {
|
|
||||||
auto Str = std::string(envp);
|
|
||||||
Application::Settings.set(key, bool(Str == "1" || Str == "true"));
|
|
||||||
} },
|
|
||||||
|
|
||||||
Application::Settings.get(key));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
std::visit([&Table, &Category, &Key, &key](auto&& arg) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
|
||||||
using T = std::decay_t<decltype(arg)>;
|
if (!Env.empty()) {
|
||||||
if constexpr (std::is_same_v<T, std::string>) {
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
if (Table[Category.c_str()][Key.data()].is_string())
|
auto Str = std::string(envp);
|
||||||
Application::Settings.set(key, Table[Category.c_str()][Key.data()].as_string());
|
OutValue = Str == "1" || Str == "true";
|
||||||
else
|
return;
|
||||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'string'", Category, Key);
|
|
||||||
} else if constexpr (std::is_same_v<T, int>) {
|
|
||||||
if (Table[Category.c_str()][Key.data()].is_integer())
|
|
||||||
Application::Settings.set(key, int(Table[Category.c_str()][Key.data()].as_integer()));
|
|
||||||
else
|
|
||||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'integer'", Category, Key);
|
|
||||||
} else if constexpr (std::is_same_v<T, bool>) {
|
|
||||||
if (Table[Category.c_str()][Key.data()].is_boolean())
|
|
||||||
Application::Settings.set(key, Table[Category.c_str()][Key.data()].as_boolean());
|
|
||||||
else
|
|
||||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'boolean'", Category, Key);
|
|
||||||
} else {
|
|
||||||
throw std::logic_error { "Invalid type for config value during read attempt" };
|
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
Application::Settings.get(key));
|
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
|
||||||
|
if (!Env.empty()) {
|
||||||
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
|
OutValue = int(std::strtol(envp, nullptr, 10));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||||
|
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseFromFile(std::string_view name) {
|
void TConfig::ParseFromFile(std::string_view name) {
|
||||||
try {
|
try {
|
||||||
toml::value data {};
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
if (!mDisableConfig) {
|
|
||||||
data = toml::parse(name.data());
|
|
||||||
}
|
|
||||||
|
|
||||||
// GENERAL
|
// GENERAL
|
||||||
|
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
|
||||||
// Read into new Settings Singleton
|
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
|
||||||
TryReadValue(data, "General", StrDebug, EnvStrDebug, Settings::Key::General_Debug);
|
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
|
||||||
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Settings::Key::General_Private);
|
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
|
||||||
TryReadValue(data, "General", StrInformationPacket, EnvStrInformationPacket, Settings::Key::General_InformationPacket);
|
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
if (Env::Get(Env::Key::PROVIDER_PORT_ENV).has_value()) {
|
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
|
||||||
TryReadValue(data, "General", StrPort, Env::Get(Env::Key::PROVIDER_PORT_ENV).value(), Settings::Key::General_Port);
|
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
|
||||||
} else {
|
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
|
||||||
TryReadValue(data, "General", StrPort, EnvStrPort, Settings::Key::General_Port);
|
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
|
||||||
}
|
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
|
||||||
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Settings::Key::General_MaxCars);
|
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
|
||||||
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Settings::Key::General_MaxPlayers);
|
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
|
||||||
TryReadValue(data, "General", StrMap, EnvStrMap, Settings::Key::General_Map);
|
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
|
||||||
TryReadValue(data, "General", StrName, EnvStrName, Settings::Key::General_Name);
|
|
||||||
TryReadValue(data, "General", StrDescription, EnvStrDescription, Settings::Key::General_Description);
|
|
||||||
TryReadValue(data, "General", StrTags, EnvStrTags, Settings::Key::General_Tags);
|
|
||||||
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Settings::Key::General_ResourceFolder);
|
|
||||||
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Settings::Key::General_AuthKey);
|
|
||||||
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Settings::Key::General_LogChat);
|
|
||||||
TryReadValue(data, "General", StrAllowGuests, EnvStrAllowGuests, Settings::Key::General_AllowGuests);
|
|
||||||
// Misc
|
// Misc
|
||||||
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Settings::Key::Misc_ImScaredOfUpdates);
|
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
|
||||||
TryReadValue(data, "Misc", StrUpdateReminderTime, "", Settings::Key::Misc_UpdateReminderTime);
|
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
|
||||||
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
|
||||||
} 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;
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
PrintDebug();
|
||||||
|
|
||||||
// Update in any case
|
// Update in any case
|
||||||
if (!mDisableConfig) {
|
FlushToFile();
|
||||||
FlushToFile();
|
|
||||||
}
|
|
||||||
// all good so far, let's check if there's a key
|
// all good so far, let's check if there's a key
|
||||||
if (Application::Settings.getAsString(Settings::Key::General_AuthKey).empty()) {
|
if (Application::Settings.Key.empty()) {
|
||||||
if (mDisableConfig) {
|
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
||||||
beammp_error("No AuthKey specified in the environment.");
|
|
||||||
} else {
|
|
||||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
mFailed = true;
|
mFailed = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
||||||
if (Application::Settings.getAsString(Settings::Key::General_AuthKey).size() != 36) {
|
if (Application::Settings.Key.size() != 36) {
|
||||||
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::PrintDebug() {
|
void TConfig::PrintDebug() {
|
||||||
if (mDisableConfig) {
|
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||||
beammp_debug("Provider turned off the generation and parsing of the ServerConfig.toml");
|
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||||
}
|
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_Debug) ? "true" : "false"));
|
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false"));
|
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||||
beammp_debug(std::string(StrInformationPacket) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_InformationPacket) ? "true" : "false"));
|
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)));
|
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxCars)));
|
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)));
|
|
||||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Map) + "\"");
|
|
||||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Name) + "\"");
|
|
||||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Description) + "\"");
|
|
||||||
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
|
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
|
||||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.getAsBool(Settings::Key::General_LogChat) ? "true" : "false") + "\"");
|
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "\"");
|
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||||
beammp_debug(std::string(StrAllowGuests) + ": \"" + (Application::Settings.getAsBool(Settings::Key::General_AllowGuests) ? "true" : "false") + "\"");
|
|
||||||
// special!
|
// special!
|
||||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.getAsString(Settings::Key::General_AuthKey).length()) + "");
|
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||||
|
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TConfig::ParseOldFormat() {
|
||||||
|
std::ifstream File("Server.cfg");
|
||||||
|
// read all, strip comments
|
||||||
|
std::string Content;
|
||||||
|
for (;;) {
|
||||||
|
std::string Line;
|
||||||
|
std::getline(File, Line);
|
||||||
|
if (!Line.empty() && Line.at(0) != '#') {
|
||||||
|
Line = Line.substr(0, Line.find_first_of('#'));
|
||||||
|
Content += Line + "\n";
|
||||||
|
}
|
||||||
|
if (!File.good()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::stringstream Str(Content);
|
||||||
|
std::string Key, Ignore, Value;
|
||||||
|
for (;;) {
|
||||||
|
Str >> Key >> std::ws >> Ignore >> std::ws;
|
||||||
|
std::getline(Str, Value);
|
||||||
|
if (Str.eof()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::stringstream ValueStream(Value);
|
||||||
|
ValueStream >> std::ws; // strip leading whitespace if any
|
||||||
|
Value = ValueStream.str();
|
||||||
|
if (Key == "Debug") {
|
||||||
|
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
|
||||||
|
} else if (Key == "Private") {
|
||||||
|
Application::Settings.Private = Value.find("true") != std::string::npos;
|
||||||
|
} else if (Key == "Port") {
|
||||||
|
ValueStream >> Application::Settings.Port;
|
||||||
|
} else if (Key == "Cars") {
|
||||||
|
ValueStream >> Application::Settings.MaxCars;
|
||||||
|
} else if (Key == "MaxPlayers") {
|
||||||
|
ValueStream >> Application::Settings.MaxPlayers;
|
||||||
|
} else if (Key == "Map") {
|
||||||
|
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "Name") {
|
||||||
|
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "Desc") {
|
||||||
|
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "use") {
|
||||||
|
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
|
||||||
|
} else if (Key == "AuthKey") {
|
||||||
|
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||||
|
} else {
|
||||||
|
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||||
|
}
|
||||||
|
Str >> std::ws;
|
||||||
|
}
|
||||||
|
}
|
||||||
std::string TConfig::TagsAsPrettyArray() const {
|
std::string TConfig::TagsAsPrettyArray() const {
|
||||||
std::vector<std::string> TagsArray = {};
|
std::vector<std::string> TagsArray = {};
|
||||||
SplitString(Application::Settings.getAsString(Settings::General_Tags), ',', TagsArray);
|
SplitString(Application::Settings.ServerTags, ',', TagsArray);
|
||||||
std::string Pretty = {};
|
std::string Pretty = {};
|
||||||
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
|
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
|
||||||
Pretty += '\"' + TagsArray[i] + "\", ";
|
Pretty += '\"' + TagsArray[i] + "\", ";
|
||||||
|
|||||||
+65
-232
@@ -1,37 +1,14 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
#include <lua.hpp>
|
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <openssl/opensslv.h>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <stdexcept>
|
|
||||||
#include <unordered_map>
|
|
||||||
|
|
||||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||||
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||||
@@ -80,7 +57,7 @@ static std::string GetDate() {
|
|||||||
auto local_tm = std::localtime(&tt);
|
auto local_tm = std::localtime(&tt);
|
||||||
char buf[30];
|
char buf[30];
|
||||||
std::string date;
|
std::string date;
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||||
date += buf;
|
date += buf;
|
||||||
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||||
@@ -108,6 +85,41 @@ void TConsole::BackupOldLog() {
|
|||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_warn(e.what());
|
beammp_warn(e.what());
|
||||||
}
|
}
|
||||||
|
/*
|
||||||
|
int err = 0;
|
||||||
|
zip* z = zip_open("ServerLogs.zip", ZIP_CREATE, &err);
|
||||||
|
if (!z) {
|
||||||
|
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
FILE* File = std::fopen(Path.string().c_str(), "r");
|
||||||
|
if (!File) {
|
||||||
|
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::vector<uint8_t> Buffer;
|
||||||
|
Buffer.resize(fs::file_size(Path));
|
||||||
|
std::fread(Buffer.data(), 1, Buffer.size(), File);
|
||||||
|
std::fclose(File);
|
||||||
|
|
||||||
|
auto s = zip_source_buffer(z, Buffer.data(), Buffer.size(), 0);
|
||||||
|
|
||||||
|
auto TimePoint = fs::last_write_time(Path);
|
||||||
|
auto Secs = TimePoint.time_since_epoch().count();
|
||||||
|
auto MyTimeT = std::time(&Secs);
|
||||||
|
|
||||||
|
std::string NewName = Path.stem().string();
|
||||||
|
NewName += "_";
|
||||||
|
std::string Time;
|
||||||
|
Time.resize(32);
|
||||||
|
size_t n = strftime(Time.data(), Time.size(), "%F_%H.%M.%S", localtime(&MyTimeT));
|
||||||
|
Time.resize(n);
|
||||||
|
NewName += Time;
|
||||||
|
NewName += ".log";
|
||||||
|
|
||||||
|
zip_file_add(z, NewName.c_str(), s, 0);
|
||||||
|
zip_close(z);
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,8 +228,7 @@ void TConsole::Command_Help(const std::string&, const std::vector<std::string>&
|
|||||||
lua [state id] switches to lua, optionally into a specific state id's lua
|
lua [state id] switches to lua, optionally into a specific state id's lua
|
||||||
settings [command] sets or gets settings for the server, run `settings help` for more info
|
settings [command] sets or gets settings for the server, run `settings help` for more info
|
||||||
status how the server is doing and what it's up to
|
status how the server is doing and what it's up to
|
||||||
clear clears the console window
|
clear clears the console window)";
|
||||||
version displays the server version)";
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,32 +248,6 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
|
|||||||
mCommandline->write("\x1b[;H\x1b[2J");
|
mCommandline->write("\x1b[;H\x1b[2J");
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Version(const std::string& cmd, const std::vector<std::string>& args) {
|
|
||||||
if (!EnsureArgsCount(args, 0)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string platform;
|
|
||||||
#if defined(BEAMMP_WINDOWS)
|
|
||||||
platform = "Windows";
|
|
||||||
#elif defined(BEAMMP_LINUX)
|
|
||||||
platform = "Linux";
|
|
||||||
#elif defined(BEAMMP_FREEBSD)
|
|
||||||
platform = "FreeBSD";
|
|
||||||
#elif defined(BEAMMP_APPLE)
|
|
||||||
platform = "Apple";
|
|
||||||
#else
|
|
||||||
platform = "Unknown";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Application::Console().WriteRaw("Platform: " + platform);
|
|
||||||
Application::Console().WriteRaw("Server: v" + Application::ServerVersionString());
|
|
||||||
std::string lua_version = fmt::format("Lua: v{}.{}.{}", LUA_VERSION_MAJOR, LUA_VERSION_MINOR, LUA_VERSION_RELEASE);
|
|
||||||
Application::Console().WriteRaw(lua_version);
|
|
||||||
std::string openssl_version = fmt::format("OpenSSL: v{}.{}.{}", OPENSSL_VERSION_MAJOR, OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH);
|
|
||||||
Application::Console().WriteRaw(openssl_version);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||||
return;
|
return;
|
||||||
@@ -280,17 +265,15 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
|
|||||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||||
};
|
};
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
if (!Client.expired()) {
|
/*mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||||
auto locked = Client.lock();
|
if (NameCompare(Client->Name.get(), Name)) {
|
||||||
if (NameCompare(locked->GetName(), Name)) {
|
mLuaEngine->Network().ClientKick(*Client, Reason);
|
||||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
|
||||||
Kicked = true;
|
Kicked = true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});*/
|
||||||
if (!Kicked) {
|
if (!Kicked) {
|
||||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||||
} else {
|
} else {
|
||||||
@@ -353,142 +336,8 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
return { Command, Args };
|
return { Command, Args };
|
||||||
}
|
}
|
||||||
|
|
||||||
template <class... Ts>
|
|
||||||
struct overloaded : Ts... {
|
|
||||||
using Ts::operator()...;
|
|
||||||
};
|
|
||||||
template <class... Ts>
|
|
||||||
overloaded(Ts...) -> overloaded<Ts...>;
|
|
||||||
|
|
||||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 1, 2)) {
|
||||||
static constexpr const char* sHelpString = R"(
|
|
||||||
Settings:
|
|
||||||
settings help displays this help
|
|
||||||
settings list lists all settings
|
|
||||||
settings get <category> <setting> prints current value of specified setting
|
|
||||||
settings set <category> <setting> <value> sets specified setting to value
|
|
||||||
)";
|
|
||||||
|
|
||||||
if (args.size() == 0) {
|
|
||||||
beammp_errorf("No arguments specified for command 'settings'!");
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (args.front() == "help") {
|
|
||||||
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
|
||||||
return;
|
|
||||||
} else if (args.front() == "get") {
|
|
||||||
if (args.size() < 3) {
|
|
||||||
beammp_errorf("'settings get' needs at least two arguments!");
|
|
||||||
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) });
|
|
||||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
|
||||||
|
|
||||||
std::visit(
|
|
||||||
overloaded {
|
|
||||||
[&args](std::string keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
|
||||||
},
|
|
||||||
[&args](int keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
|
||||||
},
|
|
||||||
[&args](bool keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
|
||||||
}
|
|
||||||
|
|
||||||
},
|
|
||||||
keyType);
|
|
||||||
|
|
||||||
} catch (std::logic_error& e) {
|
|
||||||
beammp_errorf("Error when getting key: {}", e.what());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else if (args.front() == "set") {
|
|
||||||
if (args.size() <= 3) {
|
|
||||||
beammp_errorf("'settings set' needs at least three arguments!");
|
|
||||||
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) });
|
|
||||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
|
||||||
|
|
||||||
std::visit(
|
|
||||||
overloaded {
|
|
||||||
[&args](std::string keyValue) {
|
|
||||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, std::string(args.at(3)));
|
|
||||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), std::string(args.at(3))));
|
|
||||||
},
|
|
||||||
[&args](int keyValue) {
|
|
||||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, std::stoi(args.at(3)));
|
|
||||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), std::stoi(args.at(3))));
|
|
||||||
},
|
|
||||||
[&args](bool keyValue) {
|
|
||||||
if (args.at(3) == "true") {
|
|
||||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, true);
|
|
||||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), "true"));
|
|
||||||
} else if (args.at(3) == "false") {
|
|
||||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, false);
|
|
||||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), "false"));
|
|
||||||
} else {
|
|
||||||
beammp_errorf("Error when setting key: {}::{} : Unknown literal, use either 'true', or 'false' to set boolean values.", args.at(1), args.at(2));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
},
|
|
||||||
keyType);
|
|
||||||
|
|
||||||
} catch (std::logic_error& e) {
|
|
||||||
beammp_errorf("Exception when setting settings key via console: {}", e.what());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (args.front() == "list") {
|
|
||||||
for (const auto& [composedKey, keyACL] : Application::Settings.getAccessControlMap()) {
|
|
||||||
// even though we have the value, we want to ignore it in order to make use of access
|
|
||||||
// control checks
|
|
||||||
|
|
||||||
if (keyACL.second != Settings::SettingsAccessMask::NO_ACCESS) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(composedKey);
|
|
||||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
|
||||||
|
|
||||||
std::visit(
|
|
||||||
overloaded {
|
|
||||||
[&composedKey](std::string keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
|
||||||
},
|
|
||||||
[&composedKey](int keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
|
||||||
},
|
|
||||||
[&composedKey](bool keyValue) {
|
|
||||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
|
||||||
}
|
|
||||||
|
|
||||||
},
|
|
||||||
keyType);
|
|
||||||
} catch (std::logic_error& e) {
|
|
||||||
beammp_errorf("Error when getting key: {}", e.what());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
beammp_errorf("Unknown argument for command 'settings': {}", args.front());
|
|
||||||
|
|
||||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -497,7 +346,7 @@ void TConsole::Command_Say(const std::string& FullCmd) {
|
|||||||
if (FullCmd.size() > 3) {
|
if (FullCmd.size() > 3) {
|
||||||
auto Message = FullCmd.substr(4);
|
auto Message = FullCmd.substr(4);
|
||||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||||
if (!Application::Settings.getAsBool(Settings::Key::General_LogChat)) {
|
if (!Application::Settings.LogChat) {
|
||||||
Application::Console().WriteRaw("Chat message sent!");
|
Application::Console().WriteRaw("Chat message sent!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -507,23 +356,24 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
|
|||||||
if (!EnsureArgsCount(args, 0)) {
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Implement once running
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
if (mLuaEngine->Server().ClientCount() == 0) {
|
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||||
Application::Console().WriteRaw("No players online.");
|
Application::Console().WriteRaw("No players online.");
|
||||||
} else {
|
} else {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||||
if (!Client.expired()) {
|
ss << std::left << std::setw(25) << Client->Name.get()
|
||||||
auto locked = Client.lock();
|
<< std::setw(6) << Client->ID.get()
|
||||||
ss << std::left << std::setw(25) << locked->GetName()
|
<< std::setw(6) << Client->GetCarCount() << "\n";
|
||||||
<< std::setw(6) << locked->GetID()
|
|
||||||
<< std::setw(6) << locked->GetCarCount() << "\n";
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
auto Str = ss.str();
|
auto Str = ss.str();
|
||||||
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||||
@@ -532,29 +382,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
}
|
}
|
||||||
std::stringstream Status;
|
std::stringstream Status;
|
||||||
|
|
||||||
size_t CarCount = 0;
|
|
||||||
size_t ConnectedCount = 0;
|
|
||||||
size_t GuestCount = 0;
|
|
||||||
size_t SyncedCount = 0;
|
|
||||||
size_t SyncingCount = 0;
|
|
||||||
size_t MissedPacketQueueSum = 0;
|
|
||||||
int LargestSecondsSinceLastPing = 0;
|
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
|
||||||
if (!Client.expired()) {
|
|
||||||
auto Locked = Client.lock();
|
|
||||||
CarCount += Locked->GetCarCount();
|
|
||||||
ConnectedCount += Locked->IsUDPConnected() ? 1 : 0;
|
|
||||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
|
||||||
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
|
||||||
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
|
||||||
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
|
||||||
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
|
||||||
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
size_t SystemsStarting = 0;
|
size_t SystemsStarting = 0;
|
||||||
size_t SystemsGood = 0;
|
size_t SystemsGood = 0;
|
||||||
size_t SystemsBad = 0;
|
size_t SystemsBad = 0;
|
||||||
@@ -599,15 +426,21 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
||||||
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||||
|
|
||||||
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
auto ElapsedTime = mUptimeTimer.GetElapsedTime();
|
||||||
|
|
||||||
|
auto network = mLuaEngine->Network();
|
||||||
|
auto clients = network->all_clients();
|
||||||
|
|
||||||
Status << "BeamMP-Server Status:\n"
|
Status << "BeamMP-Server Status:\n"
|
||||||
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
<< "\tTotal Players: " << clients.size() << "\n"
|
||||||
<< "\tSyncing Players: " << SyncingCount << "\n"
|
<< "\tPlayers identifying: " << network->clients_in_state_count(bmp::State::Identification) << "\n"
|
||||||
<< "\tSynced Players: " << SyncedCount << "\n"
|
<< "\tPlayers authenticating: " << network->clients_in_state_count(bmp::State::Authentication) << "\n"
|
||||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
<< "\tPlayers downloading mods: " << network->clients_in_state_count(bmp::State::ModDownload) << "\n"
|
||||||
<< "\tGuests: " << GuestCount << "\n"
|
<< "\tPlayers spawning in: " << network->clients_in_state_count(bmp::State::SessionSetup) << "\n"
|
||||||
<< "\tCars: " << CarCount << "\n"
|
<< "\tPlayers playing: " << network->clients_in_state_count(bmp::State::Playing) << "\n"
|
||||||
|
<< "\tPlayers leaving: " << network->clients_in_state_count(bmp::State::Leaving) << "\n"
|
||||||
|
<< "\tGuests: " << network->guest_count() << "\n"
|
||||||
|
<< "\tVehicles: " << network->vehicle_count() << "\n"
|
||||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||||
<< "\tLua:\n"
|
<< "\tLua:\n"
|
||||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||||
|
|||||||
+51
-84
@@ -1,31 +1,13 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
|
|
||||||
#include "ChronoWrapper.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
// #include "SocketIO.h"
|
// #include "SocketIO.h"
|
||||||
#include <nlohmann/json.hpp>
|
#include <rapidjson/document.h>
|
||||||
|
#include <rapidjson/rapidjson.h>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
namespace json = rapidjson;
|
||||||
|
|
||||||
void THeartbeatThread::operator()() {
|
void THeartbeatThread::operator()() {
|
||||||
RegisterThread("Heartbeat");
|
RegisterThread("Heartbeat");
|
||||||
std::string Body;
|
std::string Body;
|
||||||
@@ -35,17 +17,15 @@ void THeartbeatThread::operator()() {
|
|||||||
static std::string Last;
|
static std::string Last;
|
||||||
|
|
||||||
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||||
static std::chrono::high_resolution_clock::time_point LastUpdateReminderTime = std::chrono::high_resolution_clock::now();
|
|
||||||
bool isAuth = false;
|
bool isAuth = false;
|
||||||
std::chrono::high_resolution_clock::duration UpdateReminderTimePassed;
|
size_t UpdateReminderCounter = 0;
|
||||||
while (!Application::IsShuttingDown()) {
|
while (!Application::IsShuttingDown()) {
|
||||||
auto UpdateReminderTimeout = ChronoWrapper::TimeFromStringWithLiteral(Application::Settings.getAsString(Settings::Key::Misc_UpdateReminderTime));
|
++UpdateReminderCounter;
|
||||||
Body = GenerateCall();
|
Body = GenerateCall();
|
||||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||||
auto Now = std::chrono::high_resolution_clock::now();
|
auto Now = std::chrono::high_resolution_clock::now();
|
||||||
bool Unchanged = Last == Body;
|
bool Unchanged = Last == Body;
|
||||||
auto TimePassed = (Now - LastNormalUpdateTime);
|
auto TimePassed = (Now - LastNormalUpdateTime);
|
||||||
UpdateReminderTimePassed = (Now - LastUpdateReminderTime);
|
|
||||||
auto Threshold = Unchanged ? 30 : 5;
|
auto Threshold = Unchanged ? 30 : 5;
|
||||||
if (TimePassed < std::chrono::seconds(Threshold)) {
|
if (TimePassed < std::chrono::seconds(Threshold)) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
@@ -55,23 +35,22 @@ void THeartbeatThread::operator()() {
|
|||||||
|
|
||||||
Last = Body;
|
Last = Body;
|
||||||
LastNormalUpdateTime = Now;
|
LastNormalUpdateTime = Now;
|
||||||
|
if (!Application::Settings.CustomIP.empty()) {
|
||||||
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
|
}
|
||||||
|
|
||||||
auto Target = "/heartbeat";
|
auto Target = "/heartbeat";
|
||||||
unsigned int ResponseCode = 0;
|
unsigned int ResponseCode = 0;
|
||||||
|
|
||||||
nlohmann::json Doc;
|
json::Document Doc;
|
||||||
bool Ok = false;
|
bool Ok = false;
|
||||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
T = Http::POST(Url + Target, Body, "application/json", &ResponseCode, { { "api-v", "2" } });
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
|
Doc.Parse(T.data(), T.size());
|
||||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
beammp_debug("Backend response was: `" + T + "`");
|
if (!Application::Settings.Private) {
|
||||||
}
|
|
||||||
|
|
||||||
Doc = nlohmann::json::parse(T, nullptr, false);
|
|
||||||
if (Doc.is_discarded() || !Doc.is_object()) {
|
|
||||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
|
||||||
beammp_trace("Backend response failed to parse as valid json");
|
beammp_trace("Backend response failed to parse as valid json");
|
||||||
|
beammp_trace("Response was: `" + T + "`");
|
||||||
}
|
}
|
||||||
} else if (ResponseCode != 200) {
|
} else if (ResponseCode != 200) {
|
||||||
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
|
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
|
||||||
@@ -90,18 +69,18 @@ void THeartbeatThread::operator()() {
|
|||||||
const auto MessageKey = "msg";
|
const auto MessageKey = "msg";
|
||||||
|
|
||||||
if (Ok) {
|
if (Ok) {
|
||||||
if (Doc.contains(StatusKey) && Doc[StatusKey].is_string()) {
|
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
||||||
Status = Doc[StatusKey];
|
Status = Doc[StatusKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
if (Doc.contains(CodeKey) && Doc[CodeKey].is_string()) {
|
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||||
Code = Doc[CodeKey];
|
Code = Doc[CodeKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
if (Doc.contains(MessageKey) && Doc[MessageKey].is_string()) {
|
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||||
Message = Doc[MessageKey];
|
Message = Doc[MessageKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
@@ -109,12 +88,12 @@ void THeartbeatThread::operator()() {
|
|||||||
beammp_error("Missing/invalid json members in backend response");
|
beammp_error("Missing/invalid json members in backend response");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
if (!Application::Settings.Private) {
|
||||||
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Ok && !isAuth && !Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||||
if (Status == "2000") {
|
if (Status == "2000") {
|
||||||
beammp_info(("Authenticated! " + Message));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
@@ -128,45 +107,38 @@ void THeartbeatThread::operator()() {
|
|||||||
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isAuth || Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
if (isAuth || Application::Settings.Private) {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
}
|
}
|
||||||
if (!Application::Settings.getAsBool(Settings::Key::Misc_ImScaredOfUpdates) && UpdateReminderTimePassed.count() > UpdateReminderTimeout.count()) {
|
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||||
LastUpdateReminderTime = std::chrono::high_resolution_clock::now();
|
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string THeartbeatThread::GenerateCall() {
|
std::string THeartbeatThread::GenerateCall() {
|
||||||
nlohmann::json Ret = {
|
std::stringstream Ret;
|
||||||
{ "players", std::to_string(mServer.ClientCount()) },
|
|
||||||
{ "maxplayers", std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)) },
|
|
||||||
{ "port", std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)) },
|
|
||||||
{ "map", Application::Settings.getAsString(Settings::Key::General_Map) },
|
|
||||||
{ "private", Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false" },
|
|
||||||
{ "version", Application::ServerVersionString() },
|
|
||||||
{ "clientversion", Application::ClientMinimumVersion().AsString() },
|
|
||||||
{ "name", Application::Settings.getAsString(Settings::Key::General_Name) },
|
|
||||||
{ "tags", Application::Settings.getAsString(Settings::Key::General_Tags) },
|
|
||||||
{ "guests", Application::Settings.getAsBool(Settings::Key::General_AllowGuests) ? "true" : "false" },
|
|
||||||
{ "modlist", mResourceManager.TrimmedList() },
|
|
||||||
{ "modstotalsize", std::to_string(mResourceManager.MaxModSize()) },
|
|
||||||
{ "modstotal", std::to_string(mResourceManager.ModsLoaded()) },
|
|
||||||
{ "playerslist", GetPlayers() },
|
|
||||||
{ "desc", Application::Settings.getAsString(Settings::Key::General_Description) }
|
|
||||||
};
|
|
||||||
|
|
||||||
lastCall = Ret.dump();
|
Ret << "uuid=" << Application::Settings.Key
|
||||||
|
<< "&players=" << m_network->authenticated_client_count()
|
||||||
// Add sensitive information here because value of lastCall is used for the information packet.
|
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||||
Ret["uuid"] = Application::Settings.getAsString(Settings::Key::General_AuthKey);
|
<< "&port=" << Application::Settings.Port
|
||||||
|
<< "&map=" << Application::Settings.MapName
|
||||||
return Ret.dump();
|
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||||
|
<< "&version=" << Application::ServerVersionString()
|
||||||
|
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||||
|
<< "&name=" << Application::Settings.ServerName
|
||||||
|
<< "&tags=" << Application::Settings.ServerTags
|
||||||
|
<< "&modlist=" << "-"//mResourceManager.TrimmedList()
|
||||||
|
<< "&modstotalsize=" << 0 //mResourceManager.MaxModSize()
|
||||||
|
<< "&modstotal=" << 0 // mResourceManager.ModsLoaded()
|
||||||
|
<< "&playerslist=" << GetPlayers()
|
||||||
|
<< "&desc=" << Application::Settings.ServerDesc
|
||||||
|
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||||
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
|
||||||
: mResourceManager(ResourceManager)
|
: m_network(std::move(network)) {
|
||||||
, mServer(Server) {
|
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||||
@@ -178,15 +150,10 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
|
|||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
std::string THeartbeatThread::GetPlayers() {
|
std::string THeartbeatThread::GetPlayers() {
|
||||||
std::string Return;
|
std::string players;
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
for (const auto& [id, client] : m_network->authenticated_clients()) {
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
players += client->name.get() + ";";
|
||||||
if (!ClientPtr.expired()) {
|
}
|
||||||
Return += ClientPtr.lock()->GetName() + ";";
|
return players;
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return Return;
|
|
||||||
}
|
}
|
||||||
/*THeartbeatThread::~THeartbeatThread() {
|
|
||||||
}*/
|
|
||||||
|
|||||||
+95
-322
@@ -1,63 +1,25 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Profiling.h"
|
|
||||||
#include "TLuaPlugin.h"
|
#include "TLuaPlugin.h"
|
||||||
#include "sol/object.hpp"
|
#include "sol/object.hpp"
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <fmt/core.h>
|
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
#include <optional>
|
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <sol/stack_core.hpp>
|
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
|
|
||||||
TLuaEngine* LuaAPI::MP::Engine;
|
TLuaEngine* LuaAPI::MP::Engine;
|
||||||
|
|
||||||
static sol::protected_function AddTraceback(sol::state_view StateView, sol::protected_function RawFn);
|
|
||||||
|
|
||||||
static std::optional<sol::function> GetLuaHandler(sol::state_view StateView, const std::string Handler, const std::string EventName);
|
|
||||||
|
|
||||||
static std::optional<sol::function> GetLuaHandler(sol::state_view StateView, const std::string Handler, const std::string EventName) {
|
|
||||||
auto Res = StateView.safe_script("return " + Handler, sol::script_pass_on_error);
|
|
||||||
if (!Res.valid()) {
|
|
||||||
beammp_errorf("invalid handler for event \"{}\". handler: \"{}\"", EventName, Handler);
|
|
||||||
} else if (Res.get_type() == sol::type::function) {
|
|
||||||
return Res.get<sol::function>();
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
TLuaEngine::TLuaEngine()
|
TLuaEngine::TLuaEngine()
|
||||||
: mResourceServerPath(fs::path(Application::Settings.getAsString(Settings::Key::General_ResourceFolder)) / "Server") {
|
: mResourceServerPath(fs::path(Application::Settings.Resource) / "Server") {
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
|
||||||
LuaAPI::MP::Engine = this;
|
LuaAPI::MP::Engine = this;
|
||||||
if (!fs::exists(Application::Settings.getAsString(Settings::Key::General_ResourceFolder))) {
|
if (!fs::exists(Application::Settings.Resource)) {
|
||||||
fs::create_directory(Application::Settings.getAsString(Settings::Key::General_ResourceFolder));
|
fs::create_directory(Application::Settings.Resource);
|
||||||
}
|
}
|
||||||
if (!fs::exists(mResourceServerPath)) {
|
if (!fs::exists(mResourceServerPath)) {
|
||||||
fs::create_directory(mResourceServerPath);
|
fs::create_directory(mResourceServerPath);
|
||||||
@@ -69,20 +31,19 @@ TLuaEngine::TLuaEngine()
|
|||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
IThreaded::Start();
|
mThread = boost::scoped_thread<>(&TLuaEngine::Start, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_CASE("TLuaEngine ctor & dtor") {
|
TEST_CASE("TLuaEngine ctor & dtor") {
|
||||||
Application::Settings.set(Settings::Key::General_ResourceFolder, "beammp_server_test_resources");
|
Application::Settings.Resource = "beammp_server_test_resources";
|
||||||
TLuaEngine engine;
|
TLuaEngine engine;
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::operator()() {
|
void TLuaEngine::Start() {
|
||||||
RegisterThread("LuaEngine");
|
RegisterThread("LuaEngine");
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
|
||||||
// lua engine main thread
|
// lua engine main thread
|
||||||
beammp_infof("Lua v{}.{}.{}", LUA_VERSION_MAJOR, LUA_VERSION_MINOR, LUA_VERSION_RELEASE);
|
|
||||||
CollectAndInitPlugins();
|
CollectAndInitPlugins();
|
||||||
// now call all onInit's
|
// now call all onInit's
|
||||||
auto Futures = TriggerEvent("onInit", "");
|
auto Futures = TriggerEvent("onInit", "");
|
||||||
@@ -285,7 +246,7 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const st
|
|||||||
|
|
||||||
for (size_t i = 0; i < keys.size(); ++i) {
|
for (size_t i = 0; i < keys.size(); ++i) {
|
||||||
auto obj = current.get<sol::object>(keys.at(i));
|
auto obj = current.get<sol::object>(keys.at(i));
|
||||||
if (obj.get_type() == sol::type::lua_nil) {
|
if (obj.get_type() == sol::type::nil) {
|
||||||
// error
|
// error
|
||||||
break;
|
break;
|
||||||
} else if (i == keys.size() - 1) {
|
} else if (i == keys.size() - 1) {
|
||||||
@@ -370,39 +331,26 @@ std::shared_ptr<TLuaResult> TLuaEngine::EnqueueScript(TLuaStateId StateID, const
|
|||||||
return mLuaStates.at(StateID)->EnqueueScript(Script);
|
return mLuaStates.at(StateID)->EnqueueScript(Script);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName) {
|
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
|
||||||
std::unique_lock Lock(mLuaStatesMutex);
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args, EventName);
|
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::CollectAndInitPlugins() {
|
void TLuaEngine::CollectAndInitPlugins() {
|
||||||
if (!fs::exists(mResourceServerPath)) {
|
if (!fs::exists(mResourceServerPath)) {
|
||||||
fs::create_directories(mResourceServerPath);
|
fs::create_directories(mResourceServerPath);
|
||||||
}
|
}
|
||||||
|
for (const auto& Dir : fs::directory_iterator(mResourceServerPath)) {
|
||||||
std::vector<fs::path> PluginsEntries;
|
auto Path = Dir.path();
|
||||||
for (const auto& Entry : fs::directory_iterator(mResourceServerPath)) {
|
Path = fs::relative(Path);
|
||||||
if (Entry.is_directory()) {
|
if (!Dir.is_directory()) {
|
||||||
PluginsEntries.push_back(Entry);
|
beammp_error("\"" + Dir.path().string() + "\" is not a directory, skipping");
|
||||||
} else {
|
} else {
|
||||||
beammp_error("\"" + Entry.path().string() + "\" is not a directory, skipping");
|
TLuaPluginConfig Config { Path.stem().string() };
|
||||||
|
FindAndParseConfig(Path, Config);
|
||||||
|
InitializePlugin(Path, Config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::sort(PluginsEntries.begin(), PluginsEntries.end(), [](const fs::path& first, const fs::path& second) {
|
|
||||||
auto firstStr = first.string();
|
|
||||||
auto secondStr = second.string();
|
|
||||||
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
|
|
||||||
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
|
|
||||||
return firstStr < secondStr;
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const auto& Dir : PluginsEntries) {
|
|
||||||
auto Path = fs::relative(Dir);
|
|
||||||
TLuaPluginConfig Config { Path.stem().string() };
|
|
||||||
FindAndParseConfig(Path, Config);
|
|
||||||
InitializePlugin(Path, Config);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config) {
|
void TLuaEngine::InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config) {
|
||||||
@@ -445,7 +393,7 @@ void TLuaEngine::EnsureStateExists(TLuaStateId StateId, const std::string& Name,
|
|||||||
mLuaStates[StateId] = std::move(DataPtr);
|
mLuaStates[StateId] = std::move(DataPtr);
|
||||||
RegisterEvent("onInit", StateId, "onInit");
|
RegisterEvent("onInit", StateId, "onInit");
|
||||||
if (!DontCallOnInit) {
|
if (!DontCallOnInit) {
|
||||||
auto Res = EnqueueFunctionCall(StateId, "onInit", {}, "onInit");
|
auto Res = EnqueueFunctionCall(StateId, "onInit", {});
|
||||||
Res->WaitUntilReady();
|
Res->WaitUntilReady();
|
||||||
if (Res->Error && Res->ErrorMessage != TLuaEngine::BeamMPFnNotFoundError) {
|
if (Res->Error && Res->ErrorMessage != TLuaEngine::BeamMPFnNotFoundError) {
|
||||||
beammp_lua_error("Calling \"onInit\" on \"" + StateId + "\" failed: " + Res->ErrorMessage);
|
beammp_lua_error("Calling \"onInit\" on \"" + StateId + "\" failed: " + Res->ErrorMessage);
|
||||||
@@ -463,64 +411,20 @@ std::set<std::string> TLuaEngine::GetEventHandlersForState(const std::string& Ev
|
|||||||
return mLuaEvents[EventName][StateId];
|
return mLuaEvents[EventName][StateId];
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<sol::object> TLuaEngine::StateThreadData::JsonStringToArray(JsonString Str) {
|
|
||||||
auto LocalTable = Lua_JsonDecode(Str.value).as<std::vector<sol::object>>();
|
|
||||||
for (auto& value : LocalTable) {
|
|
||||||
if (value.is<std::string>() && value.as<std::string>() == BEAMMP_INTERNAL_NIL) {
|
|
||||||
value = sol::object {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return LocalTable;
|
|
||||||
}
|
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
||||||
auto Table = mStateView.create_table();
|
auto Return = mEngine->TriggerEvent(EventName, mStateId, EventArgs);
|
||||||
int i = 1;
|
|
||||||
for (auto Arg : EventArgs) {
|
|
||||||
switch (Arg.get_type()) {
|
|
||||||
case sol::type::none:
|
|
||||||
case sol::type::userdata:
|
|
||||||
case sol::type::lightuserdata:
|
|
||||||
case sol::type::thread:
|
|
||||||
case sol::type::function:
|
|
||||||
case sol::type::poly:
|
|
||||||
Table.set(i, BEAMMP_INTERNAL_NIL);
|
|
||||||
beammp_warnf("Passed a value of type '{}' to TriggerGlobalEvent(\"{}\", ...). This type can not be serialized, and cannot be passed between states. It will arrive as <nil> in handlers.", sol::type_name(EventArgs.lua_state(), Arg.get_type()), EventName);
|
|
||||||
break;
|
|
||||||
case sol::type::lua_nil:
|
|
||||||
Table.set(i, BEAMMP_INTERNAL_NIL);
|
|
||||||
break;
|
|
||||||
case sol::type::string:
|
|
||||||
case sol::type::number:
|
|
||||||
case sol::type::boolean:
|
|
||||||
case sol::type::table:
|
|
||||||
Table.set(i, Arg);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
++i;
|
|
||||||
}
|
|
||||||
JsonString Str { LuaAPI::MP::JsonEncode(Table) };
|
|
||||||
beammp_debugf("json: {}", Str.value);
|
|
||||||
auto Return = mEngine->TriggerEvent(EventName, mStateId, Str);
|
|
||||||
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
|
||||||
|
|
||||||
sol::variadic_results LocalArgs = JsonStringToArray(Str);
|
|
||||||
for (const auto& Handler : MyHandlers) {
|
for (const auto& Handler : MyHandlers) {
|
||||||
auto Res = GetLuaHandler(mStateView, Handler, EventName);
|
auto Fn = mStateView[Handler];
|
||||||
if (Res.has_value()) {
|
if (Fn.valid()) {
|
||||||
sol::function Fn = Res.value();
|
auto LuaResult = Fn(EventArgs);
|
||||||
Fn = AddTraceback(mStateView, Fn);
|
|
||||||
|
|
||||||
auto LuaResult = Fn(LocalArgs);
|
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
if (LuaResult.valid()) {
|
if (LuaResult.valid()) {
|
||||||
Result->Error = false;
|
Result->Error = false;
|
||||||
Result->Result = LuaResult;
|
Result->Result = LuaResult;
|
||||||
} else {
|
} else {
|
||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
sol::error Err = LuaResult;
|
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
||||||
Result->ErrorMessage = Err.what();
|
|
||||||
beammp_errorf("An error occured while executing local event handler \"{}\" for event \"{}\": {}", Handler, EventName, Result->ErrorMessage);
|
|
||||||
}
|
}
|
||||||
Result->MarkAsReady();
|
Result->MarkAsReady();
|
||||||
Return.push_back(Result);
|
Return.push_back(Result);
|
||||||
@@ -544,13 +448,11 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
sol::table Result = StateView.create_table();
|
sol::table Result = StateView.create_table();
|
||||||
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
|
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
|
||||||
int i = 1;
|
|
||||||
for (const auto& Value : Vector) {
|
for (const auto& Value : Vector) {
|
||||||
if (!Value->Ready) {
|
if (!Value->Ready) {
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
Result.set(i, Value->Result);
|
Result.add(Value->Result);
|
||||||
++i;
|
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
});
|
});
|
||||||
@@ -560,15 +462,12 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
|
||||||
// TODO: make asynchronous?
|
// TODO: make asynchronous?
|
||||||
sol::table Result = mStateView.create_table();
|
sol::table Result = mStateView.create_table();
|
||||||
int i = 1;
|
|
||||||
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
|
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
|
||||||
auto Res = GetLuaHandler(mStateView, Handler, EventName);
|
auto Fn = mStateView[Handler];
|
||||||
if (Res.has_value()) {
|
if (Fn.valid() && Fn.get_type() == sol::type::function) {
|
||||||
sol::function Fn = Res.value();
|
|
||||||
auto FnRet = Fn(EventArgs);
|
auto FnRet = Fn(EventArgs);
|
||||||
if (FnRet.valid()) {
|
if (FnRet.valid()) {
|
||||||
Result.set(i, FnRet);
|
Result.add(FnRet);
|
||||||
++i;
|
|
||||||
} else {
|
} else {
|
||||||
sol::error Err = FnRet;
|
sol::error Err = FnRet;
|
||||||
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
|
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
|
||||||
@@ -579,14 +478,14 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
|
|||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
|
auto IDs = MaybeClient.value()->identifiers.synchronize();
|
||||||
if (IDs.empty()) {
|
if (IDs->empty()) {
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
sol::table Result = mStateView.create_table();
|
sol::table Result = mStateView.create_table();
|
||||||
for (const auto& Pair : IDs) {
|
for (const auto& Pair : *IDs) {
|
||||||
Result[Pair.first] = Pair.second;
|
Result[Pair.first] = Pair.second;
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
@@ -595,41 +494,23 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::variant<std::string, sol::nil_t> TLuaEngine::StateThreadData::Lua_GetPlayerRole(int ID) {
|
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
|
||||||
if (MaybeClient) {
|
|
||||||
return MaybeClient.value().lock()->GetRoles();
|
|
||||||
} else {
|
|
||||||
return sol::nil;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
|
||||||
sol::table Result = mStateView.create_table();
|
sol::table result = mStateView.create_table();
|
||||||
mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
auto clients = mEngine->Network()->authenticated_clients();
|
||||||
if (!Client.expired()) {
|
for (const auto& [id, client] : clients) {
|
||||||
auto locked = Client.lock();
|
result[client->id] = client->name.get();
|
||||||
Result[locked->GetID()] = locked->GetName();
|
}
|
||||||
}
|
return result;
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
||||||
int Id = -1;
|
auto clients = mEngine->Network()->authenticated_clients();
|
||||||
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
|
for (const auto& [id, client] : clients) {
|
||||||
if (!Client.expired()) {
|
if (client->name.get() == Name) {
|
||||||
auto locked = Client.lock();
|
return int(client->id);
|
||||||
if (locked->GetName() == Name) {
|
|
||||||
Id = locked->GetID();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return true;
|
}
|
||||||
});
|
return -1;
|
||||||
return Id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
|
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
|
||||||
@@ -659,60 +540,51 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto maybe_client = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (maybe_client) {
|
||||||
return MaybeClient.value().lock()->GetName();
|
return maybe_client.value()->name.get();
|
||||||
} else {
|
} else {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto vehicles = mEngine->Network()->get_vehicles_owned_by(ClientID(ID));
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (vehicles.empty()) {
|
||||||
auto Client = MaybeClient.value().lock();
|
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
|
||||||
{ // Vehicle Data Lock Scope
|
|
||||||
auto LockedData = Client->GetAllCars();
|
|
||||||
VehicleData = *LockedData.VehicleData;
|
|
||||||
} // End Vehicle Data Lock Scope
|
|
||||||
if (VehicleData.empty()) {
|
|
||||||
return sol::lua_nil;
|
|
||||||
}
|
|
||||||
sol::state_view StateView(mState);
|
|
||||||
sol::table Result = StateView.create_table();
|
|
||||||
for (const auto& v : VehicleData) {
|
|
||||||
Result[v.ID()] = v.Data().substr(3);
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
} else
|
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
sol::state_view state_view(mState);
|
||||||
|
sol::table result = state_view.create_table();
|
||||||
|
for (const auto& [vid, vehicle] : vehicles) {
|
||||||
|
result[vid] = vehicle->data.get();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
|
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetVehicleStatus(int VID) {
|
||||||
std::pair<sol::table, std::string> Result;
|
auto maybe_vehicle = mEngine->Network()->get_vehicle(VehicleID(VID));
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), PID);
|
if (maybe_vehicle) {
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
sol::state_view state_view(mState);
|
||||||
auto Client = MaybeClient.value().lock();
|
sol::table result = state_view.create_table();
|
||||||
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
auto veh = maybe_vehicle.value();
|
||||||
|
auto status = veh->get_status();
|
||||||
if (VehiclePos.empty()) {
|
result["pos"]["x"] = status.pos.x;
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
result["pos"]["y"] = status.pos.y;
|
||||||
Result.second = "Vehicle not found";
|
result["pos"]["z"] = status.pos.z;
|
||||||
return Result;
|
result["vel"]["x"] = status.vel.x;
|
||||||
}
|
result["vel"]["y"] = status.vel.y;
|
||||||
|
result["vel"]["z"] = status.vel.z;
|
||||||
sol::table t = Lua_JsonDecode(VehiclePos);
|
result["rvel"]["x"] = status.rvel.x;
|
||||||
if (t == sol::lua_nil) {
|
result["rvel"]["y"] = status.rvel.y;
|
||||||
Result.second = "Packet decode failed";
|
result["rvel"]["z"] = status.rvel.z;
|
||||||
}
|
result["rot"]["x"] = status.rot.x;
|
||||||
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
result["rot"]["y"] = status.rot.y;
|
||||||
Result.first = t;
|
result["rot"]["z"] = status.rot.z;
|
||||||
return Result;
|
result["rot"]["w"] = status.rot.w;
|
||||||
|
result["time"] = status.time;
|
||||||
|
return { result, "" };
|
||||||
} else {
|
} else {
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
return { sol::lua_nil, fmt::format("Vehicle {} not found", VID) };
|
||||||
Result.second = "No such player";
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -750,7 +622,6 @@ static void AddToTable(sol::table& table, const std::string& left, const T& valu
|
|||||||
static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, const std::string& left, const nlohmann::json& right) {
|
static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, const std::string& left, const nlohmann::json& right) {
|
||||||
switch (right.type()) {
|
switch (right.type()) {
|
||||||
case nlohmann::detail::value_t::null:
|
case nlohmann::detail::value_t::null:
|
||||||
AddToTable(table, left, sol::lua_nil_t {});
|
|
||||||
return;
|
return;
|
||||||
case nlohmann::detail::value_t::object: {
|
case nlohmann::detail::value_t::object: {
|
||||||
auto value = table.create();
|
auto value = table.create();
|
||||||
@@ -875,21 +746,10 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
||||||
return Lua_GetPlayerVehicles(ID);
|
return Lua_GetPlayerVehicles(ID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> {
|
MPTable.set_function("GetVehicleStatus", [&](int VID) -> std::pair<sol::table, std::string> {
|
||||||
return Lua_GetPositionRaw(PID, VID);
|
return Lua_GetVehicleStatus(VID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
||||||
MPTable.set_function("SendNotification", [&](sol::variadic_args Args) {
|
|
||||||
if (Args.size() == 2) {
|
|
||||||
LuaAPI::MP::SendNotification(Args.get<int>(0), Args.get<std::string>(1), "", Args.get<std::string>(1));
|
|
||||||
} else if (Args.size() == 3) {
|
|
||||||
LuaAPI::MP::SendNotification(Args.get<int>(0), Args.get<std::string>(1), Args.get<std::string>(2), Args.get<std::string>(1));
|
|
||||||
} else if (Args.size() == 4) {
|
|
||||||
LuaAPI::MP::SendNotification(Args.get<int>(0), Args.get<std::string>(1), Args.get<std::string>(2), Args.get<std::string>(3));
|
|
||||||
} else {
|
|
||||||
beammp_lua_error("SendNotification expects 2, 3 or 4 arguments.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
||||||
return Lua_GetPlayers();
|
return Lua_GetPlayers();
|
||||||
});
|
});
|
||||||
@@ -904,9 +764,6 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("GetPlayerIdentifiers", [&](int ID) -> sol::table {
|
MPTable.set_function("GetPlayerIdentifiers", [&](int ID) -> sol::table {
|
||||||
return Lua_GetPlayerIdentifiers(ID);
|
return Lua_GetPlayerIdentifiers(ID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("GetPlayerRole", [&](int ID) -> std::variant<std::string, sol::nil_t> {
|
|
||||||
return Lua_GetPlayerRole(ID);
|
|
||||||
});
|
|
||||||
MPTable.set_function("Sleep", &LuaAPI::MP::Sleep);
|
MPTable.set_function("Sleep", &LuaAPI::MP::Sleep);
|
||||||
// const std::string& EventName, size_t IntervalMS, int strategy
|
// const std::string& EventName, size_t IntervalMS, int strategy
|
||||||
MPTable.set_function("CreateEventTimer", [&](sol::variadic_args Args) {
|
MPTable.set_function("CreateEventTimer", [&](sol::variadic_args Args) {
|
||||||
@@ -934,43 +791,8 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
mEngine->CancelEventTimers(EventName, mStateId);
|
mEngine->CancelEventTimers(EventName, mStateId);
|
||||||
});
|
});
|
||||||
MPTable.set_function("Set", &LuaAPI::MP::Set);
|
MPTable.set_function("Set", &LuaAPI::MP::Set);
|
||||||
MPTable.set_function("Get", &LuaAPI::MP::Get);
|
|
||||||
|
|
||||||
auto UtilTable = StateView.create_named_table("Util");
|
auto UtilTable = StateView.create_named_table("Util");
|
||||||
UtilTable.set_function("LogDebug", [this](sol::variadic_args args) {
|
|
||||||
std::string ToPrint = "";
|
|
||||||
for (const auto& arg : args) {
|
|
||||||
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
|
|
||||||
ToPrint += "\t";
|
|
||||||
}
|
|
||||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
|
||||||
beammp_lua_log("DEBUG", mStateId, ToPrint);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
UtilTable.set_function("LogInfo", [this](sol::variadic_args args) {
|
|
||||||
std::string ToPrint = "";
|
|
||||||
for (const auto& arg : args) {
|
|
||||||
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
|
|
||||||
ToPrint += "\t";
|
|
||||||
}
|
|
||||||
beammp_lua_log("INFO", mStateId, ToPrint);
|
|
||||||
});
|
|
||||||
UtilTable.set_function("LogWarn", [this](sol::variadic_args args) {
|
|
||||||
std::string ToPrint = "";
|
|
||||||
for (const auto& arg : args) {
|
|
||||||
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
|
|
||||||
ToPrint += "\t";
|
|
||||||
}
|
|
||||||
beammp_lua_log("WARN", mStateId, ToPrint);
|
|
||||||
});
|
|
||||||
UtilTable.set_function("LogError", [this](sol::variadic_args args) {
|
|
||||||
std::string ToPrint = "";
|
|
||||||
for (const auto& arg : args) {
|
|
||||||
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
|
|
||||||
ToPrint += "\t";
|
|
||||||
}
|
|
||||||
beammp_lua_log("ERROR", mStateId, ToPrint);
|
|
||||||
});
|
|
||||||
UtilTable.set_function("JsonEncode", &LuaAPI::MP::JsonEncode);
|
UtilTable.set_function("JsonEncode", &LuaAPI::MP::JsonEncode);
|
||||||
UtilTable.set_function("JsonDecode", [this](const std::string& str) {
|
UtilTable.set_function("JsonDecode", [this](const std::string& str) {
|
||||||
return Lua_JsonDecode(str);
|
return Lua_JsonDecode(str);
|
||||||
@@ -989,30 +811,6 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
UtilTable.set_function("RandomIntRange", [this](int64_t min, int64_t max) -> int64_t {
|
UtilTable.set_function("RandomIntRange", [this](int64_t min, int64_t max) -> int64_t {
|
||||||
return std::uniform_int_distribution(min, max)(mMersenneTwister);
|
return std::uniform_int_distribution(min, max)(mMersenneTwister);
|
||||||
});
|
});
|
||||||
UtilTable.set_function("DebugExecutionTime", [this]() -> sol::table {
|
|
||||||
sol::state_view StateView(mState);
|
|
||||||
sol::table Result = StateView.create_table();
|
|
||||||
auto stats = mProfile.all_stats();
|
|
||||||
for (const auto& [name, stat] : stats) {
|
|
||||||
Result[name] = StateView.create_table();
|
|
||||||
Result[name]["mean"] = stat.mean;
|
|
||||||
Result[name]["stdev"] = stat.stdev;
|
|
||||||
Result[name]["min"] = stat.min;
|
|
||||||
Result[name]["max"] = stat.max;
|
|
||||||
Result[name]["n"] = stat.n;
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
});
|
|
||||||
UtilTable.set_function("DebugStartProfile", [this](const std::string& name) {
|
|
||||||
mProfileStarts[name] = prof::now();
|
|
||||||
});
|
|
||||||
UtilTable.set_function("DebugStopProfile", [this](const std::string& name) {
|
|
||||||
if (!mProfileStarts.contains(name)) {
|
|
||||||
beammp_lua_errorf("DebugStopProfile('{}') failed, because a profile for '{}' wasn't started", name, name);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
mProfile.add_sample(name, prof::duration(mProfileStarts.at(name), prof::now()));
|
|
||||||
});
|
|
||||||
|
|
||||||
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) {
|
||||||
@@ -1026,8 +824,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
"MaxPlayers", 3,
|
"MaxPlayers", 3,
|
||||||
"Map", 4,
|
"Map", 4,
|
||||||
"Name", 5,
|
"Name", 5,
|
||||||
"Description", 6,
|
"Description", 6);
|
||||||
"InformationPacket", 7);
|
|
||||||
|
|
||||||
MPTable.create_named("CallStrategy",
|
MPTable.create_named("CallStrategy",
|
||||||
"BestEffort", CallStrategy::BestEffort,
|
"BestEffort", CallStrategy::BestEffort,
|
||||||
@@ -1051,7 +848,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
FSTable.set_function("ListDirectories", [this](const std::string& Path) {
|
FSTable.set_function("ListDirectories", [this](const std::string& Path) {
|
||||||
return Lua_FS_ListDirectories(Path);
|
return Lua_FS_ListDirectories(Path);
|
||||||
});
|
});
|
||||||
Start();
|
mThread = boost::scoped_thread<>(&StateThreadData::Start, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
|
||||||
@@ -1061,7 +858,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLu
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy) {
|
||||||
// TODO: Document all this
|
// TODO: Document all this
|
||||||
decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end();
|
decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end();
|
||||||
if (Strategy == CallStrategy::BestEffort) {
|
if (Strategy == CallStrategy::BestEffort) {
|
||||||
@@ -1083,12 +880,12 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFrom
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
Result->StateId = mStateId;
|
Result->StateId = mStateId;
|
||||||
Result->Function = FunctionName;
|
Result->Function = FunctionName;
|
||||||
std::unique_lock Lock(mStateFunctionQueueMutex);
|
std::unique_lock Lock(mStateFunctionQueueMutex);
|
||||||
mStateFunctionQueue.push_back({ FunctionName, Result, Args, EventName });
|
mStateFunctionQueue.push_back({ FunctionName, Result, Args, "" });
|
||||||
mStateFunctionQueueCond.notify_all();
|
mStateFunctionQueueCond.notify_all();
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
@@ -1097,22 +894,7 @@ void TLuaEngine::StateThreadData::RegisterEvent(const std::string& EventName, co
|
|||||||
mEngine->RegisterEvent(EventName, mStateId, FunctionName);
|
mEngine->RegisterEvent(EventName, mStateId, FunctionName);
|
||||||
}
|
}
|
||||||
|
|
||||||
static sol::protected_function AddTraceback(sol::state_view StateView, sol::protected_function RawFn) {
|
void TLuaEngine::StateThreadData::Start() {
|
||||||
StateView["INTERNAL_ERROR_HANDLER"] = [](lua_State *L) {
|
|
||||||
auto Error = sol::stack::get<std::optional<std::string>>(L);
|
|
||||||
std::string ErrorString = "<Unknown error>";
|
|
||||||
if (Error.has_value()) {
|
|
||||||
ErrorString = Error.value();
|
|
||||||
}
|
|
||||||
auto DebugTracebackFn = sol::state_view(L).globals().get<sol::table>("debug").get<sol::protected_function>("traceback");
|
|
||||||
// 2 = start collecting the trace one above the current function (1=current function)
|
|
||||||
std::string Traceback = DebugTracebackFn(ErrorString, 2);
|
|
||||||
return sol::stack::push(L, Traceback);
|
|
||||||
};
|
|
||||||
return sol::protected_function(RawFn, StateView["INTERNAL_ERROR_HANDLER"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaEngine::StateThreadData::operator()() {
|
|
||||||
RegisterThread("Lua:" + mStateId);
|
RegisterThread("Lua:" + mStateId);
|
||||||
while (!Application::IsShuttingDown()) {
|
while (!Application::IsShuttingDown()) {
|
||||||
{ // StateExecuteQueue Scope
|
{ // StateExecuteQueue Scope
|
||||||
@@ -1166,7 +948,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
std::chrono::milliseconds(500),
|
std::chrono::milliseconds(500),
|
||||||
[&]() -> bool { return !mStateFunctionQueue.empty(); });
|
[&]() -> bool { return !mStateFunctionQueue.empty(); });
|
||||||
if (NotExpired) {
|
if (NotExpired) {
|
||||||
auto ProfStart = prof::now();
|
|
||||||
auto TheQueuedFunction = std::move(mStateFunctionQueue.front());
|
auto TheQueuedFunction = std::move(mStateFunctionQueue.front());
|
||||||
mStateFunctionQueue.erase(mStateFunctionQueue.begin());
|
mStateFunctionQueue.erase(mStateFunctionQueue.begin());
|
||||||
Lock.unlock();
|
Lock.unlock();
|
||||||
@@ -1176,31 +957,27 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
// TODO: Use TheQueuedFunction.EventName for errors, warnings, etc
|
// TODO: Use TheQueuedFunction.EventName for errors, warnings, etc
|
||||||
Result->StateId = mStateId;
|
Result->StateId = mStateId;
|
||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
|
auto Fn = StateView[FnName];
|
||||||
auto Res = GetLuaHandler(StateView, FnName, TheQueuedFunction.EventName);
|
if (Fn.valid() && Fn.get_type() == sol::type::function) {
|
||||||
if (Res.has_value()) {
|
|
||||||
sol::function Fn = Res.value();
|
|
||||||
std::vector<sol::object> LuaArgs;
|
std::vector<sol::object> LuaArgs;
|
||||||
for (const auto& Arg : Args) {
|
for (const auto& Arg : Args) {
|
||||||
if (Arg.valueless_by_exception()) {
|
if (Arg.valueless_by_exception()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
switch (Arg.index()) {
|
switch (Arg.index()) {
|
||||||
case TLuaType::String:
|
case TLuaArgTypes_String:
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::Int:
|
case TLuaArgTypes_Int:
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::Json: {
|
case TLuaArgTypes_VariadicArgs:
|
||||||
auto LocalArgs = JsonStringToArray(std::get<JsonString>(Arg));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<sol::variadic_args>(Arg)));
|
||||||
LuaArgs.insert(LuaArgs.end(), LocalArgs.begin(), LocalArgs.end());
|
|
||||||
break;
|
break;
|
||||||
}
|
case TLuaArgTypes_Bool:
|
||||||
case TLuaType::Bool:
|
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
||||||
break;
|
break;
|
||||||
case TLuaType::StringStringMap: {
|
case TLuaArgTypes_StringStringMap: {
|
||||||
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
|
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
|
||||||
auto Table = StateView.create_table();
|
auto Table = StateView.create_table();
|
||||||
for (const auto& [k, v] : Map) {
|
for (const auto& [k, v] : Map) {
|
||||||
@@ -1214,7 +991,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Fn = AddTraceback(StateView, Fn);
|
|
||||||
auto Res = Fn(sol::as_args(LuaArgs));
|
auto Res = Fn(sol::as_args(LuaArgs));
|
||||||
if (Res.valid()) {
|
if (Res.valid()) {
|
||||||
Result->Error = false;
|
Result->Error = false;
|
||||||
@@ -1230,9 +1006,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
||||||
Result->MarkAsReady();
|
Result->MarkAsReady();
|
||||||
}
|
}
|
||||||
auto ProfEnd = prof::now();
|
|
||||||
auto ProfDuration = prof::duration(ProfStart, ProfEnd);
|
|
||||||
mProfile.add_sample(FnName, ProfDuration);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TLuaPlugin.h"
|
#include "TLuaPlugin.h"
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
|||||||
-1041
File diff suppressed because it is too large
Load Diff
@@ -1,90 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TPPSMonitor.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "TNetwork.h"
|
|
||||||
|
|
||||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
|
||||||
: mServer(Server) {
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
|
||||||
Application::SetPPS("-");
|
|
||||||
Application::RegisterShutdownHandler([&] {
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
|
||||||
if (mThread.joinable()) {
|
|
||||||
beammp_debug("shutting down PPSMonitor");
|
|
||||||
mThread.join();
|
|
||||||
beammp_debug("shut down PPSMonitor");
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
|
||||||
});
|
|
||||||
Start();
|
|
||||||
}
|
|
||||||
void TPPSMonitor::operator()() {
|
|
||||||
RegisterThread("PPSMonitor");
|
|
||||||
while (!mNetwork) {
|
|
||||||
// hard(-ish) spin
|
|
||||||
std::this_thread::yield();
|
|
||||||
}
|
|
||||||
beammp_debug("PPSMonitor starting");
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
|
||||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
|
||||||
while (!Application::IsShuttingDown()) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
|
||||||
int C = 0, V = 0;
|
|
||||||
if (mServer.ClientCount() == 0) {
|
|
||||||
Application::SetPPS("-");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> c;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
c = ClientPtr.lock();
|
|
||||||
} else
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (c->GetCarCount() > 0) {
|
|
||||||
C++;
|
|
||||||
V += c->GetCarCount();
|
|
||||||
}
|
|
||||||
// kick on "no ping"
|
|
||||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
|
||||||
beammp_debugf("client {} ({}) timing out: {}", c->GetID(), c->GetName(), c->SecondsSinceLastPing());
|
|
||||||
TimedOutClients.push_back(c);
|
|
||||||
} else if (c->IsSynced() && c->SecondsSinceLastPing() > (1 * 60)) {
|
|
||||||
beammp_debugf("client {} ({}) timing out: {}", c->GetName(), c->GetID(), c->SecondsSinceLastPing());
|
|
||||||
TimedOutClients.push_back(c);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
for (auto& ClientToKick : TimedOutClients) {
|
|
||||||
ClientToKick->Disconnect("Timeout");
|
|
||||||
}
|
|
||||||
TimedOutClients.clear();
|
|
||||||
if (C == 0 || mInternalPPS == 0) {
|
|
||||||
Application::SetPPS("-");
|
|
||||||
} else {
|
|
||||||
int R = (mInternalPPS / C) / V;
|
|
||||||
Application::SetPPS(std::to_string(R));
|
|
||||||
}
|
|
||||||
mInternalPPS = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TPluginMonitor.h"
|
#include "TPluginMonitor.h"
|
||||||
|
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|||||||
@@ -1,141 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "Common.h"
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <fmt/core.h>
|
|
||||||
#include <ios>
|
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
#include <openssl/evp.h>
|
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
|
||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
|
||||||
std::string Path = Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "/Client";
|
|
||||||
if (!fs::exists(Path))
|
|
||||||
fs::create_directories(Path);
|
|
||||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
|
||||||
std::string File(entry.path().string());
|
|
||||||
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
|
||||||
if (File.length() - pos == 4) {
|
|
||||||
std::replace(File.begin(), File.end(), '\\', '/');
|
|
||||||
mFileList += File + ';';
|
|
||||||
if (auto i = File.find_last_of('/'); i != std::string::npos) {
|
|
||||||
++i;
|
|
||||||
File = File.substr(i, pos - i);
|
|
||||||
}
|
|
||||||
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
|
||||||
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
|
||||||
mMaxModSize += size_t(fs::file_size(entry.path()));
|
|
||||||
mModsLoaded++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mModsLoaded) {
|
|
||||||
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
|
||||||
}
|
|
||||||
|
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TResourceManager::NewFileList() const {
|
|
||||||
return mMods.dump();
|
|
||||||
}
|
|
||||||
void TResourceManager::RefreshFiles() {
|
|
||||||
mMods.clear();
|
|
||||||
std::unique_lock Lock(mModsMutex);
|
|
||||||
|
|
||||||
std::string Path = Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "/Client";
|
|
||||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
|
||||||
std::string File(entry.path().string());
|
|
||||||
|
|
||||||
if (entry.path().extension() != ".zip" || std::filesystem::is_directory(entry.path())) {
|
|
||||||
beammp_warnf("'{}' is not a ZIP file and will be ignored", File);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
EVP_MD_CTX* mdctx;
|
|
||||||
const EVP_MD* md;
|
|
||||||
uint8_t sha256_value[EVP_MAX_MD_SIZE];
|
|
||||||
md = EVP_sha256();
|
|
||||||
if (md == nullptr) {
|
|
||||||
throw std::runtime_error("EVP_sha256() failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
mdctx = EVP_MD_CTX_new();
|
|
||||||
if (mdctx == nullptr) {
|
|
||||||
throw std::runtime_error("EVP_MD_CTX_new() failed");
|
|
||||||
}
|
|
||||||
if (!EVP_DigestInit_ex2(mdctx, md, NULL)) {
|
|
||||||
EVP_MD_CTX_free(mdctx);
|
|
||||||
throw std::runtime_error("EVP_DigestInit_ex2() failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
std::ifstream stream(File, std::ios::binary);
|
|
||||||
|
|
||||||
const size_t FileSize = std::filesystem::file_size(File);
|
|
||||||
size_t Read = 0;
|
|
||||||
std::vector<char> Data;
|
|
||||||
while (Read < FileSize) {
|
|
||||||
Data.resize(size_t(std::min<size_t>(FileSize - Read, 4096)));
|
|
||||||
size_t RealDataSize = Data.size();
|
|
||||||
stream.read(Data.data(), std::streamsize(Data.size()));
|
|
||||||
if (stream.eof() || stream.fail()) {
|
|
||||||
RealDataSize = size_t(stream.gcount());
|
|
||||||
}
|
|
||||||
Data.resize(RealDataSize);
|
|
||||||
if (RealDataSize == 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (RealDataSize > 0 && !EVP_DigestUpdate(mdctx, Data.data(), Data.size())) {
|
|
||||||
EVP_MD_CTX_free(mdctx);
|
|
||||||
throw std::runtime_error("EVP_DigestUpdate() failed");
|
|
||||||
}
|
|
||||||
Read += RealDataSize;
|
|
||||||
}
|
|
||||||
unsigned int sha256_len = 0;
|
|
||||||
if (!EVP_DigestFinal_ex(mdctx, sha256_value, &sha256_len)) {
|
|
||||||
EVP_MD_CTX_free(mdctx);
|
|
||||||
throw std::runtime_error("EVP_DigestFinal_ex() failed");
|
|
||||||
}
|
|
||||||
EVP_MD_CTX_free(mdctx);
|
|
||||||
|
|
||||||
stream.close();
|
|
||||||
|
|
||||||
std::string result;
|
|
||||||
for (size_t i = 0; i < sha256_len; i++) {
|
|
||||||
result += fmt::format("{:02x}", sha256_value[i]);
|
|
||||||
}
|
|
||||||
beammp_debugf("sha256('{}'): {}", File, result);
|
|
||||||
mMods.push_back(nlohmann::json {
|
|
||||||
{ "file_name", std::filesystem::path(File).filename() },
|
|
||||||
{ "file_size", std::filesystem::file_size(File) },
|
|
||||||
{ "hash_algorithm", "sha256" },
|
|
||||||
{ "hash", result },
|
|
||||||
});
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_errorf("Sha256 hashing of '{}' failed: {}", File, e.what());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TScopedTimer.h"
|
#include "TScopedTimer.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
|
|||||||
-567
@@ -1,567 +0,0 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "TServer.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "TLuaEngine.h"
|
|
||||||
#include "TNetwork.h"
|
|
||||||
#include "TPPSMonitor.h"
|
|
||||||
#include <TLuaPlugin.h>
|
|
||||||
#include <algorithm>
|
|
||||||
#include <any>
|
|
||||||
#include <optional>
|
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
|
|
||||||
#include "LuaAPI.h"
|
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
|
||||||
|
|
||||||
#include "Json.h"
|
|
||||||
|
|
||||||
static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
|
|
||||||
auto IDSep = str.find('-');
|
|
||||||
std::string pid = str.substr(0, IDSep);
|
|
||||||
std::string vid = str.substr(IDSep + 1);
|
|
||||||
|
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
|
||||||
try {
|
|
||||||
int PID = stoi(pid);
|
|
||||||
int VID = stoi(vid);
|
|
||||||
return { { PID, VID } };
|
|
||||||
} catch (const std::exception&) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("GetPidVid") {
|
|
||||||
SUBCASE("Valid singledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-1");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 0);
|
|
||||||
CHECK_EQ(vid, 1);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("10-12");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 10);
|
|
||||||
CHECK_EQ(vid, 12);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit 2") {
|
|
||||||
const auto MaybePidVid = GetPidVid("10-2");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 10);
|
|
||||||
CHECK_EQ(vid, 2);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit 3") {
|
|
||||||
const auto MaybePidVid = GetPidVid("33-23");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 33);
|
|
||||||
CHECK_EQ(vid, 23);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit 4") {
|
|
||||||
const auto MaybePidVid = GetPidVid("3-23");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 3);
|
|
||||||
CHECK_EQ(vid, 23);
|
|
||||||
}
|
|
||||||
SUBCASE("Empty string") {
|
|
||||||
const auto MaybePidVid = GetPidVid("");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid separator") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0x0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("x-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-x");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
|
||||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
|
||||||
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
|
||||||
try {
|
|
||||||
LockedClientPtr = WeakClientPtr.lock();
|
|
||||||
} catch (const std::exception&) {
|
|
||||||
// silently fail, as there's nothing to do
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
beammp_assert(LockedClientPtr != nullptr);
|
|
||||||
TClient& Client = *LockedClientPtr;
|
|
||||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
|
||||||
Client.ClearCars();
|
|
||||||
WriteLock Lock(mClientsMutex);
|
|
||||||
mClients.erase(WeakClientPtr.lock());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
|
||||||
decltype(mClients) Clients;
|
|
||||||
{
|
|
||||||
ReadLock lock(mClientsMutex);
|
|
||||||
Clients = mClients;
|
|
||||||
}
|
|
||||||
for (auto& Client : Clients) {
|
|
||||||
if (!Fn(Client)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t TServer::ClientCount() const {
|
|
||||||
ReadLock Lock(mClientsMutex);
|
|
||||||
return mClients.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
|
||||||
constexpr std::string_view ABG = "ABG:";
|
|
||||||
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
|
||||||
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
|
||||||
try {
|
|
||||||
Packet = DeComp(Packet);
|
|
||||||
} catch (const InvalidDataError& ) {
|
|
||||||
auto LockedClient = Client.lock();
|
|
||||||
beammp_errorf("Failed to decompress packet from client {}. The client sent invalid data and will now be disconnected.", LockedClient->GetID());
|
|
||||||
Network.ClientKick(*LockedClient, "Sent invalid compressed packet (this is likely a bug on your end)");
|
|
||||||
return;
|
|
||||||
} catch (const std::runtime_error& e) {
|
|
||||||
auto LockedClient = Client.lock();
|
|
||||||
beammp_errorf("Failed to decompress packet from client {}: {}. The server might be out of RAM! The client will now be disconnected.", LockedClient->GetID(), e.what());
|
|
||||||
Network.ClientKick(*LockedClient, "Decompression failed (likely a server-side problem)");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (Packet.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Client.expired()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto LockedClient = Client.lock();
|
|
||||||
|
|
||||||
std::any Res;
|
|
||||||
char Code = Packet.at(0);
|
|
||||||
|
|
||||||
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
|
||||||
|
|
||||||
// V to Y
|
|
||||||
if (Code <= 89 && Code >= 86) {
|
|
||||||
PPSMonitor.IncrementInternalPPS();
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch (Code) {
|
|
||||||
case 'H': // initial connection
|
|
||||||
if (!Network.SyncClient(Client)) {
|
|
||||||
// TODO handle
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'p':
|
|
||||||
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
|
||||||
// failed to send
|
|
||||||
LockedClient->Disconnect("Failed to send ping");
|
|
||||||
} else {
|
|
||||||
Network.UpdatePlayer(*LockedClient);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'O':
|
|
||||||
if (Packet.size() > 1000) {
|
|
||||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
|
||||||
}
|
|
||||||
ParseVehicle(*LockedClient, StringPacket, Network);
|
|
||||||
return;
|
|
||||||
case 'C': {
|
|
||||||
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
|
||||||
break;
|
|
||||||
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
|
||||||
std::string Message = "";
|
|
||||||
const auto ColonPos = PacketAsString.find(':', 3);
|
|
||||||
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
|
|
||||||
Message = PacketAsString.substr(ColonPos + 2);
|
|
||||||
}
|
|
||||||
if (Message.empty()) {
|
|
||||||
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
|
||||||
bool Rejected = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
|
||||||
return !Elem->Error
|
|
||||||
&& Elem->Result.is<int>()
|
|
||||||
&& bool(Elem->Result.as<int>());
|
|
||||||
});
|
|
||||||
if (!Rejected) {
|
|
||||||
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
|
||||||
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
|
||||||
}
|
|
||||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postChatMessage", "", !Rejected, LockedClient->GetID(), LockedClient->GetName(), Message);
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'E':
|
|
||||||
HandleEvent(*LockedClient, StringPacket);
|
|
||||||
return;
|
|
||||||
case 'N':
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
|
||||||
return;
|
|
||||||
case 'Z': // position packet
|
|
||||||
PPSMonitor.IncrementInternalPPS();
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
HandlePosition(*LockedClient, StringPacket);
|
|
||||||
return;
|
|
||||||
default:
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
|
||||||
// E:Name:Data
|
|
||||||
// Data is allowed to have ':'
|
|
||||||
if (RawData.size() < 2) {
|
|
||||||
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto NameDataSep = RawData.find(':', 2);
|
|
||||||
if (NameDataSep == std::string::npos) {
|
|
||||||
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
try {
|
|
||||||
auto Car = nlohmann::json::parse(CarJson);
|
|
||||||
const std::string jbm = "jbm";
|
|
||||||
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
|
||||||
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
|
|
||||||
c.SetUnicycleID(ID);
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return c.GetCarCount() < Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
|
||||||
if (Pckt.length() < 6)
|
|
||||||
return;
|
|
||||||
std::string Packet = Pckt;
|
|
||||||
char Code = Packet.at(1);
|
|
||||||
int PID = -1;
|
|
||||||
int VID = -1;
|
|
||||||
std::string Data = Packet.substr(3), pid, vid;
|
|
||||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
|
||||||
case 's':
|
|
||||||
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
|
||||||
if (Data.at(0) == '0') {
|
|
||||||
int CarID = c.GetOpenCarID();
|
|
||||||
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
|
||||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
bool SpawnConfirmed = false;
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
|
||||||
c.AddNewCar(CarID, Packet);
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
|
||||||
SpawnConfirmed = true;
|
|
||||||
} else {
|
|
||||||
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), CarID));
|
|
||||||
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
|
||||||
SpawnConfirmed = false;
|
|
||||||
}
|
|
||||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postVehicleSpawn", "", SpawnConfirmed, c.GetID(), CarID, Packet.substr(3));
|
|
||||||
// the post event is not cancellable so we dont wait for it
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'c': {
|
|
||||||
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
|
||||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
auto FoundPos = Packet.find('{');
|
|
||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
|
||||||
bool Allowed = false;
|
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
|
||||||
&& !ShouldntAllow) {
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
Apply(c, VID, Packet);
|
|
||||||
Allowed = true;
|
|
||||||
} else {
|
|
||||||
if (c.GetUnicycleID() == VID) {
|
|
||||||
c.SetUnicycleID(-1);
|
|
||||||
}
|
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
|
||||||
c.DeleteCar(VID);
|
|
||||||
Allowed = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postVehicleEdited", "", Allowed, c.GetID(), VID, Packet.substr(3));
|
|
||||||
// the post event is not cancellable so we dont wait for it
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'd': {
|
|
||||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
if (c.GetUnicycleID() == VID) {
|
|
||||||
c.SetUnicycleID(-1);
|
|
||||||
}
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
|
||||||
// TODO: should this trigger on all vehicle deletions?
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
|
||||||
c.DeleteCar(VID);
|
|
||||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'r': {
|
|
||||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
Data = Data.substr(Data.find('{'));
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 't': {
|
|
||||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'm': {
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'p': {
|
|
||||||
beammp_trace(std::string(("got 'Op' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
Data = Data.substr(Data.find('['));
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehiclePaintChanged", "", c.GetID(), VID, Data));
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|
||||||
auto FoundPos = pckt.find('{');
|
|
||||||
if (FoundPos == std::string::npos) {
|
|
||||||
beammp_error("Malformed packet received, no '{' found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string Packet = pckt.substr(FoundPos);
|
|
||||||
std::string VD = c.GetCarData(VID);
|
|
||||||
if (VD.empty()) {
|
|
||||||
beammp_error("Tried to apply change to vehicle that does not exist");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string Header = VD.substr(0, VD.find('{'));
|
|
||||||
|
|
||||||
FoundPos = VD.find('{');
|
|
||||||
if (FoundPos == std::string::npos) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
VD = VD.substr(FoundPos);
|
|
||||||
rapidjson::Document Veh, Pack;
|
|
||||||
Veh.Parse(VD.c_str());
|
|
||||||
if (Veh.HasParseError()) {
|
|
||||||
beammp_error("Could not get vehicle config!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Pack.Parse(Packet.c_str());
|
|
||||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
|
||||||
beammp_error("Could not get active vehicle config!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (auto& M : Pack.GetObject()) {
|
|
||||||
if (Veh[M.name].IsNull()) {
|
|
||||||
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
|
|
||||||
} else {
|
|
||||||
Veh[M.name] = Pack[M.name];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rapidjson::StringBuffer Buffer;
|
|
||||||
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
|
|
||||||
Veh.Accept(writer);
|
|
||||||
c.SetCarData(VID, Header + Buffer.GetString());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
|
||||||
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
|
||||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
|
||||||
(void)mClients.insert(NewClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PidVidData {
|
|
||||||
int PID;
|
|
||||||
int VID;
|
|
||||||
std::string Data;
|
|
||||||
};
|
|
||||||
|
|
||||||
static std::optional<PidVidData> ParsePositionPacket(const std::string& Packet) {
|
|
||||||
if (Packet.size() < 3) {
|
|
||||||
// invalid packet
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
// Zp:PID-VID:DATA
|
|
||||||
std::string withoutCode = Packet.substr(3);
|
|
||||||
|
|
||||||
// parse veh ID
|
|
||||||
if (auto DataBeginPos = withoutCode.find('{'); DataBeginPos != std::string::npos && DataBeginPos != 0) {
|
|
||||||
// separator is :{, so position of { minus one
|
|
||||||
auto PidVidOnly = withoutCode.substr(0, DataBeginPos - 1);
|
|
||||||
auto MaybePidVid = GetPidVid(PidVidOnly);
|
|
||||||
if (MaybePidVid) {
|
|
||||||
int PID = -1;
|
|
||||||
int VID = -1;
|
|
||||||
// FIXME: check that the VID and PID are valid, so that we don't waste memory
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
|
|
||||||
std::string Data = withoutCode.substr(DataBeginPos);
|
|
||||||
return PidVidData {
|
|
||||||
.PID = PID,
|
|
||||||
.VID = VID,
|
|
||||||
.Data = Data,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
// invalid packet
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// invalid packet
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("ParsePositionPacket") {
|
|
||||||
const auto TestData = R"({"tim":10.428000331623,"vel":[-2.4171722121385e-05,-9.7184734153252e-06,-7.6420763232237e-06],"rot":[-0.0001296154171915,0.0031575385950029,0.98994906610295,0.14138903660382],"rvel":[5.3640324636461e-05,-9.9824529946024e-05,5.1664064641372e-05],"pos":[-0.27281248907838,-0.20515357944633,0.49695488960431],"ping":0.032999999821186})";
|
|
||||||
SUBCASE("All the pids and vids") {
|
|
||||||
for (int pid = 0; pid < 100; ++pid) {
|
|
||||||
for (int vid = 0; vid < 100; ++vid) {
|
|
||||||
std::optional<PidVidData> MaybeRes = ParsePositionPacket(fmt::format("Zp:{}-{}:{}", pid, vid, TestData));
|
|
||||||
CHECK(MaybeRes.has_value());
|
|
||||||
CHECK_EQ(MaybeRes.value().PID, pid);
|
|
||||||
CHECK_EQ(MaybeRes.value().VID, vid);
|
|
||||||
CHECK_EQ(MaybeRes.value().Data, TestData);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
|
||||||
if (auto Parsed = ParsePositionPacket(Packet); Parsed.has_value()) {
|
|
||||||
c.SetCarPosition(Parsed.value().VID, Parsed.value().Data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|||||||
+48
-67
@@ -1,54 +1,31 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#include "ArgsParser.h"
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Settings.h"
|
|
||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "TNetwork.h"
|
|
||||||
#include "TPPSMonitor.h"
|
|
||||||
#include "TPluginMonitor.h"
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdlib>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <spdlog/sinks/rotating_file_sink.h>
|
||||||
|
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||||
|
#include <spdlog/spdlog.h>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
static const std::string sCommandlineArguments = R"(
|
static const std::string sCommandlineArguments = R"(
|
||||||
USAGE:
|
USAGE:
|
||||||
BeamMP-Server [arguments]
|
BeamMP-Server [arguments]
|
||||||
|
|
||||||
ARGUMENTS:
|
ARGUMENTS:
|
||||||
--help
|
--help
|
||||||
Displays this help and exits.
|
Displays this help and exits.
|
||||||
--port=1234
|
|
||||||
Sets the server's listening TCP and
|
|
||||||
UDP port. Overrides ENV and ServerConfig.
|
|
||||||
--config=/path/to/ServerConfig.toml
|
--config=/path/to/ServerConfig.toml
|
||||||
Absolute or relative path to the
|
Absolute or relative path to the
|
||||||
Server Config file, including the
|
Server Config file, including the
|
||||||
filename. For paths and filenames with
|
filename. For paths and filenames with
|
||||||
spaces, put quotes around the path.
|
spaces, put quotes around the path.
|
||||||
--working-directory=/path/to/folder
|
--working-directory=/path/to/folder
|
||||||
Sets the working directory of the Server.
|
Sets the working directory of the Server.
|
||||||
@@ -59,7 +36,7 @@ ARGUMENTS:
|
|||||||
|
|
||||||
EXAMPLES:
|
EXAMPLES:
|
||||||
BeamMP-Server --config=../MyWestCoastServerConfig.toml
|
BeamMP-Server --config=../MyWestCoastServerConfig.toml
|
||||||
Runs the BeamMP-Server and uses the server config file
|
Runs the BeamMP-Server and uses the server config file
|
||||||
which is one directory above it and is named
|
which is one directory above it and is named
|
||||||
'MyWestCoastServerConfig.toml'.
|
'MyWestCoastServerConfig.toml'.
|
||||||
)";
|
)";
|
||||||
@@ -90,13 +67,37 @@ int main(int argc, char** argv) {
|
|||||||
std::exit(MainRet);
|
std::exit(MainRet);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static std::shared_ptr<spdlog::logger> default_logger;
|
||||||
|
|
||||||
|
static void setup_logger() {
|
||||||
|
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||||
|
console_sink->set_pattern("[%H:%M:%S] [%^%l%$] %v");
|
||||||
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
|
console_sink->set_level(spdlog::level::debug);
|
||||||
|
} else {
|
||||||
|
console_sink->set_level(spdlog::level::info);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("Launcher.log", 1024 * 1024, 3, true);
|
||||||
|
file_sink->set_level(spdlog::level::trace);
|
||||||
|
file_sink->set_pattern("[%H:%M:%S.%e] [%t] [%l] %v");
|
||||||
|
|
||||||
|
default_logger = std::make_shared<spdlog::logger>(spdlog::logger("default", { console_sink, file_sink }));
|
||||||
|
|
||||||
|
default_logger->set_level(spdlog::level::trace);
|
||||||
|
default_logger->flush_on(spdlog::level::trace);
|
||||||
|
|
||||||
|
spdlog::set_default_logger(default_logger);
|
||||||
|
|
||||||
|
spdlog::debug("Logger initialized");
|
||||||
|
}
|
||||||
|
|
||||||
int BeamMPServerMain(MainArguments Arguments) {
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
setlocale(LC_ALL, "C");
|
setlocale(LC_ALL, "C");
|
||||||
ArgsParser Parser;
|
ArgsParser Parser;
|
||||||
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||||
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||||
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
|
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
|
||||||
Parser.RegisterArgument({ "port" }, ArgsParser::HAS_VALUE);
|
|
||||||
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
|
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
|
||||||
Parser.Parse(Arguments.List);
|
Parser.Parse(Arguments.List);
|
||||||
if (!Parser.Verify()) {
|
if (!Parser.Verify()) {
|
||||||
@@ -111,14 +112,18 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// badly seed C's rng - this is only because rand() is used here and there for unimportant stuff
|
||||||
|
std::srand(std::time(0));
|
||||||
|
|
||||||
std::string ConfigPath = "ServerConfig.toml";
|
std::string ConfigPath = "ServerConfig.toml";
|
||||||
if (Parser.FoundArgument({ "config" })) {
|
if (Parser.FoundArgument({ "config" })) {
|
||||||
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||||
if (MaybeConfigPath.has_value()) {
|
if (MaybeConfigPath.has_value()) {
|
||||||
ConfigPath = MaybeConfigPath.value();
|
ConfigPath = MaybeConfigPath.value();
|
||||||
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
// beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
setup_logger();
|
||||||
if (Parser.FoundArgument({ "working-directory" })) {
|
if (Parser.FoundArgument({ "working-directory" })) {
|
||||||
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
||||||
if (MaybeWorkingDirectory.has_value()) {
|
if (MaybeWorkingDirectory.has_value()) {
|
||||||
@@ -141,24 +146,6 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
}
|
}
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// override port if provided via arguments
|
|
||||||
if (Parser.FoundArgument({ "port" })) {
|
|
||||||
auto Port = Parser.GetValueOfArgument({ "port" });
|
|
||||||
if (Port.has_value()) {
|
|
||||||
auto P = int(std::strtoul(Port.value().c_str(), nullptr, 10));
|
|
||||||
if (P == 0 || P < 0 || P > UINT16_MAX) {
|
|
||||||
beammp_errorf("Custom port requested via --port is invalid: '{}'", Port.value());
|
|
||||||
return 1;
|
|
||||||
} else {
|
|
||||||
Application::Settings.set(Settings::Key::General_Port, P);
|
|
||||||
beammp_info("Custom port requested via commandline arguments: " + Port.value());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Config.PrintDebug();
|
|
||||||
|
|
||||||
Application::InitializeConsole();
|
Application::InitializeConsole();
|
||||||
Application::Console().StartLoggingToFile();
|
Application::Console().StartLoggingToFile();
|
||||||
|
|
||||||
@@ -166,9 +153,6 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
|
|
||||||
SetupSignalHandlers();
|
SetupSignalHandlers();
|
||||||
|
|
||||||
Settings settings {};
|
|
||||||
beammp_infof("Server name set in new impl: {}", settings.getAsString(Settings::Key::General_Name));
|
|
||||||
|
|
||||||
bool Shutdown = false;
|
bool Shutdown = false;
|
||||||
Application::RegisterShutdownHandler([&Shutdown] {
|
Application::RegisterShutdownHandler([&Shutdown] {
|
||||||
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
||||||
@@ -180,25 +164,22 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||||
});
|
});
|
||||||
|
|
||||||
TServer Server(Arguments.List);
|
|
||||||
|
|
||||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
LuaEngine->SetServer(&Server);
|
|
||||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
RegisterThread("Main");
|
RegisterThread("Main");
|
||||||
|
|
||||||
beammp_trace("Running in debug mode on a debug build");
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
TResourceManager ResourceManager;
|
std::shared_ptr<Network> network = std::make_shared<Network>();
|
||||||
ResourceManager.RefreshFiles();
|
THeartbeatThread Heartbeat(network);
|
||||||
TPPSMonitor PPSMonitor(Server);
|
LuaEngine->SetNetwork(network);
|
||||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
|
||||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
|
||||||
LuaEngine->SetNetwork(&Network);
|
|
||||||
PPSMonitor.SetNetwork(Network);
|
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.getAsString(Settings::Key::General_ResourceFolder)) / "Server", LuaEngine);
|
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||||
|
|
||||||
|
if (Application::Settings.HTTPServerEnabled) {
|
||||||
|
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||||
|
}
|
||||||
|
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||||
RegisterThread("Main(Waiting)");
|
RegisterThread("Main(Waiting)");
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
local function assert_eq(x, y, explain)
|
|
||||||
if x ~= y then
|
|
||||||
print("assertion '"..explain.."' failed:\n\tgot:\t", x, "\n\texpected:", y)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
---@param o1 any|table First object to compare
|
|
||||||
---@param o2 any|table Second object to compare
|
|
||||||
---@param ignore_mt boolean True to ignore metatables (a recursive function to tests tables inside tables)
|
|
||||||
function equals(o1, o2, ignore_mt)
|
|
||||||
if o1 == o2 then return true end
|
|
||||||
local o1Type = type(o1)
|
|
||||||
local o2Type = type(o2)
|
|
||||||
if o1Type ~= o2Type then return false end
|
|
||||||
if o1Type ~= 'table' then return false end
|
|
||||||
|
|
||||||
if not ignore_mt then
|
|
||||||
local mt1 = getmetatable(o1)
|
|
||||||
if mt1 and mt1.__eq then
|
|
||||||
--compare using built in method
|
|
||||||
return o1 == o2
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
local keySet = {}
|
|
||||||
|
|
||||||
for key1, value1 in pairs(o1) do
|
|
||||||
local value2 = o2[key1]
|
|
||||||
if value2 == nil or equals(value1, value2, ignore_mt) == false then
|
|
||||||
return false
|
|
||||||
end
|
|
||||||
keySet[key1] = true
|
|
||||||
end
|
|
||||||
|
|
||||||
for key2, _ in pairs(o2) do
|
|
||||||
if not keySet[key2] then return false end
|
|
||||||
end
|
|
||||||
return true
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
local function assert_table_eq(x, y, explain)
|
|
||||||
if not equals(x, y, true) then
|
|
||||||
print("assertion '"..explain.."' failed:\n\tgot:\t", x, "\n\texpected:", y)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
assert_eq(Util.JsonEncode({1, 2, 3, 4, 5}), "[1,2,3,4,5]", "table to array")
|
|
||||||
assert_eq(Util.JsonEncode({"a", 1, 2, 3, 4, 5}), '["a",1,2,3,4,5]', "table to array")
|
|
||||||
assert_eq(Util.JsonEncode({"a", 1, 2.0, 3, 4, 5}), '["a",1,2.0,3,4,5]', "table to array")
|
|
||||||
assert_eq(Util.JsonEncode({hello="world", john={doe = 1, jane = 2.5, mike = {2, 3, 4}}, dave={}}), '{"dave":{},"hello":"world","john":{"doe":1,"jane":2.5,"mike":[2,3,4]}}', "table to obj")
|
|
||||||
assert_eq(Util.JsonEncode({a = nil}), "{}", "null obj member")
|
|
||||||
assert_eq(Util.JsonEncode({1, nil, 3}), "[1,3]", "null array member")
|
|
||||||
assert_eq(Util.JsonEncode({}), "{}", "empty array/table")
|
|
||||||
assert_eq(Util.JsonEncode({1234}), "[1234]", "int")
|
|
||||||
assert_eq(Util.JsonEncode({1234.0}), "[1234.0]", "double")
|
|
||||||
|
|
||||||
assert_table_eq(Util.JsonDecode("[1,2,3,4,5]"), {1, 2, 3, 4, 5}, "decode table to array")
|
|
||||||
assert_table_eq(Util.JsonDecode('["a",1,2,3,4,5]'), {"a", 1, 2, 3, 4, 5}, "decode table to array")
|
|
||||||
assert_table_eq(Util.JsonDecode('["a",1,2.0,3,4,5]'), {"a", 1, 2.0, 3, 4, 5}, "decode table to array")
|
|
||||||
assert_table_eq(Util.JsonDecode('{"dave":{},"hello":"world","john":{"doe":1,"jane":2.5,"mike":[2,3,4]}}'), {hello="world", john={doe = 1, jane = 2.5, mike = {2, 3, 4}}, dave={}}, "decode table to obj")
|
|
||||||
assert_table_eq(Util.JsonDecode("{}"), {a = nil}, "decode null obj member")
|
|
||||||
assert_table_eq(Util.JsonDecode("[1,3]"), {1, 3}, "decode null array member")
|
|
||||||
assert_table_eq(Util.JsonDecode("{}"), {}, "decode empty array/table")
|
|
||||||
assert_table_eq(Util.JsonDecode("[1234]"), {1234}, "decode int")
|
|
||||||
assert_table_eq(Util.JsonDecode("[1234.0]"), {1234.0}, "decode double")
|
|
||||||
@@ -1,21 +1,3 @@
|
|||||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
|
||||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
|
||||||
//
|
|
||||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
|
||||||
//
|
|
||||||
// This program is free software: you can redistribute it and/or modify
|
|
||||||
// it under the terms of the GNU Affero General Public License as published
|
|
||||||
// by the Free Software Foundation, either version 3 of the License, or
|
|
||||||
// (at your option) any later version.
|
|
||||||
//
|
|
||||||
// This program is distributed in the hope that it will be useful,
|
|
||||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
// GNU Affero General Public License for more details.
|
|
||||||
//
|
|
||||||
// You should have received a copy of the GNU Affero General Public License
|
|
||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
#define DOCTEST_CONFIG_IMPLEMENT
|
#define DOCTEST_CONFIG_IMPLEMENT
|
||||||
#include <doctest/doctest.h>
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule vcpkg updated: 6978381401...8397227251
+7
-2
@@ -6,14 +6,19 @@
|
|||||||
"boost-spirit",
|
"boost-spirit",
|
||||||
"boost-uuid",
|
"boost-uuid",
|
||||||
"boost-variant",
|
"boost-variant",
|
||||||
|
"boost-iostreams",
|
||||||
"cpp-httplib",
|
"cpp-httplib",
|
||||||
"doctest",
|
"doctest",
|
||||||
"fmt",
|
"fmt",
|
||||||
"libzip",
|
|
||||||
"nlohmann-json",
|
"nlohmann-json",
|
||||||
"openssl",
|
"openssl",
|
||||||
"rapidjson",
|
"rapidjson",
|
||||||
"sol2",
|
"sol2",
|
||||||
"curl"
|
"toml11",
|
||||||
|
"zstd",
|
||||||
|
"glm",
|
||||||
|
"libzip",
|
||||||
|
"spdlog",
|
||||||
|
"readline"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user