Compare commits

..
53 changed files with 1013 additions and 977 deletions

No files matched your search

+1
View File
@@ -1,6 +1,7 @@
--- ---
name: Bug report name: Bug report
about: Create a report to help us improve about: Create a report to help us improve
title: "[Bug] Enter issue title here"
labels: bug labels: bug
assignees: '' assignees: ''
+2 -1
View File
@@ -1,7 +1,8 @@
--- ---
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
labels: feature title: "[Feature Request]"
labels: enhancement
assignees: '' assignees: ''
--- ---
+67 -69
View File
@@ -2,33 +2,15 @@ name: Linux
on: [push] on: [push]
env: env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_FORCE_SYSTEM_BINARIES: 1
CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs: jobs:
x86_64-matrix: debian-11-build:
runs-on: ubuntu-22.04 runs-on: ubuntu-latest
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: ${{ matrix.distro }}:${{ matrix.version }} image: debian:11
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -47,59 +29,37 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh run: bash ./scripts/debian-11/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh run: bash ./scripts/debian-11/1-install-deps.sh
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh run: bash ./scripts/debian-11/3-build.sh
- name: Archive server artifact - name: Archive server artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64 name: BeamMP-Server-debian
path: ./bin/BeamMP-Server path: ./bin/BeamMP-Server
- name: Archive server debug info artifact - name: Build Tests
run: bash ./scripts/debian-11/3-build-tests.sh
- name: Archive server tests artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64 name: BeamMP-Server-debian-tests
path: ./bin/BeamMP-Server.debug path: ./bin/BeamMP-Server-tests
- name: Build Tests ubuntu-22-04-build:
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh runs-on: ubuntu-latest
- name: Install Runtime Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
- name: Test
run: ./bin/BeamMP-Server-tests
arm64-matrix:
runs-on: [Linux, ARM64]
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: ${{ matrix.distro }}:${{ matrix.version }} image: ubuntu:22.04
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -118,35 +78,73 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh 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 - name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh run: bash ./scripts/ubuntu-22.04/3-build.sh
- name: Archive server artifact - name: Archive server artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64 name: BeamMP-Server-ubuntu
path: ./bin/BeamMP-Server path: ./bin/BeamMP-Server
- name: Archive server debug info artifact - name: Build Tests
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
- name: Archive server tests artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64 name: BeamMP-Server-ubuntu-tests
path: ./bin/BeamMP-Server.debug path: ./bin/BeamMP-Server-tests
- name: Build Tests run-debian-11-tests:
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh 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 - name: Install Runtime Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh run: |
apt-get update -y
apt-get install -y liblua5.3-0
- name: Test - name: Test
run: ./bin/BeamMP-Server-tests 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
+27 -73
View File
@@ -7,8 +7,6 @@ on:
env: env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs: jobs:
create-release: create-release:
@@ -28,30 +26,18 @@ jobs:
draft: false draft: false
prerelease: true prerelease: true
body: | body: |
Files included in this release are: Files included in this release:
- `BeamMP-Server.$DISTRO.$DISTROVERSION.$ARCH` for linux builds, for example `BeamMP-Server.debian.11.x86_64` for the Debian 11 build for x86_64. All require `liblua5.3` to be installed. - `BeamMP-Server.exe` is the windows build.
- `BeamMP-Server.exe` for the Windows build (x86_64). You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this. - `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`.
x86_64-matrix: upload-release-files-debian-11:
name: Build and upload Debian 11 Release Files
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
needs: create-release needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: ${{ matrix.distro }}:${{ matrix.version }} image: debian:11
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -70,16 +56,21 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh run: bash ./scripts/debian-11/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh run: bash ./scripts/debian-11/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh run: bash ./scripts/debian-11/3-build.sh
- name: Upload Release Asset - name: Upload Release Asset
id: upload-release-asset id: upload-release-asset
@@ -87,44 +78,18 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server asset_path: ./bin/BeamMP-Server
asset_name: BeamMP-Server-debian
asset_content_type: application/x-elf asset_content_type: application/x-elf
- name: Upload Debug Info upload-release-files-ubuntu-22-04:
id: upload-debug-info name: Build and upload Ubuntu 22.04 Release Files
uses: actions/upload-release-asset@v1 runs-on: ubuntu-22.04
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_content_type: application/x-elf
arm64-matrix:
runs-on: [Linux, ARM64]
needs: create-release needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
container: container:
image: ${{ matrix.distro }}:${{ matrix.version }} image: ubuntu:22.04
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -143,16 +108,16 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh run: bash ./scripts/ubuntu-22.04/3-build.sh
- name: Upload Release Asset - name: Upload Release Asset
id: upload-release-asset id: upload-release-asset
@@ -160,20 +125,9 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server asset_path: ./bin/BeamMP-Server
asset_content_type: application/x-elf asset_name: BeamMP-Server-ubuntu
- name: Upload Debug Info
id: upload-debug-info
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_content_type: application/x-elf asset_content_type: application/x-elf
upload-release-files-windows: upload-release-files-windows:
@@ -209,6 +163,6 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/Release/BeamMP-Server.exe asset_path: ./bin/BeamMP-Server.exe
asset_name: BeamMP-Server.exe asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable asset_content_type: application/vnd.microsoft.portable-executable
+1 -2
View File
@@ -5,7 +5,6 @@ on: [push]
env: env:
VCPKG_DEFAULT_TRIPLET: x64-windows-static VCPKG_DEFAULT_TRIPLET: x64-windows-static
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release"
jobs: jobs:
windows-build: windows-build:
@@ -39,5 +38,5 @@ jobs:
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-windows name: BeamMP-Server-windows
path: ./bin/Release/BeamMP-Server.exe path: ./bin/BeamMP-Server.exe
+3 -6
View File
@@ -48,7 +48,6 @@ set(PRJ_HEADERS
include/TScopedTimer.h include/TScopedTimer.h
include/TServer.h include/TServer.h
include/VehicleData.h include/VehicleData.h
include/Env.h
) )
# add all source files (.cpp) to this, except the one with main() # add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES set(PRJ_SOURCES
@@ -71,7 +70,6 @@ set(PRJ_SOURCES
src/TScopedTimer.cpp src/TScopedTimer.cpp
src/TServer.cpp src/TServer.cpp
src/VehicleData.cpp src/VehicleData.cpp
src/Env.cpp
) )
find_package(Lua REQUIRED) find_package(Lua REQUIRED)
@@ -128,10 +126,9 @@ include(FindThreads)
# enables compile_commands.json for clang-related tools (such as the clang LS) # enables compile_commands.json for clang-related tools (such as the clang LS)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# build release builds by default (if not specified otherwise) # build debug builds by default (if not specified otherwise)
if(NOT DEFINED CMAKE_BUILD_TYPE) if(NOT CMAKE_BUILD_TYPE)
message(NOTICE "No build type specified, defaulting to 'Release'") set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_BUILD_TYPE "Release")
endif() endif()
if(UNIX) if(UNIX)
+156
View File
@@ -0,0 +1,156 @@
# v3.1.1
- FIXED bug which caused GetPlayerIdentifiers, GetPlayerName, etc not to work in `onPlayerDisconnect`
- FIXED some issues which could cause the server to crash when receiving malformed data
- FIXED a bug which caused a server to crash during authentication when receiving malformed data
- FIXED minor vulnerability in chat message handling
- FIXED a minor formatting bug in the `status` command
# v3.1.0
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
- ADDED Util.JsonEncode() and Util.JsonDecode(), which turn lua tables into json and vice-versa
- ADDED FS.ListFiles and FS.ListDirectories
- ADDED onFileChanged event, triggered when a server plugin file changes
- ADDED MP.GetPositionRaw(), which can be used to retrieve the latest position packet per player, per vehicle
- ADDED error messages to some lua functions
- ADDED HOME and END button working in console
- ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON
- ADDED identifiers (beammp id, ip) to onPlayerAuth (4th argument)
- ADDED more network debug logging
- CHANGED all networking to be more stable, performant, and safe
- FIXED `ip` in MP.GetPlayerIdentifiers
- FIXED issue with client->server events which contain `:`
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
- FIXED onInit not being called on hot-reload
- FIXED incorrect timing calculation of Lua EventTimer loop
- FIXED bug which caused hot-reload not to report syntax errors
- FIXED missing error messages on some event handler calls
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
- FIXED server not handling binary UDP packets properly
- REMOVED "Backend response failed to parse as valid json" message
# v3.0.2
- ADDED Periodic update message if a new server is released
- ADDED Config setting for the IP the http server listens on
- CHANGED Default MaxPlayers to 8
- CHANGED Default http server listen IP to localhost
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
- FIXED Lua result queue handling not checking all results
- FIXED bug which caused ServerConfig.toml to generate incorrectly
# v3.0.1
- ADDED Backup URLs to UpdateCheck (will fail less often now)
- ADDED console cursor left and right movement (with arrow keys) and working HOME and END key (via github.com/lionkor/commandline)
- FIXED infinite snowmen / infinite unicycle spawning bug
- FIXED a bug where, when run with --working-directory, the Server.log would still be in the original directory
- FIXED a bug which could cause the plugin reload thread to spin at 100% if the reloaded plugin's didn't terminate
- FIXED an issue which would cause servers to crash on mod download via SIGPIPE on POSIX
- FIXED an issue which would cause servers to crash when checking if a vehicle is a unicycle
# v3.0.0
- CHANGED entire plugin Lua implementation (rewrite)
- CHANGED moved *almost all* Lua functions into MP.\*
- CHANGED console to use a custom language (type `help`, `list`, or `status`!)
- CHANGED all files of a Lua plugin to share a Lua state (no more state-per-file)
- ADDED many new Lua API functions, which can be found at <https://wiki.beammp.com/en/Scripting/functions>
- ADDED Commandline options. Run with `--help` to see all options.
- ADDED HTTP(S) Server (OpenAPI spec coming soon!)
- ADDED plugin directories to `package.path` and `package.cpath` before `onInit`
- ADDED ability to add `PluginConfig.toml` to your plugin folder to change some settings
- ADDED ability to share a lua state with other plugins via `StateId` setting in `PluginConfig.toml`
- ADDED ability to see name-to-thread-ID association in debug mode
- ADDED dumping tables with `print()` (try it with `print(MP)`)
- ADDED `MP.GetOSName()`, `MP.CreateTimer()`, `MP.GetLuaMemoryUsage()` and many more (see <https://wiki.beammp.com/en/Scripting/functions>)
- ADDED `MP.Settings` table to make usage of `MP.Set()` easier
- ADDED `FS.*` table with common filesystem operations (do `print(FS)` to see them!)
- FIXED i/o thread spin when stdout is /dev/null on linux
- FIXED removed extra whitespace infront of onChatMessage message
# v2.3.3
- CHANGED servers to be private by default
# v2.3.2
- ADDED Ctrl+C causes a graceful shutdown on windows (did already on linux)
- ADDED more meaningful shutdown messages
- ADDED even better backend connection error reporting
- ADDED `SendErrors` config in `ServerConfig.toml` to opt-out of error reporting
- ADDED hard-shutdown if Ctrl+C pressed 3 times
- FIXED issue with shells like bash being unusable after server exit
# v2.3.1
- CHANGED join/sync timeout to 20 minutes, players wont drop if loading takes >5 mins
# v2.3.0
- ADDED version check - the server will now let you know when a new release is out
- ADDED logging of various errors, crashes and exceptions to the backend
- ADDED chat messages are now logged to the server console as [CHAT]
- ADDED debug message telling you when the server heartbeats to the backend
- REMOVED various [DEBUG] messages which were confusing (such as "breaking client loop")
- FIXED various crashes and issues with handling unexpected backend responses
- FIXED minor bugs due to code correctness
# v2.2.0
- FIXED major security flaw
- FIXED minor bugs
# v2.1.4
- ADDED debug heartbeat print
- ADDED kicking every player before shutdown
- FIXED rare bug which led to violent crash
- FIXED minor bugs
# v2.1.3
- FIXED Lua events not cancelling properly on Linux
# v2.1.2
- CHANGED default map to gridmap v2
- FIXED version number display
# v2.1.1
# v2.1.0 (pre-v2.1.1)
# v2.0.4 (pre-v2.1.0)
- REMOVED boost as a runtime dependency
- FIXED Lua plugins on Linux
- FIXED console history on Windows
- CHANGED to new config format TOML
# v2.0.3
- WORKAROUND for timeout bug / ghost player bug
- FIXED 100% CPU spin when stdin is /dev/null.
# v2.0.2
- ADDED fully new commandline
- ADDED new backend
- ADDED automated build system
- ADDED lua GetPlayerIdentifiers
- ADDED lots of debug info
- ADDED better POSTing and GETing
- ADDED a license
- FIXED ghost players in player list issue
- FIXED ghost vehicle after joining issue
- FIXED missing vehicle after joining issue
- FIXED a lot of desync issues
- FIXED some memory leaks
- FIXED various crashes
- FIXED various data-races
- FIXED some linux-specific crashes
- FIXED some linux-specific issues
- FIXED bug which caused kicking to be logged as leaving
- FIXED various internal developer quality-of-life things
+113 -22
View File
@@ -6,12 +6,13 @@
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/). This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com). The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
**For Linux, you __need__ the runtime dependencies, which are listed below under [Runtime Dependencies](#runtime-dependencies)** **For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
## Support + Contact ## Support + Contact
Feel free to ask any questions via the following channels: Feel free to ask any questions via the following channels:
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
- **Discord**: [click for invite](https://discord.gg/beammp) - **Discord**: [click for invite](https://discord.gg/beammp)
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33) - **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
@@ -42,7 +43,7 @@ We only allow building unmodified (original) source code for public use. `master
## Supported Operating Systems ## Supported Operating Systems
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine. The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and sometimes Linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
Recommended compilers: MSVC, GCC, CLANG. Recommended compilers: MSVC, GCC, CLANG.
@@ -50,37 +51,127 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
## Build Instructions ## Build Instructions
On Linux, you need some dependencies to **build** the server (on Windows, you don't): **__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__**
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
### Prerequisites
#### Windows
There are **no runtime libraries** needed for Windows.
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
Dependencies for **Windows** can be installed with `vcpkg`.
These are:
``` ```
liblua5.3-dev curl zip unzip tar cmake make git g++ lua zlib rapidjson openssl websocketpp curl
``` ```
The triplet we use for releases is `x64-windows-static`.
You can install these with your distribution's package manager. You will need sudo or need root for ONLY this step. #### Linux
The names of each package may change depending on your platform. We recommend Ubuntu 22.04 or Arch Linux. Any Linux distribution will work, but you have to figure out the package names yourself (please feel free to PR in a change to this README with that info).
If you are building for ARM (like aarch64), you need to run `export VCPKG_FORCE_SYSTEM_BINARIES=1` before the following commands. ##### Runtime Dependencies
You can build on **Windows, Linux** or other platforms by following these steps:
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
2. Go into the directory `cd BeamMP-Server`.
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
5. Your executable can be found in `bin/`.
When you make changes to the code, you only have to run step 4 again.
### Runtime Dependencies
These are needed to *run* the server. These are needed to *run* the server.
Debian, Ubuntu and friends: `liblua5.3-0` <details>
<summary>
Ubuntu 22.04
</summary>
Other Linux distros: `liblua` of *some kind*. `apt-get install` the following libraries:
```
liblua5.3-0
libssl3
curl
```
</details>
Windows: No libraries. <details>
<summary>
Arch Linux
</summary>
`pacman -Syu` the following libraries:
```
lua53
openssl
curl
```
</details>
##### Build Dependencies
These are needed for you to *build* the server, in addition to the [runtime dependencies](#runtime-dependencies).
<details>
<summary>
Ubuntu 22.04
</summary>
`apt-get install` the following libraries and programs:
```
git
libz-dev
rapidjson-dev
liblua5.3-dev
libssl-dev
libwebsocketpp-dev
libcurl4-openssl-dev
cmake
g++-10
libboost1.74-all-dev
libssl3
curl
```
</details>
<details>
<summary>
Arch Linux
</summary>
`pacman -Syu` the following libraries and programs:
```
lua53
openssl
curl
git
cmake
g++
zlib
boost
websocketpp
```
</details>
#### macOS
Dependencies for **macOS** can be installed with homebrew.
```
brew install lua@5.3 rapidjson websocketpp cmake openssl@1.1
```
Some packages are included in **macOS** but you might want to install homebrew versions.
```
brew install curl zlib git make
```
### How to build
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
1. Make sure you have all [prerequisites](#prerequisites) installed
2. Clone the repository in a location of your choice with `git clone https://github.com/BeamMP/BeamMP-Server` .
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
4. Checkout the branch or tag of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`). This may take some time, and will update all submodules and prepare the build.
7. Run `make -j` . This step will take some time and will use a lot of CPU and RAM. Remove the `-j` if you run out of memory. *If you change something in the source code, you only have to re-run this step.*
8. You now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
## Support ## Support
The BeamMP project is supported by community donations via our [Patreon](https://www.patreon.com/BeamMP). This brings perks such as Patreon-only channels on our Discord, early access to new updates, and more server keys. The BeamMP project is supported by community donations via our [Patreon](https://www.patreon.com/BeamMP). This brings perks such as Patreon-only channels on our Discord, early access to new updates, and more server keys.
+60 -32
View File
@@ -10,8 +10,6 @@
#include "BoostAliases.h" #include "BoostAliases.h"
#include "Common.h" #include "Common.h"
#include "Compat.h" #include "Compat.h"
#include "RWMutex.h"
#include "Sync.h"
#include "VehicleData.h" #include "VehicleData.h"
class TServer; class TServer;
@@ -30,6 +28,11 @@ class TClient final {
public: public:
using TSetOfVehicleData = std::vector<TVehicleData>; using TSetOfVehicleData = std::vector<TVehicleData>;
struct TVehicleDataLockPair {
TSetOfVehicleData* VehicleData;
std::unique_lock<std::mutex> Lock;
};
TClient(TServer& Server, ip::tcp::socket&& Socket); TClient(TServer& Server, ip::tcp::socket&& Socket);
TClient(const TClient&) = delete; TClient(const TClient&) = delete;
~TClient(); ~TClient();
@@ -38,51 +41,76 @@ public:
void AddNewCar(int Ident, const std::string& Data); void AddNewCar(int Ident, const std::string& Data);
void SetCarData(int Ident, const std::string& Data); void SetCarData(int Ident, const std::string& Data);
void SetCarPosition(int Ident, const std::string& Data); void SetCarPosition(int Ident, const std::string& Data);
TVehicleDataLockPair GetAllCars();
void SetName(const std::string& NewName) { Name = NewName; } void SetName(const std::string& Name) { mName = Name; }
void SetRoles(const std::string& NewRole) { Role = NewRole; } void SetRoles(const std::string& Role) { mRole = Role; }
void SetIdentifier(const std::string& key, const std::string& value); void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
std::string GetCarData(int Ident); std::string GetCarData(int Ident);
std::string GetCarPositionRaw(int Ident); std::string GetCarPositionRaw(int Ident);
bool IsDisconnected() const { return !TCPSocket->is_open(); } void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
void Disconnect(std::string_view Reason);
bool IsDisconnected() const { return !mSocket.is_open(); }
// locks // locks
void DeleteCar(int Ident); void DeleteCar(int Ident);
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
[[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; }
void SetID(int ID) { mID = ID; }
[[nodiscard]] int GetOpenCarID() const; [[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const; [[nodiscard]] int GetCarCount() const;
void ClearCars(); void ClearCars();
[[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::vector<uint8_t>& Packet); void EnqueuePacket(const std::vector<uint8_t>& Packet);
void SetIsConnected(bool NewIsConnected) { IsConnected = NewIsConnected; } [[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
[[nodiscard]] TServer& Server() const; [[nodiscard]] TServer& Server() const;
void UpdatePingTime(); void UpdatePingTime();
int SecondsSinceLastPing(); int SecondsSinceLastPing();
Sync<bool> IsConnected = false;
Sync<bool> IsSynced = false;
Sync<bool> IsSyncing = false;
Sync<std::unordered_map<std::string, std::string>> Identifiers;
Sync<ip::tcp::socket> TCPSocket;
Sync<ip::tcp::socket> DownSocket;
Sync<ip::udp::endpoint> UDPAddress {};
Sync<int> UnicycleID = -1;
Sync<std::string> Role;
Sync<std::string> DID;
Sync<int> ID = -1;
Sync<bool> IsGuest = false;
Sync<std::string> Name = std::string("Unknown Client");
Sync<TSetOfVehicleData> VehicleData;
Sync<SparseArray<std::string>> VehiclePosition;
Sync<std::queue<std::vector<uint8_t>>> MissedPacketsQueue;
Sync<std::chrono::time_point<std::chrono::high_resolution_clock>> LastPingTime;
friend class TNetwork;
private: private:
/// ONLY call after the client has been cleaned up, all cars deleted, etc.
void CloseSockets(std::string_view Reason);
void InsertVehicle(int ID, const std::string& Data); void InsertVehicle(int ID, const std::string& Data);
TServer& mServer; TServer& mServer;
bool mIsConnected = false;
bool mIsSynced = false;
bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex;
std::queue<std::vector<uint8_t>> mPacketsSync;
std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex;
mutable std::mutex mVehiclePositionMutex;
TSetOfVehicleData mVehicleData;
SparseArray<std::string> mVehiclePosition;
std::string mName = "Unknown Client";
ip::tcp::socket mSocket;
ip::tcp::socket mDownSocket;
ip::udp::endpoint mUDPAddress {};
int mUnicycleID = -1;
std::string mRole;
std::string mDID;
int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
}; };
std::optional<std::shared_ptr<TClient>> GetClient(class TServer& Server, int ID); std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
+6 -7
View File
@@ -43,7 +43,6 @@ public:
struct TSettings { struct TSettings {
std::string ServerName { "BeamMP Server" }; std::string ServerName { "BeamMP Server" };
std::string ServerDesc { "BeamMP Default Description" }; std::string ServerDesc { "BeamMP Default Description" };
std::string ServerTags { "Freeroam" };
std::string Resource { "Resources" }; std::string Resource { "Resources" };
std::string MapName { "/levels/gridmap_v2/info.json" }; std::string MapName { "/levels/gridmap_v2/info.json" };
std::string Key {}; std::string Key {};
@@ -76,7 +75,7 @@ public:
static void RegisterShutdownHandler(const TShutdownHandler& Handler); static void RegisterShutdownHandler(const TShutdownHandler& Handler);
// Causes all threads to finish up and exit gracefull gracefully // Causes all threads to finish up and exit gracefull gracefully
static void GracefullyShutdown(); static void GracefullyShutdown();
static TConsole& Console() { return mConsole; } static TConsole& Console() { return *mConsole; }
static std::string ServerVersionString(); static std::string ServerVersionString();
static const Version& ServerVersion() { return mVersion; } static const Version& ServerVersion() { return mVersion; }
static uint8_t ClientMajorVersion() { return 2; } static uint8_t ClientMajorVersion() { return 2; }
@@ -102,7 +101,9 @@ public:
static void SleepSafeSeconds(size_t Seconds); static void SleepSafeSeconds(size_t Seconds);
static void InitializeConsole() { static void InitializeConsole() {
mConsole.InitializeCommandline(); if (!mConsole) {
mConsole = std::make_unique<TConsole>();
}
} }
enum class Status { enum class Status {
@@ -128,17 +129,15 @@ private:
static inline SystemStatusMap mSystemStatusMap {}; static inline SystemStatusMap mSystemStatusMap {};
static inline std::mutex mSystemStatusMapMutex {}; static inline std::mutex mSystemStatusMapMutex {};
static inline std::string mPPS; static inline std::string mPPS;
static inline TConsole mConsole; static inline std::unique_ptr<TConsole> mConsole;
static inline std::shared_mutex mShutdownMtx {}; static inline std::shared_mutex mShutdownMtx {};
static inline bool mShutdown { false }; static inline bool mShutdown { false };
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, 2 }; static inline Version mVersion { 3, 1, 2 };
}; };
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
std::string ThreadName(bool DebugModeOverride = false); std::string ThreadName(bool DebugModeOverride = false);
void RegisterThread(const std::string& str); void RegisterThread(const std::string& str);
#define RegisterThreadAuto() RegisterThread(__func__) #define RegisterThreadAuto() RegisterThread(__func__)
-16
View File
@@ -1,16 +0,0 @@
#pragma once
#include <optional>
#include <string>
namespace Env {
enum class Key {
// provider settings
PROVIDER_UPDATE_MESSAGE,
};
std::optional<std::string> Get(Key key);
std::string_view ToString(Key key);
}
-9
View File
@@ -1,9 +0,0 @@
#pragma once
#include <boost/thread/synchronized_value.hpp>
/// This header provides convenience aliases for synchronization primitives.
template<typename T>
using Sync = boost::synchronized_value<T>;
+3 -4
View File
@@ -22,12 +22,11 @@ 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, const std::string_view& Env, std::string& OutValue); 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, const std::string_view& Env, bool& 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, const std::string_view& Env, int& OutValue); void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
void ParseOldFormat(); void ParseOldFormat();
std::string TagsAsPrettyArray() const;
bool IsDefault(); bool IsDefault();
bool mFailed { false }; bool mFailed { false };
std::string mConfigFileName; std::string mConfigFileName;
+2 -5
View File
@@ -17,15 +17,12 @@ class TConsole {
public: public:
TConsole(); TConsole();
// Initializes the commandline app to take over I/O
void InitializeCommandline();
void Write(const std::string& str); void Write(const std::string& str);
void WriteRaw(const std::string& str); void WriteRaw(const std::string& str);
void InitializeLuaConsole(TLuaEngine& Engine); void InitializeLuaConsole(TLuaEngine& Engine);
void BackupOldLog(); void BackupOldLog();
void StartLoggingToFile(); void StartLoggingToFile();
Commandline& Internal() { return *mCommandline; } Commandline& Internal() { return mCommandline; }
private: private:
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false); void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
@@ -59,7 +56,7 @@ private:
{ "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::unique_ptr<Commandline> mCommandline { nullptr }; Commandline mCommandline;
std::vector<std::string> mCachedLuaHistory; std::vector<std::string> mCachedLuaHistory;
std::vector<std::string> mCachedRegularHistory; std::vector<std::string> mCachedRegularHistory;
TLuaEngine* mLuaEngine { nullptr }; TLuaEngine* mLuaEngine { nullptr };
+4 -2
View File
@@ -18,6 +18,9 @@
#include <vector> #include <vector>
#define SOL_ALL_SAFETIES_ON 1 #define SOL_ALL_SAFETIES_ON 1
#define SOL_USER_C_ASSERT SOL_ON
#define SOL_C_ASSERT(...) \
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__)
#include <sol/sol.hpp> #include <sol/sol.hpp>
using TLuaStateId = std::string; using TLuaStateId = std::string;
@@ -221,8 +224,6 @@ private:
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue(); std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue(); std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
sol::table Lua_JsonDecode(const std::string& str);
private: private:
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs); sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs); sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
@@ -232,6 +233,7 @@ private:
sol::table Lua_GetPlayerVehicles(int ID); sol::table Lua_GetPlayerVehicles(int ID);
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID); std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port); sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
sol::table Lua_JsonDecode(const std::string& str);
int Lua_GetPlayerIDByName(const std::string& Name); int Lua_GetPlayerIDByName(const std::string& Name);
sol::table Lua_FS_ListFiles(const std::string& Path); sol::table Lua_FS_ListFiles(const std::string& Path);
sol::table Lua_FS_ListDirectories(const std::string& Path); sol::table Lua_FS_ListDirectories(const std::string& Path);
+7 -8
View File
@@ -19,9 +19,6 @@ public:
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock); std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
std::vector<uint8_t> TCPRcv(TClient& c); std::vector<uint8_t> TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R); void ClientKick(TClient& c, const std::string& R);
void Disconnect(const std::shared_ptr<TClient>& ClientPtr);
void Disconnect(const std::weak_ptr<TClient>& ClientPtr);
void Disconnect(TClient& Client);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c); [[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(TConnection&& client); void Identify(TConnection&& client);
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection); std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
@@ -44,13 +41,15 @@ private:
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);
void OnConnect(const std::weak_ptr<TClient>& c); void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::shared_ptr<TClient>& c); void TCPClient(const std::weak_ptr<TClient>& c);
void Looper(const std::shared_ptr<TClient>& c); void Looper(const std::weak_ptr<TClient>& c);
int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
void Parse(TClient& c, const std::vector<uint8_t>& Packet); void Parse(TClient& c, const std::vector<uint8_t>& Packet);
void SendFile(TClient& c, const std::string& Name); void SendFile(TClient& c, const std::string& Name);
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);
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);
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::string HashPassword(const std::string& str);
+3 -7
View File
@@ -22,18 +22,14 @@ 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 RemoveClient(TClient&);
// in Fn, return true to continue, return false to break // in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(const std::shared_ptr<TClient>&)> Fn); void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
size_t ClientCount() const; size_t ClientCount() const;
void GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network); static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data); static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; } RWMutex& GetClientMutex() const { return mClientsMutex; }
// thread-safe ID lookup & claim
void ClaimFreeIDFor(TClient& Client);
const TScopedTimer UptimeTimer; const TScopedTimer UptimeTimer;
// asio io context // asio io context
@@ -47,7 +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);
void HandlePosition(TClient& c, const std::string& Packet); static void HandlePosition(TClient& c, const std::string& Packet);
}; };
struct BufferView { struct BufferView {
+1 -1
View File
@@ -4,4 +4,4 @@ set -ex
apt-get update -y apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
+1 -3
View File
@@ -2,6 +2,4 @@
set -ex set -ex
./vcpkg/bootstrap-vcpkg.sh 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
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
-5
View File
@@ -3,8 +3,3 @@
set -ex set -ex
cmake --build bin --parallel -t BeamMP-Server cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
-7
View File
@@ -1,7 +0,0 @@
#!/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++ ninja-build
-7
View File
@@ -1,7 +0,0 @@
#!/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
-7
View File
@@ -1,7 +0,0 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
-10
View File
@@ -1,10 +0,0 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
@@ -1,8 +0,0 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
-7
View File
@@ -1,7 +0,0 @@
#!/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++ ninja-build
-7
View File
@@ -1,7 +0,0 @@
#!/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
-7
View File
@@ -1,7 +0,0 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
-10
View File
@@ -1,10 +0,0 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
@@ -1,8 +0,0 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+1 -1
View File
@@ -4,4 +4,4 @@ set -ex
apt-get update -y apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
+1 -3
View File
@@ -2,6 +2,4 @@
set -ex set -ex
./vcpkg/bootstrap-vcpkg.sh 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
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
-5
View File
@@ -3,8 +3,3 @@
set -ex set -ex
cmake --build bin --parallel -t BeamMP-Server cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
Executable → Regular
-2
View File
@@ -2,6 +2,4 @@
set -ex set -ex
./vcpkg/vcpkg add port lua
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
+1 -1
View File
@@ -2,4 +2,4 @@
set -ex set -ex
cmake --build bin --parallel -t BeamMP-Server --config Release cmake --build bin --parallel -t BeamMP-Server
+49 -50
View File
@@ -7,28 +7,29 @@
void TClient::DeleteCar(int Ident) { void TClient::DeleteCar(int Ident) {
// TODO: Send delete packets // TODO: Send delete packets
auto VehData = VehicleData.synchronize(); std::unique_lock lock(mVehicleDataMutex);
auto iter = std::find_if(VehData->begin(), VehData->end(), [&](auto& elem) { auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
return Ident == elem.ID(); return Ident == elem.ID();
}); });
if (iter != VehData->end()) { if (iter != mVehicleData.end()) {
VehData->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)");
} }
} }
void TClient::ClearCars() { void TClient::ClearCars() {
VehicleData->clear(); std::unique_lock lock(mVehicleDataMutex);
mVehicleData.clear();
} }
int TClient::GetOpenCarID() const { int TClient::GetOpenCarID() const {
int OpenID = 0; int OpenID = 0;
bool found; bool found;
auto VehData = VehicleData.synchronize(); std::unique_lock lock(mVehicleDataMutex);
do { do {
found = true; found = true;
for (auto& v : *VehData) { for (auto& v : mVehicleData) {
if (v.ID() == OpenID) { if (v.ID() == OpenID) {
OpenID++; OpenID++;
found = false; found = false;
@@ -39,49 +40,46 @@ int TClient::GetOpenCarID() const {
} }
void TClient::AddNewCar(int Ident, const std::string& Data) { void TClient::AddNewCar(int Ident, const std::string& Data) {
VehicleData->emplace_back(Ident, Data); std::unique_lock lock(mVehicleDataMutex);
mVehicleData.emplace_back(Ident, Data);
}
TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
} }
std::string TClient::GetCarPositionRaw(int Ident) { std::string TClient::GetCarPositionRaw(int Ident) {
std::unique_lock lock(mVehiclePositionMutex);
try { try {
return VehiclePosition->at(size_t(Ident)); return mVehiclePosition.at(size_t(Ident));
} catch (const std::out_of_range& oor) { } catch (const std::out_of_range& oor) {
beammp_debugf("GetCarPositionRaw failed for id {}, as that car doesn't exist on client id {}: {}", Ident, int(ID), oor.what());
return ""; return "";
} }
return "";
} }
void TClient::CloseSockets(std::string_view Reason) { void TClient::Disconnect(std::string_view Reason) {
auto LockedSocket = TCPSocket.synchronize(); beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
beammp_debugf("Disconnecting client {} for reason: {}", int(ID), Reason);
boost::system::error_code ec; boost::system::error_code ec;
LockedSocket->shutdown(socket_base::shutdown_both, ec); mSocket.shutdown(socket_base::shutdown_both, ec);
if (ec) { if (ec) {
beammp_debugf("Failed to shutdown client socket of client {}: {}", ID.get(), ec.message()); beammp_debugf("Failed to shutdown client socket: {}", ec.message());
} }
LockedSocket->close(ec); mSocket.close(ec);
if (ec) { if (ec) {
beammp_debugf("Failed to close client socket of client {}: {}", ID.get(), ec.message()); beammp_debugf("Failed to close client socket: {}", ec.message());
}
DownSocket->shutdown(socket_base::shutdown_both, ec);
if (ec) {
beammp_debugf("Failed to shutdown client download socket of client {}: {}", ID.get(), ec.message());
}
DownSocket->close(ec);
if (ec) {
beammp_debugf("Failed to close client download socket of client {}: {}", ID.get(), ec.message());
} }
} }
void TClient::SetCarPosition(int Ident, const std::string& Data) { void TClient::SetCarPosition(int Ident, const std::string& Data) {
// ugly but this is c++ so std::unique_lock lock(mVehiclePositionMutex);
VehiclePosition->operator[](size_t(Ident)) = Data; mVehiclePosition[size_t(Ident)] = Data;
} }
std::string TClient::GetCarData(int Ident) { std::string TClient::GetCarData(int Ident) {
{ // lock { // lock
auto Lock = VehicleData.synchronize(); std::unique_lock lock(mVehicleDataMutex);
for (auto& v : *Lock) { for (auto& v : mVehicleData) {
if (v.ID() == Ident) { if (v.ID() == Ident) {
return v.Data(); return v.Data();
} }
@@ -93,8 +91,8 @@ std::string TClient::GetCarData(int Ident) {
void TClient::SetCarData(int Ident, const std::string& Data) { void TClient::SetCarData(int Ident, const std::string& Data) {
{ // lock { // lock
auto Lock = VehicleData.synchronize(); std::unique_lock lock(mVehicleDataMutex);
for (auto& v : *Lock) { for (auto& v : mVehicleData) {
if (v.ID() == Ident) { if (v.ID() == Ident) {
v.SetData(Data); v.SetData(Data);
return; return;
@@ -105,7 +103,7 @@ void TClient::SetCarData(int Ident, const std::string& Data) {
} }
int TClient::GetCarCount() const { int TClient::GetCarCount() const {
return int(VehicleData->size()); return int(mVehicleData.size());
} }
TServer& TClient::Server() const { TServer& TClient::Server() const {
@@ -113,42 +111,43 @@ TServer& TClient::Server() const {
} }
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) { void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
MissedPacketsQueue->push(Packet); std::unique_lock Lock(mMissedPacketsMutex);
mPacketsSync.push(Packet);
} }
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket) TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
: TCPSocket(std::move(Socket)) : mServer(Server)
, DownSocket(ip::tcp::socket(Server.IoCtx())) , mSocket(std::move(Socket))
, LastPingTime(std::chrono::high_resolution_clock::now()) , mDownSocket(ip::tcp::socket(Server.IoCtx()))
, mServer(Server) { , mLastPingTime(std::chrono::high_resolution_clock::now()) {
} }
TClient::~TClient() { TClient::~TClient() {
beammp_debugf("client destroyed: {} ('{}')", ID.get(), Name.get()); beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
} }
void TClient::UpdatePingTime() { void TClient::UpdatePingTime() {
LastPingTime = std::chrono::high_resolution_clock::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>(
std::chrono::high_resolution_clock::now() - LastPingTime.get()) std::chrono::high_resolution_clock::now() - mLastPingTime)
.count(); .count();
return int(seconds); return int(seconds);
} }
std::optional<std::shared_ptr<TClient>> GetClient(TServer& Server, int ID) { std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::optional<std::shared_ptr<TClient>> MaybeClient { std::nullopt }; std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClient([ID, &MaybeClient](const auto& Client) -> bool { Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
if (Client->ID.get() == ID) { ReadLock Lock(Server.GetClientMutex());
MaybeClient = Client; if (!CPtr.expired()) {
return false; auto C = CPtr.lock();
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
} }
return true; return true;
}); });
return MaybeClient; return MaybeClient;
} }
void TClient::SetIdentifier(const std::string& key, const std::string& value) {
// I know this is bad, but what can ya do
Identifiers->operator[](key) = value;
}
+2 -18
View File
@@ -1,10 +1,8 @@
#include "Common.h" #include "Common.h"
#include "Env.h"
#include "TConsole.h" #include "TConsole.h"
#include <array> #include <array>
#include <charconv> #include <charconv>
#include <fmt/core.h>
#include <iostream> #include <iostream>
#include <map> #include <map>
#include <regex> #include <regex>
@@ -203,11 +201,8 @@ void Application::CheckForUpdates() {
auto MyVersion = ServerVersion(); auto MyVersion = ServerVersion();
auto RemoteVersion = Version(VersionStrToInts(Response)); auto RemoteVersion = Version(VersionStrToInts(Response));
if (IsOutdated(MyVersion, RemoteVersion)) { if (IsOutdated(MyVersion, RemoteVersion)) {
std::string RealVersionString = std::string("v") + RemoteVersion.AsString(); std::string RealVersionString = RemoteVersion.AsString();
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server"; beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET));
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
} else { } else {
if (FirstTime) { if (FirstTime) {
beammp_info("Server up-to-date!"); beammp_info("Server up-to-date!");
@@ -353,14 +348,3 @@ std::string GetPlatformAgnosticErrorString() {
return "(no human-readable errors on this platform)"; return "(no human-readable errors on this platform)";
#endif #endif
} }
// TODO: add unit tests to SplitString
void SplitString(const std::string& str, const char delim, std::vector<std::string>& out) {
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
-20
View File
@@ -1,20 +0,0 @@
#include "Env.h"
#include <optional>
std::optional<std::string> Env::Get(Env::Key key) {
auto StrKey = ToString(key);
auto Value = std::getenv(StrKey.data());
if (!Value || std::string_view(Value).empty()) {
return std::nullopt;
}
return Value;
}
std::string_view Env::ToString(Env::Key key) {
switch (key) {
case Key::PROVIDER_UPDATE_MESSAGE:
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
break;
}
return "";
}
+16 -17
View File
@@ -120,14 +120,14 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
return { true, "" }; return { true, "" };
} else { } else {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
if (!MaybeClient) { 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" };
} }
auto c = MaybeClient.value(); auto c = MaybeClient.value().lock();
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID); beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
LuaAPI::MP::Engine->Network().Disconnect(*c); 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, "" };
@@ -141,11 +141,11 @@ 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 MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient) { 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" };
} }
auto c = MaybeClient.value(); auto c = MaybeClient.value().lock();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason")); LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" }; return { true, "" };
} }
@@ -159,18 +159,17 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
Result.first = true; Result.first = true;
} else { } else {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
auto c = MaybeClient.value(); auto c = MaybeClient.value().lock();
if (!c->IsSynced) { if (!c->IsSynced()) {
Result.first = false; Result.first = false;
Result.second = "Player still syncing data"; Result.second = "Player still syncing data";
return Result; return Result;
} }
LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message); LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID); beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get()); // TODO: should we return an error here?
Engine->Network().Disconnect(c);
} }
Result.first = true; Result.first = true;
} else { } else {
@@ -186,13 +185,13 @@ 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 MaybeClient = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient) { 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;
} }
auto c = MaybeClient.value(); auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) { if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true); Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
@@ -275,8 +274,8 @@ void LuaAPI::MP::Sleep(size_t Ms) {
bool LuaAPI::MP::IsPlayerConnected(int ID) { bool LuaAPI::MP::IsPlayerConnected(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value()->IsConnected.get(); return MaybeClient.value().lock()->IsConnected();
} else { } else {
return false; return false;
} }
@@ -284,8 +283,8 @@ bool LuaAPI::MP::IsPlayerConnected(int ID) {
bool LuaAPI::MP::IsPlayerGuest(int ID) { bool LuaAPI::MP::IsPlayerGuest(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value()->IsGuest.get(); return MaybeClient.value().lock()->IsGuest();
} else { } else {
return false; return false;
} }
+53 -70
View File
@@ -1,7 +1,6 @@
#include "Common.h" #include "Common.h"
#include "TConfig.h" #include "TConfig.h"
#include <cstdlib>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <istream> #include <istream>
@@ -9,29 +8,16 @@
// General // General
static constexpr std::string_view StrDebug = "Debug"; static constexpr std::string_view StrDebug = "Debug";
static constexpr std::string_view EnvStrDebug = "BEAMMP_DEBUG";
static constexpr std::string_view StrPrivate = "Private"; static constexpr std::string_view StrPrivate = "Private";
static constexpr std::string_view EnvStrPrivate = "BEAMMP_PRIVATE";
static constexpr std::string_view StrPort = "Port"; static constexpr std::string_view StrPort = "Port";
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
static constexpr std::string_view StrMaxCars = "MaxCars"; static constexpr std::string_view StrMaxCars = "MaxCars";
static constexpr std::string_view EnvStrMaxCars = "BEAMMP_MAX_CARS";
static constexpr std::string_view StrMaxPlayers = "MaxPlayers"; static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
static constexpr std::string_view EnvStrMaxPlayers = "BEAMMP_MAX_PLAYERS";
static constexpr std::string_view StrMap = "Map"; static constexpr std::string_view StrMap = "Map";
static constexpr std::string_view EnvStrMap = "BEAMMP_MAP";
static constexpr std::string_view StrName = "Name"; static constexpr std::string_view StrName = "Name";
static constexpr std::string_view EnvStrName = "BEAMMP_NAME";
static constexpr std::string_view StrDescription = "Description"; static constexpr std::string_view StrDescription = "Description";
static constexpr std::string_view EnvStrDescription = "BEAMMP_DESCRIPTION";
static constexpr std::string_view StrTags = "Tags";
static constexpr std::string_view EnvStrTags = "BEAMMP_TAGS";
static constexpr std::string_view StrResourceFolder = "ResourceFolder"; static constexpr std::string_view StrResourceFolder = "ResourceFolder";
static constexpr std::string_view EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
static constexpr std::string_view StrAuthKey = "AuthKey"; static constexpr std::string_view StrAuthKey = "AuthKey";
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
static constexpr std::string_view StrLogChat = "LogChat"; static constexpr std::string_view StrLogChat = "LogChat";
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
static constexpr std::string_view StrPassword = "Password"; static constexpr std::string_view StrPassword = "Password";
// Misc // Misc
@@ -39,6 +25,14 @@ static constexpr std::string_view StrSendErrors = "SendErrors";
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage"; static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates"; 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);
@@ -62,6 +56,7 @@ TEST_CASE("TConfig::TConfig") {
const auto table = toml::parse(CfgFile); const auto table = toml::parse(CfgFile);
CHECK(table.at("General").is_table()); CHECK(table.at("General").is_table());
CHECK(table.at("Misc").is_table()); CHECK(table.at("Misc").is_table());
CHECK(table.at("HTTP").is_table());
fs::remove(CfgFile); fs::remove(CfgFile);
} }
@@ -107,26 +102,34 @@ void TConfig::FlushToFile() {
data["General"][StrPrivate.data()] = Application::Settings.Private; data["General"][StrPrivate.data()] = Application::Settings.Private;
data["General"][StrPort.data()] = Application::Settings.Port; data["General"][StrPort.data()] = Application::Settings.Port;
data["General"][StrName.data()] = Application::Settings.ServerName; data["General"][StrName.data()] = Application::Settings.ServerName;
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
data["General"][StrTags.data()] = Application::Settings.ServerTags;
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars; data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers; data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
data["General"][StrMap.data()] = Application::Settings.MapName; data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::Settings.ServerDesc; data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::Settings.Resource; data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
// data["General"][StrPassword.data()] = Application::Settings.Password; data["General"][StrPassword.data()] = Application::Settings.Password;
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password."); SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
// Misc // Misc
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages; 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::Settings.SendErrors; data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`"); SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled; data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here"); SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
// HTTP
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
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.");
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
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"
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n" "# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n" "# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
<< data; << data;
auto File = std::fopen(mConfigFileName.c_str(), "w+"); auto File = std::fopen(mConfigFileName.c_str(), "w+");
if (!File) { if (!File) {
@@ -156,38 +159,19 @@ void TConfig::CreateConfigFile() {
FlushToFile(); FlushToFile();
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = std::string(envp);
return;
}
}
if (Table[Category.c_str()][Key.data()].is_string()) { if (Table[Category.c_str()][Key.data()].is_string()) {
OutValue = Table[Category.c_str()][Key.data()].as_string(); OutValue = Table[Category.c_str()][Key.data()].as_string();
} }
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
auto Str = std::string(envp);
OutValue = Str == "1" || Str == "true";
return;
}
}
if (Table[Category.c_str()][Key.data()].is_boolean()) { if (Table[Category.c_str()][Key.data()].is_boolean()) {
OutValue = Table[Category.c_str()][Key.data()].as_boolean(); OutValue = Table[Category.c_str()][Key.data()].as_boolean();
} }
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = int(std::strtol(envp, nullptr, 10));
return;
}
}
if (Table[Category.c_str()][Key.data()].is_integer()) { if (Table[Category.c_str()][Key.data()].is_integer()) {
OutValue = int(Table[Category.c_str()][Key.data()].as_integer()); OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
} }
@@ -197,23 +181,29 @@ 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, EnvStrDebug, Application::Settings.DebugModeEnabled); TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private); TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port); TryReadValue(data, "General", StrPort, Application::Settings.Port);
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars); TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers); TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName); TryReadValue(data, "General", StrMap, Application::Settings.MapName);
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName); TryReadValue(data, "General", StrName, Application::Settings.ServerName);
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc); TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags); TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource); TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key); TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat); TryReadValue(data, "General", StrPassword, Application::Settings.Password);
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
// Misc // Misc
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors); TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages); TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled); TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
// HTTP
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
} catch (const std::exception& err) { } catch (const std::exception& err) {
beammp_error("Error parsing config file value: " + std::string(err.what())); beammp_error("Error parsing config file value: " + std::string(err.what()));
mFailed = true; mFailed = true;
@@ -246,9 +236,12 @@ void TConfig::PrintDebug() {
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\""); beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\""); beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\""); beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\""); beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\""); beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
// special! // special!
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + ""); beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true")); beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
@@ -306,13 +299,3 @@ void TConfig::ParseOldFormat() {
Str >> std::ws; Str >> std::ws;
} }
} }
std::string TConfig::TagsAsPrettyArray() const {
std::vector<std::string> TagsArray = {};
SplitString(Application::Settings.ServerTags, ',', TagsArray);
std::string Pretty = {};
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
Pretty += '\"' + TagsArray[i] + "\", ";
}
Pretty += '\"' + TagsArray.at(TagsArray.size() - 1) + "\"";
return Pretty;
}
+52 -46
View File
@@ -52,6 +52,17 @@ TEST_CASE("TrimString") {
CHECK(TrimString("") == ""); CHECK(TrimString("") == "");
} }
// TODO: add unit tests to SplitString
static inline void SplitString(std::string const& str, const char delim, std::vector<std::string>& out) {
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
static std::string GetDate() { static std::string GetDate() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t(now); time_t tt = std::chrono::system_clock::to_time_t(now);
@@ -146,13 +157,13 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
mIsLuaConsole = true; mIsLuaConsole = true;
if (mStateId != mDefaultStateId) { if (mStateId != mDefaultStateId) {
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`"); Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`");
mCommandline->set_prompt("lua @" + LuaStateId + "> "); mCommandline.set_prompt("lua @" + LuaStateId + "> ");
} else { } else {
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`"); Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
mCommandline->set_prompt("lua> "); mCommandline.set_prompt("lua> ");
} }
mCachedRegularHistory = mCommandline->history(); mCachedRegularHistory = mCommandline.history();
mCommandline->set_history(mCachedLuaHistory); mCommandline.set_history(mCachedLuaHistory);
} }
} }
@@ -164,9 +175,9 @@ void TConsole::ChangeToRegularConsole() {
} else { } else {
Application::Console().WriteRaw("Detached from Lua."); Application::Console().WriteRaw("Detached from Lua.");
} }
mCachedLuaHistory = mCommandline->history(); mCachedLuaHistory = mCommandline.history();
mCommandline->set_history(mCachedRegularHistory); mCommandline.set_history(mCachedRegularHistory);
mCommandline->set_prompt("> "); mCommandline.set_prompt("> ");
mStateId = mDefaultStateId; mStateId = mDefaultStateId;
} }
} }
@@ -246,7 +257,7 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
if (!EnsureArgsCount(args, 0, size_t(-1))) { if (!EnsureArgsCount(args, 0, size_t(-1))) {
return; return;
} }
mCommandline->write("\x1b[;H\x1b[2J"); mCommandline.write("\x1b[;H\x1b[2J");
} }
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) {
@@ -266,12 +277,15 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); }); std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1); return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
}; };
mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (NameCompare(Client->Name.get(), Name)) { if (!Client.expired()) {
mLuaEngine->Network().ClientKick(*Client, Reason); auto locked = Client.lock();
if (NameCompare(locked->GetName(), Name)) {
mLuaEngine->Network().ClientKick(*locked, Reason);
Kicked = true; Kicked = true;
return false; return false;
} }
}
return true; return true;
}); });
if (!Kicked) { if (!Kicked) {
@@ -361,10 +375,13 @@ 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 std::shared_ptr<TClient>& Client) -> bool { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
ss << std::left << std::setw(25) << Client->Name.get() if (!Client.expired()) {
<< std::setw(6) << Client->ID.get() 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; return true;
}); });
auto Str = ss.str(); auto Str = ss.str();
@@ -385,15 +402,18 @@ 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([&](std::shared_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
CarCount += size_t(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->MissedPacketsQueue->size(); 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; return true;
}); });
@@ -569,20 +589,16 @@ Commands
} }
TConsole::TConsole() { TConsole::TConsole() {
} mCommandline.enable_history();
mCommandline.set_history_limit(20);
void TConsole::InitializeCommandline() { mCommandline.set_prompt("> ");
mCommandline = std::make_unique<Commandline>();
mCommandline->enable_history();
mCommandline->set_history_limit(20);
mCommandline->set_prompt("> ");
BackupOldLog(); BackupOldLog();
mCommandline->on_command = [this](Commandline& c) { mCommandline.on_command = [this](Commandline& c) {
try { try {
auto TrimmedCmd = c.get_command(); auto TrimmedCmd = c.get_command();
TrimmedCmd = TrimString(TrimmedCmd); TrimmedCmd = TrimString(TrimmedCmd);
auto [cmd, args] = ParseCommand(TrimmedCmd); auto [cmd, args] = ParseCommand(TrimmedCmd);
mCommandline->write(mCommandline->prompt() + TrimmedCmd); mCommandline.write(mCommandline.prompt() + TrimmedCmd);
if (mIsLuaConsole) { if (mIsLuaConsole) {
if (!mLuaEngine) { if (!mLuaEngine) {
beammp_info("Lua not started yet, please try again in a second"); beammp_info("Lua not started yet, please try again in a second");
@@ -617,7 +633,7 @@ void TConsole::InitializeCommandline() {
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate."); beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
} }
}; };
mCommandline->on_autocomplete = [this](Commandline&, std::string stub, int) { mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
std::vector<std::string> suggestions; std::vector<std::string> suggestions;
try { try {
if (mIsLuaConsole) { // if lua if (mIsLuaConsole) { // if lua
@@ -687,21 +703,11 @@ void TConsole::InitializeCommandline() {
void TConsole::Write(const std::string& str) { void TConsole::Write(const std::string& str) {
auto ToWrite = GetDate() + str; auto ToWrite = GetDate() + str;
// allows writing to stdout without an initialized console mCommandline.write(ToWrite);
if (mCommandline) {
mCommandline->write(ToWrite);
} else {
std::cout << ToWrite << std::endl;
}
} }
void TConsole::WriteRaw(const std::string& str) { void TConsole::WriteRaw(const std::string& str) {
// allows writing to stdout without an initialized console mCommandline.write(str);
if (mCommandline) {
mCommandline->write(str);
} else {
std::cout << str << std::endl;
}
} }
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) { void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
+5 -3
View File
@@ -129,7 +129,6 @@ std::string THeartbeatThread::GenerateCall() {
<< "&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::Settings.ServerName << "&name=" << Application::Settings.ServerName
<< "&tags=" << Application::Settings.ServerTags
<< "&modlist=" << mResourceManager.TrimmedList() << "&modlist=" << mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.MaxModSize() << "&modstotalsize=" << mResourceManager.MaxModSize()
<< "&modstotal=" << mResourceManager.ModsLoaded() << "&modstotal=" << mResourceManager.ModsLoaded()
@@ -153,8 +152,11 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
} }
std::string THeartbeatThread::GetPlayers() { std::string THeartbeatThread::GetPlayers() {
std::string Return; std::string Return;
mServer.ForEachClient([&](const std::shared_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
Return += ClientPtr->Name.get() + ";"; ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Return += ClientPtr.lock()->GetName() + ";";
}
return true; return true;
}); });
return Return; return Return;
+31 -21
View File
@@ -480,13 +480,13 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
auto IDs = MaybeClient.value()->Identifiers.synchronize(); auto IDs = MaybeClient.value().lock()->GetIdentifiers();
if (IDs->empty()) { if (IDs.empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::table Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
for (const auto& Pair : *IDs) { for (const auto& Pair : IDs) {
Result[Pair.first] = Pair.second; Result[Pair.first] = Pair.second;
} }
return Result; return Result;
@@ -497,8 +497,11 @@ 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 std::shared_ptr<TClient>& Client) -> bool { mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
Result[Client->ID.get()] = Client->Name.get(); if (!Client.expired()) {
auto locked = Client.lock();
Result[locked->GetID()] = locked->GetName();
}
return true; return true;
}); });
return Result; return Result;
@@ -506,10 +509,13 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
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 std::shared_ptr<TClient>& Client) -> bool { mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
if (Client->Name.get() == Name) { if (!Client.expired()) {
Id = Client->ID.get(); auto locked = Client.lock();
return false; if (locked->GetName() == Name) {
Id = locked->GetID();
return false;
}
} }
return true; return true;
}); });
@@ -544,8 +550,8 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) { std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value()->Name.get(); return MaybeClient.value().lock()->GetName();
} else { } else {
return ""; return "";
} }
@@ -553,15 +559,19 @@ std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value(); auto Client = MaybeClient.value().lock();
auto VehicleData = Client->VehicleData.synchronize(); TClient::TSetOfVehicleData VehicleData;
if (VehicleData->empty()) { { // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (VehicleData.empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::state_view StateView(mState); sol::state_view StateView(mState);
sol::table Result = StateView.create_table(); sol::table Result = StateView.create_table();
for (const auto& v : *VehicleData) { for (const auto& v : VehicleData) {
Result[v.ID()] = v.Data().substr(3); Result[v.ID()] = v.Data().substr(3);
} }
return Result; return Result;
@@ -572,8 +582,8 @@ 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 MaybeClient = GetClient(mEngine->Server(), PID); auto MaybeClient = GetClient(mEngine->Server(), PID);
if (MaybeClient) { if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value(); auto Client = MaybeClient.value().lock();
std::string VehiclePos = Client->GetCarPositionRaw(VID); std::string VehiclePos = Client->GetCarPositionRaw(VID);
if (VehiclePos.empty()) { if (VehiclePos.empty()) {
@@ -591,7 +601,7 @@ std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionR
return Result; return Result;
} else { } else {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired")); // return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
Result.second = "No such player"; Result.second = "Client expired";
return Result; return Result;
} }
} }
@@ -1073,7 +1083,7 @@ void TLuaResult::MarkAsReady() {
void TLuaResult::WaitUntilReady() { void TLuaResult::WaitUntilReady() {
std::unique_lock readyLock(*this->ReadyMutex); std::unique_lock readyLock(*this->ReadyMutex);
// wait if not ready yet // wait if not ready yet
if (!this->Ready) if(!this->Ready)
this->ReadyCondition->wait(readyLock); this->ReadyCondition->wait(readyLock);
} }
+237 -186
View File
@@ -9,7 +9,6 @@
#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 <boost/thread/synchronized_value.hpp>
#include <cstring> #include <cstring>
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option; typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option;
@@ -36,8 +35,10 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting); Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
beammp_debug("Kicking all players due to shutdown"); beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](std::shared_ptr<TClient> Client) -> bool { Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
ClientKick(*Client, "Server shutdown"); if (!client.expired()) {
ClientKick(*client.lock(), "Server shutdown");
}
return true; return true;
}); });
}); });
@@ -86,13 +87,23 @@ void TNetwork::UDPServerMain() {
if (Data.empty() || Pos > Data.begin() + 2) if (Data.empty() || Pos > Data.begin() + 2)
continue; continue;
uint8_t ID = uint8_t(Data.at(0)) - 1; uint8_t ID = uint8_t(Data.at(0)) - 1;
mServer.ForEachClient([&](std::shared_ptr<TClient> Client) -> bool { mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
if (Client->ID == ID) { std::shared_ptr<TClient> Client;
Client->UDPAddress = client; {
Client->IsConnected = true; ReadLock Lock(mServer.GetClientMutex());
Data.erase(Data.begin(), Data.begin() + 2); if (!ClientPtr.expired()) {
mServer.GlobalParser(Client, std::move(Data), mPPSMonitor, *this); Client = ClientPtr.lock();
} else
return true;
} }
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; return true;
}); });
} catch (const std::exception& e) { } catch (const std::exception& e) {
@@ -180,8 +191,8 @@ void TNetwork::Identify(TConnection&& RawConnection) {
} else { } else {
beammp_errorf("Invalid code got in Identify: '{}'", Code); beammp_errorf("Invalid code got in Identify: '{}'", Code);
} }
} catch (const std::exception& e) { } catch(const std::exception& e) {
beammp_errorf("Error during handling of code {}->client left in invalid state, closing socket", Code); 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;
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec); RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
if (ec) { if (ec) {
@@ -204,11 +215,16 @@ void TNetwork::HandleDownload(TConnection&& Conn) {
return; return;
} }
auto ID = uint8_t(D); auto ID = uint8_t(D);
auto Client = GetClient(mServer, ID); mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
if (Client.has_value()) { ReadLock Lock(mServer.GetClientMutex());
auto New = Sync<ip::tcp::socket>(std::move(Conn.Socket)); if (!ClientPtr.expired()) {
Client.value()->DownSocket.swap(New); auto c = ClientPtr.lock();
} if (c->GetID() == ID) {
c->SetDownSock(std::move(Conn.Socket));
}
}
return true;
});
} }
std::string HashPassword(const std::string& str) { std::string HashPassword(const std::string& str) {
@@ -244,9 +260,8 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
if (!TCPSend(*Client, StringToVector("A"))) { // changed to A for Accepted version if (!TCPSend(*Client, StringToVector("A"))) { //changed to A for Accepted version
Disconnect(Client); // TODO: handle
return nullptr;
} }
Data = TCPRcv(*Client); Data = TCPRcv(*Client);
@@ -258,8 +273,8 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
std::string key(reinterpret_cast<const char*>(Data.data()), Data.size()); std::string key(reinterpret_cast<const char*>(Data.data()), Data.size());
nlohmann::json AuthReq {}; nlohmann::json AuthReq{};
std::string AuthResStr {}; std::string AuthResStr{};
try { try {
AuthReq = nlohmann::json { AuthReq = nlohmann::json {
{ "key", key } { "key", key }
@@ -283,7 +298,7 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
Client->SetName(AuthRes["username"]); Client->SetName(AuthRes["username"]);
Client->SetRoles(AuthRes["roles"]); Client->SetRoles(AuthRes["roles"]);
Client->IsGuest = AuthRes["guest"]; Client->SetIsGuest(AuthRes["guest"]);
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(':');
@@ -301,33 +316,41 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
if (!Application::Settings.Password.empty()) { // ask password if(!Application::Settings.Password.empty()) { // ask password
if (!TCPSend(*Client, StringToVector("S"))) { if(!TCPSend(*Client, StringToVector("S"))) {
Disconnect(Client); // TODO: handle
return {};
} }
beammp_info("Waiting for password"); beammp_info("Waiting for password");
Data = TCPRcv(*Client); Data = TCPRcv(*Client);
std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size()); std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size());
if (Pass != HashPassword(Application::Settings.Password)) { if(Pass != HashPassword(Application::Settings.Password)) {
beammp_debug(Client->Name.get() + " attempted to connect with a wrong password"); beammp_debug(Client->GetName() + " attempted to connect with a wrong password");
ClientKick(*Client, "Wrong password!"); ClientKick(*Client, "Wrong password!");
return {}; return {};
} else { } else {
beammp_debug(Client->Name.get() + " used the correct password"); beammp_debug(Client->GetName() + " used the correct password");
} }
} }
beammp_debug("Name-> " + Client->Name.get() + ", Guest-> " + std::to_string(Client->IsGuest.get()) + ", Roles-> " + Client->Role.get()); beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
mServer.ForEachClient([&](const std::shared_ptr<TClient>& Cl) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
if (Cl->Name.get() == Client->Name.get() && Cl->IsGuest == Client->IsGuest) { std::shared_ptr<TClient> Cl;
Disconnect(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 false;
} }
return true; return true;
}); });
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->Name.get(), Client->Role.get(), Client->IsGuest.get(), Client->Identifiers.get()); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers());
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) {
@@ -354,13 +377,7 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) { if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
beammp_info("Identification success"); beammp_info("Identification success");
mServer.InsertClient(Client); mServer.InsertClient(Client);
try { TCPClient(Client);
TCPClient(Client);
} catch (const std::exception& e) {
beammp_infof("Client {} disconnected: {}", Client->ID.get(), e.what());
Disconnect(Client);
return {};
}
} else { } else {
ClientKick(*Client, "Server full!"); ClientKick(*Client, "Server full!");
} }
@@ -375,7 +392,7 @@ std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) { bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) {
if (!IsSync) { if (!IsSync) {
if (c.IsSyncing) { if (c.IsSyncing()) {
if (!Data.empty()) { if (!Data.empty()) {
if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') { if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') {
c.EnqueuePacket(Data); c.EnqueuePacket(Data);
@@ -385,6 +402,8 @@ bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync
} }
} }
auto& Sock = c.GetTCPSock();
/* /*
* our TCP protocol sends a header of 4 bytes, followed by the data. * our TCP protocol sends a header of 4 bytes, followed by the data.
* *
@@ -399,10 +418,10 @@ bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync
std::memcpy(ToSend.data(), &Size, sizeof(Size)); std::memcpy(ToSend.data(), &Size, sizeof(Size));
std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size()); std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size());
boost::system::error_code ec; boost::system::error_code ec;
write(*c.TCPSocket.synchronize(), buffer(ToSend), ec); write(Sock, buffer(ToSend), ec);
if (ec) { if (ec) {
beammp_debugf("write(): {}", ec.message()); beammp_debugf("write(): {}", ec.message());
Disconnect(c); c.Disconnect("write() failed");
return false; return false;
} }
c.UpdatePingTime(); c.UpdatePingTime();
@@ -416,10 +435,11 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
} }
int32_t Header {}; int32_t Header {};
auto& Sock = c.GetTCPSock();
boost::system::error_code ec; boost::system::error_code ec;
std::array<uint8_t, sizeof(Header)> HeaderData; std::array<uint8_t, sizeof(Header)> HeaderData;
read(*c.TCPSocket.synchronize(), buffer(HeaderData), ec); read(Sock, buffer(HeaderData), ec);
if (ec) { if (ec) {
// TODO: handle this case (read failed) // TODO: handle this case (read failed)
beammp_debugf("TCPRcv: Reading header failed: {}", ec.message()); beammp_debugf("TCPRcv: Reading header failed: {}", ec.message());
@@ -428,8 +448,8 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
Header = *reinterpret_cast<int32_t*>(HeaderData.data()); Header = *reinterpret_cast<int32_t*>(HeaderData.data());
if (Header < 0) { if (Header < 0) {
ClientKick(c, "Invalid packet->header negative"); ClientKick(c, "Invalid packet - header negative");
beammp_errorf("Client {} send negative TCP header, ignoring packet", c.ID.get()); beammp_errorf("Client {} send negative TCP header, ignoring packet", c.GetID());
return {}; return {};
} }
@@ -439,10 +459,10 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
Data.resize(Header); Data.resize(Header);
} else { } else {
ClientKick(c, "Header size limit exceeded"); ClientKick(c, "Header size limit exceeded");
beammp_warn("Client " + c.Name.get() + " (" + std::to_string(c.ID.get()) + ") sent header of >100MB->assuming malicious intent and disconnecting the client."); beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
return {}; return {};
} }
auto N = read(*c.TCPSocket.synchronize(), buffer(Data), ec); auto N = read(Sock, buffer(Data), ec);
if (ec) { if (ec) {
// TODO: handle this case properly // TODO: handle this case properly
beammp_debugf("TCPRcv: Reading data failed: {}", ec.message()); beammp_debugf("TCPRcv: Reading data failed: {}", ec.message());
@@ -465,30 +485,37 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
void TNetwork::ClientKick(TClient& c, const std::string& R) { void TNetwork::ClientKick(TClient& c, const std::string& R) {
beammp_info("Client kicked: " + R); beammp_info("Client kicked: " + R);
if (!TCPSend(c, StringToVector("K" + R))) { if (!TCPSend(c, StringToVector("K" + R))) {
beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.Name.get(), c.ID.get()); beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.GetName(), c.GetID());
} }
Disconnect(c); c.Disconnect("Kicked");
} }
void TNetwork::Looper(const std::shared_ptr<TClient>& Client) { void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
RegisterThreadAuto(); RegisterThreadAuto();
while (!Client->IsDisconnected()) { while (!c.expired()) {
if (!Client->IsSyncing.get() && Client->IsSynced.get() && Client->MissedPacketsQueue->size() != 0) { auto Client = c.lock();
while (Client->MissedPacketsQueue->size() > 0) { if (Client->IsDisconnected()) {
beammp_debug("client is disconnected, breaking client loop");
break;
}
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
// debug("sending " + std::to_string(Client->MissedPacketQueueSize()) + " queued packets");
while (Client->MissedPacketQueueSize() > 0) {
std::vector<uint8_t> QData {}; std::vector<uint8_t> QData {};
{ // locked context { // locked context
auto Lock = Client->MissedPacketsQueue; std::unique_lock lock(Client->MissedPacketQueueMutex());
if (Lock->size() <= 0) { if (Client->MissedPacketQueueSize() <= 0) {
break; break;
} }
QData = Lock->front(); QData = Client->MissedPacketQueue().front();
Lock->pop(); Client->MissedPacketQueue().pop();
} // end locked context } // end locked context
// beammp_debug("sending a missed packet: " + QData);
if (!TCPSend(*Client, QData, true)) { if (!TCPSend(*Client, QData, true)) {
Disconnect(Client); Client->Disconnect("Failed to TCPSend while clearing the missed packet queue");
auto Lock = Client->MissedPacketsQueue; std::unique_lock lock(Client->MissedPacketQueueMutex());
while (!Lock->empty()) { while (!Client->MissedPacketQueue().empty()) {
Lock->pop(); Client->MissedPacketQueue().pop();
} }
break; break;
} }
@@ -499,38 +526,54 @@ void TNetwork::Looper(const std::shared_ptr<TClient>& Client) {
} }
} }
void TNetwork::TCPClient(const std::shared_ptr<TClient>& c) { void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
if (c.expired() || !c.lock()->GetTCPSock().is_open()) {
mServer.RemoveClient(c);
return;
}
OnConnect(c); OnConnect(c);
RegisterThread("(" + std::to_string(c->ID.get()) + ") \"" + c->Name.get() + "\""); RegisterThread("(" + std::to_string(c.lock()->GetID()) + ") \"" + c.lock()->GetName() + "\"");
std::thread QueueSync(&TNetwork::Looper, this, c); std::thread QueueSync(&TNetwork::Looper, this, c);
while (true) { while (true) {
if (c->IsDisconnected()) { if (c.expired())
break;
auto Client = c.lock();
if (Client->IsDisconnected()) {
beammp_debug("client status < 0, breaking client loop"); beammp_debug("client status < 0, breaking client loop");
break; break;
} }
auto res = TCPRcv(*c); auto res = TCPRcv(*Client);
if (res.empty()) { if (res.empty()) {
beammp_debug("TCPRcv empty"); beammp_debug("TCPRcv empty");
Disconnect(c); Client->Disconnect("TCPRcv failed");
break; break;
} }
mServer.GlobalParser(c, std::move(res), mPPSMonitor, *this); TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this);
} }
if (QueueSync.joinable()) if (QueueSync.joinable())
QueueSync.join(); QueueSync.join();
Disconnect(c); if (!c.expired()) {
auto Client = c.lock();
OnDisconnect(c);
} else {
beammp_warn("client expired in TCPClient, should never happen");
}
} }
void TNetwork::UpdatePlayer(TClient& Client) { void TNetwork::UpdatePlayer(TClient& Client) {
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":"; std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex()); ReadLock Lock(mServer.GetClientMutex());
Packet += Client->Name.get() + ","; if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
Packet += c->GetName() + ",";
}
return true; return true;
}); });
Packet = Packet.substr(0, Packet.length() - 1); Packet = Packet.substr(0, Packet.length() - 1);
@@ -538,66 +581,74 @@ void TNetwork::UpdatePlayer(TClient& Client) {
//(void)Respond(Client, Packet, true); //(void)Respond(Client, Packet, true);
} }
void TNetwork::Disconnect(const std::weak_ptr<TClient>& ClientPtr) { void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) {
// this is how one checks that the ClientPtr is not empty (as opposed to expired)
if (ClientPtr.owner_before(std::weak_ptr<TClient> {})) {
return;
}
std::shared_ptr<TClient> LockedClientPtr { nullptr }; std::shared_ptr<TClient> LockedClientPtr { nullptr };
try { try {
LockedClientPtr = ClientPtr.lock(); LockedClientPtr = ClientPtr.lock();
} catch (const std::exception&) { } catch (const std::exception&) {
beammp_warn("Client expired in CloseSockets, this is unexpected"); beammp_warn("Client expired in OnDisconnect, this is unexpected");
return; return;
} }
beammp_assert(LockedClientPtr != nullptr); beammp_assert(LockedClientPtr != nullptr);
TClient& c = *LockedClientPtr; TClient& c = *LockedClientPtr;
Disconnect(c); beammp_info(c.GetName() + (" Connection Terminated"));
}
void TNetwork::Disconnect(TClient& Client) {
beammp_info(Client.Name.get() + (" Connection Terminated"));
std::string Packet; std::string Packet;
{ TClient::TSetOfVehicleData VehicleData;
auto Locked = Client.VehicleData.synchronize(); { // Vehicle Data Lock Scope
for (auto& v : *Locked) { auto LockedData = c.GetAllCars();
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", Client.ID.get(), v.ID())); VehicleData = *LockedData.VehicleData;
Packet = "Od:" + std::to_string(Client.ID.get()) + "-" + std::to_string(v.ID()); } // End Vehicle Data Lock Scope
SendToAll(&Client, StringToVector(Packet), false, true); for (auto& v : VehicleData) {
} Packet = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(v.ID());
SendToAll(&c, StringToVector(Packet), false, true);
} }
Packet = ("L") + Client.Name.get() + (" left the server!"); Packet = ("L") + c.GetName() + (" left the server!");
SendToAll(&Client, StringToVector(Packet), false, true); SendToAll(&c, StringToVector(Packet), false, true);
Packet.clear(); Packet.clear();
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", Client.ID.get()); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", c.GetID());
TLuaEngine::WaitForAll(Futures); LuaAPI::MP::Engine->WaitForAll(Futures);
Client.CloseSockets("Normal disconnect"); c.Disconnect("Already Disconnected (OnDisconnect)");
mServer.RemoveClient(Client); mServer.RemoveClient(ClientPtr);
} }
void TNetwork::Disconnect(const std::shared_ptr<TClient>& ClientPtr) {
if (ClientPtr == nullptr) { int TNetwork::OpenID() {
return; int ID = 0;
} bool found;
Disconnect(*ClientPtr); do {
found = true;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
if (c->GetID() == ID) {
found = false;
ID++;
}
}
return true;
});
} while (!found);
return ID;
} }
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) { 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();
mServer.ClaimFreeIDFor(*LockedClient); LockedClient->SetID(OpenID());
beammp_info("Assigned ID " + std::to_string(LockedClient->ID.get()) + " to " + LockedClient->Name.get()); beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->ID.get())); 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::Settings.MapName), true); // Send the Map on connect (void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
beammp_info(LockedClient->Name.get() + " : Connected"); beammp_info(LockedClient->GetName() + " : Connected");
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->ID.get())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
} }
void TNetwork::SyncResources(TClient& c) { void TNetwork::SyncResources(TClient& c) {
if (!TCPSend(c, StringToVector("P" + std::to_string(c.ID.get())))) { if (!TCPSend(c, StringToVector("P" + std::to_string(c.GetID())))) {
throw std::runtime_error("Failed to send 'P' to client"); // TODO handle
} }
std::vector<uint8_t> Data; std::vector<uint8_t> Data;
while (!c.IsDisconnected()) { while (!c.IsDisconnected()) {
@@ -629,7 +680,7 @@ void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
if (ToSend.empty()) if (ToSend.empty())
ToSend = "-"; ToSend = "-";
if (!TCPSend(c, StringToVector(ToSend))) { if (!TCPSend(c, StringToVector(ToSend))) {
throw std::runtime_error("Failed to send packet to client"); // TODO: error
} }
} }
return; return;
@@ -639,12 +690,11 @@ void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
} }
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) { void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
beammp_info(c.Name.get() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/'))); beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
if (!fs::path(UnsafeName).has_filename()) { if (!fs::path(UnsafeName).has_filename()) {
if (!TCPSend(c, StringToVector("CO"))) { if (!TCPSend(c, StringToVector("CO"))) {
Disconnect(c); // TODO: handle
return;
} }
beammp_warn("File " + UnsafeName + " is not a file!"); beammp_warn("File " + UnsafeName + " is not a file!");
return; return;
@@ -654,29 +704,27 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
if (!std::filesystem::exists(FileName)) { if (!std::filesystem::exists(FileName)) {
if (!TCPSend(c, StringToVector("CO"))) { if (!TCPSend(c, StringToVector("CO"))) {
Disconnect(c); // TODO: handle
return;
} }
beammp_warn("File " + UnsafeName + " could not be accessed!"); beammp_warn("File " + UnsafeName + " could not be accessed!");
return; return;
} }
if (!TCPSend(c, StringToVector("AG"))) { if (!TCPSend(c, StringToVector("AG"))) {
Disconnect(c); // TODO: handle
return;
} }
/// Wait for connections /// Wait for connections
int T = 0; int T = 0;
while (!c.DownSocket->is_open() && T < 50) { while (!c.GetDownSock().is_open() && T < 50) {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
T++; T++;
} }
if (!c.DownSocket->is_open()) { if (!c.GetDownSock().is_open()) {
beammp_error("Client doesn't have a download socket!"); beammp_error("Client doesn't have a download socket!");
if (!c.IsDisconnected()) if (!c.IsDisconnected())
Disconnect(c); c.Disconnect("Missing download socket");
return; return;
} }
@@ -756,54 +804,31 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
Data.resize(Split); Data.resize(Split);
else else
Data.resize(Size); Data.resize(Size);
ip::tcp::socket* TCPSock { nullptr };
if (D) { if (D)
auto TCPSock = c.DownSocket.synchronize(); TCPSock = &c.GetDownSock();
while (!c.IsDisconnected() && Sent < Size) { else
size_t Diff = Size - Sent; TCPSock = &c.GetTCPSock();
if (Diff > Split) { while (!c.IsDisconnected() && Sent < Size) {
f.seekg(Sent, std::ios_base::beg); size_t Diff = Size - Sent;
f.read(reinterpret_cast<char*>(Data.data()), Split); if (Diff > Split) {
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) { f.seekg(Sent, std::ios_base::beg);
if (!c.IsDisconnected()) f.read(reinterpret_cast<char*>(Data.data()), Split);
Disconnect(c); if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
break; if (!c.IsDisconnected())
} c.Disconnect("TCPSendRaw failed in mod download (1)");
Sent += Split; break;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Diff);
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Diff;
} }
} Sent += Split;
} else { } else {
auto TCPSock = c.TCPSocket.synchronize(); f.seekg(Sent, std::ios_base::beg);
while (!c.IsDisconnected() && Sent < Size) { f.read(reinterpret_cast<char*>(Data.data()), Diff);
size_t Diff = Size - Sent; if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (Diff > Split) { if (!c.IsDisconnected())
f.seekg(Sent, std::ios_base::beg); c.Disconnect("TCPSendRaw failed in mod download (2)");
f.read(reinterpret_cast<char*>(Data.data()), Split); break;
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Diff);
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Diff;
} }
Sent += Diff;
} }
} }
} }
@@ -844,24 +869,36 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
return false; return false;
} }
auto LockedClient = c.lock(); auto LockedClient = c.lock();
if (LockedClient->IsSynced.get()) if (LockedClient->IsSynced())
return true; return true;
// Syncing, later set isSynced // Syncing, later set isSynced
// after syncing is done, we apply all packets they missed // after syncing is done, we apply all packets they missed
if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->Name.get()), true)) { if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->GetName()), true)) {
return false; return false;
} }
// ignore error // ignore error
(void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->Name.get() + "!"), false, true); (void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->GetName() + "!"), false, true);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->ID.get())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID()));
LockedClient->IsSyncing = true; LockedClient->SetIsSyncing(true);
bool Return = false; bool Return = false;
bool res = true; bool res = true;
mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
auto VehicleData = Client->VehicleData.synchronize(); std::shared_ptr<TClient> client;
if (Client != LockedClient) { {
for (auto& v : *VehicleData) { ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
client = ClientPtr.lock();
} else
return true;
}
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (client != LockedClient) {
for (auto& v : VehicleData) {
if (LockedClient->IsDisconnected()) { if (LockedClient->IsDisconnected()) {
Return = true; Return = true;
res = false; res = false;
@@ -873,22 +910,32 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
return true; return true;
}); });
LockedClient->IsSyncing = false; LockedClient->SetIsSyncing(false);
if (Return) { if (Return) {
return res; return res;
} }
LockedClient->IsSynced = true; LockedClient->SetIsSynced(true);
beammp_info(LockedClient->Name.get() + (" is now synced!")); beammp_info(LockedClient->GetName() + (" is now synced!"));
return true; return true;
} }
void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) { void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) {
if (!Self) if (!Self)
beammp_assert(c); beammp_assert(c);
char C = static_cast<char>(Data.at(0)); char C = Data.at(0);
mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool { bool ret = true;
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') {
if (C == 'O' || C == 'T' || Data.size() > 1000) { if (C == 'O' || C == 'T' || Data.size() > 1000) {
if (Data.size() > 400) { if (Data.size() > 400) {
@@ -898,38 +945,42 @@ void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self
} else { } else {
Client->EnqueuePacket(Data); Client->EnqueuePacket(Data);
} }
// ret = SendLarge(*Client, Data);
} else { } else {
Client->EnqueuePacket(Data); Client->EnqueuePacket(Data);
// ret = TCPSend(*Client, Data);
} }
} else { } else {
if (!UDPSend(*Client, Data)) { ret = UDPSend(*Client, Data);
Disconnect(Client);
}
} }
} }
} }
return true; return true;
}); });
if (!ret) {
// TODO: handle
}
return;
} }
bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) { bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
if (!Client.IsConnected || Client.IsDisconnected()) { if (!Client.IsConnected() || Client.IsDisconnected()) {
// this can happen if we try to send a packet to a client that is either // this can happen if we try to send a packet to a client that is either
// 1. not yet fully connected, or // 1. not yet fully connected, or
// 2. disconnected and not yet fully removed // 2. disconnected and not yet fully removed
// this is fine can can be ignored :^) // this is fine can can be ignored :^)
return true; return true;
} }
const auto Addr = Client.UDPAddress; const auto Addr = Client.GetUDPAddr();
if (Data.size() > 400) { if (Data.size() > 400) {
CompressProperly(Data); CompressProperly(Data);
} }
boost::system::error_code ec; boost::system::error_code ec;
mUDPSock.send_to(buffer(Data), *Addr, 0, ec); mUDPSock.send_to(buffer(Data), Addr, 0, ec);
if (ec) { if (ec) {
beammp_debugf("UDP sendto() failed: {}", ec.message()); beammp_debugf("UDP sendto() failed: {}", ec.message());
if (!Client.IsDisconnected()) if (!Client.IsDisconnected())
Disconnect(Client); Client.Disconnect("UDP send failed");
return false; return false;
} }
return true; return true;
+10 -2
View File
@@ -33,14 +33,22 @@ void TPPSMonitor::operator()() {
Application::SetPPS("-"); Application::SetPPS("-");
continue; continue;
} }
mServer.ForEachClient([&](const std::shared_ptr<TClient>& c) -> bool { mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> c;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
c = ClientPtr.lock();
} else
return true;
}
if (c->GetCarCount() > 0) { if (c->GetCarCount() > 0) {
C++; C++;
V += c->GetCarCount(); V += c->GetCarCount();
} }
// kick on "no ping" // kick on "no ping"
if (c->SecondsSinceLastPing() > (20 * 60)) { if (c->SecondsSinceLastPing() > (20 * 60)) {
beammp_debug("client " + std::string("(") + std::to_string(c->ID.get()) + ")" + c->Name.get() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS()); 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(c); TimedOutClients.push_back(c);
} }
+1 -2
View File
@@ -1,7 +1,6 @@
#include "TPluginMonitor.h" #include "TPluginMonitor.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include <filesystem>
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine) TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
: mEngine(Engine) : mEngine(Engine)
@@ -10,7 +9,7 @@ TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine>
if (!fs::exists(mPath)) { if (!fs::exists(mPath)) {
fs::create_directories(mPath); fs::create_directories(mPath);
} }
for (const auto& Entry : fs::recursive_directory_iterator(mPath, fs::directory_options::follow_directory_symlink)) { for (const auto& Entry : fs::recursive_directory_iterator(mPath)) {
// TODO: trigger an event when a subfolder file changes // TODO: trigger an event when a subfolder file changes
if (Entry.is_regular_file()) { if (Entry.is_regular_file()) {
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path()); mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
+74 -148
View File
@@ -7,7 +7,6 @@
#include <TLuaPlugin.h> #include <TLuaPlugin.h>
#include <algorithm> #include <algorithm>
#include <any> #include <any>
#include <optional>
#include <sstream> #include <sstream>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -52,30 +51,6 @@ TEST_CASE("GetPidVid") {
CHECK_EQ(pid, 10); CHECK_EQ(pid, 10);
CHECK_EQ(vid, 12); CHECK_EQ(vid, 12);
} }
SUBCASE("Valid doubledigit 2") {
const auto MaybePidVid = GetPidVid("10-2");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 10);
CHECK_EQ(vid, 2);
}
SUBCASE("Valid doubledigit 3") {
const auto MaybePidVid = GetPidVid("33-23");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 33);
CHECK_EQ(vid, 23);
}
SUBCASE("Valid doubledigit 4") {
const auto MaybePidVid = GetPidVid("3-23");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 3);
CHECK_EQ(vid, 23);
}
SUBCASE("Empty string") { SUBCASE("Empty string") {
const auto MaybePidVid = GetPidVid(""); const auto MaybePidVid = GetPidVid("");
CHECK(!MaybePidVid); CHECK(!MaybePidVid);
@@ -118,17 +93,7 @@ TServer::TServer(const std::vector<std::string_view>& Arguments) {
} }
Application::SetSubsystemStatus("Server", Application::Status::Good); Application::SetSubsystemStatus("Server", Application::Status::Good);
} }
void TServer::RemoveClient(TClient& Client) {
beammp_debug("removing client " + Client.Name.get() + " (" + std::to_string(ClientCount()) + ")");
Client.ClearCars();
WriteLock Lock(mClientsMutex);
// erase all clients whose id matches, and those who have expired
std::erase_if(mClients,
[&](const std::weak_ptr<TClient>& C) {
return C.expired()
|| C.lock()->ID.get() == Client.ID.get();
});
}
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) { void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
std::shared_ptr<TClient> LockedClientPtr { nullptr }; std::shared_ptr<TClient> LockedClientPtr { nullptr };
try { try {
@@ -139,26 +104,14 @@ void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
} }
beammp_assert(LockedClientPtr != nullptr); beammp_assert(LockedClientPtr != nullptr);
TClient& Client = *LockedClientPtr; TClient& Client = *LockedClientPtr;
RemoveClient(Client); beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
// TODO: Send delete packets for all cars
Client.ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock());
} }
void TServer::ClaimFreeIDFor(TClient& ClientToChange) { void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
ReadLock lock(mClientsMutex);
int ID = 0;
bool found = true;
do {
found = true;
for (const auto& Client : mClients) {
if (Client->ID.get() == ID) {
found = false;
++ID;
}
}
} while (!found);
ClientToChange.ID = ID;
}
void TServer::ForEachClient(const std::function<bool(const std::shared_ptr<TClient>&)> Fn) {
decltype(mClients) Clients; decltype(mClients) Clients;
{ {
ReadLock lock(mClientsMutex); ReadLock lock(mClientsMutex);
@@ -176,7 +129,7 @@ size_t TServer::ClientCount() const {
return mClients.size(); return mClients.size();
} }
void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, 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());
@@ -186,6 +139,11 @@ void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<u
return; return;
} }
if (Client.expired()) {
return;
}
auto LockedClient = Client.lock();
std::any Res; std::any Res;
char Code = Packet.at(0); char Code = Packet.at(0);
@@ -194,7 +152,7 @@ void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<u
// V to Y // V to Y
if (Code <= 89 && Code >= 86) { if (Code <= 89 && Code >= 86) {
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(Client.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
return; return;
} }
switch (Code) { switch (Code) {
@@ -204,18 +162,18 @@ void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<u
} }
return; return;
case 'p': case 'p':
if (!Network.Respond(*Client, StringToVector("p"), false)) { if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
// failed to send // failed to send
Network.Disconnect(Client); LockedClient->Disconnect("Failed to send ping");
} else { } else {
Network.UpdatePlayer(*Client); Network.UpdatePlayer(*LockedClient);
} }
return; return;
case 'O': case 'O':
if (Packet.size() > 1000) { if (Packet.size() > 1000) {
beammp_debug(("Received data from: ") + Client->Name.get() + (" Size: ") + std::to_string(Packet.size())); beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
} }
ParseVehicle(*Client, StringPacket, Network); ParseVehicle(*LockedClient, StringPacket, Network);
return; return;
case 'C': { case 'C': {
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end()) if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
@@ -227,12 +185,12 @@ void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<u
Message = PacketAsString.substr(ColonPos + 2); Message = PacketAsString.substr(ColonPos + 2);
} }
if (Message.empty()) { if (Message.empty()) {
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", Client->Name.get(), Client->ID.get()); beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
return; return;
} }
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", Client->ID.get(), Client->Name.get(), Message); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
LogChatMessage(Client->Name.get(), Client->ID.get(), PacketAsString.substr(PacketAsString.find(':', 3) + 1)); LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
if (std::any_of(Futures.begin(), Futures.end(), if (std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Elem) { [](const std::shared_ptr<TLuaResult>& Elem) {
return !Elem->Error return !Elem->Error
@@ -241,22 +199,21 @@ void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<u
})) { })) {
break; break;
} }
std::string SanitizedPacket = fmt::format("C:{}: {}", Client->Name.get(), Message); std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true); Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
return; return;
} }
case 'E': case 'E':
HandleEvent(*Client, StringPacket); HandleEvent(*LockedClient, StringPacket);
return; return;
case 'N': case 'N':
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")"); beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(Client.get(), Packet, false, true); Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
case 'Z': // position packet case 'Z': // position packet
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(Client.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
HandlePosition(*Client, StringPacket); HandlePosition(*LockedClient, StringPacket);
return;
default: default:
return; return;
} }
@@ -266,7 +223,7 @@ void TServer::HandleEvent(TClient& c, const std::string& RawData) {
// E:Name:Data // E:Name:Data
// Data is allowed to have ':' // Data is allowed to have ':'
if (RawData.size() < 2) { if (RawData.size() < 2) {
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.Name.get(), c.ID.get()); beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
return; return;
} }
auto NameDataSep = RawData.find(':', 2); auto NameDataSep = RawData.find(':', 2);
@@ -275,7 +232,7 @@ void TServer::HandleEvent(TClient& c, const std::string& RawData) {
} }
std::string Name = RawData.substr(2, NameDataSep - 2); std::string Name = RawData.substr(2, NameDataSep - 2);
std::string Data = RawData.substr(NameDataSep + 1); std::string Data = RawData.substr(NameDataSep + 1);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.ID.get(), Data)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
} }
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) { bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
@@ -286,15 +243,14 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
return true; return true;
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.ID.get()) + ": '" + CarJson + "'."); beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
} }
return false; return false;
} }
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) { bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
auto UnicycleID = c.UnicycleID.synchronize(); if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
if (IsUnicycle(c, CarJson) && *UnicycleID < 0) { c.SetUnicycleID(ID);
*UnicycleID = ID;
return true; return true;
} else { } else {
return c.GetCarCount() < Application::Settings.MaxCars; return c.GetCarCount() < Application::Settings.MaxCars;
@@ -314,11 +270,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size()); beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
if (Data.at(0) == '0') { if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID(); int CarID = c.GetOpenCarID();
beammp_debugf("'{}' created a car with ID {}", c.Name.get(), CarID); beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
std::string CarJson = Packet.substr(5); std::string CarJson = Packet.substr(5);
Packet = "Os:" + c.Role.get() + ":" + c.Name.get() + ":" + std::to_string(c.ID.get()) + "-" + std::to_string(CarID) + ":" + CarJson; Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.ID.get(), CarID, Packet.substr(3)); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(), bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -332,11 +288,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (!Network.Respond(c, StringToVector(Packet), true)) { if (!Network.Respond(c, StringToVector(Packet), true)) {
// TODO: handle // TODO: handle
} }
std::string Destroy = "Od:" + std::to_string(c.ID.get()) + "-" + std::to_string(CarID); std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, StringToVector(Destroy), true)) { if (!Network.Respond(c, StringToVector(Destroy), true)) {
// TODO: handle // TODO: handle
} }
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.Name.get(), CarID); beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
} }
} }
return; return;
@@ -346,8 +302,8 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.ID.get()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.ID.get(), VID, Packet.substr(3)); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(), bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -356,16 +312,15 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
auto FoundPos = Packet.find('{'); auto FoundPos = Packet.find('{');
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
auto UnicycleID = c.UnicycleID.synchronize(); if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
if ((*UnicycleID != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& !ShouldntAllow) { && !ShouldntAllow) {
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, StringToVector(Packet), false, true);
Apply(c, VID, Packet); Apply(c, VID, Packet);
} else { } else {
if (*UnicycleID == VID) { if (c.GetUnicycleID() == VID) {
*UnicycleID = -1; c.SetUnicycleID(-1);
} }
std::string Destroy = "Od:" + std::to_string(c.ID.get()) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
Network.SendToAll(nullptr, StringToVector(Destroy), true, true); Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
c.DeleteCar(VID); c.DeleteCar(VID);
} }
@@ -378,16 +333,15 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.ID.get()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
auto UnicycleID = c.UnicycleID.synchronize(); if (c.GetUnicycleID() == VID) {
if (*UnicycleID == VID) { c.SetUnicycleID(-1);
*UnicycleID = -1;
} }
Network.SendToAll(nullptr, StringToVector(Packet), true, true); Network.SendToAll(nullptr, StringToVector(Packet), true, true);
// TODO: should this trigger on all vehicle deletions? // TODO: should this trigger on all vehicle deletions?
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.ID.get(), VID)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
c.DeleteCar(VID); c.DeleteCar(VID);
beammp_debug(c.Name.get() + (" deleted car with ID ") + std::to_string(VID)); beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
} }
return; return;
} }
@@ -398,9 +352,9 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.ID.get()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
Data = Data.substr(Data.find('{')); Data = Data.substr(Data.find('{'));
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.ID.get(), VID, Data)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, StringToVector(Packet), false, true);
} }
return; return;
@@ -434,7 +388,7 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
FoundPos = VD.find('{'); FoundPos = VD.find('{');
if (FoundPos == std::string::npos) { if (FoundPos == std::string::npos) {
return; return;
} }
VD = VD.substr(FoundPos); VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack; rapidjson::Document Veh, Pack;
@@ -468,63 +422,35 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
(void)mClients.insert(NewClient); (void)mClients.insert(NewClient);
} }
struct PidVidData { void TServer::HandlePosition(TClient& c, const std::string& Packet) {
int PID;
int VID;
std::string Data;
};
static std::optional<PidVidData> ParsePositionPacket(const std::string& Packet) {
if (Packet.size() < 3) { if (Packet.size() < 3) {
// invalid packet // invalid packet
return std::nullopt; return;
} }
// Zp:PID-VID:DATA // Zp:serverVehicleID:data
// Zp:0:data
std::string withoutCode = Packet.substr(3); 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);
// parse veh ID // parse veh ID
if (auto DataBeginPos = withoutCode.find('{'); DataBeginPos != std::string::npos && DataBeginPos != 0) { auto MaybePidVid = GetPidVid(ServerVehicleID);
// separator is :{, so position of { minus one if (MaybePidVid) {
auto PidVidOnly = withoutCode.substr(0, DataBeginPos - 1); int PID = -1;
auto MaybePidVid = GetPidVid(PidVidOnly); int VID = -1;
if (MaybePidVid) { // FIXME: check that the VID and PID are valid, so that we don't waste memory
int PID = -1; std::tie(PID, VID) = MaybePidVid.value();
int VID = -1;
// FIXME: check that the VID and PID are valid, so that we don't waste memory
std::tie(PID, VID) = MaybePidVid.value();
std::string Data = withoutCode.substr(DataBeginPos); c.SetCarPosition(VID, Data);
return PidVidData {
.PID = PID,
.VID = VID,
.Data = Data,
};
} else {
// invalid packet
return std::nullopt;
}
}
// invalid packet
return std::nullopt;
}
TEST_CASE("ParsePositionPacket") {
const auto TestData = R"({"tim":10.428000331623,"vel":[-2.4171722121385e-05,-9.7184734153252e-06,-7.6420763232237e-06],"rot":[-0.0001296154171915,0.0031575385950029,0.98994906610295,0.14138903660382],"rvel":[5.3640324636461e-05,-9.9824529946024e-05,5.1664064641372e-05],"pos":[-0.27281248907838,-0.20515357944633,0.49695488960431],"ping":0.032999999821186})";
SUBCASE("All the pids and vids") {
for (int pid = 0; pid < 100; ++pid) {
for (int vid = 0; vid < 100; ++vid) {
std::optional<PidVidData> MaybeRes = ParsePositionPacket(fmt::format("Zp:{}-{}:{}", pid, vid, TestData));
CHECK(MaybeRes.has_value());
CHECK_EQ(MaybeRes.value().PID, pid);
CHECK_EQ(MaybeRes.value().VID, vid);
CHECK_EQ(MaybeRes.value().Data, TestData);
}
}
}
}
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
if (auto Parsed = ParsePositionPacket(Packet); Parsed.has_value()) {
c.SetCarPosition(Parsed.value().VID, Parsed.value().Data);
} }
} }
+15 -14
View File
@@ -69,6 +69,7 @@ int main(int argc, char** argv) {
int BeamMPServerMain(MainArguments Arguments) { int BeamMPServerMain(MainArguments Arguments) {
setlocale(LC_ALL, "C"); setlocale(LC_ALL, "C");
Application::InitializeConsole();
ArgsParser Parser; ArgsParser Parser;
Parser.RegisterArgument({ "help" }, ArgsParser::NONE); Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
Parser.RegisterArgument({ "version" }, ArgsParser::NONE); Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
@@ -79,10 +80,12 @@ 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().Internal().set_prompt("");
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString()); Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
return 0; return 0;
} }
@@ -107,21 +110,10 @@ int BeamMPServerMain(MainArguments Arguments) {
} }
} }
TConfig Config(ConfigPath);
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;
}
Application::InitializeConsole();
Application::Console().StartLoggingToFile();
Application::SetSubsystemStatus("Main", Application::Status::Starting); Application::SetSubsystemStatus("Main", Application::Status::Starting);
Application::Console().StartLoggingToFile();
SetupSignalHandlers(); SetupSignalHandlers();
bool Shutdown = false; bool Shutdown = false;
@@ -136,11 +128,20 @@ int BeamMPServerMain(MainArguments Arguments) {
}); });
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");
+1 -1
Submodule vcpkg updated: 8397227251...72010900b7.
+6 -6
View File
@@ -2,18 +2,18 @@
"name": "server", "name": "server",
"version-string": "0.1.0", "version-string": "0.1.0",
"dependencies": [ "dependencies": [
"fmt",
"doctest",
"boost-asio", "boost-asio",
"boost-variant",
"boost-spirit", "boost-spirit",
"boost-uuid", "boost-uuid",
"boost-variant",
"cpp-httplib", "cpp-httplib",
"doctest", "toml11",
"fmt",
"libzip", "libzip",
"rapidjson",
"nlohmann-json", "nlohmann-json",
"openssl", "openssl",
"rapidjson", "sol2"
"sol2",
"toml11"
] ]
} }