Compare commits

..

25 Commits

Author SHA1 Message Date
Lion 39badf432d remove whitespace 2024-01-17 13:15:30 +01:00
Lion Kortlepel 03307e71fb use a beammp_lua_errorf instead of a std::terminate on sol2 assertion failure 2023-12-05 18:25:27 +01:00
Lion 872c2d410d New buildsystem (#197) 2023-12-05 18:21:20 +01:00
Lion Kortlepel f98704e0f3 fix warnings about implicit conversion 2023-12-05 18:05:35 +01:00
Lion Kortlepel dea203c108 make IThreaded::~IThreaded virtual to make destruction happen 2023-12-05 18:03:13 +01:00
Lion Kortlepel e245c9e9e2 fix pps monitor warning about virtual dtor 2023-12-05 18:02:35 +01:00
Lion Kortlepel 11fe5ad200 fix invalid timeout value 2023-12-05 18:00:34 +01:00
Lion Kortlepel 667da22b0e Merge remote-tracking branch 'origin/master' into new-buildsystem 2023-12-05 17:59:05 +01:00
Lion Kortlepel a6eb2f7bfe switch to vcpkg+cmake, add debian build to workflows
using lionkor's template (MIT licensed)

This is a combination of 64 commits.
2023-12-05 17:57:19 +01:00
Lion Kortlepel 103d2dc030 update vcpkg in workflows 2023-12-03 17:50:45 +01:00
Lion Kortlepel 7f206fd0d4 bump version to 3.1.2 2023-12-03 17:49:12 +01:00
Lion Kortlepel 22805af716 fix crash in authentication 2023-12-03 17:43:41 +01:00
Lion 2c29a195f9 optimize: Add conditional variable to LuaResult (#162)
Implementing TODO for optimization I saw in the code.
2023-03-27 13:31:21 +02:00
rgnter 222d2492ff Merge branch 'master' into optimize/add_cv_to_luaresult 2023-03-21 20:17:17 +01:00
Simon 879b9772f5 Apply suggestions from code review
Co-authored-by: Lion <development@kortlepel.com>
2023-01-15 17:12:35 +00:00
Anonymous275 c51cf090ef fix linux build 2023-01-15 17:12:35 +00:00
Anonymous275 d677d8d58d rename Hash function to HashPassword
move HashPassword to cpp only
move check to line 285
2023-01-15 17:12:35 +00:00
Anonymous275 4b30918659 - add 120 seconds timeout 2023-01-15 17:12:35 +00:00
Anonymous275 688e46f524 - fix linux build 2023-01-15 17:12:35 +00:00
Anonymous275 9f59c27b1f - add hash function
- add password config
- add debug messages for password stages
- add pass boolean for heartbeat
- adjust network codes
2023-01-15 17:12:35 +00:00
Lion 6a11bcd20b fix bad package name for Ubuntu in Readme (#161)
The package name for liblua required to build is not correct. The
correct name is
[`liblua-5.3-dev`](https://packages.ubuntu.com/search?suite=all&searchon=names&keywords=liblua5.3)
2022-12-21 16:29:49 +01:00
rgnter b7b578bf3e add conditional variable to LuaResult 2022-12-18 14:45:33 +01:00
rgnter 6c145a6dbf fix: Bad package name for Ubuntu 2022-12-18 12:32:45 +01:00
Lion 67d792e0e0 remove repeated dependency from README (#155) 2022-11-14 14:32:19 +01:00
Qest333 eaeef0c7d0 Remove double dependency from README 2022-11-14 14:00:21 +01:00
86 changed files with 1705 additions and 2242 deletions
-78
View File
@@ -1,78 +0,0 @@
name: CMake Linux Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
linux-build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v2
with:
submodules: "recursive"
- name: Install Dependencies
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: |
echo ${#beammp_sentry_url}
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build Server
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
- name: Build Tests
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server-tests --parallel
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-linux
path: ${{github.workspace}}/build-linux/BeamMP-Server
- name: Archive test artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-linux-tests
path: ${{github.workspace}}/build-linux/BeamMP-Server-tests
run-tests:
needs: linux-build
runs-on: ubuntu-22.04
steps:
- uses: actions/download-artifact@master
with:
name: BeamMP-Server-linux-tests
path: ${{github.workspace}}
- name: Install Runtime Dependencies
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y liblua5.3-0 libssl3 curl
- name: Test
working-directory: ${{github.workspace}}
shell: bash
run: |
chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests
-58
View File
@@ -1,58 +0,0 @@
name: CMake Windows Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
windows-build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@v7
id: runvcpkg
with:
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio boost-uuid'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: "06b5f4a769d848d1a20fa0acd556019728b56273"
vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Archive artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server.exe
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
- name: Build debug
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: |
cmake --build . --config Debug
- name: Archive debug artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-debug.exe
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
+150
View File
@@ -0,0 +1,150 @@
name: Linux
on: [push]
env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
jobs:
debian-11-build:
runs-on: ubuntu-latest
container:
image: debian:11
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/debian-11/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/debian-11/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-debian
path: ./bin/BeamMP-Server
- name: Build Tests
run: bash ./scripts/debian-11/3-build-tests.sh
- name: Archive server tests artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-debian-tests
path: ./bin/BeamMP-Server-tests
ubuntu-22-04-build:
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/ubuntu-22.04/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-ubuntu
path: ./bin/BeamMP-Server
- name: Build Tests
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
- name: Archive server tests artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-ubuntu-tests
path: ./bin/BeamMP-Server-tests
run-debian-11-tests:
needs: debian-11-build
runs-on: ubuntu-latest
container:
image: debian:11
steps:
- uses: actions/download-artifact@master
with:
name: BeamMP-Server-debian-tests
- name: Install Runtime Dependencies
run: |
apt-get update -y
apt-get install -y liblua5.3-0
- name: Test
run: |
chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests
run-ubuntu-22-04-tests:
needs: ubuntu-22-04-build
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
steps:
- uses: actions/download-artifact@master
with:
name: BeamMP-Server-ubuntu-tests
- name: Install Runtime Dependencies
run: |
apt-get update -y
apt-get install -y liblua5.3-0
- name: Test
run: |
chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests
-115
View File
@@ -1,115 +0,0 @@
name: Release Create & Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
BUILD_TYPE: Release
jobs:
create-release:
runs-on: ubuntu-latest
name: Create Release
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: true
body: |
Files included in this release:
- `BeamMP-Server.exe` is the windows build
- `BeamMP-Server-linux` is a ubuntu build, so you need the dependencies listed in README.md to run it. For any other distros please build from source as described in README.md.
upload-release-files-linux:
name: Upload Linux Release Files
runs-on: ubuntu-22.04
needs: create-release
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev libboost-dev libboost1.74-all-dev libboost1.74-dev
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-linux/BeamMP-Server
asset_name: BeamMP-Server-linux
asset_content_type: application/x-elf
upload-release-files-windows:
name: Upload Windows Release Files
runs-on: windows-latest
needs: create-release
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@v7
id: runvcpkg
with:
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl boost-variant boost-spirit boost-phoenix boost-core boost-system boost-asio'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '06b5f4a769d848d1a20fa0acd556019728b56273'
vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable
+168
View File
@@ -0,0 +1,168 @@
name: Release Create & Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
jobs:
create-release:
runs-on: ubuntu-latest
name: Create Release
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: true
body: |
Files included in this release:
- `BeamMP-Server.exe` is the windows build.
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`.
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
upload-release-files-debian-11:
name: Build and upload Debian 11 Release Files
runs-on: ubuntu-22.04
needs: create-release
container:
image: debian:11
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/debian-11/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/debian-11/3-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server
asset_name: BeamMP-Server-debian
asset_content_type: application/x-elf
upload-release-files-ubuntu-22-04:
name: Build and upload Ubuntu 22.04 Release Files
runs-on: ubuntu-22.04
needs: create-release
container:
image: ubuntu:22.04
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/ubuntu-22.04/3-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server
asset_name: BeamMP-Server-ubuntu
asset_content_type: application/x-elf
upload-release-files-windows:
name: Build and upload Windows Release Files
runs-on: windows-latest
needs: create-release
env:
VCPKG_DEFAULT_TRIPLET: x64-windows-static
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Create Build Environment
shell: bash
run: ./scripts/windows/1-configure.sh
- name: Build Server
shell: bash
run: bash ./scripts/windows/2-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.exe
asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable
+42
View File
@@ -0,0 +1,42 @@
name: Windows
on: [push]
env:
VCPKG_DEFAULT_TRIPLET: x64-windows-static
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
jobs:
windows-build:
runs-on: windows-latest
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
shell: bash
run: ./scripts/windows/1-configure.sh
- name: Build Server
shell: bash
run: bash ./scripts/windows/2-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-windows
path: ./bin/BeamMP-Server.exe
+3 -33
View File
@@ -1,36 +1,6 @@
[submodule "deps/commandline"] [submodule "deps/commandline"]
path = deps/commandline path = deps/commandline
url = https://github.com/lionkor/commandline url = https://github.com/lionkor/commandline
[submodule "deps/asio"] [submodule "vcpkg"]
path = deps/asio path = vcpkg
url = https://github.com/chriskohlhoff/asio url = https://github.com/Microsoft/vcpkg.git
[submodule "deps/rapidjson"]
path = deps/rapidjson
url = https://github.com/Tencent/rapidjson
[submodule "deps/toml11"]
path = deps/toml11
url = https://github.com/ToruNiina/toml11
[submodule "deps/sentry-native"]
path = deps/sentry-native
url = https://github.com/getsentry/sentry-native
[submodule "deps/sol2"]
path = deps/sol2
url = https://github.com/ThePhD/sol2
[submodule "deps/libzip"]
path = deps/libzip
url = https://github.com/nih-at/libzip
[submodule "deps/cpp-httplib"]
path = deps/cpp-httplib
url = https://github.com/yhirose/cpp-httplib
[submodule "deps/json"]
path = deps/json
url = https://github.com/nlohmann/json
[submodule "deps/fmt"]
path = deps/fmt
url = https://github.com/fmtlib/fmt
[submodule "deps/doctest"]
path = deps/doctest
url = https://github.com/doctest/doctest
[submodule "deps/lk-result"]
path = deps/lk-result
url = https://gitlab.com/lionkor/lk-result.git
+188 -262
View File
@@ -1,286 +1,212 @@
# 3.4 is required for imported targets. cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
message(STATUS "You can find build instructions and a list of dependencies in the README at \ if (WIN32)
https://github.com/BeamMP/BeamMP-Server") set(VCPKG_TARGET_TRIPLET x64-windows-static)
endif()
include(FetchContent) include(cmake/Vcpkg.cmake) # needs to happen before project()
FetchContent_Declare(
cmake-tools project(
GIT_REPOSITORY https://github.com/brobeson/cmake-tools.git "BeamMP-Server" # replace this
GIT_TAG main VERSION 3.3.0
) )
FetchContent_MakeAvailable(cmake-tools)
list(APPEND CMAKE_MODULE_PATH "${cmake-tools_SOURCE_DIR}")
include(CMakeToolsVersionFromGit) include(cmake/StandardSettings.cmake)
include(cmake/StaticAnalyzers.cmake)
include(cmake/Git.cmake)
execute_process( # below are options which should be changed
COMMAND git log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE GIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
project(BeamMP-Server ### SETTINGS ###
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
HOMEPAGE_URL https://beammp.com
LANGUAGES CXX C)
# quality of life stuff # add all headers (.h, .hpp) to this
set(CMAKE_COLOR_DIAGNOSTICS ON) set(PRJ_HEADERS
include/ArgsParser.h
find_package(Git REQUIRED)
# Update submodules as needed
option(GIT_SUBMODULE "Check submodules during build" ON)
if(GIT_SUBMODULE)
message(STATUS "Submodule update")
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
endif()
endif()
set(HTTPLIB_REQUIRE_OPENSSL ON)
set(SENTRY_BUILD_SHARED_LIBS OFF)
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
option(WIN32_STATIC_RUNTIME "Build statically-linked runtime on windows (don't touch unless you know what you're doing)" ON)
# ------------------------ APPLE ---------------------------------
if(APPLE)
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
set(LUA_INCLUDE_DIR /opt/homebrew/Cellar/lua@5.3/5.3.6/include/lua5.3)
link_directories(/opt/homebrew/Cellar/lua@5.3/5.3.6/lib)
else()
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
endif()
set(LUA_LIBRARIES lua)
if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
include_directories(/opt/homebrew/opt/openssl@1.1/include)
link_directories(/opt/homebrew/opt/openssl@1.1/lib)
else()
include_directories(/usr/local/opt/openssl@1.1/include)
link_directories(/usr/local/opt/openssl@1.1/lib)
endif()
# ------------------------ WINDOWS ---------------------------------
elseif (WIN32)
if (WIN32_STATIC_RUNTIME)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
endif()
# ------------------------ UNIX ------------------------------------
elseif (UNIX)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2")
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
if (SANITIZE)
message(STATUS "sanitize is ON")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize={address,thread,undefined}")
endif (SANITIZE)
endif ()
set(BUILD_SHARED_LIBS OFF)
# ------------------------ SENTRY ---------------------------------
message(STATUS "Checking for Sentry URL")
# this is set by the build system.
# IMPORTANT: if you're building from source, just leave this empty
if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
set(BEAMMP_SECRET_SENTRY_URL "")
set(SENTRY_BACKEND none)
else()
set(SENTRY_BACKEND breakpad)
endif()
add_subdirectory("deps/sentry-native")
# ------------------------ C++ SETUP ---------------------------------
set(CMAKE_CXX_STANDARD 20)
# ------------------------ DEPENDENCIES ------------------------------
message(STATUS "Adding local source dependencies")
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
add_subdirectory(deps)
# ------------------------ VARIABLES ---------------------------------
include(FindLua)
include(FindOpenSSL)
include(FindThreads)
include(FindZLIB)
find_package(Boost 1.70 REQUIRED COMPONENTS system)
set(BeamMP_Sources
include/TConsole.h src/TConsole.cpp
include/TServer.h src/TServer.cpp
include/Compat.h src/Compat.cpp
include/Common.h src/Common.cpp
include/Client.h src/Client.cpp
include/VehicleData.h src/VehicleData.cpp
include/TConfig.h src/TConfig.cpp
include/TLuaEngine.h src/TLuaEngine.cpp
include/TLuaPlugin.h src/TLuaPlugin.cpp
include/TResourceManager.h src/TResourceManager.cpp
include/THeartbeatThread.h src/THeartbeatThread.cpp
include/Http.h src/Http.cpp
include/TSentry.h src/TSentry.cpp
include/TPPSMonitor.h src/TPPSMonitor.cpp
include/TNetwork.h src/TNetwork.cpp
include/LuaAPI.h src/LuaAPI.cpp
include/TScopedTimer.h src/TScopedTimer.cpp
include/SignalHandling.h src/SignalHandling.cpp
include/ArgsParser.h src/ArgsParser.cpp
include/TPluginMonitor.h src/TPluginMonitor.cpp
include/Environment.h
include/BoostAliases.h include/BoostAliases.h
include/Uuid.h src/Uuid.cpp include/Client.h
include/Common.h
include/Compat.h
include/Cryptography.h
include/CustomAssert.h
include/Defer.h
include/Environment.h
include/Http.h
include/IThreaded.h
include/Json.h
include/LuaAPI.h
include/RWMutex.h
include/SignalHandling.h
include/TConfig.h
include/TConsole.h
include/THeartbeatThread.h
include/TLuaEngine.h
include/TLuaPlugin.h
include/TNetwork.h
include/TPluginMonitor.h
include/TPPSMonitor.h
include/TResourceManager.h
include/TScopedTimer.h
include/TServer.h
include/VehicleData.h
)
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES
src/ArgsParser.cpp
src/Client.cpp
src/Common.cpp
src/Compat.cpp
src/Http.cpp
src/LuaAPI.cpp
src/SignalHandling.cpp
src/TConfig.cpp
src/TConsole.cpp
src/THeartbeatThread.cpp
src/TLuaEngine.cpp
src/TLuaPlugin.cpp
src/TNetwork.cpp
src/TPluginMonitor.cpp
src/TPPSMonitor.cpp
src/TResourceManager.cpp
src/TScopedTimer.cpp
src/TServer.cpp
src/VehicleData.cpp
) )
set(BeamMP_Includes find_package(Lua REQUIRED)
${LUA_INCLUDE_DIR}
${CURL_INCLUDE_DIRS}
"${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/lk-result/include"
"${CMAKE_CURRENT_SOURCE_DIR}/deps"
"${CMAKE_CURRENT_SOURCE_DIR}/deps/fmt/include"
)
set(BeamMP_Definitions # set the source file containing main()
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}" set(PRJ_MAIN src/main.cpp)
BEAMMP_GIT_HASH="${GIT_HASH}" # set the source file containing the test's main
LK_RESULT_USE_FMT set(PRJ_TEST_MAIN test/test_main.cpp)
) # set include paths not part of libraries
set(PRJ_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
if (WIN32) # set compile features (e.g. standard version)
list(APPEND BeamMP_Definitions _WIN32_WINNT=0x0601) set(PRJ_COMPILE_FEATURES cxx_std_20)
list(APPEND BeamMP_Definitions _CRT_SECURE_NO_WARNINGS) # set #defines (test enable/disable not included here)
endif() set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
if (UNIX) # add all libraries used by the project (WARNING: also set them in vcpkg.json!)
set(BeamMP_CompileOptions set(PRJ_LIBRARIES
-Wall
-Wextra
-Wpedantic
-Werror=uninitialized
-Werror=float-equal
-Werror=pointer-arith
-Werror=double-promotion
-Werror=write-strings
-Werror=cast-qual
-Werror=init-self
-Werror=cast-align
-Werror=unreachable-code
-Werror=strict-aliasing -fstrict-aliasing
-Werror=redundant-decls
-Werror=missing-declarations
-Werror=missing-field-initializers
-Werror=write-strings
-Werror=ctor-dtor-privacy
-Wswitch-enum
-Wswitch-default
-Werror=old-style-cast
-Werror=overloaded-virtual
-Werror=overloaded-virtual
-Werror=missing-include-dirs
-Werror=unused-result
-fstack-protector
-Wzero-as-null-pointer-constant
)
else()
set(BeamMP_CompileOptions
/bigobj
/INCREMENTAL:NO /NODEFAULTLIB:MSVCRT /NODEFAULTLIB:LIBCMT
)
endif()
set(BeamMP_Libraries
Boost::boost
Boost::system
doctest::doctest
OpenSSL::SSL
OpenSSL::Crypto
sol2::sol2
Threads::Threads
ZLIB::ZLIB
${LUA_LIBRARIES}
commandline
sentry
fmt::fmt fmt::fmt
doctest::doctest
Threads::Threads
commandline_static
toml11::toml11
rapidjson
sol2
httplib::httplib
libzip::zip
OpenSSL::SSL OpenSSL::Crypto
${LUA_LIBRARIES}
) )
if (WIN32) # add dependency find_package calls and similar here
set(BeamMP_PlatformLibs wsock32 ws2_32) find_package(fmt CONFIG REQUIRED)
endif () find_package(OpenSSL REQUIRED)
find_package(doctest CONFIG REQUIRED)
find_package(Boost REQUIRED)
find_package(httplib CONFIG REQUIRED)
find_package(libzip CONFIG REQUIRED)
find_package(RapidJSON CONFIG REQUIRED)
find_package(sol2 CONFIG REQUIRED)
find_package(toml11 CONFIG REQUIRED)
# ------------------------ BEAMMP SERVER ----------------------------- include_directories(include)
add_executable(BeamMP-Server # to enable multithreading and the Threads::Threads dependency
src/main.cpp include(FindThreads)
${BeamMP_Sources}
)
target_compile_definitions(BeamMP-Server PRIVATE ### END SETTINGS ###
${BeamMP_Definitions}
DOCTEST_CONFIG_DISABLE
)
target_compile_options(BeamMP-Server PRIVATE # DONT change anything beyond this point unless you've read the cmake bible and
${BeamMP_CompileOptions} # swore on it not to bonk up the ci/cd pipelines with your changes.
)
target_include_directories(BeamMP-Server PRIVATE ####################
"${CMAKE_CURRENT_SOURCE_DIR}/include"
)
target_include_directories(BeamMP-Server SYSTEM PRIVATE
${BeamMP_Includes}
)
target_link_libraries(BeamMP-Server # enables compile_commands.json for clang-related tools (such as the clang LS)
${BeamMP_Libraries} set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
${BeamMP_PlatformLibs}
)
# ------------------------ BEAMMP SERVER TESTS ----------------------- # build debug builds by default (if not specified otherwise)
if(NOT CMAKE_BUILD_TYPE)
option(BUILD_TESTS "Build BeamMP-Server tests" ON) set(CMAKE_BUILD_TYPE "Debug")
endif()
if(BUILD_TESTS)
add_executable(BeamMP-Server-tests if(UNIX)
test/test_main.cpp # this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
${BeamMP_Sources} add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
) endif(UNIX)
target_compile_definitions(BeamMP-Server-tests PRIVATE if (WIN32)
${BeamMP_Definitions} add_compile_options("-D_WIN32_WINNT=0x0601")
) endif(WIN32)
target_compile_options(BeamMP-Server-tests PRIVATE
${BeamMP_CompileOptions} include(cmake/CompilerWarnings.cmake)
)
# set MT library for msvc - this is required (says documentation)
target_include_directories(BeamMP-Server-tests PRIVATE # linux/mac/etc should simply ignore this by default.
"${CMAKE_CURRENT_SOURCE_DIR}/include" set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
)
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
target_include_directories(BeamMP-Server-tests SYSTEM PRIVATE PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
${BeamMP_Includes} PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
) PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
)
target_link_libraries(BeamMP-Server-tests
${BeamMP_Libraries} # build commandline manually for funky windows flags to carry over without a custom toolchain file
${BeamMP_PlatformLibs} add_library(commandline_static
) deps/commandline/src/impls.h
deps/commandline/src/windows_impl.cpp
deps/commandline/src/linux_impl.cpp
deps/commandline/src/backends/InteractiveBackend.cpp
deps/commandline/src/backends/InteractiveBackend.h
deps/commandline/src/backends/Backend.cpp
deps/commandline/src/backends/Backend.h
deps/commandline/src/commandline.h
deps/commandline/src/commandline.cpp
deps/commandline/src/backends/BufferedBackend.cpp
deps/commandline/src/backends/BufferedBackend.h
)
if (WIN32)
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
else ()
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_LINUX=1)
endif ()
target_include_directories(commandline_static PUBLIC "deps/commandline/src")
target_link_libraries(commandline_static Threads::Threads)
# end of commandline custom build
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
set_target_properties(${PROJECT_NAME} PROPERTIES
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
)
if(MSVC)
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
endif(MSVC)
# setup all warnings (from cmake/CompilerWarnings.cmake)
set_project_warnings(${PROJECT_NAME})
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
set_project_warnings(${PROJECT_NAME}-tests)
if(MSVC)
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
endif(MSVC)
endif() endif()
-9
View File
@@ -1,12 +1,3 @@
# v3.2.0
- ADDED `settings` command, which lets you `get`, `list`, and `set` config options from the console
- ADDED `debug` command, which shows info about connected clients & networking (for developers)
- ADDED `Util.GenerateUUID()`, which generates an RFC4122 UUID (universally unique identifier)
- ADDED `version` command, which shows version information
- ADDED `onPlayerRequestMods` event, letting Lua disallow individual mods from being sent to clients
- CHANGED `onShutdown` to be called before all players are kicked
# v3.1.1 # v3.1.1
- FIXED bug which caused GetPlayerIdentifiers, GetPlayerName, etc not to work in `onPlayerDisconnect` - FIXED bug which caused GetPlayerIdentifiers, GetPlayerName, etc not to work in `onPlayerDisconnect`
+2 -3
View File
@@ -66,7 +66,7 @@ Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/Beam
Dependencies for **Windows** can be installed with `vcpkg`. Dependencies for **Windows** can be installed with `vcpkg`.
These are: These are:
``` ```
lua zlib rapidjson openssl websocketpp curl boost lua zlib rapidjson openssl websocketpp curl
``` ```
The triplet we use for releases is `x64-windows-static`. The triplet we use for releases is `x64-windows-static`.
@@ -117,7 +117,7 @@ Ubuntu 22.04
git git
libz-dev libz-dev
rapidjson-dev rapidjson-dev
liblua5.3 liblua5.3-dev
libssl-dev libssl-dev
libwebsocketpp-dev libwebsocketpp-dev
libcurl4-openssl-dev libcurl4-openssl-dev
@@ -142,7 +142,6 @@ curl
git git
cmake cmake
g++ g++
cmake
zlib zlib
boost boost
websocketpp websocketpp
+115
View File
@@ -0,0 +1,115 @@
# from here:
#
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
# Courtesy of Jason Turner
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
#
# This version has been modified by the owners of the current respository.
# Modifications have mostly been marked with "modified" or similar, though this is not
# strictly required.
function(set_project_warnings project_name)
set(MSVC_WARNINGS
/W4 # Baseline reasonable warnings
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
# of data
/w14254 # 'operator': conversion from 'type1:field_bits' to
# 'type2:field_bits', possible loss of data
/w14263 # 'function': member function does not override any base class
# virtual member function
/w14265 # 'classname': class has virtual functions, but destructor is not
# virtual instances of this class may not be destructed correctly
/w14287 # 'operator': unsigned/negative constant mismatch
/we4289 # nonstandard extension used: 'variable': loop control variable
# declared in the for-loop is used outside the for-loop scope
/w14296 # 'operator': expression is always 'boolean_value'
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
/w14545 # expression before comma evaluates to a function which is missing
# an argument list
/w14546 # function call before comma missing argument list
/w14547 # 'operator': operator before comma has no effect; expected
# operator with side-effect
/w14549 # 'operator': operator before comma has no effect; did you intend
# 'operator'?
/w14555 # expression has no effect; expected expression with side- effect
/w14619 # pragma warning: there is no warning number 'number'
/w14640 # Enable warning on thread un-safe static member initialization
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
# cause unexpected runtime behavior.
/w14905 # wide string literal cast to 'LPSTR'
/w14906 # string literal cast to 'LPWSTR'
/w14928 # illegal copy-initialization; more than one user-defined
# conversion has been implicitly applied
/permissive- # standards conformance mode for MSVC compiler.
)
set(CLANG_WARNINGS
-Wall
-Wextra # reasonable and standard
-Wshadow # warn the user if a variable declaration shadows one from a
# parent context
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
# non-virtual destructor. This helps catch hard to
# track down memory errors
-Wold-style-cast # warn for c-style casts
-Wcast-align # warn for potential performance problem casts
-Wunused # warn on anything being unused
-Woverloaded-virtual # warn if you overload (not override) a virtual
# function
-Wpedantic # warn if non-standard C++ is used
-Wconversion # warn on type conversions that may lose data
-Wsign-conversion # warn on sign conversions
-Wnull-dereference # warn if a null dereference is detected
-Wdouble-promotion # warn if float is implicit promoted to double
-Wformat=2 # warn on security issues around functions that format output
# (ie printf)
# modified; added more errors / warnings
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
# (see below) should still be used in strict pipelines.
-Werror=uninitialized
-Werror=float-equal
-Werror=write-strings
-Werror=strict-aliasing -fstrict-aliasing
-Werror=missing-declarations
-Werror=missing-field-initializers
-Werror=ctor-dtor-privacy
-Werror=switch-enum
-Wswitch-default
-Werror=unused-result
-Werror=implicit-fallthrough
-Werror=return-type
-Wmissing-include-dirs
)
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
endif()
set(GCC_WARNINGS
${CLANG_WARNINGS}
-Wmisleading-indentation # warn if indentation implies blocks where blocks
# do not exist
-Wduplicated-cond # warn if if / else chain has duplicated conditions
-Wduplicated-branches # warn if if / else branches have duplicated code
-Wlogical-op # warn about logical operations being used where bitwise were
# probably wanted
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
)
if(MSVC)
set(PRJ_WARNINGS ${MSVC_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
set(PRJ_WARNINGS ${CLANG_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(PRJ_WARNINGS ${GCC_WARNINGS})
else()
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
endif()
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
if(NOT TARGET ${project_name})
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
endif()
endfunction()
+21
View File
@@ -0,0 +1,21 @@
find_package(Git)
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
if(Git_FOUND)
message(STATUS "Git found, submodule update and init")
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
endif()
else()
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
endif()
endif()
if(Git_FOUND)
else()
message(STATUS "Git not found - the version will not include a git hash.")
set(PRJ_GIT_HASH "unknown")
endif()
+44
View File
@@ -0,0 +1,44 @@
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
# TODO Implement code coverage
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
# Generate compile_commands.json for clang based tools
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Export all symbols when building a shared library
if(BUILD_SHARED_LIBS)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
endif()
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF)
if(${PROJECT_NAME}_ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT result OUTPUT output)
if(result)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
message(SEND_ERROR "IPO is not supported: ${output}.")
endif()
endif()
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
endif()
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
if(${PROJECT_NAME}_ENABLE_SANITIZER)
add_compile_options(-fsanitize=address,undefined)
add_link_options(-fsanitize=address,undefined)
endif()
+20
View File
@@ -0,0 +1,20 @@
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
find_program(CLANGTIDY clang-tidy)
if(CLANGTIDY)
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
message("Clang-Tidy finished setting up.")
else()
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
endif()
endif()
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
find_program(CPPCHECK cppcheck)
if(CPPCHECK)
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
--inline-suppr --inconclusive)
message("Cppcheck finished setting up.")
else()
message(SEND_ERROR "Cppcheck requested but executable not found.")
endif()
endif()
+17
View File
@@ -0,0 +1,17 @@
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
find_package(Git)
if(Git_FOUND)
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive vcpkg
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
endif()
else()
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
endif()
endif()
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
endif()
-6
View File
@@ -1,6 +0,0 @@
include_directories("${PROJECT_SOURCE_DIR}/deps")
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
Vendored
-1
Submodule deps/asio deleted from 4915cfd8a1
-1
Submodule deps/cpp-httplib deleted from d92c314466
-1
Submodule deps/doctest deleted from b7c21ec5ce
Vendored
-1
Submodule deps/fmt deleted from c4ee726532
Vendored
-1
Submodule deps/json deleted from 69d744867f
Vendored
-1
Submodule deps/libzip deleted from 5532f9baa0
-1
Submodule deps/lk-result deleted from 4a4eda8092
-1
Submodule deps/rapidjson deleted from 00dbcf2c6e
Submodule deps/sentry-native deleted from 28be51f5e3
Vendored
-1
Submodule deps/sol2 deleted from eba86625b7
Vendored
-1
Submodule deps/toml11 deleted from c7627ff6a1
+2 -24
View File
@@ -10,7 +10,6 @@
#include "BoostAliases.h" #include "BoostAliases.h"
#include "Common.h" #include "Common.h"
#include "Compat.h" #include "Compat.h"
#include "TResourceManager.h"
#include "VehicleData.h" #include "VehicleData.h"
class TServer; class TServer;
@@ -71,7 +70,6 @@ public:
void ClearCars(); void ClearCars();
[[nodiscard]] int GetID() const { return mID; } [[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; } [[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
bool mUDPCONNECTED = false;
[[nodiscard]] bool IsConnected() const { return mIsConnected; } [[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; } [[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; } [[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
@@ -89,24 +87,6 @@ public:
void UpdatePingTime(); void UpdatePingTime();
int SecondsSinceLastPing(); int SecondsSinceLastPing();
// bytes received on UDP
std::atomic_size_t UdpReceived = 0;
// number of packets received on UDP
std::atomic_size_t UdpPacketsReceived = 0;
// bytes sent on UDP
std::atomic_size_t UdpSent = 0;
// number of packets sent on UDP
std::atomic_size_t UdpPacketsSent = 0;
// bytes received on TCP
std::atomic_size_t TcpReceived = 0;
// bytes sent on TCP
std::atomic_size_t TcpSent = 0;
TimeType::time_point ConnectionTime {};
ModMap AllowedMods;
private: private:
void InsertVehicle(int ID, const std::string& Data); void InsertVehicle(int ID, const std::string& Data);
@@ -130,9 +110,7 @@ private:
std::string mRole; std::string mRole;
std::string mDID; std::string mDID;
int mID = -1; int mID = -1;
std::chrono::time_point<TimeType> mLastPingTime; std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
std::mutex mDisconnectMtx;
}; };
// Returns a valid client, or nullptr if no such client exists std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
std::shared_ptr<TClient> GetClient(class TServer& Server, int ID);
+55 -154
View File
@@ -1,9 +1,5 @@
#pragma once #pragma once
#include "CustomAssert.h"
#include "TSentry.h"
extern TSentry Sentry;
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cstring> #include <cstring>
@@ -24,50 +20,6 @@ namespace fs = std::filesystem;
#include "TConsole.h" #include "TConsole.h"
#include <boost/container/flat_map.hpp>
#include <boost/variant.hpp>
#include <chrono>
#include <variant>
using TimeType = std::chrono::system_clock;
#include <lk/Result.h>
template <typename T>
using Result = lk::Result<T>;
using Error = lk::Error;
// General
constexpr std::string_view StrDebug = "Debug";
constexpr std::string_view StrPrivate = "Private";
constexpr std::string_view StrPort = "Port";
constexpr std::string_view StrMaxCars = "MaxCars";
constexpr std::string_view StrMaxPlayers = "MaxPlayers";
constexpr std::string_view StrMap = "Map";
constexpr std::string_view StrName = "Name";
constexpr std::string_view StrDescription = "Description";
constexpr std::string_view StrResourceFolder = "ResourceFolder";
constexpr std::string_view StrAuthKey = "AuthKey";
constexpr std::string_view StrLogChat = "LogChat";
// Misc
constexpr std::string_view StrSendErrors = "SendErrors";
constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
constexpr std::string_view StrIncludeSubdirectories = "IncludeSubdirectories";
// HTTP
constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
constexpr std::string_view StrSSLCertPath = "SSLCertPath";
constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
// Unused
constexpr std::string_view StrCustomIP = "Unused.CustomIP";
struct Version { struct Version {
uint8_t major; uint8_t major;
uint8_t minor; uint8_t minor;
@@ -80,12 +32,6 @@ struct Version {
template <typename T> template <typename T>
using SparseArray = std::unordered_map<size_t, T>; using SparseArray = std::unordered_map<size_t, T>;
template <typename K, typename V>
using HashMap = std::unordered_map<K, V>;
using boost::variant;
using boost::container::flat_map;
// static class handling application start, shutdown, etc. // static class handling application start, shutdown, etc.
// yes, static classes, singletons, globals are all pretty // yes, static classes, singletons, globals are all pretty
// bad idioms. In this case we need a central way to access // bad idioms. In this case we need a central way to access
@@ -94,17 +40,31 @@ using boost::container::flat_map;
class Application final { class Application final {
public: public:
// types // types
struct TSettings {
using SettingValue = std::variant<std::string, bool, int>; std::string ServerName { "BeamMP Server" };
using SettingsMap = flat_map<std::string_view, SettingValue>; std::string ServerDesc { "BeamMP Default Description" };
std::string Resource { "Resources" };
static SettingsMap mSettings; std::string MapName { "/levels/gridmap_v2/info.json" };
std::string Key {};
static std::string GetSettingString(std::string_view Name); std::string Password{};
static int GetSettingInt(std::string_view Name); std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
static bool GetSettingBool(std::string_view Name); std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
bool HTTPServerEnabled { false };
static void SetSetting(std::string_view Name, const SettingValue& value); int MaxPlayers { 8 };
bool Private { true };
int MaxCars { 1 };
bool DebugModeEnabled { false };
int Port { 30814 };
std::string CustomIP {};
bool LogChat { true };
bool SendErrors { true };
bool SendErrorsMessageEnabled { true };
int HTTPServerPort { 8080 };
std::string HTTPServerIP { "127.0.0.1" };
bool HTTPServerUseSSL { false };
bool HideUpdateMessages { false };
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
};
using TShutdownHandler = std::function<void()>; using TShutdownHandler = std::function<void()>;
@@ -122,6 +82,8 @@ public:
static std::string PPS() { return mPPS; } static std::string PPS() { return mPPS; }
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; } static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
static TSettings Settings;
static std::vector<std::string> GetBackendUrlsInOrder() { static std::vector<std::string> GetBackendUrlsInOrder() {
return { return {
"backend.beammp.com", "backend.beammp.com",
@@ -161,16 +123,6 @@ public:
static void SetSubsystemStatus(const std::string& Subsystem, Status status); static void SetSubsystemStatus(const std::string& Subsystem, Status status);
static std::string SettingToString(const SettingValue& Value);
// Keeps track of how many packets we dropped on UDP due to fundamentally being malformed
static inline std::atomic_size_t MalformedUdpPackets { 0 };
// Keeps track of how many packets we dropped on UDP due to
// 1) not having a valid (known) player id
// 2) player disconnecting
// 3) packet failing to parse
static inline std::atomic_size_t InvalidUdpPackets { 0 };
private: private:
static void SetShutdown(bool Val); static void SetShutdown(bool Val);
@@ -183,7 +135,7 @@ private:
static inline std::mutex mShutdownHandlersMutex {}; static inline std::mutex mShutdownHandlersMutex {};
static inline std::deque<TShutdownHandler> mShutdownHandlers {}; static inline std::deque<TShutdownHandler> mShutdownHandlers {};
static inline Version mVersion { 3, 2, 0 }; static inline Version mVersion { 3, 1, 2 };
}; };
std::string ThreadName(bool DebugModeOverride = false); std::string ThreadName(bool DebugModeOverride = false);
@@ -193,7 +145,6 @@ void RegisterThread(const std::string& str);
#define KB 1024llu #define KB 1024llu
#define MB (KB * 1024llu) #define MB (KB * 1024llu)
#define GB (MB * 1024llu) #define GB (MB * 1024llu)
#define TB (GB * 1024llu)
#define SSU_UNRAW SECRET_SENTRY_URL #define SSU_UNRAW SECRET_SENTRY_URL
#define _file_basename std::filesystem::path(__FILE__).filename().string() #define _file_basename std::filesystem::path(__FILE__).filename().string()
@@ -234,88 +185,40 @@ void RegisterThread(const std::string& str);
#endif // defined(DEBUG) #endif // defined(DEBUG)
#define beammp_internal_error(x) Application::Console().Write(_this_location + std::string("[INTERNAL ERROR] ") + (x)) #define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
#define beammp_warn(x) \ #define beammp_error(x) \
do { \ do { \
try{ \ Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
Application::Console().Write(_this_location + std::string("[WARN] ") + (x)); \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false) } while (false)
#define beammp_info(x) \ #define beammp_lua_error(x) \
do { \ do { \
try{ \ Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
Application::Console().Write(_this_location + std::string("[INFO] ") + (x)); \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false) } while (false)
#define beammp_error(x) \ #define beammp_lua_warn(x) \
do { \ do { \
try{ \ Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false) } while (false)
#define beammp_lua_error(x) \ #define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
do { \ #define beammp_debug(x) \
try{ \ do { \
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \ if (Application::Settings.DebugModeEnabled) { \
} catch (const std::exception& e) { \ Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\ } \
} \
} while (false) } while (false)
#define beammp_lua_warn(x) \ #define beammp_event(x) \
do { \ do { \
try{ \ if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \ Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
} catch (const std::exception& e) { \ } \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false)
#define luaprint(x) \
do { \
try{ \
Application::Console().Write(_this_location + std::string("[LUA] ") + (x)); \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false)
#define beammp_debug(x) \
do { \
try{ \
if (Application::GetSettingBool("Debug")) { \
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
} \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false)
#define beammp_event(x) \
do { \
try{ \
if (Application::GetSettingBool("Debug")) { \
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
} \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}': {}", #x, e.what()));\
} \
} while (false) } while (false)
// trace() is a debug-build debug() // trace() is a debug-build debug()
#if defined(DEBUG) #if defined(DEBUG)
#define beammp_trace(x) \ #define beammp_trace(x) \
do { \ do { \
try{ \ if (Application::Settings.DebugModeEnabled) { \
if (Application::GetSettingBool("Debug")) { \ Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \ } \
} \
} catch (const std::exception& e) { \
beammp_internal_error(fmt::format("Exception in logging function, failed to print '{}'", #x)); \
} \
} while (false) } while (false)
#else #else
#define beammp_trace(x) #define beammp_trace(x)
@@ -415,5 +318,3 @@ inline T DeComp(const T& Compressed) {
std::string GetPlatformAgnosticErrorString(); std::string GetPlatformAgnosticErrorString();
#define S_DSN SU_RAW #define S_DSN SU_RAW
std::string ToHumanReadableSize(size_t Size);
+2 -4
View File
@@ -63,12 +63,10 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
bool result = (cond); \ bool result = (cond); \
if (!result) { \ if (!result) { \
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \ beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
} \ } \
} while (false) } while (false)
#define beammp_assert_not_reachable() \ #define beammp_assert_not_reachable() \
do { \ do { \
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \ beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
} while (false) } while (false)
#endif // DEBUG #endif // DEBUG
+1 -1
View File
@@ -8,7 +8,7 @@ public:
IThreaded() IThreaded()
// invokes operator() on this object // invokes operator() on this object
: mThread() { } : mThread() { }
~IThreaded() noexcept { virtual ~IThreaded() noexcept {
if (mThread.joinable()) { if (mThread.joinable()) {
mThread.join(); mThread.join();
} }
-6
View File
@@ -1,6 +0,0 @@
#pragma once
enum IterationDecision {
Continue,
Break,
};
+2 -2
View File
@@ -3,7 +3,7 @@
// //
#pragma once #pragma once
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h" #include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h" #include "rapidjson/writer.h"
+1 -1
View File
@@ -6,8 +6,8 @@
* and write locks and read locks are mutually exclusive. * and write locks and read locks are mutually exclusive.
*/ */
#include <mutex>
#include <shared_mutex> #include <shared_mutex>
#include <mutex>
// Use ReadLock(m) and WriteLock(m) to lock it. // Use ReadLock(m) and WriteLock(m) to lock it.
using RWMutex = std::shared_mutex; using RWMutex = std::shared_mutex;
+4 -2
View File
@@ -6,7 +6,7 @@
#include <filesystem> #include <filesystem>
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT #define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
#include <toml11/toml.hpp> // header-only version of TOML++ #include <toml.hpp> // header-only version of TOML++
namespace fs = std::filesystem; namespace fs = std::filesystem;
@@ -22,7 +22,9 @@ private:
void CreateConfigFile(); void CreateConfigFile();
void ParseFromFile(std::string_view name); void ParseFromFile(std::string_view name);
void PrintDebug(); void PrintDebug();
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key); void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
void ParseOldFormat(); void ParseOldFormat();
bool IsDefault(); bool IsDefault();
+1 -14
View File
@@ -5,6 +5,7 @@
#include <atomic> #include <atomic>
#include <fstream> #include <fstream>
#include <functional> #include <functional>
#include <mutex>
#include <string> #include <string>
#include <tuple> #include <tuple>
#include <unordered_map> #include <unordered_map>
@@ -36,12 +37,6 @@ private:
void Command_Status(const std::string& cmd, const std::vector<std::string>& args); void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args); void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
void Command_Clear(const std::string&, const std::vector<std::string>& args); void Command_Clear(const std::string&, const std::vector<std::string>& args);
void Command_Debug(const std::string&, const std::vector<std::string>& args);
void Command_Version(const std::string&, const std::vector<std::string>& args);
void Autocomplete_Lua(const std::string&, std::vector<std::string>& suggestions);
void Autocomplete_Kick(const std::string&, std::vector<std::string>& suggestions);
void Autocomplete_Settings(const std::string&, std::vector<std::string>& suggestions);
void Command_Say(const std::string& FullCommand); void Command_Say(const std::string& FullCommand);
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n); bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
@@ -58,17 +53,9 @@ private:
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } }, { "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } }, { "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } }, { "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
{ "debug", [this](const auto& a, const auto& b) { Command_Debug(a, b); } },
{ "version", [this](const auto& a, const auto& b) { Command_Version(a, b); } },
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called { "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
}; };
std::unordered_map<std::string, std::function<void(const std::string&, std::vector<std::string>&)>> mCommandAutocompleteMap = {
{ "lua", [this](const auto& a, auto& b) { Autocomplete_Lua(a, b); } },
{ "kick", [this](const auto& a, auto& b) { Autocomplete_Kick(a, b); } },
{ "settings", [this](const auto& a, auto& b) { Autocomplete_Settings(a, b); } },
};
Commandline mCommandline; Commandline mCommandline;
std::vector<std::string> mCachedLuaHistory; std::vector<std::string> mCachedLuaHistory;
std::vector<std::string> mCachedRegularHistory; std::vector<std::string> mCachedRegularHistory;
+26 -39
View File
@@ -10,49 +10,30 @@
#include <lua.hpp> #include <lua.hpp>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <nlohmann/json.hpp>
#include <queue> #include <queue>
#include <random> #include <random>
#include <set> #include <set>
#include <toml11/toml.hpp> #include <toml.hpp>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#define SOL_ALL_SAFETIES_ON 1 #define SOL_ALL_SAFETIES_ON 1
#define SOL_USER_C_ASSERT SOL_ON #define SOL_USER_C_ASSERT SOL_ON
#define SOL_C_ASSERT(...) \ #define SOL_C_ASSERT(...) \
do { \ beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__)
if (!(__VA_ARGS__)) { \
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__); \
std::abort(); \
} \
} while (0)
#include <sol/sol.hpp> #include <sol/sol.hpp>
struct JsonString {
std::string value;
};
// value used to keep nils in a table or array, across serialization boundaries like
// JsonEncode, so that the nil stays at the same index and isn't treated like a special
// value (e.g. one that can be ignored or discarded).
const inline std::string BEAMMP_INTERNAL_NIL = "BEAMMP_SERVER_INTERNAL_NIL_VALUE";
using TLuaStateId = std::string; using TLuaStateId = std::string;
namespace fs = std::filesystem; namespace fs = std::filesystem;
/** /**
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args * std::variant means, that TLuaArgTypes may be one of the Types listed as template args
*/ */
using TLuaValue = std::variant<std::string, int, JsonString, bool, std::unordered_map<std::string, std::string>, std::unordered_map<std::string, size_t>, float>; using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
enum TLuaType { static constexpr size_t TLuaArgTypes_String = 0;
String = 0, static constexpr size_t TLuaArgTypes_Int = 1;
Int = 1, static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
Json = 2, static constexpr size_t TLuaArgTypes_Bool = 3;
Bool = 3, static constexpr size_t TLuaArgTypes_StringStringMap = 4;
StringStringMap = 4,
StringSizeTMap = 5,
Float = 6,
};
class TLuaPlugin; class TLuaPlugin;
@@ -63,7 +44,14 @@ struct TLuaResult {
sol::object Result { sol::lua_nil }; sol::object Result { sol::lua_nil };
TLuaStateId StateId; TLuaStateId StateId;
std::string Function; std::string Function;
// TODO: Add condition_variable std::shared_ptr<std::mutex> ReadyMutex {
std::make_shared<std::mutex>()
};
std::shared_ptr<std::condition_variable> ReadyCondition {
std::make_shared<std::condition_variable>()
};
void MarkAsReady();
void WaitUntilReady(); void WaitUntilReady();
}; };
@@ -93,7 +81,7 @@ public:
struct QueuedFunction { struct QueuedFunction {
std::string FunctionName; std::string FunctionName;
std::shared_ptr<TLuaResult> Result; std::shared_ptr<TLuaResult> Result;
std::vector<TLuaValue> Args; std::vector<TLuaArgTypes> Args;
std::string EventName; // optional, may be empty std::string EventName; // optional, may be empty
}; };
@@ -142,11 +130,11 @@ public:
} }
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
const std::optional<TimeType::duration>& Max = std::nullopt); const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results); void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
bool HasState(TLuaStateId StateId); bool HasState(TLuaStateId StateId);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false); void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName); void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
/** /**
@@ -166,7 +154,7 @@ public:
} }
std::vector<std::shared_ptr<TLuaResult>> Results; std::vector<std::shared_ptr<TLuaResult>> Results;
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... }; std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
for (const auto& Event : mLuaEvents.at(EventName)) { for (const auto& Event : mLuaEvents.at(EventName)) {
for (const auto& Function : Event.second) { for (const auto& Function : Event.second) {
@@ -185,7 +173,7 @@ public:
return {}; return {};
} }
std::vector<std::shared_ptr<TLuaResult>> Results; std::vector<std::shared_ptr<TLuaResult>> Results;
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... }; std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
const auto Handlers = GetEventHandlersForState(EventName, StateId); const auto Handlers = GetEventHandlersForState(EventName, StateId);
for (const auto& Handler : Handlers) { for (const auto& Handler : Handlers) {
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments)); Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
@@ -222,8 +210,8 @@ private:
StateThreadData(const StateThreadData&) = delete; StateThreadData(const StateThreadData&) = delete;
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); } virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
void RegisterEvent(const std::string& EventName, const std::string& FunctionName); void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
void AddPath(const fs::path& Path); // to be added to path and cpath void AddPath(const fs::path& Path); // to be added to path and cpath
void operator()() override; void operator()() override;
@@ -265,12 +253,11 @@ private:
std::recursive_mutex mPathsMutex; std::recursive_mutex mPathsMutex;
std::mt19937 mMersenneTwister; std::mt19937 mMersenneTwister;
std::uniform_real_distribution<double> mUniformRealDistribution01; std::uniform_real_distribution<double> mUniformRealDistribution01;
std::vector<sol::object> JsonStringToArray(JsonString Str);
}; };
struct TimedEvent { struct TimedEvent {
TimeType::duration Duration {}; std::chrono::high_resolution_clock::duration Duration {};
TimeType::time_point LastCompletion {}; std::chrono::high_resolution_clock::time_point LastCompletion {};
std::string EventName; std::string EventName;
TLuaStateId StateId; TLuaStateId StateId;
CallStrategy Strategy; CallStrategy Strategy;
+2 -3
View File
@@ -37,7 +37,6 @@ private:
TResourceManager& mResourceManager; TResourceManager& mResourceManager;
std::thread mUDPThread; std::thread mUDPThread;
std::thread mTCPThread; std::thread mTCPThread;
std::mutex mOpenIDMutex;
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint); std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
void HandleDownload(TConnection&& TCPSock); void HandleDownload(TConnection&& TCPSock);
@@ -46,12 +45,12 @@ private:
void Looper(const std::weak_ptr<TClient>& c); void Looper(const std::weak_ptr<TClient>& c);
int OpenID(); int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr); void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
ModMap GetClientMods(TClient& Client); void Parse(TClient& c, const std::vector<uint8_t>& Packet);
void HandleResourcePackets(TClient& c, const std::vector<uint8_t>& Packet);
void SendFile(TClient& c, const std::string& Name); void SendFile(TClient& c, const std::string& Name);
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size); static bool TCPSendRaw(TClient& C, 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 const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const 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::string HashPassword(const std::string& str);
std::vector<uint8_t> StringToVector(const std::string& Str); std::vector<uint8_t> StringToVector(const std::string& Str);
+1
View File
@@ -9,6 +9,7 @@ class TNetwork;
class TPPSMonitor : public IThreaded { class TPPSMonitor : public IThreaded {
public: public:
explicit TPPSMonitor(TServer& Server); explicit TPPSMonitor(TServer& Server);
virtual ~TPPSMonitor() {}
void operator()() override; void operator()() override;
+10 -11
View File
@@ -1,22 +1,21 @@
#pragma once #pragma once
#include "Common.h" #include "Common.h"
#include <optional>
using ModMap = HashMap<std::string, size_t>;
class TResourceManager { class TResourceManager {
public: public:
TResourceManager(); TResourceManager();
[[nodiscard]] size_t TotalModsSize() const { return mTotalModSize; } [[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
[[nodiscard]] ModMap FileMap() const { return mMods; } [[nodiscard]] std::string FileList() const { return mFileList; }
[[nodiscard]] static std::string FormatForBackend(const ModMap& mods); [[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
[[nodiscard]] static std::string FormatForClient(const ModMap& mods); [[nodiscard]] std::string FileSizes() const { return mFileSizes; }
[[nodiscard]] static std::optional<std::string> IsModValid(std::string& pathString, const ModMap& mods); [[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
[[nodiscard]] int LoadedModCount() const { return mMods.size(); }
private: private:
size_t mTotalModSize = 0; // size of all mods size_t mMaxModSize = 0;
ModMap mMods; // map of mod names std::string mFileSizes;
std::string mFileList;
std::string mTrimmedList;
int mModsLoaded = 0;
}; };
+2 -4
View File
@@ -4,8 +4,6 @@
#include <functional> #include <functional>
#include <string> #include <string>
#include "Common.h"
class TScopedTimer { class TScopedTimer {
public: public:
TScopedTimer(); TScopedTimer();
@@ -13,7 +11,7 @@ public:
TScopedTimer(std::function<void(size_t)> OnDestroy); TScopedTimer(std::function<void(size_t)> OnDestroy);
~TScopedTimer(); ~TScopedTimer();
auto GetElapsedTime() const { auto GetElapsedTime() const {
auto EndTime = TimeType::now(); auto EndTime = std::chrono::high_resolution_clock::now();
auto Delta = EndTime - mStartTime; auto Delta = EndTime - mStartTime;
size_t TimeDelta = Delta / std::chrono::milliseconds(1); size_t TimeDelta = Delta / std::chrono::milliseconds(1);
return TimeDelta; return TimeDelta;
@@ -22,6 +20,6 @@ public:
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr }; std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
private: private:
TimeType::time_point mStartTime; std::chrono::high_resolution_clock::time_point mStartTime;
std::string Name; std::string Name;
}; };
-38
View File
@@ -1,38 +0,0 @@
#ifndef SENTRY_H
#define SENTRY_H
#include <mutex>
#include <string>
#include <unordered_map>
enum class SentryLevel {
Debug = -1,
Info = 0,
Warning = 1,
Error = 2,
Fatal = 3,
};
// singleton, dont make this twice
class TSentry final {
public:
TSentry();
~TSentry();
void PrintWelcome();
void SetupUser();
void Log(SentryLevel level, const std::string& logger, const std::string& text);
void LogError(const std::string& text, const std::string& file, const std::string& line);
void SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map);
void LogException(const std::exception& e, const std::string& file, const std::string& line);
void LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function);
void AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line);
// cleared when Logged
void SetTransaction(const std::string& id);
[[nodiscard]] std::unique_lock<std::mutex> CreateExclusiveContext();
private:
bool mValid { true };
std::mutex mMutex;
};
#endif // SENTRY_H
+3 -57
View File
@@ -1,14 +1,11 @@
#pragma once #pragma once
#include "IThreaded.h" #include "IThreaded.h"
#include "IterationDecision.h"
#include "RWMutex.h" #include "RWMutex.h"
#include "TScopedTimer.h" #include "TScopedTimer.h"
#include <concepts>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <type_traits>
#include <unordered_set> #include <unordered_set>
#include "BoostAliases.h" #include "BoostAliases.h"
@@ -17,21 +14,6 @@ class TClient;
class TNetwork; class TNetwork;
class TPPSMonitor; class TPPSMonitor;
// clang-format doesn't know how to deal with concepts
// clang-format off
template <typename FnT>
concept ForEachHandlerWithDecision = requires(FnT Fn, const std::shared_ptr<TClient>& Ptr) {
requires std::invocable<FnT, const std::shared_ptr<TClient>&> ;
{ std::invoke(Fn, Ptr) } -> std::convertible_to<IterationDecision>;
};
template <typename FnT>
concept ForEachHandler = requires(FnT Fn, const std::shared_ptr<TClient>& Ptr) {
requires std::invocable <FnT, const std::shared_ptr<TClient>&> ;
{ std::invoke(Fn, Ptr) } -> std::same_as<void>;
};
// clang-format on
class TServer final { class TServer final {
public: public:
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>; using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
@@ -40,46 +22,11 @@ public:
void InsertClient(const std::shared_ptr<TClient>& Ptr); void InsertClient(const std::shared_ptr<TClient>& Ptr);
void RemoveClient(const std::weak_ptr<TClient>&); void RemoveClient(const std::weak_ptr<TClient>&);
void RemoveClientById(int Id);
// in Fn, return true to continue, return false to break // in Fn, return true to continue, return false to break
[[deprecated("use ForEachClient instead")]] void ForEachClientWeak(const std::function<bool(std::weak_ptr<TClient>)>& Fn); void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
// in Fn, return Break or Continue
template <ForEachHandlerWithDecision FnT>
void ForEachClient(FnT Fn) {
decltype(mClients) Clients;
{
ReadLock lock(mClientsMutex);
Clients = mClients;
}
for (auto& Client : Clients) {
if (Client) [[likely]] {
IterationDecision Decision = std::invoke(Fn, Client);
if (Decision == IterationDecision::Break) {
break;
}
} else {
beammp_assert_not_reachable();
}
}
}
template <ForEachHandler FnT>
void ForEachClient(FnT Fn) {
decltype(mClients) Clients;
{
ReadLock lock(mClientsMutex);
Clients = mClients;
}
for (auto& Client : Clients) {
if (Client) [[likely]] {
std::invoke(Fn, Client);
} else {
beammp_assert_not_reachable();
}
}
}
size_t ClientCount() const; size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TNetwork& Network); static void GlobalParser(const std::weak_ptr<TClient>& Client, std::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; }
@@ -96,8 +43,7 @@ private:
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID); static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson); static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt); static void Apply(TClient& c, int VID, const std::string& pckt);
static bool HandlePosition(TClient& c, const std::string& PacketStr); static void HandlePosition(TClient& c, const std::string& Packet);
static bool HandleVehicleUpdate(const std::string& PacketStr, const int playerID);
}; };
struct BufferView { struct BufferView {
-9
View File
@@ -1,9 +0,0 @@
#pragma once
#include <string>
namespace uuid {
std::string GenerateUuid();
}
-3
View File
@@ -1,3 +0,0 @@
FROM archlinux
RUN pacman -Syu --noconfirm lua53 openssl curl git cmake gcc make zlib boost websocketpp
-9
View File
@@ -1,9 +0,0 @@
FROM debian:11
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y
RUN apt-get install -y git cmake g++-10 curl libboost1.74-all-dev libssl-dev libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
ENV CXX=g++-10
-9
View File
@@ -1,9 +0,0 @@
FROM ubuntu:20.04
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y
RUN apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev git make cmake g++
RUN apt-get install -y libboost1.71-all-dev
-9
View File
@@ -1,9 +0,0 @@
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y
RUN apt-get install -y git libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev libssl3 curl
ENV CXX=g++-10
-18
View File
@@ -1,18 +0,0 @@
#!/bin/sh
set -e
printf "enter DSN (optional): "
read DSN
docker build -f Ubuntu-20.04-Dockerfile . -t beammp-server-build:Ubuntu-20.04
docker build -f Ubuntu-22.04-Dockerfile . -t beammp-server-build:Ubuntu-22.04
docker build -f ArchLinux-Dockerfile . -t beammp-server-build:ArchLinux
docker build -f Debian-11-Dockerfile . -t beammp-server-build:Debian-11
CMD="cd /beammp; cmake . -DGIT_SUBMODULE=OFF -DCMAKE_BUILD_TYPE=Release -DBEAMMP_SECRET_SENTRY_URL=\"${DSN}\" -B /build && make -j -C /build BeamMP-Server"
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-20.04:/build -it --rm beammp-server-build:Ubuntu-20.04 bash -c "${CMD}"
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-ubuntu-22.04:/build -it --rm beammp-server-build:Ubuntu-22.04 bash -c "${CMD}"
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-archlinux:/build -it --rm beammp-server-build:ArchLinux bash -c "${CMD}"
docker run -v $(pwd)/..:/beammp -v $(pwd)/../build-debian-11:/build -it --rm beammp-server-build:Debian-11 bash -c "${CMD}"
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -s -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
-5
View File
@@ -1,5 +0,0 @@
#!/bin/sh
cmake . -B build -DCMAKE_BUILD_TYPE=Release -DGIT_SUBMODULE=OFF
make -j -C build BeamMP-Server
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -s -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
+6 -6
View File
@@ -13,7 +13,7 @@ void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
ConsumeLongFlag(std::string(Arg)); ConsumeLongFlag(std::string(Arg));
} }
} else { } else {
fmt::print(stderr, "Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg); beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
} }
} }
} }
@@ -22,17 +22,17 @@ bool ArgsParser::Verify() {
bool Ok = true; bool Ok = true;
for (const auto& RegisteredArg : mRegisteredArguments) { for (const auto& RegisteredArg : mRegisteredArguments) {
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) { if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
fmt::print(stderr, "Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0)); beammp_errorf("Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
Ok = false; Ok = false;
continue; continue;
} else if (FoundArgument(RegisteredArg.Names)) { } else if (FoundArgument(RegisteredArg.Names)) {
if (RegisteredArg.Flags & Flags::HAS_VALUE) { if (RegisteredArg.Flags & Flags::HAS_VALUE) {
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) { if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
fmt::print(stderr, "Error in commandline arguments: Argument '{}' expects a value, but no value was given.", RegisteredArg.Names.at(0)); beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' expects a value, but no value was given.");
Ok = false; Ok = false;
} }
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) { } else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
fmt::print(stderr, "Error in commandline arguments: Argument '{}' does not expect a value, but one was given.", RegisteredArg.Names.at(0)); beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' does not expect a value, but one was given.");
Ok = false; Ok = false;
} }
} }
@@ -81,7 +81,7 @@ void ArgsParser::ConsumeLongAssignment(const std::string& Arg) {
auto Value = Arg.substr(Arg.rfind("=") + 1); auto Value = Arg.substr(Arg.rfind("=") + 1);
auto Name = Arg.substr(2, Arg.rfind("=") - 2); auto Name = Arg.substr(2, Arg.rfind("=") - 2);
if (!IsRegistered(Name)) { if (!IsRegistered(Name)) {
fmt::print(stdout, "Argument '{}' was supplied but isn't a known argument, so it is likely being ignored.", Name); beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
} }
mFoundArgs.push_back({ Name, Value }); mFoundArgs.push_back({ Name, Value });
} }
@@ -90,7 +90,7 @@ void ArgsParser::ConsumeLongFlag(const std::string& Arg) {
auto Name = Arg.substr(2, Arg.rfind("=") - 2); auto Name = Arg.substr(2, Arg.rfind("=") - 2);
mFoundArgs.push_back({ Name, std::nullopt }); mFoundArgs.push_back({ Name, std::nullopt });
if (!IsRegistered(Name)) { if (!IsRegistered(Name)) {
fmt::print(stdout, "Argument '{}' was supplied but isn't a known argument, so it is likely being ignored.", Name); beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
} }
} }
+17 -26
View File
@@ -1,7 +1,6 @@
#include "Client.h" #include "Client.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "LuaAPI.h"
#include "TServer.h" #include "TServer.h"
#include <memory> #include <memory>
#include <optional> #include <optional>
@@ -13,8 +12,6 @@ void TClient::DeleteCar(int Ident) {
return Ident == elem.ID(); return Ident == elem.ID();
}); });
if (iter != mVehicleData.end()) { if (iter != mVehicleData.end()) {
std::string Destroy = "Od:" + std::to_string(GetID()) + "-" + std::to_string(iter->ID());
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
mVehicleData.erase(iter); mVehicleData.erase(iter);
} else { } else {
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)"); beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
@@ -23,10 +20,6 @@ void TClient::DeleteCar(int Ident) {
void TClient::ClearCars() { void TClient::ClearCars() {
std::unique_lock lock(mVehicleDataMutex); std::unique_lock lock(mVehicleDataMutex);
for (const auto& Car : mVehicleData) {
std::string Destroy = "Od:" + std::to_string(GetID()) + "-" + std::to_string(Car.ID());
LuaAPI::MP::Engine->Network().SendToAll(this, StringToVector(Destroy), false, true);
}
mVehicleData.clear(); mVehicleData.clear();
} }
@@ -58,7 +51,7 @@ 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(size_t(Ident));
} catch (const std::out_of_range& oor) { } catch (const std::out_of_range& oor) {
return ""; return "";
} }
@@ -66,12 +59,7 @@ std::string TClient::GetCarPositionRaw(int Ident) {
} }
void TClient::Disconnect(std::string_view Reason) { void TClient::Disconnect(std::string_view Reason) {
// we need exclusivity here in case we can't
std::unique_lock Lock(mDisconnectMtx);
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason); beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
if (mSocket.is_open()) {
beammp_debugf("Socket for client {} already closed", GetID());
}
boost::system::error_code ec; boost::system::error_code ec;
mSocket.shutdown(socket_base::shutdown_both, ec); mSocket.shutdown(socket_base::shutdown_both, ec);
if (ec) { if (ec) {
@@ -81,12 +69,11 @@ void TClient::Disconnect(std::string_view Reason) {
if (ec) { if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message()); beammp_debugf("Failed to close client socket: {}", ec.message());
} }
mServer.RemoveClientById(GetID());
} }
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[size_t(Ident)] = Data;
} }
std::string TClient::GetCarData(int Ident) { std::string TClient::GetCarData(int Ident) {
@@ -132,7 +119,7 @@ TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
: mServer(Server) : mServer(Server)
, mSocket(std::move(Socket)) , mSocket(std::move(Socket))
, mDownSocket(ip::tcp::socket(Server.IoCtx())) , mDownSocket(ip::tcp::socket(Server.IoCtx()))
, mLastPingTime(TimeType::now()) { , mLastPingTime(std::chrono::high_resolution_clock::now()) {
} }
TClient::~TClient() { TClient::~TClient() {
@@ -140,23 +127,27 @@ TClient::~TClient() {
} }
void TClient::UpdatePingTime() { void TClient::UpdatePingTime() {
mLastPingTime = TimeType::now(); mLastPingTime = std::chrono::high_resolution_clock::now();
} }
int TClient::SecondsSinceLastPing() { int TClient::SecondsSinceLastPing() {
auto seconds = std::chrono::duration_cast<std::chrono::seconds>( auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
TimeType::now() - mLastPingTime) std::chrono::high_resolution_clock::now() - mLastPingTime)
.count(); .count();
return int(seconds); return int(seconds);
} }
std::shared_ptr<TClient> GetClient(TServer& Server, int ID) { std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::shared_ptr<TClient> Result {}; std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClient([&](const auto& Client) { Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
if (Client->GetID() == ID) { ReadLock Lock(Server.GetClientMutex());
Result = Client; if (!CPtr.expired()) {
return Break; auto C = CPtr.lock();
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
} }
return Continue; return true;
}); });
return Result; return MaybeClient;
} }
+8 -103
View File
@@ -13,85 +13,7 @@
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Http.h" #include "Http.h"
Application::SettingsMap Application::mSettings = { Application::TSettings Application::Settings = {};
{ StrName, std::string("BeamMP Server") },
{ StrDescription, std::string("No description") },
{ StrResourceFolder, std::string("Resources") },
{ StrMap, std::string("/levels/gridmap_v2/info.json") },
{ StrSSLKeyPath, std::string("./.ssl/HttpServer/key.pem") },
{ StrSSLCertPath, std::string("./.ssl/HttpServer/cert.pem") },
{ StrHTTPServerEnabled, false },
{ StrMaxPlayers, int(8) },
{ StrPrivate, true },
{ StrMaxCars, int(1) },
{ StrDebug, false },
{ StrPort, int(30814) },
{ StrCustomIP, std::string("") },
{ StrLogChat, true },
{ StrSendErrors, true },
{ StrSendErrorsMessageEnabled, true },
{ StrHTTPServerPort, int(8080) },
{ StrHTTPServerIP, std::string("127.0.0.1") },
{ StrHTTPServerUseSSL, false },
{ StrHideUpdateMessages, false },
{ StrAuthKey, std::string("") },
{ StrIncludeSubdirectories, false },
};
// global, yes, this is ugly, no, it cant be done another way
TSentry Sentry {};
std::string Application::SettingToString(const Application::SettingValue& Value) {
switch (Value.index()) {
case 0:
return fmt::format("{}", std::get<std::string>(Value));
case 1:
return fmt::format("{}", std::get<bool>(Value));
case 2:
return fmt::format("{}", std::get<int>(Value));
default:
return "<unknown type>";
}
}
std::string Application::GetSettingString(std::string_view Name) {
try {
return std::get<std::string>(Application::mSettings.at(Name));
} catch (const std::exception& e) {
beammp_errorf("Failed to get string setting '{}': {}", Name, e.what());
return "";
}
}
int Application::GetSettingInt(std::string_view Name) {
try {
return std::get<int>(Application::mSettings.at(Name));
} catch (const std::exception& e) {
beammp_errorf("Failed to get int setting '{}': {}", Name, e.what());
return 0;
}
}
bool Application::GetSettingBool(std::string_view Name) {
try {
return std::get<bool>(Application::mSettings.at(Name));
} catch (const std::exception& e) {
beammp_errorf("Failed to get bool setting '{}': {}", Name, e.what());
return false;
}
}
void Application::SetSetting(std::string_view Name, const Application::SettingValue& Value) {
if (mSettings.contains(Name)) {
if (mSettings[Name].index() == Value.index()) {
mSettings[Name] = Value;
} else {
beammp_errorf("Could not change value of setting '{}', because it has a different type.", Name);
}
} else {
mSettings[Name] = Value;
}
}
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) { void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
std::unique_lock Lock(mShutdownHandlersMutex); std::unique_lock Lock(mShutdownHandlersMutex);
@@ -292,9 +214,6 @@ void Application::CheckForUpdates() {
if (FirstTime) { if (FirstTime) {
beammp_debug("Failed to fetch version from: " + url); beammp_debug("Failed to fetch version from: " + url);
beammp_trace("got " + Response); beammp_trace("got " + Response);
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("get-response", { { "response", Response } });
Sentry.LogError("failed to get server version", _file_basename, _line);
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad); Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
} }
} }
@@ -314,7 +233,7 @@ static std::mutex ThreadNameMapMutex {};
std::string ThreadName(bool DebugModeOverride) { std::string ThreadName(bool DebugModeOverride) {
auto Lock = std::unique_lock(ThreadNameMapMutex); auto Lock = std::unique_lock(ThreadNameMapMutex);
if (DebugModeOverride || Application::GetSettingBool(StrDebug)) { if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
auto id = std::this_thread::get_id(); auto id = std::this_thread::get_id();
if (threadNameMap.find(id) != threadNameMap.end()) { if (threadNameMap.find(id) != threadNameMap.end()) {
// found // found
@@ -326,21 +245,21 @@ std::string ThreadName(bool DebugModeOverride) {
TEST_CASE("ThreadName") { TEST_CASE("ThreadName") {
RegisterThread("MyThread"); RegisterThread("MyThread");
auto OrigDebug = Application::GetSettingBool(StrDebug); auto OrigDebug = Application::Settings.DebugModeEnabled;
// ThreadName adds a space at the end, legacy but we need it still // ThreadName adds a space at the end, legacy but we need it still
SUBCASE("Debug mode enabled") { SUBCASE("Debug mode enabled") {
Application::SetSetting(StrDebug, true); Application::Settings.DebugModeEnabled = true;
CHECK(ThreadName(true) == "MyThread "); CHECK(ThreadName(true) == "MyThread ");
CHECK(ThreadName(false) == "MyThread "); CHECK(ThreadName(false) == "MyThread ");
} }
SUBCASE("Debug mode disabled") { SUBCASE("Debug mode disabled") {
Application::SetSetting(StrDebug, false); Application::Settings.DebugModeEnabled = false;
CHECK(ThreadName(true) == "MyThread "); CHECK(ThreadName(true) == "MyThread ");
CHECK(ThreadName(false) == ""); CHECK(ThreadName(false) == "");
} }
// cleanup // cleanup
Application::SetSetting(StrDebug, OrigDebug); Application::Settings.DebugModeEnabled = OrigDebug;
} }
void RegisterThread(const std::string& str) { void RegisterThread(const std::string& str) {
@@ -352,7 +271,7 @@ void RegisterThread(const std::string& str) {
#elif defined(BEAMMP_LINUX) #elif defined(BEAMMP_LINUX)
ThreadId = std::to_string(gettid()); ThreadId = std::to_string(gettid());
#endif #endif
if (Application::GetSettingBool(StrDebug)) { if (Application::Settings.DebugModeEnabled) {
std::ofstream ThreadFile(".Threads.log", std::ios::app); std::ofstream ThreadFile(".Threads.log", std::ios::app);
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl; ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
} }
@@ -385,7 +304,7 @@ TEST_CASE("Version::AsString") {
} }
void LogChatMessage(const std::string& name, int id, const std::string& msg) { void LogChatMessage(const std::string& name, int id, const std::string& msg) {
if (Application::GetSettingBool(StrLogChat)) { if (Application::Settings.LogChat) {
std::stringstream ss; std::stringstream ss;
ss << ThreadName(); ss << ThreadName();
ss << "[CHAT] "; ss << "[CHAT] ";
@@ -429,17 +348,3 @@ std::string GetPlatformAgnosticErrorString() {
return "(no human-readable errors on this platform)"; return "(no human-readable errors on this platform)";
#endif #endif
} }
std::string ToHumanReadableSize(size_t Size) {
if (Size > TB) {
return fmt::format("{:.2f} TiB", double(Size) / TB);
} else if (Size > GB) {
return fmt::format("{:.2f} GiB", double(Size) / GB);
} else if (Size > MB) {
return fmt::format("{:.2f} MiB", double(Size) / MB);
} else if (Size > KB) {
return fmt::format("{:.2f} KiB", double(Size) / KB);
} else {
return fmt::format("{} B", Size);
}
}
+2 -2
View File
@@ -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::GetSettingInt(StrHTTPServerPort))); beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
std::unique_ptr<httplib::Server> HttpLibServerInstance; std::unique_ptr<httplib::Server> HttpLibServerInstance;
HttpLibServerInstance = std::make_unique<httplib::Server>(); HttpLibServerInstance = std::make_unique<httplib::Server>();
// todo: make this IP agnostic so people can set their own IP // todo: make this IP agnostic so people can set their own IP
@@ -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::GetSettingString(StrHTTPServerIP).c_str(), Application::GetSettingInt(StrHTTPServerPort)); auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
if (!ret) { if (!ret) {
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it."); beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
} }
+43 -46
View File
@@ -119,14 +119,15 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true); LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
return { true, "" }; return { true, "" };
} else { } else {
auto Client = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
if (!Client) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID); beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
return { false, "Invalid Player ID" }; return { false, "Invalid Player ID" };
} }
if (!LuaAPI::MP::Engine->Network().Respond(*Client, StringToVector(Packet), true)) { auto c = MaybeClient.value().lock();
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(*Client, "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" };
} }
return { true, "" }; return { true, "" };
@@ -139,12 +140,13 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
} }
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) { std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
auto Client = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!Client) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID); beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
return { false, "Player does not exist" }; return { false, "Player does not exist" };
} }
LuaAPI::MP::Engine->Network().ClientKick(*Client, MaybeReason.value_or("No reason")); auto c = MaybeClient.value().lock();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" }; return { true, "" };
} }
@@ -156,15 +158,16 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true); Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
Result.first = true; Result.first = true;
} else { } else {
auto Client = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
if (!Client->IsSynced()) { auto c = MaybeClient.value().lock();
if (!c->IsSynced()) {
Result.first = false; Result.first = false;
Result.second = "Player still syncing data"; Result.second = "Player still syncing data";
return Result; return Result;
} }
LogChatMessage("<Server> (to \"" + Client->GetName() + "\")", -1, Message); LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
if (!Engine->Network().Respond(*Client, StringToVector(Packet), true)) { if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID); beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
// TODO: should we return an error here? // TODO: should we return an error here?
} }
@@ -181,17 +184,18 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) { std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
std::pair<bool, std::string> Result; std::pair<bool, std::string> Result;
auto Client = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!Client) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_error("RemoveVehicle invalid Player ID"); beammp_lua_error("RemoveVehicle invalid Player ID");
Result.first = false; Result.first = false;
Result.second = "Invalid Player ID"; Result.second = "Invalid Player ID";
return Result; return Result;
} }
if (!Client->GetCarData(VID).empty()) { auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true); Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
Client->DeleteCar(VID); c->DeleteCar(VID);
Result.first = true; Result.first = true;
} else { } else {
Result.first = false; Result.first = false;
@@ -204,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::SetSetting(StrDebug, NewValue.as<bool>()); Application::Settings.DebugModeEnabled = NewValue.as<bool>();
beammp_info(std::string("Set `Debug` to ") + (Application::GetSettingBool(StrDebug) ? "true" : "false")); beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
} else { } else {
beammp_lua_error("set invalid argument [2] expected boolean"); beammp_lua_error("set invalid argument [2] expected boolean");
} }
break; break;
case 1: // private case 1: // private
if (NewValue.is<bool>()) { if (NewValue.is<bool>()) {
Application::SetSetting(StrPrivate, NewValue.as<bool>()); Application::Settings.Private = NewValue.as<bool>();
beammp_info(std::string("Set `Private` to ") + (Application::GetSettingBool(StrPrivate) ? "true" : "false")); beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
} else { } else {
beammp_lua_error("set invalid argument [2] expected boolean"); beammp_lua_error("set invalid argument [2] expected boolean");
} }
break; break;
case 2: // max cars case 2: // max cars
if (NewValue.is<int>()) { if (NewValue.is<int>()) {
Application::SetSetting(StrMaxCars, NewValue.as<int>()); Application::Settings.MaxCars = NewValue.as<int>();
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::GetSettingInt(StrMaxCars))); beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
} else { } else {
beammp_lua_error("set invalid argument [2] expected integer"); beammp_lua_error("set invalid argument [2] expected integer");
} }
break; break;
case 3: // max players case 3: // max players
if (NewValue.is<int>()) { if (NewValue.is<int>()) {
Application::SetSetting(StrMaxPlayers, NewValue.as<int>()); Application::Settings.MaxPlayers = NewValue.as<int>();
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::GetSettingInt(StrMaxPlayers))); beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
} else { } else {
beammp_lua_error("set invalid argument [2] expected integer"); beammp_lua_error("set invalid argument [2] expected integer");
} }
break; break;
case 4: // Map case 4: // Map
if (NewValue.is<std::string>()) { if (NewValue.is<std::string>()) {
Application::SetSetting(StrMap, NewValue.as<std::string>()); Application::Settings.MapName = NewValue.as<std::string>();
beammp_info(std::string("Set `Map` to ") + Application::GetSettingString(StrMap)); beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
} else { } else {
beammp_lua_error("set invalid argument [2] expected string"); beammp_lua_error("set invalid argument [2] expected string");
} }
break; break;
case 5: // Name case 5: // Name
if (NewValue.is<std::string>()) { if (NewValue.is<std::string>()) {
Application::SetSetting(StrName, NewValue.as<std::string>()); Application::Settings.ServerName = NewValue.as<std::string>();
beammp_info(std::string("Set `Name` to ") + Application::GetSettingString(StrName)); beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
} else { } else {
beammp_lua_error("set invalid argument [2] expected string"); beammp_lua_error("set invalid argument [2] expected string");
} }
break; break;
case 6: // Desc case 6: // Desc
if (NewValue.is<std::string>()) { if (NewValue.is<std::string>()) {
Application::SetSetting(StrDescription, NewValue.as<std::string>()); Application::Settings.ServerDesc = NewValue.as<std::string>();
beammp_info(std::string("Set `Description` to ") + Application::GetSettingString(StrDescription)); beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
} else { } else {
beammp_lua_error("set invalid argument [2] expected string"); beammp_lua_error("set invalid argument [2] expected string");
} }
@@ -269,18 +273,18 @@ void LuaAPI::MP::Sleep(size_t Ms) {
} }
bool LuaAPI::MP::IsPlayerConnected(int ID) { bool LuaAPI::MP::IsPlayerConnected(int ID) {
auto Client = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
return Client->IsConnected(); return MaybeClient.value().lock()->IsConnected();
} else { } else {
return false; return false;
} }
} }
bool LuaAPI::MP::IsPlayerGuest(int ID) { bool LuaAPI::MP::IsPlayerGuest(int ID) {
auto Client = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
return Client->IsGuest(); return MaybeClient.value().lock()->IsGuest();
} else { } else {
return false; return false;
} }
@@ -298,7 +302,6 @@ void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
} }
int LuaAPI::PanicHandler(lua_State* State) { int LuaAPI::PanicHandler(lua_State* State) {
// FIXME: unsafe operation, can cause stack overflow
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1)); beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
return 0; return 0;
} }
@@ -569,11 +572,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
value = right.as<std::string>(); value = right.as<std::string>();
break; break;
case sol::type::number: case sol::type::number:
if (right.is<int>()) { value = right.as<double>();
value = right.as<int>();
} else {
value = right.as<float>();
}
break; break;
case sol::type::function: case sol::type::function:
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring"); beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
@@ -583,7 +582,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
for (const auto& pair : right.as<sol::table>()) { for (const auto& pair : right.as<sol::table>()) {
if (pair.first.get_type() != sol::type::number) { if (pair.first.get_type() != sol::type::number) {
local_is_array = false; local_is_array = false;
break;
} }
} }
for (const auto& pair : right.as<sol::table>()) { for (const auto& pair : right.as<sol::table>()) {
@@ -608,11 +606,10 @@ std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
for (const auto& pair : object.as<sol::table>()) { for (const auto& pair : object.as<sol::table>()) {
if (pair.first.get_type() != sol::type::number) { if (pair.first.get_type() != sol::type::number) {
is_array = false; is_array = false;
break;
} }
} }
for (const auto& [key, value] : object) { for (const auto& entry : object) {
JsonEncodeRecursive(json, key, value, is_array); JsonEncodeRecursive(json, entry.first, entry.second, is_array);
} }
return json.dump(); return json.dump();
} }
-2
View File
@@ -1,8 +1,6 @@
#include "SignalHandling.h" #include "SignalHandling.h"
#include "Common.h" #include "Common.h"
#include "Compat.h"
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE) #if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
#include <csignal> #include <csignal>
static void UnixSignalHandler(int sig) { static void UnixSignalHandler(int sig) {
+155 -60
View File
@@ -6,6 +6,33 @@
#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";
static constexpr std::string_view StrPassword = "Password";
// 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);
@@ -67,37 +94,37 @@ void SetComment(CommentsT& Comments, const std::string& Comment) {
void TConfig::FlushToFile() { void TConfig::FlushToFile() {
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName); // auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
auto data = toml::value {}; auto data = toml::value {};
data["General"][StrAuthKey.data()] = Application::GetSettingString(StrAuthKey.data()); data["General"][StrAuthKey.data()] = Application::Settings.Key;
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server"); SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
data["General"][StrLogChat.data()] = Application::GetSettingBool(StrLogChat.data()); data["General"][StrLogChat.data()] = Application::Settings.LogChat;
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log"); SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
data["General"][StrDebug.data()] = Application::GetSettingBool(StrDebug.data()); data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
data["General"][StrPrivate.data()] = Application::GetSettingBool(StrPrivate.data()); data["General"][StrPrivate.data()] = Application::Settings.Private;
data["General"][StrPort.data()] = Application::GetSettingInt(StrPort.data()); data["General"][StrPort.data()] = Application::Settings.Port;
data["General"][StrName.data()] = Application::GetSettingString(StrName.data()); data["General"][StrName.data()] = Application::Settings.ServerName;
data["General"][StrMaxCars.data()] = Application::GetSettingInt(StrMaxCars.data()); data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
data["General"][StrMaxPlayers.data()] = Application::GetSettingInt(StrMaxPlayers.data()); data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
data["General"][StrMap.data()] = Application::GetSettingString(StrMap.data()); data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::GetSettingString(StrDescription.data()); data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::GetSettingString(StrResourceFolder.data()); data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
data["General"][StrPassword.data()] = Application::Settings.Password;
SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
// Misc // Misc
data["Misc"][StrHideUpdateMessages.data()] = Application::GetSettingBool(StrHideUpdateMessages.data()); data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless."); SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
data["Misc"][StrSendErrors.data()] = Application::GetSettingBool(StrSendErrors.data()); data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here"); SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::GetSettingBool(StrSendErrorsMessageEnabled.data()); data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`"); SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
data["Misc"][StrIncludeSubdirectories.data()] = Application::GetSettingBool(StrIncludeSubdirectories.data());
SetComment(data["Misc"][StrIncludeSubdirectories.data()].comments(), " Whether or not to include subdirectories in General.ResourceFolder/Client when searching for `.zip`s");
// HTTP // HTTP
data["HTTP"][StrSSLKeyPath.data()] = Application::GetSettingString(StrSSLKeyPath.data()); data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
data["HTTP"][StrSSLCertPath.data()] = Application::GetSettingString(StrSSLCertPath.data()); data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
data["HTTP"][StrHTTPServerPort.data()] = Application::GetSettingInt(StrHTTPServerPort.data()); data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server."); SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
data["HTTP"][StrHTTPServerIP.data()] = Application::GetSettingString(StrHTTPServerIP.data()); data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::GetSettingBool(StrHTTPServerUseSSL.data()); data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files"); SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
data["HTTP"][StrHTTPServerEnabled.data()] = Application::GetSettingBool(StrHTTPServerEnabled.data()); data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server"); SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
std::stringstream Ss; std::stringstream Ss;
Ss << "# This is the BeamMP-Server config file.\n" Ss << "# This is the BeamMP-Server config file.\n"
@@ -132,42 +159,51 @@ void TConfig::CreateConfigFile() {
FlushToFile(); FlushToFile();
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
if (Table[Category.c_str()][Key.data()].is_string()) { if (Table[Category.c_str()][Key.data()].is_string()) {
Application::SetSetting(Key, std::string(Table[Category.c_str()][Key.data()].as_string())); OutValue = Table[Category.c_str()][Key.data()].as_string();
} else if (Table[Category.c_str()][Key.data()].is_boolean()) {
Application::SetSetting(Key, bool(Table[Category.c_str()][Key.data()].as_boolean()));
} else if (Table[Category.c_str()][Key.data()].is_integer()) {
Application::SetSetting(Key, int(Table[Category.c_str()][Key.data()].as_integer()));
} }
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
if (Table[Category.c_str()][Key.data()].is_boolean()) {
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
}
}
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
if (Table[Category.c_str()][Key.data()].is_integer()) {
OutValue = 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); TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
TryReadValue(data, "General", StrPrivate); TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
TryReadValue(data, "General", StrPort); TryReadValue(data, "General", StrPort, Application::Settings.Port);
TryReadValue(data, "General", StrMaxCars); TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
TryReadValue(data, "General", StrMaxPlayers); TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
TryReadValue(data, "General", StrMap); TryReadValue(data, "General", StrMap, Application::Settings.MapName);
TryReadValue(data, "General", StrName); TryReadValue(data, "General", StrName, Application::Settings.ServerName);
TryReadValue(data, "General", StrDescription); TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
TryReadValue(data, "General", StrResourceFolder); TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
TryReadValue(data, "General", StrAuthKey); TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
TryReadValue(data, "General", StrLogChat); TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
TryReadValue(data, "General", StrPassword, Application::Settings.Password);
// Misc // Misc
TryReadValue(data, "Misc", StrSendErrors); TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
TryReadValue(data, "Misc", StrHideUpdateMessages); TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled); TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
TryReadValue(data, "Misc", StrIncludeSubdirectories);
// HTTP // HTTP
TryReadValue(data, "HTTP", StrSSLKeyPath); TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
TryReadValue(data, "HTTP", StrSSLCertPath); TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
TryReadValue(data, "HTTP", StrHTTPServerPort); TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
TryReadValue(data, "HTTP", StrHTTPServerIP); TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
TryReadValue(data, "HTTP", StrHTTPServerEnabled); TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
TryReadValue(data, "HTTP", StrHTTPServerUseSSL); TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
} catch (const std::exception& err) { } catch (const std::exception& err) {
beammp_error("Error parsing config file value: " + std::string(err.what())); beammp_error("Error parsing config file value: " + std::string(err.what()));
mFailed = true; mFailed = true;
@@ -179,28 +215,87 @@ void TConfig::ParseFromFile(std::string_view name) {
// Update in any case // Update in any case
FlushToFile(); FlushToFile();
// all good so far, let's check if there's a key // all good so far, let's check if there's a key
if (Application::GetSettingString(StrAuthKey).empty()) { if (Application::Settings.Key.empty()) {
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server. Alternatively, if you only want a private server (one that doesn't show up in the server list), you may put anything as your AuthKey, like \"hello\"."); beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
Application::SetSubsystemStatus("Config", Application::Status::Bad); Application::SetSubsystemStatus("Config", Application::Status::Bad);
mFailed = true; mFailed = true;
return; return;
} }
Application::SetSubsystemStatus("Config", Application::Status::Good); Application::SetSubsystemStatus("Config", Application::Status::Good);
if (Application::GetSettingString(StrAuthKey).size() != 36) { if (Application::Settings.Key.size() != 36) {
beammp_warn("AuthKey specified is the wrong length and likely isn't valid."); beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
} }
} }
void TConfig::PrintDebug() { void TConfig::PrintDebug() {
for (const auto& [k, v] : Application::mSettings) { beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
if (k == StrAuthKey) { beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
beammp_debugf("AuthKey: length {}", std::get<std::string>(v).size()); beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
continue; beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
} beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
beammp_debugf("{}: {}", k, Application::SettingToString(v)); beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
} beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
// special!
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
} }
void TConfig::ParseOldFormat() { void TConfig::ParseOldFormat() {
beammp_warnf("You still have a 'Server.cfg' - this will not be used (this server uses 'ServerConfig.toml'. Since v3.0.2 we no longer parse and import these old settings. Remove the file to avoid confusion and disable this message."); std::ifstream File("Server.cfg");
// read all, strip comments
std::string Content;
for (;;) {
std::string Line;
std::getline(File, Line);
if (!Line.empty() && Line.at(0) != '#') {
Line = Line.substr(0, Line.find_first_of('#'));
Content += Line + "\n";
}
if (!File.good()) {
break;
}
}
std::stringstream Str(Content);
std::string Key, Ignore, Value;
for (;;) {
Str >> Key >> std::ws >> Ignore >> std::ws;
std::getline(Str, Value);
if (Str.eof()) {
break;
}
std::stringstream ValueStream(Value);
ValueStream >> std::ws; // strip leading whitespace if any
Value = ValueStream.str();
if (Key == "Debug") {
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
} else if (Key == "Private") {
Application::Settings.Private = Value.find("true") != std::string::npos;
} else if (Key == "Port") {
ValueStream >> Application::Settings.Port;
} else if (Key == "Cars") {
ValueStream >> Application::Settings.MaxCars;
} else if (Key == "MaxPlayers") {
ValueStream >> Application::Settings.MaxPlayers;
} else if (Key == "Map") {
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
} else if (Key == "Name") {
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
} else if (Key == "Desc") {
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
} else if (Key == "use") {
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
} else if (Key == "AuthKey") {
Application::Settings.Key = Value.substr(1, Value.size() - 3);
} else {
beammp_warn("unknown key in old auth file (ignored): " + Key);
}
Str >> std::ws;
}
} }
+59 -268
View File
@@ -7,34 +7,14 @@
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include <boost/asio/ip/address.hpp>
#include <boost/spirit/home/qi/directive/lexeme.hpp>
#include <boost/spirit/home/qi/parse.hpp>
#include <chrono>
#include <ctime> #include <ctime>
#include <fmt/chrono.h> #include <mutex>
#include <sstream> #include <sstream>
#include <boost/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/algorithm/string.hpp>
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) { static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith; return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
} }
static inline bool StringStartsWithLower(const std::string& Name1, const std::string& Name2) {
std::string Name1Lower = boost::algorithm::to_lower_copy(Name1);
return StringStartsWith(Name1Lower, Name2) || StringStartsWith(Name2, Name1Lower);
};
static inline bool StringStartsWithLowerBoth(const std::string& Name1, const std::string& Name2) {
std::string Name1Lower = boost::algorithm::to_lower_copy(Name1);
std::string Name2Lower = boost::algorithm::to_lower_copy(Name2);
return StringStartsWith(Name1Lower, Name2Lower) || StringStartsWith(Name2Lower, Name1Lower);
};
TEST_CASE("StringStartsWith") { TEST_CASE("StringStartsWith") {
CHECK(StringStartsWith("Hello, World", "Hello")); CHECK(StringStartsWith("Hello, World", "Hello"));
CHECK(StringStartsWith("Hello, World", "H")); CHECK(StringStartsWith("Hello, World", "H"));
@@ -84,13 +64,13 @@ static inline void SplitString(std::string const& str, const char delim, std::ve
} }
static std::string GetDate() { static std::string GetDate() {
TimeType::time_point now = TimeType::now(); std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = TimeType::to_time_t(now); time_t tt = std::chrono::system_clock::to_time_t(now);
auto local_tm = std::localtime(&tt); auto local_tm = std::localtime(&tt);
char buf[30]; char buf[30];
std::string date; std::string date;
if (Application::GetSettingBool(StrDebug)) { if (Application::Settings.DebugModeEnabled) {
std::strftime(buf, sizeof(buf), "[%Y/%m/%d %T.", local_tm); std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
date += buf; date += buf;
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now); auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds; auto fraction = now - seconds;
@@ -100,7 +80,7 @@ static std::string GetDate() {
date += fracstr; date += fracstr;
date += "] "; date += "] ";
} else { } else {
std::strftime(buf, sizeof(buf), "[%Y/%m/%d %T] ", local_tm); std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
date += buf; date += buf;
} }
@@ -253,17 +233,14 @@ void TConsole::Command_Help(const std::string&, const std::vector<std::string>&
static constexpr const char* sHelpString = R"( static constexpr const char* sHelpString = R"(
Commands: Commands:
help displays this help help displays this help
exit exit shuts down the server
quit shuts down the server
kick <name> [reason] kicks specified player with an optional reason kick <name> [reason] kicks specified player with an optional reason
list lists all players and info about them list lists all players and info about them
say <message> sends the message to all players in chat say <message> sends the message to all players in chat
lua [state id] switches to lua, optionally into a specific state id's lua lua [state id] switches to lua, optionally into a specific state id's lua
settings [command] sets or gets settings for the server, run `settings help` for more info settings [command] sets or gets settings for the server, run `settings help` for more info
status how the server is doing and what it's up to status how the server is doing and what it's up to
debug internal error and debug state of the server (for development) clear clears the console window)";
clear clears the console window
version version info)";
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString)); Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
} }
@@ -283,114 +260,33 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
mCommandline.write("\x1b[;H\x1b[2J"); mCommandline.write("\x1b[;H\x1b[2J");
} }
void TConsole::Command_Debug(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) {
return;
}
Application::Console().WriteRaw(fmt::format(R"(Debug info (for developers):
UDP:
Malformed packets: {}
Invalid packets: {})",
Application::MalformedUdpPackets,
Application::InvalidUdpPackets));
Application::Console().WriteRaw(fmt::format(R"( Clients:
Note: All data/second rates are an average across the total time since
connection and do not necessarily reflect the *current* data rate
of that client.
)"));
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
std::string State = "";
if (Client->IsSyncing()) {
State += "Syncing";
}
if (Client->IsSynced()) {
if (!State.empty()) {
State += " & ";
}
State += "Synced";
}
if (Client->IsConnected()) {
if (!State.empty()) {
State += " & ";
}
State += "Connected";
}
if (Client->IsDisconnected()) {
if (!State.empty()) {
State += " & ";
}
State += "Disconnected";
}
auto Now = TimeType::now();
auto Seconds = std::chrono::duration_cast<std::chrono::seconds>(Now - Client->ConnectionTime);
std::string ConnectedSince = fmt::format("{:%Y/%m/%d %H:%M:%S}, {:%H:%M:%S} ago ({} seconds)",
fmt::localtime(TimeType::to_time_t(Client->ConnectionTime)),
Seconds,
Seconds.count());
Application::Console().WriteRaw(fmt::format(
R"( {} ('{}'):
Roles: {}
Cars: {}
Is guest: {}
Has unicycle: {}
TCP: {} (on port {})
UDP: {} (on port {})
Sent via TCP: {}
Received via TCP: {}
Sent via UDP: {} ({} packets)
Received via UDP: {} ({} packets)
Status: {}
Queued packets: {}
Latest packet: {}s ago
Connected since: {}
Average send: {}/s
Average receive: {}/s)",
Client->GetID(), Client->GetName(),
Client->GetRoles(),
Client->GetCarCount(),
Client->IsGuest() ? "yes" : "no",
Client->GetUnicycleID() == -1 ? "no" : "yes",
Client->GetTCPSock().remote_endpoint().address() == ip::address::from_string("0.0.0.0") ? "not connected" : "connected", Client->GetTCPSock().remote_endpoint().port(),
Client->GetUDPAddr().address() == ip::address::from_string("0.0.0.0") ? "NOT connected" : "connected", Client->GetUDPAddr().port(),
ToHumanReadableSize(Client->TcpSent),
ToHumanReadableSize(Client->TcpReceived),
ToHumanReadableSize(Client->UdpSent), Client->UdpPacketsSent,
ToHumanReadableSize(Client->UdpReceived), Client->UdpPacketsReceived,
State.empty() ? "None (likely pre-sync)" : State,
Client->MissedPacketQueueSize(),
Client->SecondsSinceLastPing(),
ConnectedSince,
ToHumanReadableSize((Client->TcpSent + Client->UdpSent) / Seconds.count()),
ToHumanReadableSize((Client->TcpReceived + Client->UdpReceived) / Seconds.count())));
});
}
void TConsole::Command_Version(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) {
return;
}
Application::Console().WriteRaw(fmt::format("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH));
}
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 1, size_t(-1))) { if (!EnsureArgsCount(args, 1, size_t(-1))) {
return; return;
} }
auto Name = boost::algorithm::to_lower_copy(args.at(0)); auto Name = args.at(0);
std::string Reason = "Kicked by server console"; std::string Reason = "Kicked by server console";
if (args.size() > 1) { if (args.size() > 1) {
Reason = ConcatArgs({ args.begin() + 1, args.end() }); Reason = ConcatArgs({ args.begin() + 1, args.end() });
} }
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'"); beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
bool Kicked = false; bool Kicked = false;
// TODO: this sucks, tolower is locale-dependent.
mLuaEngine->Server().ForEachClient([&](const auto& Client) -> IterationDecision { auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
if (StringStartsWithLower(Client->GetName(), Name)) { std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = char(std::tolower(char(c))); });
mLuaEngine->Network().ClientKick(*Client, Reason); std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
Kicked = true; return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
return Break; };
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto locked = Client.lock();
if (NameCompare(locked->GetName(), Name)) {
mLuaEngine->Network().ClientKick(*locked, Reason);
Kicked = true;
return false;
}
} }
return Continue; return true;
}); });
if (!Kicked) { if (!Kicked) {
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found."); Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
@@ -455,80 +351,16 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
} }
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 1, 100)) { if (!EnsureArgsCount(args, 1, 2)) {
return; return;
} }
static const char* SETTINGS_HELP = R"(Settings:
settings help Displays this help
settings list Lists all settings
settings get <setting> Prints the current value of the specified setting
settings set <setting> <value> Sets the specified setting to the value)";
if (args.at(0) == "help") {
Application::Console().WriteRaw(SETTINGS_HELP);
} else if (args.at(0) == "list") {
Application::Console().WriteRaw("Available settings:");
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", "<NAME>", "<CURRENT VALUE>"));
for (const auto& [k, v] : Application::mSettings) {
if (k == StrAuthKey) {
Application::Console().WriteRaw(fmt::format("\t{:<25} <key of length {}>", k, Application::SettingToString(v).size()));
} else {
Application::Console().WriteRaw(fmt::format("\t{:<25} {}", k, Application::SettingToString(v)));
}
}
} else if (args.at(0) == "get") {
if (args.size() < 2) {
Application::Console().WriteRaw("Not enough arguments: `settings get` requires a setting name.");
} else {
if (Application::mSettings.contains(args.at(1))) {
if (args.at(1) != StrAuthKey) {
Application::Console().WriteRaw(fmt::format("{} = {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
} else {
Application::Console().WriteRaw(fmt::format("{} = <key of length {}>", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1))).size()));
}
} else {
Application::Console().WriteRaw(fmt::format("Setting '{}' doesn't exist.", args.at(1)));
}
}
} else if (args.at(0) == "set") {
if (args.size() < 3) {
Application::Console().WriteRaw("Not enough arguments: `settings set` requires a setting name and value.");
} else {
if (args.at(1) == StrAuthKey) {
Application::Console().WriteRaw("It's not allowed to set the AuthKey during runtime.");
} else {
using namespace boost::spirit;
using qi::_1;
std::string ValueString = args.at(2);
Application::SettingValue Value;
qi::rule<std::string::iterator, std::string()> StringRule;
StringRule
%= qi::lexeme['"' >> *(qi::char_ - '"') >> '"']
| +(qi::char_ - '"');
qi::rule<std::string::iterator, Application::SettingValue()> ValueRule
= qi::bool_
| qi::int_
| StringRule;
auto It = ValueString.begin();
if (qi::phrase_parse(It, ValueString.end(), ValueRule[boost::phoenix::ref(Value) = _1], ascii::space)
&& It == ValueString.end()) {
Application::SetSetting(args.at(1), Value);
Application::Console().WriteRaw(fmt::format("{} := {}", args.at(1), Application::SettingToString(Application::mSettings.at(args.at(1)))));
} else {
Application::Console().WriteRaw(fmt::format("New value '{}' did not parse as a valid value.", ValueString));
}
}
}
} else {
Application::Console().WriteRaw(fmt::format("Unknown argument '{}' - 'settings {}' is not a valid command.", args.at(0), args.at(0)));
}
} }
void TConsole::Command_Say(const std::string& FullCmd) { void TConsole::Command_Say(const std::string& FullCmd) {
if (FullCmd.size() > 3) { if (FullCmd.size() > 3) {
auto Message = FullCmd.substr(4); auto Message = FullCmd.substr(4);
LuaAPI::MP::SendChatMessage(-1, Message); LuaAPI::MP::SendChatMessage(-1, Message);
if (!Application::GetSettingBool(StrLogChat)) { if (!Application::Settings.LogChat) {
Application::Console().WriteRaw("Chat message sent!"); Application::Console().WriteRaw("Chat message sent!");
} }
} }
@@ -543,10 +375,14 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
} else { } else {
std::stringstream ss; std::stringstream ss;
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl; ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
mLuaEngine->Server().ForEachClient([&](const auto& Client) { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
ss << std::left << std::setw(25) << Client->GetName() if (!Client.expired()) {
<< std::setw(6) << Client->GetID() auto locked = Client.lock();
<< std::setw(6) << Client->GetCarCount() << "\n"; ss << std::left << std::setw(25) << locked->GetName()
<< std::setw(6) << locked->GetID()
<< std::setw(6) << locked->GetCarCount() << "\n";
}
return true;
}); });
auto Str = ss.str(); auto Str = ss.str();
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1)); Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
@@ -566,16 +402,20 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
size_t SyncingCount = 0; size_t SyncingCount = 0;
size_t MissedPacketQueueSum = 0; size_t MissedPacketQueueSum = 0;
int LargestSecondsSinceLastPing = 0; int LargestSecondsSinceLastPing = 0;
mLuaEngine->Server().ForEachClient([&](const auto& Client) { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
CarCount += Client->GetCarCount(); if (!Client.expired()) {
ConnectedCount += Client->IsConnected() ? 1 : 0; auto Locked = Client.lock();
GuestCount += Client->IsGuest() ? 1 : 0; CarCount += Locked->GetCarCount();
SyncedCount += Client->IsSynced() ? 1 : 0; ConnectedCount += Locked->IsConnected() ? 1 : 0;
SyncingCount += Client->IsSyncing() ? 1 : 0; GuestCount += Locked->IsGuest() ? 1 : 0;
MissedPacketQueueSum += Client->MissedPacketQueueSize(); SyncedCount += Locked->IsSynced() ? 1 : 0;
if (Client->SecondsSinceLastPing() < LargestSecondsSinceLastPing) { SyncingCount += Locked->IsSyncing() ? 1 : 0;
LargestSecondsSinceLastPing = Client->SecondsSinceLastPing(); MissedPacketQueueSum += Locked->MissedPacketQueueSize();
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
}
} }
return true;
}); });
size_t SystemsStarting = 0; size_t SystemsStarting = 0;
@@ -650,55 +490,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
Application::Console().WriteRaw(Status.str()); Application::Console().WriteRaw(Status.str());
} }
void TConsole::Autocomplete_Lua(const std::string& stub, std::vector<std::string>& suggestions) {
auto stateNames = mLuaEngine->GetLuaStateNames();
for (const auto& name : stateNames) {
if (name.find(stub) == 0) {
suggestions.push_back("lua " + name);
}
}
}
void TConsole::Autocomplete_Kick(const std::string& stub, std::vector<std::string>& suggestions) {
std::string stub_lower = boost::algorithm::to_lower_copy(stub);
mLuaEngine->Server().ForEachClient([&](const auto& Client) {
if (StringStartsWithLower(Client->GetName(), stub_lower)) {
suggestions.push_back("kick " + Client->GetName());
}
});
}
void TConsole::Autocomplete_Settings(const std::string& stub, std::vector<std::string>& suggestions) {
const std::string subcommands[] = { "help", "list", "set", "get" };
auto [command, args] = ParseCommand(stub);
std::string arg;
if (!args.empty())
arg = boost::algorithm::to_lower_copy(args.at(0));
// suggest setting names
if (command == "set" || command == "get") {
for (const auto& [k, v] : Application::mSettings) {
std::string key = std::string(k);
if (StringStartsWithLower(key, arg)) {
suggestions.push_back("settings " + command + " " + key);
}
}
return;
}
// suggest subcommands
for (const auto& cmd : subcommands) {
if (cmd.find(command) == 0) {
suggestions.push_back("settings " + cmd);
}
}
}
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) { void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
auto FutureIsNonNil = auto FutureIsNonNil =
[](const std::shared_ptr<TLuaResult>& Future) { [](const std::shared_ptr<TLuaResult>& Future) {
@@ -800,6 +591,7 @@ Commands
TConsole::TConsole() { TConsole::TConsole() {
mCommandline.enable_history(); mCommandline.enable_history();
mCommandline.set_history_limit(20); mCommandline.set_history_limit(20);
mCommandline.set_prompt("> ");
BackupOldLog(); BackupOldLog();
mCommandline.on_command = [this](Commandline& c) { mCommandline.on_command = [this](Commandline& c) {
try { try {
@@ -814,9 +606,7 @@ TConsole::TConsole() {
HandleLuaInternalCommand(cmd.substr(1)); HandleLuaInternalCommand(cmd.substr(1));
} else { } else {
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" }); auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
while (!Future->Ready) { Future->WaitUntilReady();
std::this_thread::yield(); // TODO: Add a timeout
}
if (Future->Error) { if (Future->Error) {
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage); beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
} }
@@ -824,7 +614,7 @@ TConsole::TConsole() {
} else { } else {
if (!mLuaEngine) { if (!mLuaEngine) {
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again."); beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
} else if (cmd == "exit" || cmd == "quit") { } else if (cmd == "exit") {
beammp_info("gracefully shutting down"); beammp_info("gracefully shutting down");
Application::GracefullyShutdown(); Application::GracefullyShutdown();
} else if (cmd == "say") { } else if (cmd == "say") {
@@ -886,15 +676,16 @@ TConsole::TConsole() {
} }
} }
} else { // if not lua } else { // if not lua
for (const auto& [cmd_name, autocomplete_fn] : mCommandAutocompleteMap) { if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
if (stub.find(cmd_name) == 0) { // input starts with a full command (that has autocomplete) std::string after_prefix = TrimString(stub.substr(3));
std::size_t cmd_len = cmd_name.length(); auto stateNames = mLuaEngine->GetLuaStateNames();
std::string trimmed = TrimString(stub.substr(cmd_len));
autocomplete_fn(trimmed, suggestions); for (const auto& name : stateNames) {
break; if (name.find(after_prefix) == 0) {
suggestions.push_back("lua " + name);
}
} }
} } else {
if (suggestions.empty()) {
for (const auto& [cmd_name, cmd_fn] : mCommandMap) { for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
if (cmd_name.find(stub) == 0) { if (cmd_name.find(stub) == 0) {
suggestions.push_back(cmd_name); suggestions.push_back(cmd_name);
+27 -38
View File
@@ -17,14 +17,14 @@ void THeartbeatThread::operator()() {
// these are "hot-change" related variables // these are "hot-change" related variables
static std::string Last; static std::string Last;
static TimeType::time_point LastNormalUpdateTime = TimeType::now(); static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
bool isAuth = false; bool isAuth = false;
size_t UpdateReminderCounter = 0; size_t UpdateReminderCounter = 0;
while (!Application::IsShuttingDown()) { while (!Application::IsShuttingDown()) {
++UpdateReminderCounter; ++UpdateReminderCounter;
Body = GenerateCall(); Body = GenerateCall();
// a hot-change occurs when a setting has changed, to update the backend of that change. // a hot-change occurs when a setting has changed, to update the backend of that change.
auto Now = TimeType::now(); auto Now = std::chrono::high_resolution_clock::now();
bool Unchanged = Last == Body; bool Unchanged = Last == Body;
auto TimePassed = (Now - LastNormalUpdateTime); auto TimePassed = (Now - LastNormalUpdateTime);
auto Threshold = Unchanged ? 30 : 5; auto Threshold = Unchanged ? 30 : 5;
@@ -36,20 +36,10 @@ void THeartbeatThread::operator()() {
Last = Body; Last = Body;
LastNormalUpdateTime = Now; LastNormalUpdateTime = Now;
if (!Application::GetSettingString(StrCustomIP).empty()) { if (!Application::Settings.CustomIP.empty()) {
Body += "&ip=" + Application::GetSettingString(StrCustomIP); Body += "&ip=" + Application::Settings.CustomIP;
} }
auto SentryReportError = [&](const std::string& transaction, int status) {
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("heartbeat",
{ { "response-body", T },
{ "request-body", Body } });
Sentry.SetTransaction(transaction);
beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
};
auto Target = "/heartbeat"; auto Target = "/heartbeat";
unsigned int ResponseCode = 0; unsigned int ResponseCode = 0;
@@ -59,14 +49,12 @@ void THeartbeatThread::operator()() {
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" } });
Doc.Parse(T.data(), T.size()); Doc.Parse(T.data(), T.size());
if (Doc.HasParseError() || !Doc.IsObject()) { if (Doc.HasParseError() || !Doc.IsObject()) {
if (!Application::GetSettingBool(StrPrivate)) { if (!Application::Settings.Private) {
beammp_trace("Backend response failed to parse as valid json"); beammp_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 } });
SentryReportError(Url + Target, ResponseCode);
} else if (ResponseCode != 200) { } else if (ResponseCode != 200) {
SentryReportError(Url + Target, ResponseCode); beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
} else { } else {
// all ok // all ok
Ok = true; Ok = true;
@@ -85,32 +73,28 @@ void THeartbeatThread::operator()() {
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) { if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
Status = Doc[StatusKey].GetString(); Status = Doc[StatusKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { StatusKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) { if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
Code = Doc[CodeKey].GetString(); Code = Doc[CodeKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { CodeKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) { if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
Message = Doc[MessageKey].GetString(); Message = Doc[MessageKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { MessageKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (!Ok) { if (!Ok) {
beammp_error("Missing/invalid json members in backend response"); beammp_error("Missing/invalid json members in backend response");
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
} }
} else { } else {
if (!Application::GetSettingBool(StrPrivate)) { if (!Application::Settings.Private) {
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work."); beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
} }
} }
if (Ok && !isAuth && !Application::GetSettingBool(StrPrivate)) { if (Ok && !isAuth && !Application::Settings.Private) {
if (Status == "2000") { if (Status == "2000") {
beammp_info(("Authenticated! " + Message)); beammp_info(("Authenticated! " + Message));
isAuth = true; isAuth = true;
@@ -124,10 +108,10 @@ void THeartbeatThread::operator()() {
beammp_error("Backend REFUSED the auth key. Reason: " + Message); beammp_error("Backend REFUSED the auth key. Reason: " + Message);
} }
} }
if (isAuth || Application::GetSettingBool(StrPrivate)) { if (isAuth || Application::Settings.Private) {
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good); Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
} }
if (!Application::GetSettingBool(StrHideUpdateMessages) && UpdateReminderCounter % 5) { if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
Application::CheckForUpdates(); Application::CheckForUpdates();
} }
} }
@@ -136,20 +120,21 @@ void THeartbeatThread::operator()() {
std::string THeartbeatThread::GenerateCall() { std::string THeartbeatThread::GenerateCall() {
std::stringstream Ret; std::stringstream Ret;
Ret << "uuid=" << Application::GetSettingString(StrAuthKey) Ret << "uuid=" << Application::Settings.Key
<< "&players=" << mServer.ClientCount() << "&players=" << mServer.ClientCount()
<< "&maxplayers=" << Application::GetSettingInt(StrMaxPlayers) << "&maxplayers=" << Application::Settings.MaxPlayers
<< "&port=" << Application::GetSettingInt(StrPort) << "&port=" << Application::Settings.Port
<< "&map=" << Application::GetSettingString(StrMap) << "&map=" << Application::Settings.MapName
<< "&private=" << (Application::GetSettingBool(StrPrivate) ? "true" : "false") << "&private=" << (Application::Settings.Private ? "true" : "false")
<< "&version=" << Application::ServerVersionString() << "&version=" << Application::ServerVersionString()
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf. << "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
<< "&name=" << Application::GetSettingString(StrName) << "&name=" << Application::Settings.ServerName
<< "&modlist=" << TResourceManager::FormatForBackend(mResourceManager.FileMap()) << "&modlist=" << mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.TotalModsSize() << "&modstotalsize=" << mResourceManager.MaxModSize()
<< "&modstotal=" << mResourceManager.LoadedModCount() << "&modstotal=" << mResourceManager.ModsLoaded()
<< "&playerslist=" << GetPlayers() << "&playerslist=" << GetPlayers()
<< "&desc=" << Application::GetSettingString(StrDescription); << "&desc=" << Application::Settings.ServerDesc
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
return Ret.str(); return Ret.str();
} }
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server) THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
@@ -167,8 +152,12 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
} }
std::string THeartbeatThread::GetPlayers() { std::string THeartbeatThread::GetPlayers() {
std::string Return; std::string Return;
mServer.ForEachClient([&](const auto& Client) { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
Return += Client->GetName() + ";"; ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Return += ClientPtr.lock()->GetName() + ";";
}
return true;
}); });
return Return; return Return;
} }
+83 -139
View File
@@ -4,8 +4,7 @@
#include "Http.h" #include "Http.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaPlugin.h" #include "TLuaPlugin.h"
#include "Uuid.h" #include "sol/object.hpp"
#include "sol/types.hpp"
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
@@ -17,11 +16,11 @@
TLuaEngine* LuaAPI::MP::Engine; TLuaEngine* LuaAPI::MP::Engine;
TLuaEngine::TLuaEngine() TLuaEngine::TLuaEngine()
: mResourceServerPath(fs::path(Application::GetSettingString(StrResourceFolder)) / "Server") { : mResourceServerPath(fs::path(Application::Settings.Resource) / "Server") {
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting); Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
LuaAPI::MP::Engine = this; LuaAPI::MP::Engine = this;
if (!fs::exists(Application::GetSettingString(StrResourceFolder))) { if (!fs::exists(Application::Settings.Resource)) {
fs::create_directory(Application::GetSettingString(StrResourceFolder)); fs::create_directory(Application::Settings.Resource);
} }
if (!fs::exists(mResourceServerPath)) { if (!fs::exists(mResourceServerPath)) {
fs::create_directory(mResourceServerPath); fs::create_directory(mResourceServerPath);
@@ -37,7 +36,7 @@ TLuaEngine::TLuaEngine()
} }
TEST_CASE("TLuaEngine ctor & dtor") { TEST_CASE("TLuaEngine ctor & dtor") {
Application::SetSetting(StrResourceFolder, "beammp_server_test_resources"); Application::Settings.Resource = "beammp_server_test_resources";
TLuaEngine engine; TLuaEngine engine;
Application::GracefullyShutdown(); Application::GracefullyShutdown();
} }
@@ -72,12 +71,13 @@ void TLuaEngine::operator()() {
} }
return false; return false;
}); });
} else {
mResultsToCheckCond.wait_for(Lock, std::chrono::milliseconds(20));
} }
mResultsToCheckCond.wait_for(Lock, std::chrono::milliseconds(10));
} }
}); });
// event loop // event loop
auto Before = TimeType::now(); auto Before = std::chrono::high_resolution_clock::now();
while (!Application::IsShuttingDown()) { while (!Application::IsShuttingDown()) {
{ // Timed Events Scope { // Timed Events Scope
std::unique_lock Lock(mTimedEventsMutex); std::unique_lock Lock(mTimedEventsMutex);
@@ -110,14 +110,14 @@ void TLuaEngine::operator()() {
} else { } else {
constexpr double NsFactor = 1000000.0; constexpr double NsFactor = 1000000.0;
constexpr double Expected = 10.0; // ms constexpr double Expected = 10.0; // ms
const auto Diff = (TimeType::now() - Before).count() / NsFactor; const auto Diff = (std::chrono::high_resolution_clock::now() - Before).count() / NsFactor;
if (Diff < Expected) { if (Diff < Expected) {
std::this_thread::sleep_for(std::chrono::nanoseconds(size_t((Expected - Diff) * NsFactor))); std::this_thread::sleep_for(std::chrono::nanoseconds(size_t((Expected - Diff) * NsFactor)));
} else { } else {
beammp_tracef("Event loop cannot keep up! Running {}ms behind", Diff); beammp_tracef("Event loop cannot keep up! Running {}ms behind", Diff);
} }
} }
Before = TimeType::now(); Before = std::chrono::high_resolution_clock::now();
} }
if (ResultCheckThread.joinable()) { if (ResultCheckThread.joinable()) {
@@ -253,15 +253,11 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const st
} else if (i == keys.size() - 1) { } else if (i == keys.size() - 1) {
if (obj.get_type() == sol::type::table) { if (obj.get_type() == sol::type::table) {
for (const auto& [key, value] : obj.as<sol::table>()) { for (const auto& [key, value] : obj.as<sol::table>()) {
if (key.get_type() == sol::type::string) { std::string s = key.as<std::string>();
std::string s = key.as<std::string>(); if (value.get_type() == sol::type::function) {
s += "(";
if (value.get_type() == sol::type::function) {
s += "(";
}
Result.push_back(s);
} }
Result.push_back(s);
} }
} else { } else {
Result = { obj.as<std::string>() }; Result = { obj.as<std::string>() };
@@ -285,11 +281,12 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const st
*/ */
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<TimeType::duration>& Max) { void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
for (const auto& Result : Results) { for (const auto& Result : Results) {
bool Cancelled = false; bool Cancelled = false;
size_t ms = 0; size_t ms = 0;
std::set<std::string> WarnedResults; std::set<std::string> WarnedResults;
while (!Result->Ready && !Cancelled) { while (!Result->Ready && !Cancelled) {
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
ms += 10; ms += 10;
@@ -304,6 +301,7 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
} }
} }
} }
if (Cancelled) { if (Cancelled) {
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time."); beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
LuaAPI::MP::Engine->ReportErrors({ Result }); LuaAPI::MP::Engine->ReportErrors({ Result });
@@ -334,7 +332,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::EnqueueScript(TLuaStateId StateID, const
return mLuaStates.at(StateID)->EnqueueScript(Script); return mLuaStates.at(StateID)->EnqueueScript(Script);
} }
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args) { std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
std::unique_lock Lock(mLuaStatesMutex); std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args); return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args);
} }
@@ -414,55 +412,13 @@ std::set<std::string> TLuaEngine::GetEventHandlersForState(const std::string& Ev
return mLuaEvents[EventName][StateId]; return mLuaEvents[EventName][StateId];
} }
std::vector<sol::object> TLuaEngine::StateThreadData::JsonStringToArray(JsonString Str) {
auto LocalTable = Lua_JsonDecode(Str.value).as<std::vector<sol::object>>();
for (auto& value : LocalTable) {
if (value.is<std::string>() && value.as<std::string>() == BEAMMP_INTERNAL_NIL) {
value = sol::object {};
}
}
return LocalTable;
}
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) { sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
auto Table = mStateView.create_table(); auto Return = mEngine->TriggerEvent(EventName, mStateId, EventArgs);
for (const sol::stack_proxy& Arg : EventArgs) {
switch (Arg.get_type()) {
case sol::type::none:
case sol::type::userdata:
case sol::type::lightuserdata:
case sol::type::thread:
case sol::type::function:
case sol::type::poly:
Table.add(BEAMMP_INTERNAL_NIL);
beammp_warnf("Passed a value of type '{}' to TriggerGlobalEvent(\"{}\", ...). This type can not be serialized, and cannot be passed between states. It will arrive as <nil> in handlers.", sol::type_name(EventArgs.lua_state(), Arg.get_type()), EventName);
break;
case sol::type::lua_nil:
Table.add(BEAMMP_INTERNAL_NIL);
break;
case sol::type::string:
case sol::type::number:
case sol::type::boolean:
case sol::type::table:
Table.add(Arg);
break;
}
}
JsonString Str { "" };
if (!Table.empty()) {
Str.value = LuaAPI::MP::JsonEncode(Table);
}
auto Return = mEngine->TriggerEvent(EventName, mStateId, Str);
mEngine->ReportErrors(Return);
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId); auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
sol::variadic_results LocalArgs = Str.value.empty() ? sol::variadic_results {} : JsonStringToArray(Str);
for (const auto& Handler : MyHandlers) { for (const auto& Handler : MyHandlers) {
auto Fn = mStateView[Handler]; auto Fn = mStateView[Handler];
if (Fn.valid()) { if (Fn.valid()) {
auto LuaResult = LocalArgs.empty() ? Fn() : Fn(LocalArgs); auto LuaResult = Fn(EventArgs);
auto Result = std::make_shared<TLuaResult>(); auto Result = std::make_shared<TLuaResult>();
if (LuaResult.valid()) { if (LuaResult.valid()) {
Result->Error = false; Result->Error = false;
@@ -471,7 +427,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; Result->MarkAsReady();
Return.push_back(Result); Return.push_back(Result);
} }
} }
@@ -501,44 +457,31 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
} }
return Result; return Result;
}); });
AsyncEventReturn.set_function("Wait",
[](const sol::table& Self, std::optional<float> TimeoutS) {
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
if (TimeoutS.has_value()) {
TLuaEngine::WaitForAll(Vector, std::chrono::milliseconds(size_t(TimeoutS.value() * 1000.0f)));
} else {
TLuaEngine::WaitForAll(Vector);
}
});
return AsyncEventReturn; return AsyncEventReturn;
} }
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) { sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
// TODO: make asynchronous? // TODO: make asynchronous?
auto Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) { for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
auto Fn = mStateView[Handler]; auto Fn = mStateView[Handler];
if (Fn.valid() && Fn.get_type() == sol::type::function) { if (Fn.valid() && Fn.get_type() == sol::type::function) {
auto FnRet = Fn(EventArgs); auto FnRet = Fn(EventArgs);
if (FnRet.valid()) { if (FnRet.valid()) {
for (const auto& Res : FnRet) { Result.add(FnRet);
Result.add(Res);
}
} else { } else {
sol::error Err = FnRet; sol::error Err = FnRet;
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what()); beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
} }
} else {
beammp_lua_errorf("Handler '{}' for event '{}' in state '{}' is NOT a function, and will be ignored.", Handler, EventName, mStateId);
} }
} }
return Result; return Result;
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto Client = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
auto IDs = Client->GetIdentifiers(); auto IDs = MaybeClient.value().lock()->GetIdentifiers();
if (IDs.empty()) { if (IDs.empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
@@ -554,20 +497,27 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() { sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
sol::table Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
mEngine->Server().ForEachClient([&](const auto& Client) { mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
Result[Client->GetID()] = Client->GetName(); if (!Client.expired()) {
auto locked = Client.lock();
Result[locked->GetID()] = locked->GetName();
}
return true;
}); });
return Result; return Result;
} }
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) { int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
int Id = -1; int Id = -1;
mEngine->mServer->ForEachClient([&Id, &Name](const auto& Client) -> IterationDecision { mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
if (Client->GetName() == Name) { if (!Client.expired()) {
Id = Client->GetID(); auto locked = Client.lock();
return Break; if (locked->GetName() == Name) {
Id = locked->GetID();
return false;
}
} }
return Continue; return true;
}); });
return Id; return Id;
} }
@@ -599,17 +549,18 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
} }
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) { std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto Client = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
return Client->GetName(); return MaybeClient.value().lock()->GetName();
} else { } else {
return ""; return "";
} }
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto Client = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value().lock();
TClient::TSetOfVehicleData VehicleData; TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope { // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars(); auto LockedData = Client->GetAllCars();
@@ -630,8 +581,9 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) { std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
std::pair<sol::table, std::string> Result; std::pair<sol::table, std::string> Result;
auto Client = GetClient(mEngine->Server(), PID); auto MaybeClient = GetClient(mEngine->Server(), PID);
if (Client) { if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value().lock();
std::string VehiclePos = Client->GetCarPositionRaw(VID); std::string VehiclePos = Client->GetCarPositionRaw(VID);
if (VehiclePos.empty()) { if (VehiclePos.empty()) {
@@ -776,14 +728,14 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
MPTable.set_function("CreateTimer", [&]() -> sol::table { MPTable.set_function("CreateTimer", [&]() -> sol::table {
sol::state_view StateView(mState); sol::state_view StateView(mState);
sol::table Result = StateView.create_table(); sol::table Result = StateView.create_table();
Result["__StartTime"] = TimeType::now(); Result["__StartTime"] = std::chrono::high_resolution_clock::now();
Result.set_function("GetCurrent", [&](const sol::table& Table) -> float { Result.set_function("GetCurrent", [&](const sol::table& Table) -> float {
auto End = TimeType::now(); auto End = std::chrono::high_resolution_clock::now();
auto Start = Table.get<TimeType::time_point>("__StartTime"); auto Start = Table.get<std::chrono::high_resolution_clock::time_point>("__StartTime");
return std::chrono::duration_cast<std::chrono::microseconds>(End - Start).count() / 1000000.0f; return std::chrono::duration_cast<std::chrono::microseconds>(End - Start).count() / 1000000.0f;
}); });
Result.set_function("Start", [&](sol::table Table) { Result.set_function("Start", [&](sol::table Table) {
Table["__StartTime"] = TimeType::now(); Table["__StartTime"] = std::chrono::high_resolution_clock::now();
}); });
return Result; return Result;
}); });
@@ -795,10 +747,9 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
MPTable.set_function("TriggerGlobalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table { MPTable.set_function("TriggerGlobalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
return Lua_TriggerGlobalEvent(EventName, EventArgs); return Lua_TriggerGlobalEvent(EventName, EventArgs);
}); });
MPTable.set_function( MPTable.set_function("TriggerLocalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
"TriggerLocalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> auto{ return Lua_TriggerLocalEvent(EventName, EventArgs);
return Lua_TriggerLocalEvent(EventName, EventArgs); });
});
MPTable.set_function("TriggerClientEvent", &LuaAPI::MP::TriggerClientEvent); MPTable.set_function("TriggerClientEvent", &LuaAPI::MP::TriggerClientEvent);
MPTable.set_function("TriggerClientEventJson", &LuaAPI::MP::TriggerClientEventJson); MPTable.set_function("TriggerClientEventJson", &LuaAPI::MP::TriggerClientEventJson);
MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount); MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
@@ -869,7 +820,6 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten); UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten);
UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify); UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify);
UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify); UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify);
UtilTable.set_function("GenerateUUID", &uuid::GenerateUuid);
UtilTable.set_function("Random", [this] { UtilTable.set_function("Random", [this] {
return mUniformRealDistribution01(mMersenneTwister); return mUniformRealDistribution01(mMersenneTwister);
}); });
@@ -926,7 +876,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLu
return Result; return Result;
} }
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy) { std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy) {
// TODO: Document all this // TODO: Document all this
decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end(); decltype(mStateFunctionQueue)::iterator Iter = mStateFunctionQueue.end();
if (Strategy == CallStrategy::BestEffort) { if (Strategy == CallStrategy::BestEffort) {
@@ -948,7 +898,7 @@ std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCallFrom
} }
} }
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args) { std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args) {
auto Result = std::make_shared<TLuaResult>(); auto Result = std::make_shared<TLuaResult>();
Result->StateId = mStateId; Result->StateId = mStateId;
Result->Function = FunctionName; Result->Function = FunctionName;
@@ -1007,7 +957,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; S.second->MarkAsReady();
} }
} }
{ // StateFunctionQueue Scope { // StateFunctionQueue Scope
@@ -1033,24 +983,19 @@ void TLuaEngine::StateThreadData::operator()() {
continue; continue;
} }
switch (Arg.index()) { switch (Arg.index()) {
case TLuaType::String: case TLuaArgTypes_String:
LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg))); LuaArgs.push_back(sol::make_object(StateView, std::get<std::string>(Arg)));
break; break;
case TLuaType::Int: case TLuaArgTypes_Int:
LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg))); LuaArgs.push_back(sol::make_object(StateView, std::get<int>(Arg)));
break; break;
case TLuaType::Json: { case TLuaArgTypes_VariadicArgs:
auto Str = std::get<JsonString>(Arg); LuaArgs.push_back(sol::make_object(StateView, std::get<sol::variadic_args>(Arg)));
if (!Str.value.empty()) {
auto LocalArgs = JsonStringToArray(Str);
LuaArgs.insert(LuaArgs.end(), LocalArgs.begin(), LocalArgs.end());
}
break; break;
} case TLuaArgTypes_Bool:
case TLuaType::Bool:
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg))); LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
break; break;
case TLuaType::StringStringMap: { case TLuaArgTypes_StringStringMap: {
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg); auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
auto Table = StateView.create_table(); auto Table = StateView.create_table();
for (const auto& [k, v] : Map) { for (const auto& [k, v] : Map) {
@@ -1059,15 +1004,6 @@ void TLuaEngine::StateThreadData::operator()() {
LuaArgs.push_back(sol::make_object(StateView, Table)); LuaArgs.push_back(sol::make_object(StateView, Table));
break; break;
} }
case TLuaType::StringSizeTMap: {
auto Map = std::get<std::unordered_map<std::string, size_t>>(Arg);
auto Table = StateView.create_table();
for (const auto& [k, v] : Map) {
Table[k] = v;
}
LuaArgs.push_back(sol::make_object(StateView, Table));
break;
}
default: default:
beammp_error("Unknown argument type, passed as nil"); beammp_error("Unknown argument type, passed as nil");
break; break;
@@ -1082,11 +1018,11 @@ void TLuaEngine::StateThreadData::operator()() {
sol::error Err = Res; sol::error Err = Res;
Result->ErrorMessage = Err.what(); Result->ErrorMessage = Err.what();
} }
Result->Ready = true; Result->MarkAsReady();
} else { } else {
Result->Error = true; Result->Error = true;
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
Result->Ready = true; Result->MarkAsReady();
} }
} }
} }
@@ -1106,8 +1042,8 @@ std::vector<TLuaEngine::QueuedFunction> TLuaEngine::StateThreadData::Debug_GetSt
void TLuaEngine::CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy) { void TLuaEngine::CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy) {
std::unique_lock Lock(mTimedEventsMutex); std::unique_lock Lock(mTimedEventsMutex);
TimedEvent Event { TimedEvent Event {
TimeType::duration { std::chrono::milliseconds(IntervalMS) }, std::chrono::high_resolution_clock::duration { std::chrono::milliseconds(IntervalMS) },
TimeType::now(), std::chrono::high_resolution_clock::now(),
EventName, EventName,
StateId, StateId,
Strategy Strategy
@@ -1136,11 +1072,19 @@ void TLuaEngine::StateThreadData::AddPath(const fs::path& Path) {
mPaths.push(Path); mPaths.push(Path);
} }
void TLuaResult::WaitUntilReady() { void TLuaResult::MarkAsReady() {
while (!Ready) { {
std::this_thread::yield(); std::lock_guard<std::mutex> readyLock(*this->ReadyMutex);
std::this_thread::sleep_for(std::chrono::milliseconds(10)); this->Ready = true;
} }
this->ReadyCondition->notify_all();
}
void TLuaResult::WaitUntilReady() {
std::unique_lock readyLock(*this->ReadyMutex);
// wait if not ready yet
if(!this->Ready)
this->ReadyCondition->wait(readyLock);
} }
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath) TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
@@ -1150,10 +1094,10 @@ TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName,
} }
bool TLuaEngine::TimedEvent::Expired() { bool TLuaEngine::TimedEvent::Expired() {
auto Waited = (TimeType::now() - LastCompletion); auto Waited = (std::chrono::high_resolution_clock::now() - LastCompletion);
return Waited >= Duration; return Waited >= Duration;
} }
void TLuaEngine::TimedEvent::Reset() { void TLuaEngine::TimedEvent::Reset() {
LastCompletion = TimeType::now(); LastCompletion = std::chrono::high_resolution_clock::now();
} }
+202 -160
View File
@@ -1,7 +1,6 @@
#include "TNetwork.h" #include "TNetwork.h"
#include "Client.h" #include "Client.h"
#include "Common.h" #include "Common.h"
#include "IterationDecision.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
@@ -10,9 +9,10 @@
#include <array> #include <array>
#include <boost/asio/ip/address.hpp> #include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp> #include <boost/asio/ip/address_v4.hpp>
#include <chrono>
#include <cstring> #include <cstring>
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option;
std::vector<uint8_t> StringToVector(const std::string& Str) { std::vector<uint8_t> StringToVector(const std::string& Str) {
return std::vector<uint8_t>(Str.data(), Str.data() + Str.size()); return std::vector<uint8_t>(Str.data(), Str.data() + Str.size());
} }
@@ -33,6 +33,15 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
, mResourceManager(ResourceManager) { , mResourceManager(ResourceManager) {
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting); Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting);
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting); Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
Application::RegisterShutdownHandler([&] {
beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
if (!client.expired()) {
ClientKick(*client.lock(), "Server shutdown");
}
return true;
});
});
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown); Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown);
if (mUDPThread.joinable()) { if (mUDPThread.joinable()) {
@@ -49,19 +58,11 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
}); });
mTCPThread = std::thread(&TNetwork::TCPServerMain, this); mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
mUDPThread = std::thread(&TNetwork::UDPServerMain, this); mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
Application::RegisterShutdownHandler([&] {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(60));
beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](const auto& Client) {
ClientKick(*Client, "Server shutdown");
});
});
} }
void TNetwork::UDPServerMain() { void TNetwork::UDPServerMain() {
RegisterThread("UDPServer"); RegisterThread("UDPServer");
ip::udp::endpoint UdpListenEndpoint(ip::address::from_string("0.0.0.0"), Application::GetSettingInt(StrPort)); ip::udp::endpoint UdpListenEndpoint(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
boost::system::error_code ec; boost::system::error_code ec;
mUDPSock.open(UdpListenEndpoint.protocol(), ec); mUDPSock.open(UdpListenEndpoint.protocol(), ec);
if (ec) { if (ec) {
@@ -76,45 +77,35 @@ void TNetwork::UDPServerMain() {
Application::GracefullyShutdown(); Application::GracefullyShutdown();
} }
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good); Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good);
beammp_info(("Vehicle data network online on port ") + std::to_string(Application::GetSettingInt(StrPort)) + (" with a Max of ") beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
+ std::to_string(Application::GetSettingInt(StrMaxPlayers)) + (" Clients")); + std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
while (!Application::IsShuttingDown()) { while (!Application::IsShuttingDown()) {
try { try {
ip::udp::endpoint client {}; ip::udp::endpoint client {};
std::vector<uint8_t> Data = UDPRcvFromClient(client); // Receives any data from Socket std::vector<uint8_t> Data = UDPRcvFromClient(client); // Receives any data from Socket
// It has to be size>=2, because each UDP packet has a header of auto Pos = std::find(Data.begin(), Data.end(), ':');
// <id+1>: if (Data.empty() || Pos > Data.begin() + 2)
// where id+1 is one byte.
// We discard a UDP packet if it doesn't start like this.
if (Data.size() < 2 || Data.at(1) != ':') {
++Application::MalformedUdpPackets;
continue; continue;
}
// We do -1 here, because the launcher does +1
// because it uses (or used to use) null-terminated strings
// to represent packets. This would mean that player 0 would
// cause empty packets.
uint8_t ID = uint8_t(Data.at(0)) - 1; uint8_t ID = uint8_t(Data.at(0)) - 1;
auto Client = GetClient(mServer, ID); mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
if (Client) { std::shared_ptr<TClient> Client;
try { {
if (Client->IsConnected() && Client->GetUDPAddr() != client) { ReadLock Lock(mServer.GetClientMutex());
beammp_debugf("Client at {}:{} tried to send UDP for client {}", client.address().to_string(), client.port(), Client->GetID()); if (!ClientPtr.expired()) {
++Application::InvalidUdpPackets; Client = ClientPtr.lock();
continue; } else
} else { return true;
Client->SetUDPAddr(client);
Client->SetIsConnected(true);
Client->mUDPCONNECTED = true;
}
Client->UdpReceived += Data.size();
++Client->UdpPacketsReceived;
Data.erase(Data.begin() + 0, Data.begin() + 2);
TServer::GlobalParser(Client, std::move(Data), *this);
} catch (const std::exception&) {
++Application::InvalidUdpPackets;
} }
}
if (Client->GetID() == ID) {
Client->SetUDPAddr(client);
Client->SetIsConnected(true);
Data.erase(Data.begin(), Data.begin() + 2);
TServer::GlobalParser(ClientPtr, std::move(Data), mPPSMonitor, *this);
}
return true;
});
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_error(("fatal: ") + std::string(e.what())); beammp_error(("fatal: ") + std::string(e.what()));
} }
@@ -124,7 +115,7 @@ void TNetwork::UDPServerMain() {
void TNetwork::TCPServerMain() { void TNetwork::TCPServerMain() {
RegisterThread("TCPServer"); RegisterThread("TCPServer");
ip::tcp::endpoint ListenEp(ip::address::from_string("0.0.0.0"), Application::GetSettingInt(StrPort)); ip::tcp::endpoint ListenEp(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
ip::tcp::socket Listener(mServer.IoCtx()); ip::tcp::socket Listener(mServer.IoCtx());
boost::system::error_code ec; boost::system::error_code ec;
Listener.open(ListenEp.protocol(), ec); Listener.open(ListenEp.protocol(), ec);
@@ -188,16 +179,29 @@ void TNetwork::Identify(TConnection&& RawConnection) {
return; return;
} }
std::shared_ptr<TClient> Client { nullptr }; std::shared_ptr<TClient> Client { nullptr };
if (Code == 'C') { try {
Client = Authentication(std::move(RawConnection)); if (Code == 'C') {
} else if (Code == 'D') { Client = Authentication(std::move(RawConnection));
HandleDownload(std::move(RawConnection)); } else if (Code == 'D') {
} else if (Code == 'P') { HandleDownload(std::move(RawConnection));
} else if (Code == 'P') {
boost::system::error_code ec;
write(RawConnection.Socket, buffer("P"), ec);
return;
} else {
beammp_errorf("Invalid code got in Identify: '{}'", Code);
}
} catch(const std::exception& e) {
beammp_errorf("Error during handling of code {} - client left in invalid state, closing socket", Code);
boost::system::error_code ec; boost::system::error_code ec;
write(RawConnection.Socket, buffer("P"), ec); RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
return; if (ec) {
} else { beammp_debugf("Failed to shutdown client socket: {}", ec.message());
beammp_errorf("Invalid code got in Identify: '{}'", Code); }
RawConnection.Socket.close(ec);
if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message());
}
} }
} }
@@ -211,18 +215,29 @@ void TNetwork::HandleDownload(TConnection&& Conn) {
return; return;
} }
auto ID = uint8_t(D); auto ID = uint8_t(D);
mServer.ForEachClient([&](const auto& Client) -> IterationDecision { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
if (Client->GetID() == ID) { ReadLock Lock(mServer.GetClientMutex());
Client->SetDownSock(std::move(Conn.Socket)); if (!ClientPtr.expired()) {
return Break; auto c = ClientPtr.lock();
if (c->GetID() == ID) {
c->SetDownSock(std::move(Conn.Socket));
}
} }
return Continue; return true;
}); });
} }
std::string HashPassword(const std::string& str) {
std::stringstream ret;
unsigned char* hash = SHA256(reinterpret_cast<const unsigned char*>(str.c_str()), str.length(), nullptr);
for (int i = 0; i < 32; i++) {
ret << std::hex << static_cast<int>(hash[i]);
}
return ret.str();
}
std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) { std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
auto Client = CreateClient(std::move(RawConnection.Socket)); auto Client = CreateClient(std::move(RawConnection.Socket));
Client->ConnectionTime = TimeType::now();
Client->SetIdentifier("ip", RawConnection.SockAddr.address().to_string()); Client->SetIdentifier("ip", RawConnection.SockAddr.address().to_string());
beammp_tracef("This thread is ip {}", RawConnection.SockAddr.address().to_string()); beammp_tracef("This thread is ip {}", RawConnection.SockAddr.address().to_string());
@@ -244,7 +259,8 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
ClientKick(*Client, fmt::format("Invalid version header: '{}' ({})", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()), Data.size())); ClientKick(*Client, fmt::format("Invalid version header: '{}' ({})", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()), Data.size()));
return nullptr; return nullptr;
} }
if (!TCPSend(*Client, StringToVector("S"))) {
if (!TCPSend(*Client, StringToVector("A"))) { //changed to A for Accepted version
// TODO: handle // TODO: handle
} }
@@ -255,12 +271,24 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
nlohmann::json AuthReq { std::string key(reinterpret_cast<const char*>(Data.data()), Data.size());
{ "key", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()) }
}; nlohmann::json AuthReq{};
auto Target = "/pkToUser"; std::string AuthResStr{};
unsigned int ResponseCode = 0; try {
const auto AuthResStr = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, AuthReq.dump(), "application/json", &ResponseCode); AuthReq = nlohmann::json {
{ "key", key }
};
auto Target = "/pkToUser";
unsigned int ResponseCode = 0;
AuthResStr = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, AuthReq.dump(), "application/json", &ResponseCode);
} catch (const std::exception& e) {
beammp_debugf("Invalid json sent by client, kicking: {}", e.what());
ClientKick(*Client, "Invalid Key (invalid UTF8 string)!");
return nullptr;
}
try { try {
nlohmann::json AuthRes = nlohmann::json::parse(AuthResStr); nlohmann::json AuthRes = nlohmann::json::parse(AuthResStr);
@@ -274,11 +302,7 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
for (const auto& ID : AuthRes["identifiers"]) { for (const auto& ID : AuthRes["identifiers"]) {
auto Raw = std::string(ID); auto Raw = std::string(ID);
auto SepIndex = Raw.find(':'); auto SepIndex = Raw.find(':');
if (SepIndex != std::string::npos) { Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
} else {
beammp_errorf("Invalid response from auth servers: No ':' in identifier '{}', ignoring it", Raw);
}
} }
} else { } else {
beammp_error("Invalid authentication data received from authentication backend"); beammp_error("Invalid authentication data received from authentication backend");
@@ -292,22 +316,41 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles()); if(!Application::Settings.Password.empty()) { // ask password
mServer.ForEachClient([&](const auto& ThisClient) -> IterationDecision { if(!TCPSend(*Client, StringToVector("S"))) {
// FIXME: This doesn't respect forum ID, and it should :^) // TODO: handle
if (ThisClient->GetName() == Client->GetName() && ThisClient->IsGuest() == Client->IsGuest()) {
ThisClient->Disconnect("Stale Client (replaced by new client)");
return Break;
} }
return Continue; beammp_info("Waiting for password");
Data = TCPRcv(*Client);
std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size());
if(Pass != HashPassword(Application::Settings.Password)) {
beammp_debug(Client->GetName() + " attempted to connect with a wrong password");
ClientKick(*Client, "Wrong password!");
return {};
} else {
beammp_debug(Client->GetName() + " used the correct password");
}
}
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> Cl;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Cl = ClientPtr.lock();
} else
return true;
}
if (Cl->GetName() == Client->GetName() && Cl->IsGuest() == Client->IsGuest()) {
Cl->Disconnect("Stale Client (not a real player)");
return false;
}
return true;
}); });
Client->SetID(OpenID()); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers());
beammp_info("Assigned ID " + std::to_string(Client->GetID()) + " to " + Client->GetName());
mServer.InsertClient(Client);
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers(), Client->GetID());
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(), bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -323,24 +366,23 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return false; return false;
}); });
bool fitsOnServer = mServer.ClientCount() < size_t(Application::GetSettingInt(StrMaxPlayers)); // || luaplayercountbypass;
if (!NotAllowed && !NotAllowedWithReason && fitsOnServer) {
beammp_info("Identification success");
TCPClient(Client);
return Client;
}
if (NotAllowed) { if (NotAllowed) {
ClientKick(*Client, "You are not allowed on the server!"); ClientKick(*Client, "you are not allowed on the server!");
return {};
} else if (NotAllowedWithReason) { } else if (NotAllowedWithReason) {
ClientKick(*Client, Reason); ClientKick(*Client, Reason);
return {};
}
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
beammp_info("Identification success");
mServer.InsertClient(Client);
TCPClient(Client);
} else { } else {
ClientKick(*Client, "Server full!"); ClientKick(*Client, "Server full!");
} }
mServer.RemoveClient(Client); return Client;
return {};
} }
std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) { std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
@@ -383,12 +425,11 @@ bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync
return false; return false;
} }
c.UpdatePingTime(); c.UpdatePingTime();
c.TcpSent += ToSend.size();
return true; return true;
} }
std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) { std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
if (c.IsDisconnected() || (c.mUDPCONNECTED && !c.IsConnected())) { if (c.IsDisconnected()) {
beammp_error("Client disconnected, cancelling TCPRcv"); beammp_error("Client disconnected, cancelling TCPRcv");
return {}; return {};
} }
@@ -432,7 +473,6 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
beammp_errorf("Expected to read {} bytes, instead got {}", Header, N); beammp_errorf("Expected to read {} bytes, instead got {}", Header, N);
} }
c.TcpReceived += N + HeaderData.size();
constexpr std::string_view ABG = "ABG:"; constexpr std::string_view ABG = "ABG:";
if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) { if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) {
Data.erase(Data.begin(), Data.begin() + ABG.size()); Data.erase(Data.begin(), Data.begin() + ABG.size());
@@ -512,7 +552,7 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
Client->Disconnect("TCPRcv failed"); Client->Disconnect("TCPRcv failed");
break; break;
} }
TServer::GlobalParser(c, std::move(res), *this); TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this);
} }
if (QueueSync.joinable()) if (QueueSync.joinable())
@@ -527,9 +567,14 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
} }
void TNetwork::UpdatePlayer(TClient& Client) { void TNetwork::UpdatePlayer(TClient& Client) {
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::GetSettingInt(StrMaxPlayers)) + ":"; std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
mServer.ForEachClient([&](const auto& ThisClient) { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
Packet += ThisClient->GetName() + ","; ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
Packet += c->GetName() + ",";
}
return true;
}); });
Packet = Packet.substr(0, Packet.length() - 1); Packet = Packet.substr(0, Packet.length() - 1);
Client.EnqueuePacket(StringToVector(Packet)); Client.EnqueuePacket(StringToVector(Packet));
@@ -567,19 +612,20 @@ void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) {
} }
int TNetwork::OpenID() { int TNetwork::OpenID() {
// This lock ensures that each call to OpenID is exclusive.
// If we didn't have this, two concurrent calls to this function may result
// in the same ID.
std::unique_lock Lock(mOpenIDMutex);
int ID = 0; int ID = 0;
bool found; bool found;
do { do {
found = true; found = true;
mServer.ForEachClient([&](const auto& Client) { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
if (Client->GetID() == ID) { ReadLock Lock(mServer.GetClientMutex());
found = false; if (!ClientPtr.expired()) {
ID++; auto c = ClientPtr.lock();
if (c->GetID() == ID) {
found = false;
ID++;
}
} }
return true;
}); });
} while (!found); } while (!found);
return ID; return ID;
@@ -589,11 +635,13 @@ void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
beammp_assert(!c.expired()); beammp_assert(!c.expired());
beammp_info("Client connected"); beammp_info("Client connected");
auto LockedClient = c.lock(); auto LockedClient = c.lock();
LockedClient->SetID(OpenID());
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID()));
SyncResources(*LockedClient); SyncResources(*LockedClient);
if (LockedClient->IsDisconnected()) if (LockedClient->IsDisconnected())
return; return;
(void)Respond(*LockedClient, StringToVector("M" + Application::GetSettingString(StrMap)), true); // Send the Map on connect (void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
beammp_info(LockedClient->GetName() + " : Connected"); beammp_info(LockedClient->GetName() + " : Connected");
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
} }
@@ -611,39 +659,11 @@ void TNetwork::SyncResources(TClient& c) {
constexpr std::string_view Done = "Done"; constexpr std::string_view Done = "Done";
if (std::equal(Data.begin(), Data.end(), Done.begin(), Done.end())) if (std::equal(Data.begin(), Data.end(), Done.begin(), Done.end()))
break; break;
HandleResourcePackets(c, Data); Parse(c, Data);
} }
} }
ModMap TNetwork::GetClientMods(TClient& Client) { void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
auto AllMods = mResourceManager.FileMap();
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerRequestMods", "", Client.GetName(), Client.GetRoles(), Client.IsGuest(), Client.GetIdentifiers(), Client.GetID(), AllMods);
TLuaEngine::WaitForAll(Futures);
ModMap AllowedMods = AllMods;
for (const std::shared_ptr<TLuaResult>& Future : Futures) {
sol::table Result;
if (!Future->Error && Future->Result.is<sol::table>()) {
Result = Future->Result.as<sol::table>();
for (const auto& [name, size] : AllMods) {
auto val = Result.get<sol::optional<int>>(name);
if (!val.has_value()) {
AllowedMods.erase(name);
beammp_debugf("Not sending mod '{}' to player '{}' (from state '{}')", name, Client.GetName(), Future->StateId);
}
}
}
}
Client.AllowedMods = AllowedMods;
return AllowedMods;
}
void TNetwork::HandleResourcePackets(TClient& c, const std::vector<uint8_t>& Packet) {
if (Packet.empty()) if (Packet.empty())
return; return;
char Code = Packet.at(0), SubCode = 0; char Code = Packet.at(0), SubCode = 0;
@@ -656,7 +676,7 @@ void TNetwork::HandleResourcePackets(TClient& c, const std::vector<uint8_t>& Pac
case 'S': case 'S':
if (SubCode == 'R') { if (SubCode == 'R') {
beammp_debug("Sending Mod Info"); beammp_debug("Sending Mod Info");
std::string ToSend = TResourceManager::FormatForClient(GetClientMods(c)); std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
if (ToSend.empty()) if (ToSend.empty())
ToSend = "-"; ToSend = "-";
if (!TCPSend(c, StringToVector(ToSend))) { if (!TCPSend(c, StringToVector(ToSend))) {
@@ -670,22 +690,28 @@ void TNetwork::HandleResourcePackets(TClient& c, const std::vector<uint8_t>& Pac
} }
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) { void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
beammp_infof("{} ({}) requesting mod: '{}'", c.GetName(), c.GetID(), UnsafeName); beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
auto FileName = UnsafeName; if (!fs::path(UnsafeName).has_filename()) {
auto res = TResourceManager::IsModValid(FileName, c.AllowedMods);
if (res.has_value()) {
if (!TCPSend(c, StringToVector("CO"))) { if (!TCPSend(c, StringToVector("CO"))) {
c.Disconnect("TCP send failed in SendFile, when trying to cancel file transfer because " + res.value()); // TODO: handle
} }
beammp_warn("File " + UnsafeName + " is not a file!");
return;
}
auto FileName = fs::path(UnsafeName).filename().string();
FileName = Application::Settings.Resource + "/Client/" + FileName;
if (!std::filesystem::exists(FileName)) {
if (!TCPSend(c, StringToVector("CO"))) {
// TODO: handle
}
beammp_warn("File " + UnsafeName + " could not be accessed!");
return; return;
} }
if (!TCPSend(c, StringToVector("AG"))) { if (!TCPSend(c, StringToVector("AG"))) {
c.Disconnect("TCP send failed in SendFile, when trying to send "); // TODO: handle
return;
} }
/// Wait for connections /// Wait for connections
@@ -815,7 +841,6 @@ bool TNetwork::TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Da
return false; return false;
} }
C.UpdatePingTime(); C.UpdatePingTime();
C.TcpSent += Size;
return true; return true;
} }
@@ -858,23 +883,32 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
LockedClient->SetIsSyncing(true); LockedClient->SetIsSyncing(true);
bool Return = false; bool Return = false;
bool res = true; bool res = true;
mServer.ForEachClient([&](const auto& Client) -> IterationDecision { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> client;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
client = ClientPtr.lock();
} else
return true;
}
TClient::TSetOfVehicleData VehicleData; TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope { // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars(); auto LockedData = client->GetAllCars();
VehicleData = *LockedData.VehicleData; VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope } // End Vehicle Data Lock Scope
if (Client != LockedClient) { if (client != LockedClient) {
for (auto& v : VehicleData) { for (auto& v : VehicleData) {
if (LockedClient->IsDisconnected()) { if (LockedClient->IsDisconnected()) {
Return = true; Return = true;
res = false; res = false;
return Break; return false;
} }
res = Respond(*LockedClient, StringToVector(v.Data()), true, true); res = Respond(*LockedClient, StringToVector(v.Data()), true, true);
} }
} }
return Continue;
return true;
}); });
LockedClient->SetIsSyncing(false); LockedClient->SetIsSyncing(false);
if (Return) { if (Return) {
@@ -890,7 +924,16 @@ void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self
beammp_assert(c); beammp_assert(c);
char C = Data.at(0); char C = Data.at(0);
bool ret = true; bool ret = true;
mServer.ForEachClient([&](const auto& Client) { mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
std::shared_ptr<TClient> Client;
try {
ReadLock Lock(mServer.GetClientMutex());
Client = ClientPtr.lock();
} catch (const std::exception&) {
// continue
beammp_warn("Client expired, shouldn't happen - if a client disconnected recently, you can ignore this");
return true;
}
if (Self || Client.get() != c) { if (Self || Client.get() != c) {
if (Client->IsSynced() || Client->IsSyncing()) { if (Client->IsSynced() || Client->IsSyncing()) {
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') { if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
@@ -912,6 +955,7 @@ void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self
} }
} }
} }
return true;
}); });
if (!ret) { if (!ret) {
// TODO: handle // TODO: handle
@@ -939,8 +983,6 @@ bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
Client.Disconnect("UDP send failed"); Client.Disconnect("UDP send failed");
return false; return false;
} }
Client.UdpSent += Data.size();
++Client.UdpPacketsSent;
return true; return true;
} }
+16 -6
View File
@@ -33,16 +33,26 @@ void TPPSMonitor::operator()() {
Application::SetPPS("-"); Application::SetPPS("-");
continue; continue;
} }
mServer.ForEachClient([&](const auto& Client) { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
if (Client->GetCarCount() > 0) { std::shared_ptr<TClient> c;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
c = ClientPtr.lock();
} else
return true;
}
if (c->GetCarCount() > 0) {
C++; C++;
V += Client->GetCarCount(); V += c->GetCarCount();
} }
// kick on "no ping" // kick on "no ping"
if (Client->SecondsSinceLastPing() > (20 * 60)) { if (c->SecondsSinceLastPing() > (20 * 60)) {
beammp_debugf("Client {} ({}) timing out: {}s since last contact", Client->GetName(), Client->GetID(), Client->SecondsSinceLastPing()); beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
TimedOutClients.push_back(Client); TimedOutClients.push_back(c);
} }
return true;
}); });
for (auto& ClientToKick : TimedOutClients) { for (auto& ClientToKick : TimedOutClients) {
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)"); Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
+20 -68
View File
@@ -5,79 +5,31 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string TResourceManager::FormatForBackend(const ModMap& mods) {
std::string monkey;
for (const auto& [name, size] : mods) {
monkey += fs::path(name).filename().string() + ';';
}
return monkey;
}
std::string TResourceManager::FormatForClient(const ModMap& mods) {
std::string monkey;
for (const auto& [name, size] : mods) {
monkey += '/' + name + ';';
}
for (const auto& [name, size] : mods) {
monkey += std::to_string(size) + ';';
}
return monkey;
}
/// @brief Sanitizes a requested mod string
/// @param pathString Raw mod path string
/// @param mods List of allowed mods for this client
/// @return Error, if any
std::optional<std::string> TResourceManager::IsModValid(std::string& pathString, const ModMap& mods) {
auto path = fs::path(pathString);
if (!path.has_filename()) {
beammp_warn("File " + pathString + " is not a file!");
return { "the requested file doesn't contain a valid filename" };
}
auto BasePath = fs::path(Application::GetSettingString(StrResourceFolder) + "/Client");
auto CombinedPath = fs::path(BasePath.string() + pathString).lexically_normal();
// beammp_infof("path: {}, base: {}, combined: {}", pathString, BasePath.string(), CombinedPath.string());
if (!std::filesystem::exists(CombinedPath)) {
beammp_warn("File " + pathString + " could not be accessed!");
return { "the requested file doesn't exist or couldn't be accessed" };
}
auto relative = fs::relative(CombinedPath, BasePath);
if (mods.count(relative.string()) == 0) {
beammp_warn("File " + pathString + " is disallowed for this player!");
return { "the requested file is disallowed for this player" };
}
pathString = CombinedPath.string();
return {};
}
TResourceManager::TResourceManager() { TResourceManager::TResourceManager() {
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting); Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
std::string BasePath = Application::GetSettingString(StrResourceFolder) + "/Client"; std::string Path = Application::Settings.Resource + "/Client";
if (!fs::exists(BasePath)) if (!fs::exists(Path))
fs::create_directories(BasePath); fs::create_directories(Path);
std::vector<std::string> modNames; for (const auto& entry : fs::directory_iterator(Path)) {
std::string File(entry.path().string());
auto iterator = fs::recursive_directory_iterator(BasePath, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied); if (auto pos = File.find(".zip"); pos != std::string::npos) {
for (const auto& entry : iterator) { if (File.length() - pos == 4) {
if (iterator.depth() > 0 && !Application::GetSettingBool(StrIncludeSubdirectories)) std::replace(File.begin(), File.end(), '\\', '/');
continue; mFileList += File + ';';
if ((entry.is_regular_file() || entry.is_symlink()) && entry.path().extension() == ".zip") { if (auto i = File.find_last_of('/'); i != std::string::npos) {
auto relativePath = fs::relative(entry.path(), BasePath); ++i;
File = File.substr(i, pos - i);
mMods[relativePath.string()] = entry.file_size(); }
mTotalModSize += entry.file_size(); mTrimmedList += "/" + fs::path(File).filename().string() + ';';
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
mMaxModSize += size_t(fs::file_size(entry.path()));
mModsLoaded++;
}
} }
} }
if (!mMods.empty()) { if (mModsLoaded) {
beammp_infof("Loaded {} mod{}", mMods.size(), mMods.size() != 1 ? 's' : ' '); beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
} }
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good); Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
+4 -4
View File
@@ -2,21 +2,21 @@
#include "Common.h" #include "Common.h"
TScopedTimer::TScopedTimer() TScopedTimer::TScopedTimer()
: mStartTime(TimeType::now()) { : mStartTime(std::chrono::high_resolution_clock::now()) {
} }
TScopedTimer::TScopedTimer(const std::string& mName) TScopedTimer::TScopedTimer(const std::string& mName)
: mStartTime(TimeType::now()) : mStartTime(std::chrono::high_resolution_clock::now())
, Name(mName) { , Name(mName) {
} }
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy) TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
: OnDestroy(OnDestroy) : OnDestroy(OnDestroy)
, mStartTime(TimeType::now()) { , mStartTime(std::chrono::high_resolution_clock::now()) {
} }
TScopedTimer::~TScopedTimer() { TScopedTimer::~TScopedTimer() {
auto EndTime = TimeType::now(); auto EndTime = std::chrono::high_resolution_clock::now();
auto Delta = EndTime - mStartTime; auto Delta = EndTime - mStartTime;
size_t TimeDelta = Delta / std::chrono::milliseconds(1); size_t TimeDelta = Delta / std::chrono::milliseconds(1);
if (OnDestroy) { if (OnDestroy) {
-138
View File
@@ -1,138 +0,0 @@
#include "TSentry.h"
#include "Common.h"
#include <cstring>
#include <sentry.h>
#include <sstream>
TSentry::TSentry() {
if (std::strlen(S_DSN) == /* DISABLES CODE */ (0)) {
mValid = false;
} else {
mValid = true;
sentry_options_t* options = sentry_options_new();
sentry_options_set_dsn(options, S_DSN);
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersionString();
sentry_options_set_symbolize_stacktraces(options, true);
sentry_options_set_release(options, ReleaseString.c_str());
sentry_options_set_max_breadcrumbs(options, 10);
sentry_init(options);
}
}
TSentry::~TSentry() {
if (mValid) {
sentry_close();
}
}
void TSentry::PrintWelcome() {
if (mValid) {
if (!Application::GetSettingBool("SendErrors")) {
mValid = false;
if (Application::GetSettingBool(StrSendErrors)) {
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
} else {
beammp_info("Sentry disabled");
}
} else {
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.");
} else {
beammp_info("Sentry started");
}
}
} else {
if (Application::GetSettingBool(StrSendErrors)) {
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
} else {
beammp_info("Sentry disabled in unofficial build");
}
}
}
void TSentry::SetupUser() {
if (!mValid) {
return;
}
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
sentry_value_t user = sentry_value_new_object();
if (Application::GetSettingString(StrAuthKey).size() == 36) {
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::GetSettingString(StrAuthKey).c_str()));
} else {
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
}
sentry_set_user(user);
}
void TSentry::Log(SentryLevel level, const std::string& logger, const std::string& text) {
if (!mValid) {
return;
}
SetContext("threads", { { "thread-name", ThreadName(true) } });
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
sentry_capture_event(Msg);
sentry_set_transaction(nullptr);
}
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line);
Log(SentryLevel::Error, "default", file + ": " + text);
}
void TSentry::SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map) {
if (!mValid) {
return;
}
auto ctx = sentry_value_new_object();
for (const auto& pair : map) {
std::string key = pair.first;
if (key == "type") {
// `type` is reserved
key = "_type";
}
sentry_value_set_by_key(ctx, key.c_str(), sentry_value_new_string(pair.second.c_str()));
}
sentry_set_context(context_name.c_str(), ctx);
}
void TSentry::LogException(const std::exception& e, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line);
Log(SentryLevel::Fatal, "exceptions", std::string(e.what()) + " @ " + file + ":" + line);
}
void TSentry::LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line + ":" + function);
std::stringstream ss;
ss << "\"" << condition_string << "\" failed @ " << file << ":" << line;
Log(SentryLevel::Fatal, "asserts", ss.str());
}
void TSentry::AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
auto crumb = sentry_value_new_breadcrumb("default", (msg + " @ " + file + ":" + line).c_str());
sentry_value_set_by_key(crumb, "level", sentry_value_new_string("error"));
sentry_add_breadcrumb(crumb);
}
void TSentry::SetTransaction(const std::string& id) {
if (!mValid) {
return;
}
sentry_set_transaction(id.c_str());
}
std::unique_lock<std::mutex> TSentry::CreateExclusiveContext() {
return std::unique_lock<std::mutex>(mMutex);
}
+49 -136
View File
@@ -2,81 +2,35 @@
#include "Client.h" #include "Client.h"
#include "Common.h" #include "Common.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "IterationDecision.h"
#include "TNetwork.h" #include "TNetwork.h"
#include "TPPSMonitor.h" #include "TPPSMonitor.h"
#include <TLuaPlugin.h> #include <TLuaPlugin.h>
#include <algorithm> #include <algorithm>
#include <any> #include <any>
#include <nlohmann/json.hpp>
#include <sstream> #include <sstream>
#include <nlohmann/json.hpp>
#include "LuaAPI.h" #include "LuaAPI.h"
#undef GetObject // Fixes Windows #undef GetObject // Fixes Windows
#include "Json.h" #include "Json.h"
struct VehiclePacket { static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
std::string Data;
int Pid;
int Vid;
};
static Result<std::pair<int, int>> GetPidVid(const std::string& str) {
auto IDSep = str.find('-'); auto IDSep = str.find('-');
if (IDSep == std::string::npos) {
return Error("Invalid packet: Could not parse pid/vid from packet, as there is no '-' separator: '{}'", str);
}
std::string pid = str.substr(0, IDSep); std::string pid = str.substr(0, IDSep);
std::string vid = str.substr(IDSep + 1); std::string vid = str.substr(IDSep + 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) { if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
try { try {
int PID = std::stoi(pid); int PID = stoi(pid);
int VID = std::stoi(vid); int VID = stoi(vid);
return { { PID, VID } }; return { { PID, VID } };
} catch (const std::exception&) { } catch (const std::exception&) {
return Error("Invalid packet: Could not parse pid/vid from packet, as one or both are not valid numbers: '{}'", str); return std::nullopt;
} }
} }
return Error("Invalid packet: Could not parse pid/vid from packet: '{}'", str);
}
static std::optional<VehiclePacket> ParseVehiclePacket(const std::string& Packet, const int playerID) {
if (Packet.size() < 8) { // 2 for code, 3<= for pidvid, 1<= for data, 2 for dividers
// invalid packet
return std::nullopt;
}
// Zp:serverVehicleID:data
// 0-0:data
std::string withoutCode = Packet.substr(3);
auto NameDataSep = withoutCode.find(':', 3);
if (NameDataSep == std::string::npos) {
beammp_debugf("Invalid packet from {} in ParseVehiclePacket: No ':' separator, assuming corrupted packet. Packet: '{}'", playerID, Packet);
return std::nullopt;
}
if (NameDataSep + 1 > withoutCode.size()) {
beammp_debugf("Invalid packet from {} in ParseVehiclePacket: Separator in unexpected place, assuming corrupted packet. Packet: '{}'", playerID, Packet);
return std::nullopt;
}
std::string ServerVehicleID = withoutCode.substr(0, NameDataSep);
std::string Data = withoutCode.substr(NameDataSep + 1);
// parse veh ID
auto MaybePidVid = GetPidVid(ServerVehicleID);
if (MaybePidVid) {
int PID, VID;
std::tie(PID, VID) = MaybePidVid.value();
if (PID == playerID) {
return { { Data, PID, VID } }; // std::vector<char>(Data.begin(), Data.end())
}
}
beammp_debugf("Failed to parse packet from player {}", playerID);
return std::nullopt; return std::nullopt;
} }
@@ -123,48 +77,15 @@ TEST_CASE("GetPidVid") {
} }
} }
TEST_CASE("ParseVehiclePacket") {
SUBCASE("Valid packet") {
const auto valid = ParseVehiclePacket("Zp:0-0:{jsonstring}", 0);
CHECK(valid.has_value());
}
SUBCASE("Valid packet 2") {
const auto packet = ParseVehiclePacket("Zp:12-3:{jsonstring}", 12);
CHECK(packet.has_value());
CHECK_EQ(packet.value().Pid, 12);
CHECK_EQ(packet.value().Vid, 3);
}
SUBCASE("Missing packet") {
const auto valid = ParseVehiclePacket("", 0);
CHECK(!valid.has_value());
}
SUBCASE("Missing ServerVehicleID") {
const auto valid = ParseVehiclePacket("Zp:{jsonstring}", 0);
CHECK(!valid.has_value());
}
SUBCASE("Missing data") {
const auto valid = ParseVehiclePacket("Zp:0-0:", 0);
CHECK(!valid.has_value());
}
SUBCASE("Incorrect Pid") {
const auto valid = ParseVehiclePacket("Zp:0-0:{jsonstring}", 1);
CHECK(!valid.has_value());
}
SUBCASE("Incorrect Pid 2") {
const auto valid = ParseVehiclePacket("Zp:12-0:{jsonstring}", 13);
CHECK(!valid.has_value());
}
}
TServer::TServer(const std::vector<std::string_view>& Arguments) { TServer::TServer(const std::vector<std::string_view>& Arguments) {
beammp_info("BeamMP Server v" + Application::ServerVersionString());
Application::SetSubsystemStatus("Server", Application::Status::Starting); Application::SetSubsystemStatus("Server", Application::Status::Starting);
if (Arguments.size() > 1) { if (Arguments.size() > 1) {
Application::SetSetting(StrCustomIP, std::string(Arguments[0])); Application::Settings.CustomIP = Arguments[0];
auto CustomIP = Application::GetSettingString(StrCustomIP); size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.'); auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
auto p = Application::GetSettingString(StrCustomIP).find_first_not_of(".0123456789"); if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == "127") { Application::Settings.CustomIP.clear();
Application::SetSetting(StrCustomIP, "");
beammp_warn("IP Specified is invalid! Ignoring"); beammp_warn("IP Specified is invalid! Ignoring");
} else { } else {
beammp_info("server started with custom IP"); beammp_info("server started with custom IP");
@@ -190,16 +111,7 @@ void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
mClients.erase(WeakClientPtr.lock()); mClients.erase(WeakClientPtr.lock());
} }
void TServer::RemoveClientById(int Id) { void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
auto Client = GetClient(*this, Id);
if (Client) {
Client->ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(Client);
}
}
void TServer::ForEachClientWeak(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
decltype(mClients) Clients; decltype(mClients) Clients;
{ {
ReadLock lock(mClientsMutex); ReadLock lock(mClientsMutex);
@@ -217,7 +129,7 @@ size_t TServer::ClientCount() const {
return mClients.size(); return mClients.size();
} }
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TNetwork& Network) { void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
constexpr std::string_view ABG = "ABG:"; constexpr std::string_view ABG = "ABG:";
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) { 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()); Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
@@ -239,11 +151,8 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
// V to Y // V to Y
if (Code <= 89 && Code >= 86) { if (Code <= 89 && Code >= 86) {
if (HandleVehicleUpdate(StringPacket, LockedClient->GetID())) { PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
} else {
beammp_debugf("Invalid vehicle update packet received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
}
return; return;
} }
switch (Code) { switch (Code) {
@@ -302,11 +211,9 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
Network.SendToAll(LockedClient.get(), Packet, false, true); Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
case 'Z': // position packet case 'Z': // position packet
if (HandlePosition(*LockedClient, StringPacket)) { PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
} else { HandlePosition(*LockedClient, StringPacket);
beammp_debugf("Invalid vehicle position packet received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
}
default: default:
return; return;
} }
@@ -346,7 +253,7 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
c.SetUnicycleID(ID); c.SetUnicycleID(ID);
return true; return true;
} else { } else {
return c.GetCarCount() < Application::GetSettingInt(StrMaxCars); return c.GetCarCount() < Application::Settings.MaxCars;
} }
} }
@@ -475,23 +382,13 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
std::string VD = c.GetCarData(VID); std::string VD = c.GetCarData(VID);
if (VD.empty()) { if (VD.empty()) {
beammp_error("Tried to apply change to vehicle that does not exist"); beammp_error("Tried to apply change to vehicle that does not exist");
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("vehicle-change",
{ { "packet", Packet },
{ "vehicle-id", std::to_string(VID) },
{ "client-car-count", std::to_string(c.GetCarCount()) } });
Sentry.LogError("attempt to apply change to nonexistent vehicle", _file_basename, _line);
return; return;
} }
std::string Header = VD.substr(0, VD.find('{')); std::string Header = VD.substr(0, VD.find('{'));
FoundPos = VD.find('{'); FoundPos = VD.find('{');
if (FoundPos == std::string::npos) { if (FoundPos == std::string::npos) {
auto Lock = Sentry.CreateExclusiveContext(); return;
Sentry.SetContext("vehicle-change-packet",
{ { "packet", VD } });
Sentry.LogError("malformed packet", _file_basename, _line);
return;
} }
VD = VD.substr(FoundPos); VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack; rapidjson::Document Veh, Pack;
@@ -525,19 +422,35 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
(void)mClients.insert(NewClient); (void)mClients.insert(NewClient);
} }
bool TServer::HandlePosition(TClient& c, const std::string& PacketStr) { void TServer::HandlePosition(TClient& c, const std::string& Packet) {
auto MaybePacket = ParseVehiclePacket(PacketStr, c.GetID()); if (Packet.size() < 3) {
// invalid packet
if (MaybePacket) { return;
auto packet = MaybePacket.value();
c.SetCarPosition(packet.Vid, packet.Data);
return true;
} }
return false; // Zp:serverVehicleID:data
} // Zp:0:data
std::string withoutCode = Packet.substr(3);
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);
if (NameDataSep + 1 > withoutCode.size()) {
// invalid packet
return;
}
std::string Data = withoutCode.substr(NameDataSep + 1);
bool TServer::HandleVehicleUpdate(const std::string& PacketStr, const int playerID) { // parse veh ID
auto MaybePacket = ParseVehiclePacket(PacketStr, playerID); auto MaybePidVid = GetPidVid(ServerVehicleID);
if (MaybePidVid) {
int PID = -1;
int VID = -1;
// FIXME: check that the VID and PID are valid, so that we don't waste memory
std::tie(PID, VID) = MaybePidVid.value();
return MaybePacket.has_value(); c.SetCarPosition(VID, Data);
}
} }
-15
View File
@@ -1,15 +0,0 @@
#include "Uuid.h"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>
std::string uuid::GenerateUuid() {
static thread_local boost::uuids::random_generator Generator {};
boost::uuids::uuid Id { Generator() };
return boost::uuids::to_string(Id);
}
+22 -27
View File
@@ -1,5 +1,3 @@
#include "TSentry.h"
#include "ArgsParser.h" #include "ArgsParser.h"
#include "Common.h" #include "Common.h"
#include "Http.h" #include "Http.h"
@@ -64,7 +62,6 @@ int main(int argc, char** argv) {
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_error("A fatal exception has occurred and the server is forcefully shutting down."); beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
beammp_error(e.what()); beammp_error(e.what());
Sentry.LogException(e, _file_basename, _line);
MainRet = -1; MainRet = -1;
} }
std::exit(MainRet); std::exit(MainRet);
@@ -73,7 +70,6 @@ int main(int argc, char** argv) {
int BeamMPServerMain(MainArguments Arguments) { int BeamMPServerMain(MainArguments Arguments) {
setlocale(LC_ALL, "C"); setlocale(LC_ALL, "C");
Application::InitializeConsole(); Application::InitializeConsole();
Application::Console().Internal().set_prompt("");
ArgsParser Parser; ArgsParser Parser;
Parser.RegisterArgument({ "help" }, ArgsParser::NONE); Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
Parser.RegisterArgument({ "version" }, ArgsParser::NONE); Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
@@ -84,14 +80,16 @@ int BeamMPServerMain(MainArguments Arguments) {
return 1; return 1;
} }
if (Parser.FoundArgument({ "help" })) { if (Parser.FoundArgument({ "help" })) {
Application::Console().Internal().set_prompt("");
Application::Console().WriteRaw(sCommandlineArguments); Application::Console().WriteRaw(sCommandlineArguments);
return 0; return 0;
} }
if (Parser.FoundArgument({ "version" })) { if (Parser.FoundArgument({ "version" })) {
Application::Console().WriteRaw(fmt::format("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH)); Application::Console().Internal().set_prompt("");
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
return 0; return 0;
} }
std::string ConfigPath = "ServerConfig.toml"; std::string ConfigPath = "ServerConfig.toml";
if (Parser.FoundArgument({ "config" })) { if (Parser.FoundArgument({ "config" })) {
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" }); auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
@@ -114,42 +112,39 @@ int BeamMPServerMain(MainArguments Arguments) {
Application::SetSubsystemStatus("Main", Application::Status::Starting); Application::SetSubsystemStatus("Main", Application::Status::Starting);
SetupSignalHandlers();
beammp_infof("BeamMP Server v{} ({})", Application::ServerVersionString(), BEAMMP_GIT_HASH);
TConfig Config(ConfigPath);
if (Config.Failed()) {
beammp_info("Closing in 10 seconds");
// loop to make it possible to ctrl+c instead
Application::SleepSafeSeconds(5);
beammp_info("Closing in 5 seconds");
Application::SleepSafeSeconds(5);
Application::GracefullyShutdown();
return 1;
}
Application::Console().Internal().set_prompt("> ");
Application::Console().StartLoggingToFile(); Application::Console().StartLoggingToFile();
SetupSignalHandlers();
bool Shutdown = false; bool Shutdown = false;
Application::RegisterShutdownHandler([&Shutdown] { Application::RegisterShutdownHandler([&Shutdown] {
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown."); beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown); Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
Shutdown = true; Shutdown = true;
}); });
Application::RegisterShutdownHandler([] {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
});
TServer Server(Arguments.List); TServer Server(Arguments.List);
TConfig Config(ConfigPath);
auto LuaEngine = std::make_shared<TLuaEngine>(); auto LuaEngine = std::make_shared<TLuaEngine>();
LuaEngine->SetServer(&Server); LuaEngine->SetServer(&Server);
Application::Console().InitializeLuaConsole(*LuaEngine); Application::Console().InitializeLuaConsole(*LuaEngine);
if (Config.Failed()) {
beammp_info("Closing in 10 seconds");
// loop to make it possible to ctrl+c instead
for (size_t i = 0; i < 20; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return 1;
}
RegisterThread("Main"); RegisterThread("Main");
beammp_trace("Running in debug mode on a debug build"); beammp_trace("Running in debug mode on a debug build");
Sentry.SetupUser();
Sentry.PrintWelcome();
TResourceManager ResourceManager; TResourceManager ResourceManager;
TPPSMonitor PPSMonitor(Server); TPPSMonitor PPSMonitor(Server);
THeartbeatThread Heartbeat(ResourceManager, Server); THeartbeatThread Heartbeat(ResourceManager, Server);
@@ -158,9 +153,9 @@ int BeamMPServerMain(MainArguments Arguments) {
PPSMonitor.SetNetwork(Network); PPSMonitor.SetNetwork(Network);
Application::CheckForUpdates(); Application::CheckForUpdates();
TPluginMonitor PluginMonitor(fs::path(Application::GetSettingString(StrResourceFolder)) / "Server", LuaEngine); TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
if (Application::GetSettingBool(StrHTTPServerEnabled)) { if (Application::Settings.HTTPServerEnabled) {
Http::Server::THttpServerInstance HttpServerInstance {}; Http::Server::THttpServerInstance HttpServerInstance {};
} }
Submodule
+1
Submodule vcpkg added at 72010900b7
+19
View File
@@ -0,0 +1,19 @@
{
"name": "server",
"version-string": "0.1.0",
"dependencies": [
"fmt",
"doctest",
"boost-asio",
"boost-variant",
"boost-spirit",
"boost-uuid",
"cpp-httplib",
"toml11",
"libzip",
"rapidjson",
"nlohmann-json",
"openssl",
"sol2"
]
}