mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-14 18:55:58 +00:00
Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2d8c12ccd6 | |||
| 65e0fd61ba | |||
| 5cac6da14e | |||
| d003608503 | |||
| 35fdb2f8fc | |||
| 10efab4d71 | |||
| 8472160493 | |||
| 186903be7f | |||
| e8caeb9126 | |||
| fa1944dbef | |||
| 093f905fd8 | |||
| 2a45d2282d | |||
| aeb024953a | |||
| 12a0ab7fdd | |||
| 917c501faf | |||
| 340933bbb3 | |||
| a63359479e | |||
| bdf2da758c | |||
| 88c0ed56e4 | |||
| 4256977400 | |||
| 309a9d1fa9 | |||
| ad860835ca | |||
| c6c2efb0b1 | |||
| c4c3b03b7a | |||
| fd51336a91 | |||
| 466845b314 | |||
| 92632b53b5 | |||
| 331a597ec7 | |||
| 87965433c2 | |||
| 75ff9f7571 | |||
| 94c0547a35 | |||
| 98f77e157f | |||
| 54730d2baf | |||
| 064e71e59f | |||
| 2678234d67 | |||
| 4320a91e5c | |||
| 7d1318653c | |||
| 67d02d4cf2 | |||
| 93b2559120 | |||
| ed872f730d | |||
| b25f4a875c | |||
| cc6b7846b2 | |||
| 88f5db514f | |||
| e595192829 | |||
| c69418ea5e | |||
| 917e3f98ab | |||
| c42a523532 | |||
| 95ae0f5d03 | |||
| fc0a509bd9 | |||
| 6249397fb5 | |||
| 231b13a0e7 | |||
| 7d2e4d4581 | |||
| 7446526a19 | |||
| 6e97a3cd6e | |||
| 30482d290a | |||
| 5f1d003077 | |||
| 5d3dff3c88 | |||
| cb0cb30797 | |||
| 1f14de2e71 | |||
| 658b37acac | |||
| d63c84286e | |||
| 9c6127a105 | |||
| fdf24815bb |
@@ -1,18 +1,13 @@
|
|||||||
name: CMake Linux Build
|
name: CMake Linux Build
|
||||||
|
|
||||||
on:
|
on: [push]
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, reopened]
|
|
||||||
pull_request_review:
|
|
||||||
types: [submitted]
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
BUILD_TYPE: Release
|
BUILD_TYPE: Release
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
linux-build:
|
linux-build:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-22.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
@@ -25,7 +20,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
echo ${#beammp_sentry_url}
|
echo ${#beammp_sentry_url}
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
@@ -61,23 +56,23 @@ jobs:
|
|||||||
|
|
||||||
run-tests:
|
run-tests:
|
||||||
needs: linux-build
|
needs: linux-build
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-22.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@master
|
- uses: actions/download-artifact@master
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server-linux-tests
|
name: BeamMP-Server-linux-tests
|
||||||
path: ${{github.workspace}}
|
path: ${{github.workspace}}
|
||||||
|
|
||||||
- name: Install Runtime Dependencies
|
- name: Install Runtime Dependencies
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y liblua5.3 openssl
|
sudo apt-get install -y liblua5.3-0 libssl3 curl
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
working-directory: ${{github.workspace}}
|
working-directory: ${{github.workspace}}
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
chmod +x ./BeamMP-Server-tests
|
chmod +x ./BeamMP-Server-tests
|
||||||
./BeamMP-Server-tests
|
./BeamMP-Server-tests
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
name: CMake Windows Build
|
name: CMake Windows Build
|
||||||
|
|
||||||
on:
|
on: [push]
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
types: [opened, reopened]
|
|
||||||
pull_request_review:
|
|
||||||
types: [submitted]
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
BUILD_TYPE: Release
|
BUILD_TYPE: Release
|
||||||
@@ -13,20 +8,20 @@ env:
|
|||||||
jobs:
|
jobs:
|
||||||
windows-build:
|
windows-build:
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
with:
|
with:
|
||||||
submodules: "recursive"
|
submodules: 'recursive'
|
||||||
|
|
||||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||||
uses: lukka/run-vcpkg@v7
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: "lua zlib rapidjson openssl websocketpp curl"
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio'
|
||||||
vcpkgDirectory: "${{ runner.workspace }}/b/vcpkg"
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: "a106de33bbee694e3be6243718aa2a549a692832"
|
vcpkgGitCommitId: "06b5f4a769d848d1a20fa0acd556019728b56273"
|
||||||
vcpkgTriplet: "x64-windows-static"
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
||||||
@@ -54,9 +49,10 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
cmake --build . --config Debug
|
cmake --build . --config Debug
|
||||||
|
|
||||||
- name: Archive debug artifacts
|
- name: Archive debug artifacts
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server-debug.exe
|
name: BeamMP-Server-debug.exe
|
||||||
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ jobs:
|
|||||||
|
|
||||||
upload-release-files-linux:
|
upload-release-files-linux:
|
||||||
name: Upload Linux Release Files
|
name: Upload Linux Release Files
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-22.04
|
||||||
needs: create-release
|
needs: create-release
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
@@ -42,7 +42,7 @@ jobs:
|
|||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev libboost-dev libboost1.74-all-dev libboost1.74-dev
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
@@ -83,9 +83,9 @@ jobs:
|
|||||||
uses: lukka/run-vcpkg@v7
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio'
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
vcpkgGitCommitId: '06b5f4a769d848d1a20fa0acd556019728b56273'
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
|
|||||||
+19
-7
@@ -46,11 +46,14 @@ if(APPLE)
|
|||||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||||
endif()
|
endif()
|
||||||
# ------------------------ WINDOWS ---------------------------------
|
# ------------------------ WINDOWS ---------------------------------
|
||||||
|
option(WIN32_STATIC_RUNTIME "Build statically-linked runtime on windows (don't touch unless you know what you're doing)" ON)
|
||||||
elseif (WIN32)
|
elseif (WIN32)
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
if (WIN32_STATIC_RUNTIME)
|
||||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||||
|
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||||
|
endif()
|
||||||
# ------------------------ LINUX ---------------------------------
|
# ------------------------ LINUX ---------------------------------
|
||||||
elseif (UNIX)
|
elseif (UNIX)
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
||||||
@@ -95,6 +98,8 @@ include(FindOpenSSL)
|
|||||||
include(FindThreads)
|
include(FindThreads)
|
||||||
include(FindZLIB)
|
include(FindZLIB)
|
||||||
|
|
||||||
|
find_package(Boost 1.70 REQUIRED COMPONENTS system)
|
||||||
|
|
||||||
set(BeamMP_Sources
|
set(BeamMP_Sources
|
||||||
include/TConsole.h src/TConsole.cpp
|
include/TConsole.h src/TConsole.cpp
|
||||||
include/TServer.h src/TServer.cpp
|
include/TServer.h src/TServer.cpp
|
||||||
@@ -117,6 +122,7 @@ set(BeamMP_Sources
|
|||||||
include/ArgsParser.h src/ArgsParser.cpp
|
include/ArgsParser.h src/ArgsParser.cpp
|
||||||
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
||||||
include/Environment.h
|
include/Environment.h
|
||||||
|
include/BoostAliases.h
|
||||||
)
|
)
|
||||||
|
|
||||||
set(BeamMP_Includes
|
set(BeamMP_Includes
|
||||||
@@ -135,6 +141,10 @@ set(BeamMP_Definitions
|
|||||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (WIN32)
|
||||||
|
list(APPEND BeamMP_Definitions _WIN32_WINNT=0x0601)
|
||||||
|
list(APPEND BeamMP_Definitions _CRT_SECURE_NO_WARNINGS)
|
||||||
|
endif()
|
||||||
if (UNIX)
|
if (UNIX)
|
||||||
set(BeamMP_CompileOptions
|
set(BeamMP_CompileOptions
|
||||||
-Wall
|
-Wall
|
||||||
@@ -156,20 +166,22 @@ if (UNIX)
|
|||||||
-Werror=missing-field-initializers
|
-Werror=missing-field-initializers
|
||||||
-Werror=write-strings
|
-Werror=write-strings
|
||||||
-Werror=ctor-dtor-privacy
|
-Werror=ctor-dtor-privacy
|
||||||
-Werror=switch-enum
|
-Wswitch-enum
|
||||||
-Werror=switch-default
|
-Wswitch-default
|
||||||
-Werror=old-style-cast
|
-Werror=old-style-cast
|
||||||
-Werror=overloaded-virtual
|
-Werror=overloaded-virtual
|
||||||
-Werror=zero-as-null-pointer-constant
|
|
||||||
-Werror=overloaded-virtual
|
-Werror=overloaded-virtual
|
||||||
-Werror=missing-include-dirs
|
-Werror=missing-include-dirs
|
||||||
-Werror=unused-result
|
-Werror=unused-result
|
||||||
|
|
||||||
-fstack-protector
|
-fstack-protector
|
||||||
|
-Wzero-as-null-pointer-constant
|
||||||
)
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
set(BeamMP_Libraries
|
set(BeamMP_Libraries
|
||||||
|
Boost::boost
|
||||||
|
Boost::system
|
||||||
doctest::doctest
|
doctest::doctest
|
||||||
OpenSSL::SSL
|
OpenSSL::SSL
|
||||||
OpenSSL::Crypto
|
OpenSSL::Crypto
|
||||||
@@ -210,7 +222,7 @@ target_include_directories(BeamMP-Server SYSTEM PRIVATE
|
|||||||
${BeamMP_Includes}
|
${BeamMP_Includes}
|
||||||
)
|
)
|
||||||
|
|
||||||
target_link_libraries(BeamMP-Server
|
target_link_libraries(BeamMP-Server
|
||||||
${BeamMP_Libraries}
|
${BeamMP_Libraries}
|
||||||
${BeamMP_PlatformLibs}
|
${BeamMP_PlatformLibs}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
# v3.2.0
|
||||||
|
|
||||||
|
- ADDED `settings` command, which lets you `get`, `list`, and `set` config options from the console
|
||||||
|
|
||||||
# v3.1.0
|
# v3.1.0
|
||||||
|
|
||||||
@@ -10,6 +13,9 @@
|
|||||||
- ADDED error messages to some lua functions
|
- ADDED error messages to some lua functions
|
||||||
- ADDED HOME and END button working in console
|
- ADDED HOME and END button working in console
|
||||||
- ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON
|
- ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON
|
||||||
|
- ADDED identifiers (beammp id, ip) to onPlayerAuth (4th argument)
|
||||||
|
- ADDED more network debug logging
|
||||||
|
- CHANGED all networking to be more stable, performant, and safe
|
||||||
- FIXED `ip` in MP.GetPlayerIdentifiers
|
- FIXED `ip` in MP.GetPlayerIdentifiers
|
||||||
- FIXED issue with client->server events which contain `:`
|
- FIXED issue with client->server events which contain `:`
|
||||||
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||||
@@ -18,6 +24,8 @@
|
|||||||
- FIXED bug which caused hot-reload not to report syntax errors
|
- FIXED bug which caused hot-reload not to report syntax errors
|
||||||
- FIXED missing error messages on some event handler calls
|
- FIXED missing error messages on some event handler calls
|
||||||
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
|
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
|
||||||
|
- FIXED server not handling binary UDP packets properly
|
||||||
|
- REMOVED "Backend response failed to parse as valid json" message
|
||||||
|
|
||||||
# v3.0.2
|
# v3.0.2
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ These values are guesstimated and are subject to change with each release.
|
|||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned.
|
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" or "good first issue" label or with nobody assigned.
|
||||||
|
|
||||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ 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 `v1.20`.
|
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
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__**
|
||||||
|
|
||||||
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||||
|
|
||||||
@@ -59,35 +59,110 @@ Currently only Linux and Windows are supported (generally). See [Releases](https
|
|||||||
|
|
||||||
#### Windows
|
#### Windows
|
||||||
|
|
||||||
|
There are **no runtime libraries** needed for Windows.
|
||||||
|
|
||||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||||
|
|
||||||
Dependencies for **Windows** can be installed with `vcpkg`.
|
Dependencies for **Windows** can be installed with `vcpkg`.
|
||||||
These are:
|
These are:
|
||||||
```
|
```
|
||||||
lua
|
lua zlib rapidjson openssl websocketpp curl
|
||||||
zlib
|
|
||||||
rapidjson
|
|
||||||
openssl
|
|
||||||
websocketpp
|
|
||||||
curl
|
|
||||||
```
|
```
|
||||||
|
The triplet we use for releases is `x64-windows-static`.
|
||||||
|
|
||||||
#### Linux
|
#### Linux
|
||||||
|
|
||||||
Runtime dependencies - you want to find packages for:
|
We recommend Ubuntu 22.04 or Arch Linux. Any Linux distribution will work, but you have to figure out the package names yourself (please feel free to PR in a change to this README with that info).
|
||||||
- libz
|
|
||||||
- rapidjson
|
|
||||||
- lua5.3
|
|
||||||
- ssl / openssl
|
|
||||||
- websocketpp
|
|
||||||
- curl (with ssl support)
|
|
||||||
|
|
||||||
Build-time dependencies are:
|
##### Runtime Dependencies
|
||||||
|
|
||||||
|
These are needed to *run* the server.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>
|
||||||
|
Ubuntu 22.04
|
||||||
|
</summary>
|
||||||
|
|
||||||
|
`apt-get install` the following libraries:
|
||||||
|
```
|
||||||
|
liblua5.3-0
|
||||||
|
libssl3
|
||||||
|
curl
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>
|
||||||
|
Arch Linux
|
||||||
|
</summary>
|
||||||
|
|
||||||
|
`pacman -Syu` the following libraries:
|
||||||
|
```
|
||||||
|
lua53
|
||||||
|
openssl
|
||||||
|
curl
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
##### Build Dependencies
|
||||||
|
These are needed for you to *build* the server, in addition to the [runtime dependencies](#runtime-dependencies).
|
||||||
|
|
||||||
|
**Ubuntu 22.04**
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>
|
||||||
|
Ubuntu 22.04
|
||||||
|
</summary>
|
||||||
|
|
||||||
|
`apt-get install` the following libraries and programs:
|
||||||
```
|
```
|
||||||
git
|
git
|
||||||
make
|
libz-dev
|
||||||
|
rapidjson-dev
|
||||||
|
liblua5.3
|
||||||
|
libssl-dev
|
||||||
|
libwebsocketpp-dev
|
||||||
|
libcurl4-openssl-dev
|
||||||
|
cmake
|
||||||
|
g++-10
|
||||||
|
libboost1.74-all-dev
|
||||||
|
libssl3
|
||||||
|
curl
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>
|
||||||
|
Arch Linux
|
||||||
|
</summary>
|
||||||
|
|
||||||
|
`pacman -Syu` the following libraries and programs:
|
||||||
|
```
|
||||||
|
lua53
|
||||||
|
openssl
|
||||||
|
curl
|
||||||
|
git
|
||||||
cmake
|
cmake
|
||||||
g++
|
g++
|
||||||
|
cmake
|
||||||
|
zlib
|
||||||
|
boost
|
||||||
|
websocketpp
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
#### macOS
|
||||||
|
|
||||||
|
Dependencies for **macOS** can be installed with homebrew.
|
||||||
|
```
|
||||||
|
brew install lua@5.3 rapidjson websocketpp cmake openssl@1.1
|
||||||
|
```
|
||||||
|
Some packages are included in **macOS** but you might want to install homebrew versions.
|
||||||
|
```
|
||||||
|
brew install curl zlib git make
|
||||||
```
|
```
|
||||||
|
|
||||||
### How to build
|
### How to build
|
||||||
@@ -95,13 +170,12 @@ g++
|
|||||||
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
|
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||||
|
|
||||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
1. Make sure you have all [prerequisites](#prerequisites) installed
|
||||||
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
2. Clone the repository in a location of your choice with `git clone https://github.com/BeamMP/BeamMP-Server` .
|
||||||
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
|
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
|
||||||
4. Checkout the branch of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
4. Checkout the branch or tag of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||||
5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
|
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`). This may take some time, and will update all submodules and prepare the build.
|
||||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
7. Run `make -j` . This step will take some time and will use a lot of CPU and RAM. Remove the `-j` if you run out of memory. *If you change something in the source code, you only have to re-run this step.*
|
||||||
7. Run `make`
|
8. You now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||||
8. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
|
||||||
|
|
||||||
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
||||||
|
|
||||||
|
|||||||
Vendored
+1
-1
Submodule deps/sentry-native updated: 87e67ad783...28be51f5e3
@@ -0,0 +1,6 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/system/error_code.hpp>
|
||||||
|
|
||||||
|
using namespace boost::asio;
|
||||||
+23
-19
@@ -7,6 +7,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
@@ -19,9 +20,8 @@ class TServer;
|
|||||||
#endif // WINDOWS
|
#endif // WINDOWS
|
||||||
|
|
||||||
struct TConnection final {
|
struct TConnection final {
|
||||||
SOCKET Socket;
|
ip::tcp::socket Socket;
|
||||||
struct sockaddr SockAddr;
|
ip::tcp::endpoint SockAddr;
|
||||||
socklen_t SockAddrLen;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class TClient final {
|
class TClient final {
|
||||||
@@ -33,8 +33,9 @@ public:
|
|||||||
std::unique_lock<std::mutex> Lock;
|
std::unique_lock<std::mutex> Lock;
|
||||||
};
|
};
|
||||||
|
|
||||||
explicit TClient(TServer& Server);
|
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
||||||
TClient(const TClient&) = delete;
|
TClient(const TClient&) = delete;
|
||||||
|
~TClient();
|
||||||
TClient& operator=(const TClient&) = delete;
|
TClient& operator=(const TClient&) = delete;
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
void AddNewCar(int Ident, const std::string& Data);
|
||||||
@@ -46,16 +47,20 @@ public:
|
|||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||||
std::string GetCarData(int Ident);
|
std::string GetCarData(int Ident);
|
||||||
std::string GetCarPositionRaw(int Ident);
|
std::string GetCarPositionRaw(int Ident);
|
||||||
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
||||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
||||||
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
||||||
void SetStatus(int Status) { mStatus = Status; }
|
void Disconnect(std::string_view Reason);
|
||||||
|
bool IsDisconnected() const { return !mSocket.is_open(); }
|
||||||
// locks
|
// locks
|
||||||
void DeleteCar(int Ident);
|
void DeleteCar(int Ident);
|
||||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||||
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
||||||
|
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
||||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||||
[[nodiscard]] std::string GetName() const { return mName; }
|
[[nodiscard]] std::string GetName() const { return mName; }
|
||||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
||||||
@@ -63,7 +68,6 @@ public:
|
|||||||
[[nodiscard]] int GetOpenCarID() const;
|
[[nodiscard]] int GetOpenCarID() const;
|
||||||
[[nodiscard]] int GetCarCount() const;
|
[[nodiscard]] int GetCarCount() const;
|
||||||
void ClearCars();
|
void ClearCars();
|
||||||
[[nodiscard]] int GetStatus() const { return mStatus; }
|
|
||||||
[[nodiscard]] int GetID() const { return mID; }
|
[[nodiscard]] int GetID() const { return mID; }
|
||||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||||
@@ -73,9 +77,9 @@ public:
|
|||||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
||||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
||||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
||||||
void EnqueuePacket(const std::string& Packet);
|
void EnqueuePacket(const std::vector<uint8_t>& Packet);
|
||||||
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
|
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
||||||
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
|
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
||||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||||
@@ -91,7 +95,7 @@ private:
|
|||||||
bool mIsSynced = false;
|
bool mIsSynced = false;
|
||||||
bool mIsSyncing = false;
|
bool mIsSyncing = false;
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
mutable std::mutex mMissedPacketsMutex;
|
||||||
std::queue<std::string> mPacketsSync;
|
std::queue<std::vector<uint8_t>> mPacketsSync;
|
||||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||||
bool mIsGuest = false;
|
bool mIsGuest = false;
|
||||||
mutable std::mutex mVehicleDataMutex;
|
mutable std::mutex mVehicleDataMutex;
|
||||||
@@ -99,12 +103,12 @@ private:
|
|||||||
TSetOfVehicleData mVehicleData;
|
TSetOfVehicleData mVehicleData;
|
||||||
SparseArray<std::string> mVehiclePosition;
|
SparseArray<std::string> mVehiclePosition;
|
||||||
std::string mName = "Unknown Client";
|
std::string mName = "Unknown Client";
|
||||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
ip::tcp::socket mSocket;
|
||||||
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
ip::tcp::socket mDownSocket;
|
||||||
|
ip::udp::endpoint mUDPAddress {};
|
||||||
int mUnicycleID = -1;
|
int mUnicycleID = -1;
|
||||||
std::string mRole;
|
std::string mRole;
|
||||||
std::string mDID;
|
std::string mDID;
|
||||||
int mStatus = 0;
|
|
||||||
int mID = -1;
|
int mID = -1;
|
||||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||||
};
|
};
|
||||||
|
|||||||
+54
-31
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "CustomAssert.h"
|
||||||
#include "TSentry.h"
|
#include "TSentry.h"
|
||||||
extern TSentry Sentry;
|
extern TSentry Sentry;
|
||||||
|
|
||||||
@@ -23,6 +24,38 @@ namespace fs = std::filesystem;
|
|||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
|
#include <boost/container/flat_map.hpp>
|
||||||
|
#include <boost/variant.hpp>
|
||||||
|
|
||||||
|
// General
|
||||||
|
constexpr std::string_view StrDebug = "Debug";
|
||||||
|
constexpr std::string_view StrPrivate = "Private";
|
||||||
|
constexpr std::string_view StrPort = "Port";
|
||||||
|
constexpr std::string_view StrMaxCars = "MaxCars";
|
||||||
|
constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
||||||
|
constexpr std::string_view StrMap = "Map";
|
||||||
|
constexpr std::string_view StrName = "Name";
|
||||||
|
constexpr std::string_view StrDescription = "Description";
|
||||||
|
constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||||
|
constexpr std::string_view StrAuthKey = "AuthKey";
|
||||||
|
constexpr std::string_view StrLogChat = "LogChat";
|
||||||
|
|
||||||
|
// Misc
|
||||||
|
constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
|
constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||||
|
constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||||
|
|
||||||
|
// HTTP
|
||||||
|
constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||||
|
constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
||||||
|
constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
||||||
|
constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
||||||
|
constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
||||||
|
constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||||
|
|
||||||
|
// Unused
|
||||||
|
constexpr std::string_view StrCustomIP = "CustomIP";
|
||||||
|
|
||||||
struct Version {
|
struct Version {
|
||||||
uint8_t major;
|
uint8_t major;
|
||||||
uint8_t minor;
|
uint8_t minor;
|
||||||
@@ -35,6 +68,9 @@ struct Version {
|
|||||||
template <typename T>
|
template <typename T>
|
||||||
using SparseArray = std::unordered_map<size_t, T>;
|
using SparseArray = std::unordered_map<size_t, T>;
|
||||||
|
|
||||||
|
using boost::variant;
|
||||||
|
using boost::container::flat_map;
|
||||||
|
|
||||||
// static class handling application start, shutdown, etc.
|
// static class handling application start, shutdown, etc.
|
||||||
// yes, static classes, singletons, globals are all pretty
|
// yes, static classes, singletons, globals are all pretty
|
||||||
// bad idioms. In this case we need a central way to access
|
// bad idioms. In this case we need a central way to access
|
||||||
@@ -43,30 +79,17 @@ 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" };
|
using SettingValue = variant<std::string, bool, int>;
|
||||||
std::string ServerDesc { "BeamMP Default Description" };
|
using SettingsMap = flat_map<std::string_view, SettingValue>;
|
||||||
std::string Resource { "Resources" };
|
|
||||||
std::string MapName { "/levels/gridmap_v2/info.json" };
|
static SettingsMap mSettings;
|
||||||
std::string Key {};
|
|
||||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
static std::string GetSettingString(std::string_view Name);
|
||||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
static int GetSettingInt(std::string_view Name);
|
||||||
bool HTTPServerEnabled { false };
|
static bool GetSettingBool(std::string_view Name);
|
||||||
int MaxPlayers { 8 };
|
|
||||||
bool Private { true };
|
static void SetSetting(std::string_view Name, const SettingValue& value);
|
||||||
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()>;
|
||||||
|
|
||||||
@@ -80,12 +103,10 @@ 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 std::string ClientVersionString() { return "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 TSettings Settings;
|
|
||||||
|
|
||||||
static std::vector<std::string> GetBackendUrlsInOrder() {
|
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||||
return {
|
return {
|
||||||
"backend.beammp.com",
|
"backend.beammp.com",
|
||||||
@@ -125,6 +146,8 @@ public:
|
|||||||
|
|
||||||
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
||||||
|
|
||||||
|
static std::string SettingToString(const SettingValue& Value);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static void SetShutdown(bool Val);
|
static void SetShutdown(bool Val);
|
||||||
|
|
||||||
@@ -137,7 +160,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, 1, 0 };
|
static inline Version mVersion { 3, 2, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride = false);
|
std::string ThreadName(bool DebugModeOverride = false);
|
||||||
@@ -205,13 +228,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.DebugModeEnabled) { \
|
if (Application::GetSettingBool("Debug")) { \
|
||||||
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.DebugModeEnabled) { \
|
if (Application::GetSettingBool("Debug")) { \
|
||||||
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
@@ -219,7 +242,7 @@ 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.DebugModeEnabled) { \
|
if (Application::GetSettingBool("Debug")) { \
|
||||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
|
|||||||
@@ -5,54 +5,23 @@
|
|||||||
// ======================= UNIX ========================
|
// ======================= UNIX ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_LINUX
|
#ifdef BEAMMP_LINUX
|
||||||
#include <arpa/inet.h>
|
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
using SOCKET = int;
|
|
||||||
using DWORD = unsigned long;
|
|
||||||
using PDWORD = unsigned long*;
|
|
||||||
using LPDWORD = unsigned long*;
|
|
||||||
char _getch();
|
char _getch();
|
||||||
inline void CloseSocketProper(int TheSocket) {
|
|
||||||
shutdown(TheSocket, SHUT_RDWR);
|
|
||||||
close(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= APPLE ========================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_APPLE
|
#ifdef BEAMMP_APPLE
|
||||||
#include <arpa/inet.h>
|
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
using SOCKET = int;
|
|
||||||
using DWORD = unsigned long;
|
|
||||||
using PDWORD = unsigned long*;
|
|
||||||
using LPDWORD = unsigned long*;
|
|
||||||
char _getch();
|
char _getch();
|
||||||
inline void CloseSocketProper(int TheSocket) {
|
|
||||||
shutdown(TheSocket, SHUT_RDWR);
|
|
||||||
close(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= WINDOWS =======================
|
// ======================= WINDOWS =======================
|
||||||
|
|
||||||
#ifdef BEAMMP_WINDOWS
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <conio.h>
|
#include <conio.h>
|
||||||
#include <winsock2.h>
|
|
||||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
|
||||||
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
|
||||||
closesocket(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
#ifdef INVALID_SOCKET
|
|
||||||
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
|
|
||||||
#else
|
|
||||||
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
|
|
||||||
#endif
|
|
||||||
|
|||||||
+1
-3
@@ -22,9 +22,7 @@ private:
|
|||||||
void CreateConfigFile();
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void PrintDebug();
|
void PrintDebug();
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key);
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
bool IsDefault();
|
bool IsDefault();
|
||||||
|
|||||||
@@ -25,11 +25,12 @@ 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 TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>;
|
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
|
||||||
static constexpr size_t TLuaArgTypes_String = 0;
|
static constexpr size_t TLuaArgTypes_String = 0;
|
||||||
static constexpr size_t TLuaArgTypes_Int = 1;
|
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||||
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||||
static constexpr size_t TLuaArgTypes_Bool = 3;
|
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||||
|
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||||
|
|
||||||
class TLuaPlugin;
|
class TLuaPlugin;
|
||||||
|
|
||||||
|
|||||||
+21
-17
@@ -1,8 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
#include <boost/asio/io_context.hpp>
|
||||||
|
#include <boost/asio/ip/udp.hpp>
|
||||||
|
|
||||||
struct TConnection;
|
struct TConnection;
|
||||||
|
|
||||||
@@ -10,19 +13,18 @@ class TNetwork {
|
|||||||
public:
|
public:
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
|
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
|
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
|
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
||||||
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
|
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
||||||
std::string TCPRcv(TClient& c);
|
std::vector<uint8_t> TCPRcv(TClient& c);
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
void ClientKick(TClient& c, const std::string& R);
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||||
void Identify(const TConnection& client);
|
void Identify(TConnection&& client);
|
||||||
void Authentication(const TConnection& ClientConnection);
|
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
||||||
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
|
||||||
void SyncResources(TClient& c);
|
void SyncResources(TClient& c);
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
||||||
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
|
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
||||||
void UpdatePlayer(TClient& Client);
|
void UpdatePlayer(TClient& Client);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -31,21 +33,23 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
TPPSMonitor& mPPSMonitor;
|
TPPSMonitor& mPPSMonitor;
|
||||||
SOCKET mUDPSock {};
|
ip::udp::socket mUDPSock;
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
std::thread mUDPThread;
|
std::thread mUDPThread;
|
||||||
std::thread mTCPThread;
|
std::thread mTCPThread;
|
||||||
|
|
||||||
std::string UDPRcvFromClient(sockaddr_in& client) const;
|
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
||||||
void HandleDownload(SOCKET TCPSock);
|
void HandleDownload(TConnection&& TCPSock);
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
void Looper(const std::weak_ptr<TClient>& c);
|
||||||
int OpenID();
|
int OpenID();
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
|
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
||||||
void Parse(TClient& c, const std::string& Packet);
|
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
void SendFile(TClient& c, const std::string& Name);
|
||||||
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||||
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
|
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
std::vector<uint8_t> StringToVector(const std::string& Str);
|
||||||
|
|||||||
+16
-3
@@ -8,6 +8,8 @@
|
|||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
|
|
||||||
class TClient;
|
class TClient;
|
||||||
class TNetwork;
|
class TNetwork;
|
||||||
class TPPSMonitor;
|
class TPPSMonitor;
|
||||||
@@ -19,19 +21,22 @@ public:
|
|||||||
TServer(const std::vector<std::string_view>& Arguments);
|
TServer(const std::vector<std::string_view>& Arguments);
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||||
std::weak_ptr<TClient> InsertNewClient();
|
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||||
// in Fn, return true to continue, return false to break
|
// in Fn, return true to continue, return false to break
|
||||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||||
size_t ClientCount() const;
|
size_t ClientCount() const;
|
||||||
|
|
||||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
static 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);
|
static void HandleEvent(TClient& c, const std::string& Data);
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||||
|
|
||||||
|
|
||||||
const TScopedTimer UptimeTimer;
|
const TScopedTimer UptimeTimer;
|
||||||
|
|
||||||
|
// asio io context
|
||||||
|
io_context& IoCtx() { return mIoCtx; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
io_context mIoCtx {};
|
||||||
TClientSet mClients;
|
TClientSet mClients;
|
||||||
mutable RWMutex mClientsMutex;
|
mutable RWMutex mClientsMutex;
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||||
@@ -40,3 +45,11 @@ private:
|
|||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||||
static void HandlePosition(TClient& c, const std::string& Packet);
|
static 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; }
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
FROM archlinux
|
||||||
|
|
||||||
|
RUN pacman -Syu --noconfirm lua53 openssl curl git cmake gcc make zlib boost websocketpp
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM debian:11
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND noninteractive
|
||||||
|
|
||||||
|
RUN apt-get update -y
|
||||||
|
|
||||||
|
RUN apt-get install -y git cmake g++-10 curl libboost1.74-all-dev libssl-dev libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
||||||
|
|
||||||
|
ENV CXX=g++-10
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM ubuntu:20.04
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND noninteractive
|
||||||
|
|
||||||
|
RUN apt-get update -y
|
||||||
|
|
||||||
|
RUN apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev git make cmake g++
|
||||||
|
|
||||||
|
RUN apt-get install -y libboost1.71-all-dev
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM ubuntu:22.04
|
||||||
|
|
||||||
|
ENV DEBIAN_FRONTEND noninteractive
|
||||||
|
|
||||||
|
RUN apt-get update -y
|
||||||
|
|
||||||
|
RUN apt-get install -y git libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev libssl3 curl
|
||||||
|
|
||||||
|
ENV CXX=g++-10
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
printf "enter DSN (optional): "
|
||||||
|
read DSN
|
||||||
|
|
||||||
|
docker build -f Ubuntu-20.04-Dockerfile . -t beammp-server-build:Ubuntu-20.04
|
||||||
|
docker build -f Ubuntu-22.04-Dockerfile . -t beammp-server-build:Ubuntu-22.04
|
||||||
|
docker build -f ArchLinux-Dockerfile . -t beammp-server-build:ArchLinux
|
||||||
|
docker build -f Debian-11-Dockerfile . -t beammp-server-build:Debian-11
|
||||||
|
|
||||||
|
CMD="cd /beammp; cmake . -DGIT_SUBMODULE=OFF -DCMAKE_BUILD_TYPE=Release -DBEAMMP_SECRET_SENTRY_URL=\"${DSN}\" -B /build && make -j -C /build BeamMP-Server"
|
||||||
|
|
||||||
|
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-20.04:/build -it --rm beammp-server-build:Ubuntu-20.04 bash -c "${CMD}"
|
||||||
|
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-22.04:/build -it --rm beammp-server-build:Ubuntu-22.04 bash -c "${CMD}"
|
||||||
|
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-archlinux:/build -it --rm beammp-server-build:ArchLinux bash -c "${CMD}"
|
||||||
|
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-debian-11:/build -it --rm beammp-server-build:Debian-11 bash -c "${CMD}"
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
cmake . -B build -DCMAKE_BUILD_TYPE=Release -DGIT_SUBMODULE=OFF
|
||||||
|
|
||||||
|
make -j -C build BeamMP-Server
|
||||||
+23
-6
@@ -49,16 +49,27 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|||||||
|
|
||||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
std::string TClient::GetCarPositionRaw(int Ident) {
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
std::unique_lock lock(mVehiclePositionMutex);
|
||||||
try
|
try {
|
||||||
{
|
|
||||||
return mVehiclePosition.at(Ident);
|
return mVehiclePosition.at(Ident);
|
||||||
}
|
} catch (const std::out_of_range& oor) {
|
||||||
catch (const std::out_of_range& oor) {
|
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TClient::Disconnect(std::string_view Reason) {
|
||||||
|
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
||||||
|
boost::system::error_code ec;
|
||||||
|
mSocket.shutdown(socket_base::shutdown_both, ec);
|
||||||
|
if (ec) {
|
||||||
|
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
||||||
|
}
|
||||||
|
mSocket.close(ec);
|
||||||
|
if (ec) {
|
||||||
|
beammp_debugf("Failed to close client socket: {}", ec.message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
std::unique_lock lock(mVehiclePositionMutex);
|
||||||
mVehiclePosition[Ident] = Data;
|
mVehiclePosition[Ident] = Data;
|
||||||
@@ -98,16 +109,22 @@ TServer& TClient::Server() const {
|
|||||||
return mServer;
|
return mServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::string& Packet) {
|
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
std::unique_lock Lock(mMissedPacketsMutex);
|
||||||
mPacketsSync.push(Packet);
|
mPacketsSync.push(Packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
TClient::TClient(TServer& Server)
|
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
||||||
: mServer(Server)
|
: mServer(Server)
|
||||||
|
, mSocket(std::move(Socket))
|
||||||
|
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
||||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TClient::~TClient() {
|
||||||
|
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
||||||
|
}
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
void TClient::UpdatePingTime() {
|
||||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-8
@@ -13,10 +13,83 @@
|
|||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
|
Application::SettingsMap Application::mSettings = {
|
||||||
|
{ StrName, std::string("BeamMP Server") },
|
||||||
|
{ StrDescription, std::string("No description") },
|
||||||
|
{ StrResourceFolder, std::string("Resources") },
|
||||||
|
{ StrMap, std::string("/levels/gridmap_v2/info.json") },
|
||||||
|
{ StrSSLKeyPath, std::string("./.ssl/HttpServer/key.pem") },
|
||||||
|
{ StrSSLCertPath, std::string("./.ssl/HttpServer/cert.pem") },
|
||||||
|
{ StrHTTPServerEnabled, false },
|
||||||
|
{ StrMaxPlayers, int(8) },
|
||||||
|
{ StrPrivate, true },
|
||||||
|
{ StrMaxCars, int(1) },
|
||||||
|
{ StrDebug, false },
|
||||||
|
{ StrPort, int(30814) },
|
||||||
|
{ StrCustomIP, std::string("") },
|
||||||
|
{ StrLogChat, true },
|
||||||
|
{ StrSendErrors, true },
|
||||||
|
{ StrSendErrorsMessageEnabled, true },
|
||||||
|
{ StrHTTPServerPort, int(8080) },
|
||||||
|
{ StrHTTPServerIP, std::string("127.0.0.1") },
|
||||||
|
{ StrHTTPServerUseSSL, false },
|
||||||
|
{ StrHideUpdateMessages, false },
|
||||||
|
};
|
||||||
|
|
||||||
// global, yes, this is ugly, no, it cant be done another way
|
// global, yes, this is ugly, no, it cant be done another way
|
||||||
TSentry Sentry {};
|
TSentry Sentry {};
|
||||||
|
|
||||||
Application::TSettings Application::Settings = {};
|
std::string Application::SettingToString(const Application::SettingValue& Value) {
|
||||||
|
switch (Value.which()) {
|
||||||
|
case 0:
|
||||||
|
return fmt::format("{}", boost::get<std::string>(Value));
|
||||||
|
case 1:
|
||||||
|
return fmt::format("{}", boost::get<bool>(Value));
|
||||||
|
case 2:
|
||||||
|
return fmt::format("{}", boost::get<int>(Value));
|
||||||
|
default:
|
||||||
|
return "<unknown type>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Application::GetSettingString(std::string_view Name) {
|
||||||
|
try {
|
||||||
|
return boost::get<std::string>(Application::mSettings.at(Name));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_errorf("Failed to get string setting '{}': {}", Name, e.what());
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int Application::GetSettingInt(std::string_view Name) {
|
||||||
|
try {
|
||||||
|
return boost::get<int>(Application::mSettings.at(Name));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_errorf("Failed to get int setting '{}': {}", Name, e.what());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Application::GetSettingBool(std::string_view Name) {
|
||||||
|
try {
|
||||||
|
return boost::get<bool>(Application::mSettings.at(Name));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_errorf("Failed to get bool setting '{}': {}", Name, e.what());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Application::SetSetting(std::string_view Name, const Application::SettingValue& Value) {
|
||||||
|
if (mSettings.contains(Name)) {
|
||||||
|
if (mSettings[Name].type() == Value.type()) {
|
||||||
|
mSettings[Name] = Value;
|
||||||
|
} else {
|
||||||
|
beammp_errorf("Could not change value of setting '{}', because it has a different type.", Name);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mSettings[Name] = Value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
@@ -239,7 +312,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.DebugModeEnabled) {
|
if (DebugModeOverride || Application::GetSettingBool(StrDebug)) {
|
||||||
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
|
||||||
@@ -251,21 +324,21 @@ std::string ThreadName(bool DebugModeOverride) {
|
|||||||
|
|
||||||
TEST_CASE("ThreadName") {
|
TEST_CASE("ThreadName") {
|
||||||
RegisterThread("MyThread");
|
RegisterThread("MyThread");
|
||||||
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
auto OrigDebug = Application::GetSettingBool(StrDebug);
|
||||||
|
|
||||||
// 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.DebugModeEnabled = true;
|
Application::SetSetting(StrDebug, 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.DebugModeEnabled = false;
|
Application::SetSetting(StrDebug, false);
|
||||||
CHECK(ThreadName(true) == "MyThread ");
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
CHECK(ThreadName(false) == "");
|
CHECK(ThreadName(false) == "");
|
||||||
}
|
}
|
||||||
// cleanup
|
// cleanup
|
||||||
Application::Settings.DebugModeEnabled = OrigDebug;
|
Application::SetSetting(StrDebug, OrigDebug);
|
||||||
}
|
}
|
||||||
|
|
||||||
void RegisterThread(const std::string& str) {
|
void RegisterThread(const std::string& str) {
|
||||||
@@ -277,7 +350,7 @@ void RegisterThread(const std::string& str) {
|
|||||||
#elif defined(BEAMMP_LINUX)
|
#elif defined(BEAMMP_LINUX)
|
||||||
ThreadId = std::to_string(gettid());
|
ThreadId = std::to_string(gettid());
|
||||||
#endif
|
#endif
|
||||||
if (Application::Settings.DebugModeEnabled) {
|
if (Application::GetSettingBool(StrDebug)) {
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -310,7 +383,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.LogChat) {
|
if (Application::GetSettingBool(StrLogChat)) {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << ThreadName();
|
ss << ThreadName();
|
||||||
ss << "[CHAT] ";
|
ss << "[CHAT] ";
|
||||||
|
|||||||
+2
-2
@@ -154,7 +154,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));
|
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::GetSettingInt(StrHTTPServerPort)));
|
||||||
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
|
||||||
@@ -196,7 +196,7 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
||||||
});
|
});
|
||||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||||
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
auto ret = HttpLibServerInstance->listen(Application::GetSettingString(StrHTTPServerIP).c_str(), Application::GetSettingInt(StrHTTPServerPort));
|
||||||
if (!ret) {
|
if (!ret) {
|
||||||
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-20
@@ -116,7 +116,7 @@ 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;
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
if (PlayerID == -1) {
|
if (PlayerID == -1) {
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
return { true, "" };
|
return { true, "" };
|
||||||
} else {
|
} else {
|
||||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
@@ -125,7 +125,7 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
|
|||||||
return { false, "Invalid Player ID" };
|
return { false, "Invalid Player ID" };
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||||
return { false, "Respond failed, dropping client" };
|
return { false, "Respond failed, dropping client" };
|
||||||
@@ -155,7 +155,7 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
std::string Packet = "C:Server: " + Message;
|
std::string Packet = "C:Server: " + Message;
|
||||||
if (ID == -1) {
|
if (ID == -1) {
|
||||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||||
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
@@ -167,7 +167,7 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||||
if (!Engine->Network().Respond(*c, 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?
|
// TODO: should we return an error here?
|
||||||
}
|
}
|
||||||
@@ -194,7 +194,7 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
|||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
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);
|
||||||
Engine->Network().SendToAll(nullptr, Destroy, true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
c->DeleteCar(VID);
|
c->DeleteCar(VID);
|
||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
@@ -208,56 +208,56 @@ 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.DebugModeEnabled = NewValue.as<bool>();
|
Application::SetSetting(StrDebug, NewValue.as<bool>());
|
||||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
beammp_info(std::string("Set `Debug` to ") + (Application::GetSettingBool(StrDebug) ? "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.Private = NewValue.as<bool>();
|
Application::SetSetting(StrPrivate, NewValue.as<bool>());
|
||||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
beammp_info(std::string("Set `Private` to ") + (Application::GetSettingBool(StrPrivate) ? "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.MaxCars = NewValue.as<int>();
|
Application::SetSetting(StrMaxCars, NewValue.as<int>());
|
||||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::GetSettingInt(StrMaxCars)));
|
||||||
} 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.MaxPlayers = NewValue.as<int>();
|
Application::SetSetting(StrMaxPlayers, NewValue.as<int>());
|
||||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::GetSettingInt(StrMaxPlayers)));
|
||||||
} 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.MapName = NewValue.as<std::string>();
|
Application::SetSetting(StrMap, NewValue.as<std::string>());
|
||||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
beammp_info(std::string("Set `Map` to ") + Application::GetSettingString(StrMap));
|
||||||
} 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.ServerName = NewValue.as<std::string>();
|
Application::SetSetting(StrName, NewValue.as<std::string>());
|
||||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
beammp_info(std::string("Set `Name` to ") + Application::GetSettingString(StrName));
|
||||||
} 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.ServerDesc = NewValue.as<std::string>();
|
Application::SetSetting(StrDescription, NewValue.as<std::string>());
|
||||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
beammp_info(std::string("Set `Description` to ") + Application::GetSettingString(StrDescription));
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("set invalid argument [2] expected string");
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
}
|
}
|
||||||
@@ -526,7 +526,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string key{};
|
std::string key {};
|
||||||
switch (left.get_type()) {
|
switch (left.get_type()) {
|
||||||
case sol::type::lua_nil:
|
case sol::type::lua_nil:
|
||||||
case sol::type::none:
|
case sol::type::none:
|
||||||
|
|||||||
+56
-149
@@ -6,32 +6,6 @@
|
|||||||
#include <istream>
|
#include <istream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
// General
|
|
||||||
static constexpr std::string_view StrDebug = "Debug";
|
|
||||||
static constexpr std::string_view StrPrivate = "Private";
|
|
||||||
static constexpr std::string_view StrPort = "Port";
|
|
||||||
static constexpr std::string_view StrMaxCars = "MaxCars";
|
|
||||||
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
|
||||||
static constexpr std::string_view StrMap = "Map";
|
|
||||||
static constexpr std::string_view StrName = "Name";
|
|
||||||
static constexpr std::string_view StrDescription = "Description";
|
|
||||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
|
||||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
|
||||||
static constexpr std::string_view StrLogChat = "LogChat";
|
|
||||||
|
|
||||||
// Misc
|
|
||||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
|
||||||
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
|
||||||
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
|
||||||
|
|
||||||
// HTTP
|
|
||||||
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
|
||||||
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
|
||||||
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
|
||||||
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
|
||||||
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
|
||||||
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
|
||||||
|
|
||||||
TEST_CASE("TConfig::TConfig") {
|
TEST_CASE("TConfig::TConfig") {
|
||||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||||
fs::remove(CfgFile);
|
fs::remove(CfgFile);
|
||||||
@@ -93,35 +67,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.Key;
|
data["General"][StrAuthKey.data()] = Application::GetSettingString(StrAuthKey.data());
|
||||||
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
||||||
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
|
data["General"][StrLogChat.data()] = Application::GetSettingBool(StrLogChat.data());
|
||||||
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.DebugModeEnabled;
|
data["General"][StrDebug.data()] = Application::GetSettingBool(StrDebug.data());
|
||||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
data["General"][StrPrivate.data()] = Application::GetSettingBool(StrPrivate.data());
|
||||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
data["General"][StrPort.data()] = Application::GetSettingInt(StrPort.data());
|
||||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
data["General"][StrName.data()] = Application::GetSettingString(StrName.data());
|
||||||
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
data["General"][StrMaxCars.data()] = Application::GetSettingInt(StrMaxCars.data());
|
||||||
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
data["General"][StrMaxPlayers.data()] = Application::GetSettingInt(StrMaxPlayers.data());
|
||||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
data["General"][StrMap.data()] = Application::GetSettingString(StrMap.data());
|
||||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
data["General"][StrDescription.data()] = Application::GetSettingString(StrDescription.data());
|
||||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
data["General"][StrResourceFolder.data()] = Application::GetSettingString(StrResourceFolder.data());
|
||||||
// Misc
|
// Misc
|
||||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
data["Misc"][StrHideUpdateMessages.data()] = Application::GetSettingBool(StrHideUpdateMessages.data());
|
||||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||||
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
data["Misc"][StrSendErrors.data()] = Application::GetSettingBool(StrSendErrors.data());
|
||||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::GetSettingBool(StrSendErrorsMessageEnabled.data());
|
||||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
// HTTP
|
// HTTP
|
||||||
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
data["HTTP"][StrSSLKeyPath.data()] = Application::GetSettingString(StrSSLKeyPath.data());
|
||||||
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
data["HTTP"][StrSSLCertPath.data()] = Application::GetSettingString(StrSSLCertPath.data());
|
||||||
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
data["HTTP"][StrHTTPServerPort.data()] = Application::GetSettingInt(StrHTTPServerPort.data());
|
||||||
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
||||||
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
data["HTTP"][StrHTTPServerIP.data()] = Application::GetSettingString(StrHTTPServerIP.data());
|
||||||
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
|
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::GetSettingBool(StrHTTPServerUseSSL.data());
|
||||||
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
||||||
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
data["HTTP"][StrHTTPServerEnabled.data()] = Application::GetSettingBool(StrHTTPServerEnabled.data());
|
||||||
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
||||||
std::stringstream Ss;
|
std::stringstream Ss;
|
||||||
Ss << "# This is the BeamMP-Server config file.\n"
|
Ss << "# This is the BeamMP-Server config file.\n"
|
||||||
@@ -156,50 +130,41 @@ void TConfig::CreateConfigFile() {
|
|||||||
FlushToFile();
|
FlushToFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key) {
|
||||||
if (Table[Category.c_str()][Key.data()].is_string()) {
|
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||||
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
Application::SetSetting(Key, std::string(Table[Category.c_str()][Key.data()].as_string()));
|
||||||
|
} else if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||||
|
Application::SetSetting(Key, bool(Table[Category.c_str()][Key.data()].as_boolean()));
|
||||||
|
} else if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||||
|
Application::SetSetting(Key, int(Table[Category.c_str()][Key.data()].as_integer()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
|
|
||||||
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
|
||||||
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
|
|
||||||
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
|
||||||
OutValue = 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::parse<toml::preserve_comments>(name.data());
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
// GENERAL
|
// GENERAL
|
||||||
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
TryReadValue(data, "General", StrDebug);
|
||||||
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
TryReadValue(data, "General", StrPrivate);
|
||||||
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
TryReadValue(data, "General", StrPort);
|
||||||
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
TryReadValue(data, "General", StrMaxCars);
|
||||||
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
TryReadValue(data, "General", StrMaxPlayers);
|
||||||
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
TryReadValue(data, "General", StrMap);
|
||||||
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
TryReadValue(data, "General", StrName);
|
||||||
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
TryReadValue(data, "General", StrDescription);
|
||||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
TryReadValue(data, "General", StrResourceFolder);
|
||||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
TryReadValue(data, "General", StrAuthKey);
|
||||||
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
TryReadValue(data, "General", StrLogChat);
|
||||||
// Misc
|
// Misc
|
||||||
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
TryReadValue(data, "Misc", StrSendErrors);
|
||||||
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
TryReadValue(data, "Misc", StrHideUpdateMessages);
|
||||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled);
|
||||||
// HTTP
|
// HTTP
|
||||||
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
TryReadValue(data, "HTTP", StrSSLKeyPath);
|
||||||
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
TryReadValue(data, "HTTP", StrSSLCertPath);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
TryReadValue(data, "HTTP", StrHTTPServerPort);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
TryReadValue(data, "HTTP", StrHTTPServerIP);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
TryReadValue(data, "HTTP", StrHTTPServerEnabled);
|
||||||
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
|
TryReadValue(data, "HTTP", StrHTTPServerUseSSL);
|
||||||
} 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;
|
||||||
@@ -211,86 +176,28 @@ void TConfig::ParseFromFile(std::string_view name) {
|
|||||||
// Update in any case
|
// Update in any case
|
||||||
FlushToFile();
|
FlushToFile();
|
||||||
// all good so far, let's check if there's a key
|
// all good so far, let's check if there's a key
|
||||||
if (Application::Settings.Key.empty()) {
|
if (Application::GetSettingString(StrAuthKey).empty()) {
|
||||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
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.Key.size() != 36) {
|
if (Application::GetSettingString(StrAuthKey).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() {
|
||||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
for (const auto& [k, v] : Application::mSettings) {
|
||||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
if (k == StrAuthKey) {
|
||||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
beammp_debugf("AuthKey: length {}", boost::get<std::string>(v).size());
|
||||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
continue;
|
||||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
}
|
||||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
beammp_debugf("{}: {}", k, Application::SettingToString(v));
|
||||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
}
|
||||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
|
||||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
|
||||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
|
||||||
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
|
|
||||||
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
|
|
||||||
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
|
|
||||||
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
|
||||||
// special!
|
|
||||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseOldFormat() {
|
void TConfig::ParseOldFormat() {
|
||||||
std::ifstream File("Server.cfg");
|
beammp_warnf("You still have a 'Server.cfg' - this will not be used (this server uses 'ServerConfig.toml'. Since v3.0.2 we no longer parse and import these old settings. Remove the file to avoid confusion and disable this message.");
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-5
@@ -7,9 +7,14 @@
|
|||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
|
#include <boost/spirit/home/qi/directive/lexeme.hpp>
|
||||||
|
#include <boost/spirit/home/qi/parse.hpp>
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include <boost/phoenix.hpp>
|
||||||
|
#include <boost/spirit/include/qi.hpp>
|
||||||
|
|
||||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||||
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||||
}
|
}
|
||||||
@@ -68,7 +73,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.DebugModeEnabled) {
|
if (Application::GetSettingBool(StrDebug)) {
|
||||||
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);
|
||||||
@@ -198,10 +203,10 @@ bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min,
|
|||||||
return EnsureArgsCount(args, min);
|
return EnsureArgsCount(args, min);
|
||||||
} else {
|
} else {
|
||||||
if (args.size() > max) {
|
if (args.size() > max) {
|
||||||
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
} else if (args.size() < min) {
|
} else if (args.size() < min) {
|
||||||
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -350,16 +355,81 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (!EnsureArgsCount(args, 0)) {
|
if (!EnsureArgsCount(args, 1, 100)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static const char* SETTINGS_HELP = R"(Settings:
|
||||||
|
settings help Displays this help
|
||||||
|
settings list Lists all settings
|
||||||
|
settings get <setting> Prints the current value of the specified setting
|
||||||
|
settings set <setting> <value> Sets the specified setting to the value)";
|
||||||
|
if (args.at(0) == "help") {
|
||||||
|
Application::Console().WriteRaw(SETTINGS_HELP);
|
||||||
|
} else if (args.at(0) == "list") {
|
||||||
|
Application::Console().WriteRaw("Available settings:");
|
||||||
|
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", "<NAME>", "<CURRENT VALUE>"));
|
||||||
|
for (const auto& [k, v] : Application::mSettings) {
|
||||||
|
if (k == StrAuthKey) {
|
||||||
|
Application::Console().WriteRaw(fmt::format("\t{:<25} <key of length {}>", k, Application::SettingToString(v).size()));
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", k, Application::SettingToString(v)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (args.at(0) == "get") {
|
||||||
|
if (args.size() < 2) {
|
||||||
|
Application::Console().WriteRaw("Not enough arguments: `settings get` requires a setting name.");
|
||||||
|
} else {
|
||||||
|
if (Application::mSettings.contains(args.at(1))) {
|
||||||
|
if (args.at(1) != StrAuthKey) {
|
||||||
|
Application::Console().WriteRaw(fmt::format("{} = {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(fmt::format("{} = <key of length {}>", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1))).size()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(fmt::format("Setting '{}' doesn't exist.", args.at(1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (args.at(0) == "set") {
|
||||||
|
if (args.size() < 3) {
|
||||||
|
Application::Console().WriteRaw("Not enough arguments: `settings set` requires a setting name and value.");
|
||||||
|
} else {
|
||||||
|
if (args.at(1) == StrAuthKey) {
|
||||||
|
Application::Console().WriteRaw("It's not allowed to set the AuthKey during runtime.");
|
||||||
|
} else {
|
||||||
|
using namespace boost::spirit;
|
||||||
|
using qi::_1;
|
||||||
|
std::string ValueString = args.at(2);
|
||||||
|
Application::SettingValue Value;
|
||||||
|
qi::rule<std::string::iterator, std::string()> StringRule;
|
||||||
|
StringRule
|
||||||
|
%= qi::lexeme['"' >> *(qi::char_ - '"') >> '"' ]
|
||||||
|
| +(qi::char_ - '"')
|
||||||
|
;
|
||||||
|
qi::rule<std::string::iterator, Application::SettingValue()> ValueRule
|
||||||
|
= qi::bool_
|
||||||
|
| qi::int_
|
||||||
|
| StringRule;
|
||||||
|
auto It = ValueString.begin();
|
||||||
|
if (qi::phrase_parse(It, ValueString.end(), ValueRule[boost::phoenix::ref(Value) = _1], ascii::space)
|
||||||
|
&& It == ValueString.end()) {
|
||||||
|
Application::SetSetting(args.at(1), Value);
|
||||||
|
Application::Console().WriteRaw(fmt::format("{} := {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(fmt::format("New value '{}' did not parse as a valid value.", ValueString));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(fmt::format("Unknown argument '{}' - 'settings {}' is not a valid command.", args.at(0), args.at(0)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Say(const std::string& FullCmd) {
|
void TConsole::Command_Say(const std::string& FullCmd) {
|
||||||
if (FullCmd.size() > 3) {
|
if (FullCmd.size() > 3) {
|
||||||
auto Message = FullCmd.substr(4);
|
auto Message = FullCmd.substr(4);
|
||||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||||
if (!Application::Settings.LogChat) {
|
if (!Application::GetSettingBool(StrLogChat)) {
|
||||||
Application::Console().WriteRaw("Chat message sent!");
|
Application::Console().WriteRaw("Chat message sent!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-21
@@ -36,14 +36,10 @@ void THeartbeatThread::operator()() {
|
|||||||
|
|
||||||
Last = Body;
|
Last = Body;
|
||||||
LastNormalUpdateTime = Now;
|
LastNormalUpdateTime = Now;
|
||||||
if (!Application::Settings.CustomIP.empty()) {
|
if (!Application::GetSettingString(StrCustomIP).empty()) {
|
||||||
Body += "&ip=" + Application::Settings.CustomIP;
|
Body += "&ip=" + Application::GetSettingString(StrCustomIP);
|
||||||
}
|
}
|
||||||
|
|
||||||
Body += "&pps=" + Application::PPS();
|
|
||||||
|
|
||||||
beammp_trace("heartbeat body: '" + Body + "'");
|
|
||||||
|
|
||||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
auto SentryReportError = [&](const std::string& transaction, int status) {
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
Sentry.SetContext("heartbeat",
|
Sentry.SetContext("heartbeat",
|
||||||
@@ -61,11 +57,10 @@ void THeartbeatThread::operator()() {
|
|||||||
bool Ok = false;
|
bool Ok = false;
|
||||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
beammp_trace(T);
|
|
||||||
Doc.Parse(T.data(), T.size());
|
Doc.Parse(T.data(), T.size());
|
||||||
if (Doc.HasParseError() || !Doc.IsObject()) {
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
if (!Application::Settings.Private) {
|
if (!Application::GetSettingBool(StrPrivate)) {
|
||||||
beammp_error("Backend response failed to parse as valid json");
|
beammp_trace("Backend response failed to parse as valid json");
|
||||||
beammp_trace("Response was: `" + T + "`");
|
beammp_trace("Response was: `" + T + "`");
|
||||||
}
|
}
|
||||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
||||||
@@ -110,12 +105,12 @@ void THeartbeatThread::operator()() {
|
|||||||
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!Application::Settings.Private) {
|
if (!Application::GetSettingBool(StrPrivate)) {
|
||||||
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.Private) {
|
if (Ok && !isAuth && !Application::GetSettingBool(StrPrivate)) {
|
||||||
if (Status == "2000") {
|
if (Status == "2000") {
|
||||||
beammp_info(("Authenticated! " + Message));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
@@ -129,10 +124,10 @@ void THeartbeatThread::operator()() {
|
|||||||
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (isAuth || Application::Settings.Private) {
|
if (isAuth || Application::GetSettingBool(StrPrivate)) {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
}
|
}
|
||||||
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
if (!Application::GetSettingBool(StrHideUpdateMessages) && UpdateReminderCounter % 5) {
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,20 +136,20 @@ void THeartbeatThread::operator()() {
|
|||||||
std::string THeartbeatThread::GenerateCall() {
|
std::string THeartbeatThread::GenerateCall() {
|
||||||
std::stringstream Ret;
|
std::stringstream Ret;
|
||||||
|
|
||||||
Ret << "uuid=" << Application::Settings.Key
|
Ret << "uuid=" << Application::GetSettingString(StrAuthKey)
|
||||||
<< "&players=" << mServer.ClientCount()
|
<< "&players=" << mServer.ClientCount()
|
||||||
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
<< "&maxplayers=" << Application::GetSettingInt(StrMaxPlayers)
|
||||||
<< "&port=" << Application::Settings.Port
|
<< "&port=" << Application::GetSettingInt(StrPort)
|
||||||
<< "&map=" << Application::Settings.MapName
|
<< "&map=" << Application::GetSettingString(StrMap)
|
||||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
<< "&private=" << (Application::GetSettingBool(StrPrivate) ? "true" : "false")
|
||||||
<< "&version=" << Application::ServerVersionString()
|
<< "&version=" << Application::ServerVersionString()
|
||||||
<< "&clientversion=" << Application::ClientVersionString()
|
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||||
<< "&name=" << Application::Settings.ServerName
|
<< "&name=" << Application::GetSettingString(StrName)
|
||||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||||
<< "&playerslist=" << GetPlayers()
|
<< "&playerslist=" << GetPlayers()
|
||||||
<< "&desc=" << Application::Settings.ServerDesc;
|
<< "&desc=" << Application::GetSettingString(StrDescription);
|
||||||
return Ret.str();
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||||
|
|||||||
+21
-13
@@ -4,6 +4,7 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaPlugin.h"
|
#include "TLuaPlugin.h"
|
||||||
|
#include "sol/object.hpp"
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
@@ -15,11 +16,11 @@
|
|||||||
TLuaEngine* LuaAPI::MP::Engine;
|
TLuaEngine* LuaAPI::MP::Engine;
|
||||||
|
|
||||||
TLuaEngine::TLuaEngine()
|
TLuaEngine::TLuaEngine()
|
||||||
: mResourceServerPath(fs::path(Application::Settings.Resource) / "Server") {
|
: mResourceServerPath(fs::path(Application::GetSettingString(StrResourceFolder)) / "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.Resource)) {
|
if (!fs::exists(Application::GetSettingString(StrResourceFolder))) {
|
||||||
fs::create_directory(Application::Settings.Resource);
|
fs::create_directory(Application::GetSettingString(StrResourceFolder));
|
||||||
}
|
}
|
||||||
if (!fs::exists(mResourceServerPath)) {
|
if (!fs::exists(mResourceServerPath)) {
|
||||||
fs::create_directory(mResourceServerPath);
|
fs::create_directory(mResourceServerPath);
|
||||||
@@ -35,7 +36,7 @@ TLuaEngine::TLuaEngine()
|
|||||||
}
|
}
|
||||||
|
|
||||||
TEST_CASE("TLuaEngine ctor & dtor") {
|
TEST_CASE("TLuaEngine ctor & dtor") {
|
||||||
Application::Settings.Resource = "beammp_server_test_resources";
|
Application::SetSetting(StrResourceFolder, "beammp_server_test_resources");
|
||||||
TLuaEngine engine;
|
TLuaEngine engine;
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
@@ -417,7 +418,6 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
if (Fn.valid()) {
|
if (Fn.valid()) {
|
||||||
auto LuaResult = Fn(EventArgs);
|
auto LuaResult = Fn(EventArgs);
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
Result->Ready = true;
|
|
||||||
if (LuaResult.valid()) {
|
if (LuaResult.valid()) {
|
||||||
Result->Error = false;
|
Result->Error = false;
|
||||||
Result->Result = LuaResult;
|
Result->Result = LuaResult;
|
||||||
@@ -425,6 +425,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
||||||
}
|
}
|
||||||
|
Result->Ready = true;
|
||||||
Return.push_back(Result);
|
Return.push_back(Result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -584,27 +585,25 @@ std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionR
|
|||||||
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
||||||
|
|
||||||
if (VehiclePos.empty()) {
|
if (VehiclePos.empty()) {
|
||||||
//return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
||||||
Result.second = "Vehicle not found";
|
Result.second = "Vehicle not found";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table t = Lua_JsonDecode(VehiclePos);
|
sol::table t = Lua_JsonDecode(VehiclePos);
|
||||||
if (t == sol::lua_nil){
|
if (t == sol::lua_nil) {
|
||||||
Result.second = "Packet decode failed";
|
Result.second = "Packet decode failed";
|
||||||
}
|
}
|
||||||
//return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
||||||
Result.first = t;
|
Result.first = t;
|
||||||
return Result;
|
return Result;
|
||||||
}
|
} else {
|
||||||
else {
|
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
||||||
//return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
|
||||||
Result.second = "Client expired";
|
Result.second = "Client expired";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
||||||
auto table = mStateView.create_table();
|
auto table = mStateView.create_table();
|
||||||
constexpr const char* InternalClient = "__InternalClient";
|
constexpr const char* InternalClient = "__InternalClient";
|
||||||
@@ -948,7 +947,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
}
|
}
|
||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
||||||
S.second->Ready = true;
|
|
||||||
if (Res.valid()) {
|
if (Res.valid()) {
|
||||||
S.second->Error = false;
|
S.second->Error = false;
|
||||||
S.second->Result = std::move(Res);
|
S.second->Result = std::move(Res);
|
||||||
@@ -957,6 +955,7 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
S.second->ErrorMessage = Err.what();
|
S.second->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
|
S.second->Ready = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{ // StateFunctionQueue Scope
|
{ // StateFunctionQueue Scope
|
||||||
@@ -994,6 +993,15 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
case TLuaArgTypes_Bool:
|
case TLuaArgTypes_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 TLuaArgTypes_StringStringMap: {
|
||||||
|
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
|
||||||
|
auto Table = StateView.create_table();
|
||||||
|
for (const auto& [k, v] : Map) {
|
||||||
|
Table[k] = v;
|
||||||
|
}
|
||||||
|
LuaArgs.push_back(sol::make_object(StateView, Table));
|
||||||
|
break;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
beammp_error("Unknown argument type, passed as nil");
|
beammp_error("Unknown argument type, passed as nil");
|
||||||
break;
|
break;
|
||||||
|
|||||||
+308
-425
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ namespace fs = std::filesystem;
|
|||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
TResourceManager::TResourceManager() {
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||||
std::string Path = Application::Settings.Resource + "/Client";
|
std::string Path = Application::GetSettingString(StrResourceFolder) + "/Client";
|
||||||
if (!fs::exists(Path))
|
if (!fs::exists(Path))
|
||||||
fs::create_directories(Path);
|
fs::create_directories(Path);
|
||||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||||
|
|||||||
+6
-6
@@ -28,22 +28,22 @@ TSentry::~TSentry() {
|
|||||||
|
|
||||||
void TSentry::PrintWelcome() {
|
void TSentry::PrintWelcome() {
|
||||||
if (mValid) {
|
if (mValid) {
|
||||||
if (!Application::Settings.SendErrors) {
|
if (!Application::GetSettingBool("SendErrors")) {
|
||||||
mValid = false;
|
mValid = false;
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::GetSettingBool(StrSendErrors)) {
|
||||||
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("Sentry disabled");
|
beammp_info("Sentry disabled");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::GetSettingBool(StrSendErrors)) {
|
||||||
beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
|
beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("Sentry started");
|
beammp_info("Sentry started");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::GetSettingBool(StrSendErrors)) {
|
||||||
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("Sentry disabled in unofficial build");
|
beammp_info("Sentry disabled in unofficial build");
|
||||||
@@ -57,8 +57,8 @@ void TSentry::SetupUser() {
|
|||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
||||||
sentry_value_t user = sentry_value_new_object();
|
sentry_value_t user = sentry_value_new_object();
|
||||||
if (Application::Settings.Key.size() == 36) {
|
if (Application::GetSettingString(StrAuthKey).size() == 36) {
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::GetSettingString(StrAuthKey).c_str()));
|
||||||
} else {
|
} else {
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
||||||
}
|
}
|
||||||
|
|||||||
+57
-51
@@ -4,6 +4,7 @@
|
|||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include <TLuaPlugin.h>
|
#include <TLuaPlugin.h>
|
||||||
|
#include <algorithm>
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
@@ -79,11 +80,12 @@ TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
|||||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||||
if (Arguments.size() > 1) {
|
if (Arguments.size() > 1) {
|
||||||
Application::Settings.CustomIP = Arguments[0];
|
Application::SetSetting(StrCustomIP, std::string(Arguments[0]));
|
||||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
auto CustomIP = Application::GetSettingString(StrCustomIP);
|
||||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
|
||||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
auto p = Application::GetSettingString(StrCustomIP).find_first_not_of(".0123456789");
|
||||||
Application::Settings.CustomIP.clear();
|
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == "127") {
|
||||||
|
Application::SetSetting(StrCustomIP, "");
|
||||||
beammp_warn("IP Specified is invalid! Ignoring");
|
beammp_warn("IP Specified is invalid! Ignoring");
|
||||||
} else {
|
} else {
|
||||||
beammp_info("server started with custom IP");
|
beammp_info("server started with custom IP");
|
||||||
@@ -102,13 +104,6 @@ void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
|
||||||
beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
|
||||||
WriteLock Lock(mClientsMutex);
|
|
||||||
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
|
||||||
return *Iter;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||||
decltype(mClients) Clients;
|
decltype(mClients) Clients;
|
||||||
{
|
{
|
||||||
@@ -127,12 +122,11 @@ size_t TServer::ClientCount() const {
|
|||||||
return mClients.size();
|
return mClients.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
constexpr std::string_view ABG = "ABG:";
|
||||||
// abort();
|
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());
|
||||||
if (Packet.substr(0, 4) == "ABG:") {
|
Packet = DeComp(Packet);
|
||||||
Packet = DeComp(Packet.substr(4));
|
|
||||||
}
|
}
|
||||||
if (Packet.empty()) {
|
if (Packet.empty()) {
|
||||||
return;
|
return;
|
||||||
@@ -146,6 +140,8 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
std::any Res;
|
std::any Res;
|
||||||
char Code = Packet.at(0);
|
char Code = Packet.at(0);
|
||||||
|
|
||||||
|
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
|
|
||||||
// V to Y
|
// V to Y
|
||||||
if (Code <= 89 && Code >= 86) {
|
if (Code <= 89 && Code >= 86) {
|
||||||
PPSMonitor.IncrementInternalPPS();
|
PPSMonitor.IncrementInternalPPS();
|
||||||
@@ -154,38 +150,34 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
}
|
}
|
||||||
switch (Code) {
|
switch (Code) {
|
||||||
case 'H': // initial connection
|
case 'H': // initial connection
|
||||||
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
|
||||||
if (!Network.SyncClient(Client)) {
|
if (!Network.SyncClient(Client)) {
|
||||||
// TODO handle
|
// TODO handle
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'p':
|
case 'p':
|
||||||
if (!Network.Respond(*LockedClient, ("p"), false)) {
|
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
||||||
// failed to send
|
// failed to send
|
||||||
if (LockedClient->GetStatus() > -1) {
|
LockedClient->Disconnect("Failed to send ping");
|
||||||
LockedClient->SetStatus(-1);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Network.UpdatePlayer(*LockedClient);
|
Network.UpdatePlayer(*LockedClient);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'O':
|
case 'O':
|
||||||
if (Packet.length() > 1000) {
|
if (Packet.size() > 1000) {
|
||||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
||||||
}
|
}
|
||||||
ParseVehicle(*LockedClient, Packet, Network);
|
ParseVehicle(*LockedClient, StringPacket, Network);
|
||||||
return;
|
return;
|
||||||
case 'J':
|
case 'J':
|
||||||
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
case 'C': {
|
case 'C': {
|
||||||
beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
||||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
|
||||||
break;
|
break;
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), PacketAsString.substr(PacketAsString.find(':', 3) + 2));
|
||||||
TLuaEngine::WaitForAll(Futures);
|
TLuaEngine::WaitForAll(Futures);
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1));
|
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
||||||
if (std::any_of(Futures.begin(), Futures.end(),
|
if (std::any_of(Futures.begin(), Futures.end(),
|
||||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||||
return !Elem->Error
|
return !Elem->Error
|
||||||
@@ -198,8 +190,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'E':
|
case 'E':
|
||||||
beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
HandleEvent(*LockedClient, StringPacket);
|
||||||
HandleEvent(*LockedClient, Packet);
|
|
||||||
return;
|
return;
|
||||||
case 'N':
|
case 'N':
|
||||||
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||||
@@ -209,7 +200,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
PPSMonitor.IncrementInternalPPS();
|
PPSMonitor.IncrementInternalPPS();
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
|
|
||||||
HandlePosition(*LockedClient, Packet);
|
HandlePosition(*LockedClient, StringPacket);
|
||||||
default:
|
default:
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -235,7 +226,7 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
|
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -245,12 +236,12 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
|||||||
c.SetUnicycleID(ID);
|
c.SetUnicycleID(ID);
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
return c.GetCarCount() < Application::Settings.MaxCars;
|
return c.GetCarCount() < Application::GetSettingInt(StrMaxCars);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||||
if (Pckt.length() < 4)
|
if (Pckt.length() < 6)
|
||||||
return;
|
return;
|
||||||
std::string Packet = Pckt;
|
std::string Packet = Pckt;
|
||||||
char Code = Packet.at(1);
|
char Code = Packet.at(1);
|
||||||
@@ -259,10 +250,10 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
std::string Data = Packet.substr(3), pid, vid;
|
std::string Data = Packet.substr(3), pid, vid;
|
||||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||||
case 's':
|
case 's':
|
||||||
beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
||||||
if (Data.at(0) == '0') {
|
if (Data.at(0) == '0') {
|
||||||
int CarID = c.GetOpenCarID();
|
int CarID = c.GetOpenCarID();
|
||||||
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
std::string CarJson = Packet.substr(5);
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||||
@@ -275,16 +266,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||||
c.AddNewCar(CarID, Packet);
|
c.AddNewCar(CarID, Packet);
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
} else {
|
} else {
|
||||||
if (!Network.Respond(c, Packet, true)) {
|
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||||
if (!Network.Respond(c, Destroy, true)) {
|
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -306,14 +297,14 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||||
&& !ShouldntAllow) {
|
&& !ShouldntAllow) {
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
Apply(c, VID, Packet);
|
Apply(c, VID, Packet);
|
||||||
} else {
|
} else {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||||
Network.SendToAll(nullptr, Destroy, true, true);
|
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -321,7 +312,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
}
|
}
|
||||||
case 'd': {
|
case 'd': {
|
||||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
auto MaybePidVid = GetPidVid(Data);
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
if (MaybePidVid) {
|
if (MaybePidVid) {
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
}
|
}
|
||||||
@@ -329,7 +320,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
// TODO: should this trigger on all vehicle deletions?
|
// TODO: should this trigger on all vehicle deletions?
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
@@ -339,7 +330,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
}
|
}
|
||||||
case 'r': {
|
case 'r': {
|
||||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
auto MaybePidVid = GetPidVid(Data);
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
if (MaybePidVid) {
|
if (MaybePidVid) {
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
}
|
}
|
||||||
@@ -347,16 +338,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
Data = Data.substr(Data.find('{'));
|
Data = Data.substr(Data.find('{'));
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 't':
|
case 't':
|
||||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
return;
|
return;
|
||||||
case 'm':
|
case 'm':
|
||||||
Network.SendToAll(&c, Packet, true, true);
|
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||||
@@ -425,10 +416,24 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
||||||
|
if (Packet.size() < 3) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
// Zp:serverVehicleID:data
|
// Zp:serverVehicleID:data
|
||||||
|
// Zp:0:data
|
||||||
std::string withoutCode = Packet.substr(3);
|
std::string withoutCode = Packet.substr(3);
|
||||||
auto NameDataSep = withoutCode.find(':', 2);
|
auto NameDataSep = withoutCode.find(':', 2);
|
||||||
|
if (NameDataSep == std::string::npos || NameDataSep < 2) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// FIXME: ensure that -2 does what it should... it seems weird.
|
||||||
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
||||||
|
if (NameDataSep + 1 > withoutCode.size()) {
|
||||||
|
// invalid packet
|
||||||
|
return;
|
||||||
|
}
|
||||||
std::string Data = withoutCode.substr(NameDataSep + 1);
|
std::string Data = withoutCode.substr(NameDataSep + 1);
|
||||||
|
|
||||||
// parse veh ID
|
// parse veh ID
|
||||||
@@ -436,6 +441,7 @@ void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
|||||||
if (MaybePidVid) {
|
if (MaybePidVid) {
|
||||||
int PID = -1;
|
int PID = -1;
|
||||||
int VID = -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::tie(PID, VID) = MaybePidVid.value();
|
||||||
|
|
||||||
c.SetCarPosition(VID, Data);
|
c.SetCarPosition(VID, Data);
|
||||||
|
|||||||
+2
-2
@@ -158,9 +158,9 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
PPSMonitor.SetNetwork(Network);
|
PPSMonitor.SetNetwork(Network);
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
TPluginMonitor PluginMonitor(fs::path(Application::GetSettingString(StrResourceFolder)) / "Server", LuaEngine);
|
||||||
|
|
||||||
if (Application::Settings.HTTPServerEnabled) {
|
if (Application::GetSettingBool(StrHTTPServerEnabled)) {
|
||||||
Http::Server::THttpServerInstance HttpServerInstance {};
|
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user