mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
144 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0d560405c | |||
| 98c69561b5 | |||
| d0cc23333c | |||
| c173ffdbdc | |||
| 7d813f7562 | |||
| ee74d6291b | |||
| 8654beb706 | |||
| 630d5f1cfa | |||
| bde689d31a | |||
| 303a619ece | |||
| 24723c01da | |||
| b06991aaca | |||
| e0fe6693e0 | |||
| b882174ae7 | |||
| 3de142a6d0 | |||
| 9502048525 | |||
| 9e99177fcb | |||
| dbab9eb894 | |||
| 9ea0931e13 | |||
| e9805c3679 | |||
| ff33f1d42f | |||
| 65d2ba3556 | |||
| 6a411171f9 | |||
| 05dfb4e0c3 | |||
| 4aca87d3e6 | |||
| 7e9bb0cbf2 | |||
| 443871ec0f | |||
| 130e1acdb3 | |||
| aa29d04b60 | |||
| b9f73f77c3 | |||
| c6aa7776fc | |||
| b0f5976121 | |||
| 1bd47fa649 | |||
| 0e924d0d51 | |||
| 70a7a41882 | |||
| 6ee816d10d | |||
| 8695413211 | |||
| 52c5a995cc | |||
| 9d5568dc56 | |||
| c62a1b6add | |||
| 4228e18c90 | |||
| 023e968302 | |||
| a4eb10b6a4 | |||
| 0166e488d0 | |||
| 0836fd3af8 | |||
| 9791b8875c | |||
| 01e8a1644a | |||
| cebb2634a1 | |||
| 21a7ca1b64 | |||
| bd4ab2b10d | |||
| 1cdc8e8f48 | |||
| 1f72a45231 | |||
| 002223afda | |||
| ecc79b1918 | |||
| d5000aea87 | |||
| 810788a3e4 | |||
| e724a2e467 | |||
| 54ba295fce | |||
| f419550061 | |||
| 8cccbe8542 | |||
| 6787843b37 | |||
| 16d3c6f796 | |||
| 21e5101560 | |||
| 1adf19d416 | |||
| c7e228fbae | |||
| 6e04b2d93a | |||
| 57a4c47cb0 | |||
| 416e0399af | |||
| 050b574cc0 | |||
| d65f3cf75b | |||
| 329d2eb268 | |||
| 221f491019 | |||
| 89db370e12 | |||
| aa84a65546 | |||
| b28c69a515 | |||
| ac41547123 | |||
| 2fc610f6bc | |||
| ddd3883aa9 | |||
| defadf094f | |||
| 81299db946 | |||
| c3895ec1ca | |||
| c741fe5310 | |||
| e1dfb1085e | |||
| 142b6fa47a | |||
| a6cbffc774 | |||
| dc4ead532d | |||
| f28d9bc7dc | |||
| 8c73eb8aea | |||
| 43b1b050e2 | |||
| 9f87edc6e9 | |||
| c6f78c5522 | |||
| 9f01268538 | |||
| 5523a4fe4b | |||
| 7f11d0f002 | |||
| 6b31ba35fd | |||
| d2329f0723 | |||
| ef45efeb86 | |||
| edcca75637 | |||
| c1bacf1f3a | |||
| 795b651744 | |||
| be108bb8b3 | |||
| d8b8812026 | |||
| 872c2d410d | |||
| f98704e0f3 | |||
| dea203c108 | |||
| e245c9e9e2 | |||
| 11fe5ad200 | |||
| 667da22b0e | |||
| a6eb2f7bfe | |||
| 103d2dc030 | |||
| 7f206fd0d4 | |||
| 22805af716 | |||
| 2c29a195f9 | |||
| 222d2492ff | |||
| 879b9772f5 | |||
| c51cf090ef | |||
| d677d8d58d | |||
| 4b30918659 | |||
| 688e46f524 | |||
| 9f59c27b1f | |||
| 6a11bcd20b | |||
| b7b578bf3e | |||
| 6c145a6dbf | |||
| 67d792e0e0 | |||
| eaeef0c7d0 | |||
| 47e64a7343 | |||
| 7f5b3919f4 | |||
| 896e777e23 | |||
| aa58c1e211 | |||
| 49a9226dca | |||
| b10d5d0f4e | |||
| 5581fd1692 | |||
| d36bb7962c | |||
| 4e8bd993d5 | |||
| abff9bfbdb | |||
| b024533f90 | |||
| f9251ff92c | |||
| 99f41c28cb | |||
| bbd27c9cba | |||
| 4682922467 | |||
| 83fb387dfe | |||
| 2b61f11a86 | |||
| a8b1a205f7 | |||
| dd9376447a |
@@ -1,7 +1,6 @@
|
|||||||
---
|
---
|
||||||
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: ''
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: Feature request
|
name: Feature request
|
||||||
about: Suggest an idea for this project
|
about: Suggest an idea for this project
|
||||||
title: "[Feature Request]"
|
labels: feature
|
||||||
labels: enhancement
|
|
||||||
assignees: ''
|
assignees: ''
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,78 +0,0 @@
|
|||||||
name: CMake Linux Build
|
|
||||||
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
env:
|
|
||||||
BUILD_TYPE: Release
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
linux-build:
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: "recursive"
|
|
||||||
|
|
||||||
- name: Install Dependencies
|
|
||||||
env:
|
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
|
||||||
run: |
|
|
||||||
echo ${#beammp_sentry_url}
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
|
||||||
|
|
||||||
- name: Configure CMake
|
|
||||||
shell: bash
|
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
|
||||||
env:
|
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
|
||||||
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
|
||||||
|
|
||||||
- name: Build Server
|
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
|
||||||
shell: bash
|
|
||||||
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
|
||||||
|
|
||||||
- name: Build Tests
|
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
|
||||||
shell: bash
|
|
||||||
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server-tests --parallel
|
|
||||||
|
|
||||||
- name: Archive server artifact
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server-linux
|
|
||||||
path: ${{github.workspace}}/build-linux/BeamMP-Server
|
|
||||||
|
|
||||||
- name: Archive test artifact
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server-linux-tests
|
|
||||||
path: ${{github.workspace}}/build-linux/BeamMP-Server-tests
|
|
||||||
|
|
||||||
run-tests:
|
|
||||||
needs: linux-build
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/download-artifact@master
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server-linux-tests
|
|
||||||
path: ${{github.workspace}}
|
|
||||||
|
|
||||||
- name: Install Runtime Dependencies
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y liblua5.3-0 libssl3 curl
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
working-directory: ${{github.workspace}}
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
chmod +x ./BeamMP-Server-tests
|
|
||||||
./BeamMP-Server-tests
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
name: CMake Windows Build
|
|
||||||
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
env:
|
|
||||||
BUILD_TYPE: Release
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
windows-build:
|
|
||||||
runs-on: windows-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: 'recursive'
|
|
||||||
|
|
||||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
|
||||||
uses: lukka/run-vcpkg@v7
|
|
||||||
id: runvcpkg
|
|
||||||
with:
|
|
||||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
|
||||||
vcpkgGitCommitId: "06b5f4a769d848d1a20fa0acd556019728b56273"
|
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
|
||||||
|
|
||||||
- name: Configure CMake
|
|
||||||
shell: bash
|
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
|
||||||
env:
|
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
|
||||||
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
|
||||||
shell: bash
|
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
|
||||||
|
|
||||||
- name: Archive artifacts
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server.exe
|
|
||||||
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
|
|
||||||
|
|
||||||
- name: Build debug
|
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
cmake --build . --config Debug
|
|
||||||
|
|
||||||
- name: Archive debug artifacts
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
with:
|
|
||||||
name: BeamMP-Server-debug.exe
|
|
||||||
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
|
||||||
|
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
name: Linux
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
DEBIAN_FRONTEND: "noninteractive"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
x86_64-matrix:
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- distro: debian
|
||||||
|
version: 11
|
||||||
|
- distro: debian
|
||||||
|
version: 12
|
||||||
|
- distro: ubuntu
|
||||||
|
version: 22.04
|
||||||
|
- distro: ubuntu
|
||||||
|
version: 20.04
|
||||||
|
container:
|
||||||
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
|
steps:
|
||||||
|
- name: get-cmake
|
||||||
|
uses: lukka/get-cmake@v3.28.1
|
||||||
|
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||||
|
|
||||||
|
- 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:
|
||||||
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
|
steps:
|
||||||
|
- name: get-cmake
|
||||||
|
uses: lukka/get-cmake@v3.28.1
|
||||||
|
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: ./bin/BeamMP-Server-tests
|
||||||
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
name: Release Create & Build
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
# Sequence of patterns matched against refs/tags
|
|
||||||
tags:
|
|
||||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
|
||||||
|
|
||||||
env:
|
|
||||||
BUILD_TYPE: Release
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
create-release:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
name: Create Release
|
|
||||||
outputs:
|
|
||||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
|
||||||
steps:
|
|
||||||
- name: Create Release
|
|
||||||
id: create_release
|
|
||||||
uses: actions/create-release@v1
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
tag_name: ${{ github.ref }}
|
|
||||||
release_name: ${{ github.ref }}
|
|
||||||
draft: false
|
|
||||||
prerelease: true
|
|
||||||
body: |
|
|
||||||
Files included in this release:
|
|
||||||
- `BeamMP-Server.exe` is the windows build
|
|
||||||
- `BeamMP-Server-linux` is a ubuntu build, so you need the dependencies listed in README.md to run it. For any other distros please build from source as described in README.md.
|
|
||||||
|
|
||||||
upload-release-files-linux:
|
|
||||||
name: Upload Linux Release Files
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
needs: create-release
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: 'recursive'
|
|
||||||
|
|
||||||
- name: Install Dependencies
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev libboost-dev libboost1.74-all-dev libboost1.74-dev
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
|
||||||
|
|
||||||
- name: Configure CMake
|
|
||||||
shell: bash
|
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
|
||||||
env:
|
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
|
||||||
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
|
||||||
shell: bash
|
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
|
||||||
|
|
||||||
- name: Upload Release Asset
|
|
||||||
id: upload-release-asset
|
|
||||||
uses: actions/upload-release-asset@v1
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
|
|
||||||
asset_path: ${{github.workspace}}/build-linux/BeamMP-Server
|
|
||||||
asset_name: BeamMP-Server-linux
|
|
||||||
asset_content_type: application/x-elf
|
|
||||||
|
|
||||||
upload-release-files-windows:
|
|
||||||
name: Upload Windows Release Files
|
|
||||||
runs-on: windows-latest
|
|
||||||
needs: create-release
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
with:
|
|
||||||
submodules: 'recursive'
|
|
||||||
|
|
||||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
|
||||||
uses: lukka/run-vcpkg@v7
|
|
||||||
id: runvcpkg
|
|
||||||
with:
|
|
||||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
|
||||||
vcpkgGitCommitId: '06b5f4a769d848d1a20fa0acd556019728b56273'
|
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
|
||||||
|
|
||||||
- name: Configure CMake
|
|
||||||
shell: bash
|
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
|
||||||
env:
|
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
|
||||||
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
|
||||||
shell: bash
|
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
|
||||||
|
|
||||||
- name: Upload Release Asset
|
|
||||||
id: upload-release-asset
|
|
||||||
uses: actions/upload-release-asset@v1
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
with:
|
|
||||||
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
|
|
||||||
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
|
|
||||||
asset_name: BeamMP-Server.exe
|
|
||||||
asset_content_type: application/vnd.microsoft.portable-executable
|
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
name: Release Create & Build
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
# Sequence of patterns matched against refs/tags
|
||||||
|
tags:
|
||||||
|
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
DEBIAN_FRONTEND: "noninteractive"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
create-release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
name: Create Release
|
||||||
|
outputs:
|
||||||
|
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||||
|
steps:
|
||||||
|
- name: Create Release
|
||||||
|
id: create_release
|
||||||
|
uses: actions/create-release@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.ref }}
|
||||||
|
release_name: ${{ github.ref }}
|
||||||
|
draft: false
|
||||||
|
prerelease: true
|
||||||
|
body: |
|
||||||
|
Files included in this release are:
|
||||||
|
- `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` 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.
|
||||||
|
|
||||||
|
x86_64-matrix:
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
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:
|
||||||
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
|
steps:
|
||||||
|
- name: get-cmake
|
||||||
|
uses: lukka/get-cmake@v3.28.1
|
||||||
|
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
|
- name: Upload Release Asset
|
||||||
|
id: upload-release-asset
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- 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 }}.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
|
||||||
|
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:
|
||||||
|
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||||
|
steps:
|
||||||
|
- name: get-cmake
|
||||||
|
uses: lukka/get-cmake@v3.28.1
|
||||||
|
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||||
|
|
||||||
|
- name: Upload Release Asset
|
||||||
|
id: upload-release-asset
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- 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
|
||||||
|
|
||||||
|
upload-release-files-windows:
|
||||||
|
name: Build and upload Windows Release Files
|
||||||
|
runs-on: windows-latest
|
||||||
|
needs: create-release
|
||||||
|
env:
|
||||||
|
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
shell: bash
|
||||||
|
run: ./scripts/windows/1-configure.sh
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/windows/2-build.sh
|
||||||
|
|
||||||
|
- name: Upload Release Asset
|
||||||
|
id: upload-release-asset
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/Release/BeamMP-Server.exe
|
||||||
|
asset_name: BeamMP-Server.exe
|
||||||
|
asset_content_type: application/vnd.microsoft.portable-executable
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
name: Windows
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
windows-build:
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
shell: bash
|
||||||
|
run: ./scripts/windows/1-configure.sh
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/windows/2-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-windows
|
||||||
|
path: ./bin/Release/BeamMP-Server.exe
|
||||||
|
|
||||||
+6
-30
@@ -1,33 +1,9 @@
|
|||||||
[submodule "deps/commandline"]
|
[submodule "deps/commandline"]
|
||||||
path = deps/commandline
|
path = deps/commandline
|
||||||
url = https://github.com/lionkor/commandline
|
url = https://github.com/lionkor/commandline
|
||||||
[submodule "deps/asio"]
|
[submodule "vcpkg"]
|
||||||
path = deps/asio
|
path = vcpkg
|
||||||
url = https://github.com/chriskohlhoff/asio
|
url = https://github.com/Microsoft/vcpkg.git
|
||||||
[submodule "deps/rapidjson"]
|
[submodule "deps/BeamMP-Protocol"]
|
||||||
path = deps/rapidjson
|
path = deps/BeamMP-Protocol
|
||||||
url = https://github.com/Tencent/rapidjson
|
url = https://github.com/BeamMP/BeamMP-Protocol
|
||||||
[submodule "deps/toml11"]
|
|
||||||
path = deps/toml11
|
|
||||||
url = https://github.com/ToruNiina/toml11
|
|
||||||
[submodule "deps/sentry-native"]
|
|
||||||
path = deps/sentry-native
|
|
||||||
url = https://github.com/getsentry/sentry-native
|
|
||||||
[submodule "deps/sol2"]
|
|
||||||
path = deps/sol2
|
|
||||||
url = https://github.com/ThePhD/sol2
|
|
||||||
[submodule "deps/libzip"]
|
|
||||||
path = deps/libzip
|
|
||||||
url = https://github.com/nih-at/libzip
|
|
||||||
[submodule "deps/cpp-httplib"]
|
|
||||||
path = deps/cpp-httplib
|
|
||||||
url = https://github.com/yhirose/cpp-httplib
|
|
||||||
[submodule "deps/json"]
|
|
||||||
path = deps/json
|
|
||||||
url = https://github.com/nlohmann/json
|
|
||||||
[submodule "deps/fmt"]
|
|
||||||
path = deps/fmt
|
|
||||||
url = https://github.com/fmtlib/fmt
|
|
||||||
[submodule "deps/doctest"]
|
|
||||||
path = deps/doctest
|
|
||||||
url = https://github.com/doctest/doctest
|
|
||||||
|
|||||||
+187
-233
@@ -1,261 +1,215 @@
|
|||||||
# 3.4 is required for imported targets.
|
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
|
||||||
cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
|
|
||||||
|
|
||||||
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
if (WIN32)
|
||||||
https://github.com/BeamMP/BeamMP-Server")
|
set(VCPKG_TARGET_TRIPLET x64-windows-static)
|
||||||
|
|
||||||
project(BeamMP-Server
|
|
||||||
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
|
|
||||||
HOMEPAGE_URL https://beammp.com
|
|
||||||
LANGUAGES CXX C)
|
|
||||||
|
|
||||||
find_package(Git REQUIRED)
|
|
||||||
# Update submodules as needed
|
|
||||||
option(GIT_SUBMODULE "Check submodules during build" ON)
|
|
||||||
if(GIT_SUBMODULE)
|
|
||||||
message(STATUS "Submodule update")
|
|
||||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
|
||||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
|
||||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
|
||||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
|
||||||
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
|
||||||
endif()
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
include(cmake/Vcpkg.cmake) # needs to happen before project()
|
||||||
|
|
||||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
project(
|
||||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
"BeamMP-Server" # replace this
|
||||||
|
VERSION 3.3.0
|
||||||
|
)
|
||||||
|
|
||||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
include(cmake/StandardSettings.cmake)
|
||||||
|
include(cmake/StaticAnalyzers.cmake)
|
||||||
|
include(cmake/Git.cmake)
|
||||||
|
|
||||||
# ------------------------ APPLE ---------------------------------
|
add_subdirectory(deps/BeamMP-Protocol)
|
||||||
if(APPLE)
|
|
||||||
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
|
|
||||||
set(LUA_INCLUDE_DIR /opt/homebrew/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
|
||||||
link_directories(/opt/homebrew/Cellar/lua@5.3/5.3.6/lib)
|
|
||||||
else()
|
|
||||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
|
||||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
|
||||||
endif()
|
|
||||||
set(LUA_LIBRARIES lua)
|
|
||||||
if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
|
|
||||||
include_directories(/opt/homebrew/opt/openssl@1.1/include)
|
|
||||||
link_directories(/opt/homebrew/opt/openssl@1.1/lib)
|
|
||||||
else()
|
|
||||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
|
||||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
|
||||||
endif()
|
|
||||||
# ------------------------ WINDOWS ---------------------------------
|
|
||||||
option(WIN32_STATIC_RUNTIME "Build statically-linked runtime on windows (don't touch unless you know what you're doing)" ON)
|
|
||||||
elseif (WIN32)
|
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
|
||||||
if (WIN32_STATIC_RUNTIME)
|
|
||||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
|
||||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
|
||||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
|
||||||
endif()
|
|
||||||
# ------------------------ LINUX ---------------------------------
|
|
||||||
elseif (UNIX)
|
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
|
||||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
|
||||||
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
|
||||||
if (SANITIZE)
|
|
||||||
message(STATUS "sanitize is ON")
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize={address,thread,undefined}")
|
|
||||||
endif (SANITIZE)
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
set(BUILD_SHARED_LIBS OFF)
|
# below are options which should be changed
|
||||||
# ------------------------ SENTRY ---------------------------------
|
|
||||||
message(STATUS "Checking for Sentry URL")
|
|
||||||
# this is set by the build system.
|
|
||||||
# IMPORTANT: if you're building from source, just leave this empty
|
|
||||||
if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
|
|
||||||
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
|
|
||||||
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
|
|
||||||
set(BEAMMP_SECRET_SENTRY_URL "")
|
|
||||||
set(SENTRY_BACKEND none)
|
|
||||||
else()
|
|
||||||
set(SENTRY_BACKEND breakpad)
|
|
||||||
endif()
|
|
||||||
add_subdirectory("deps/sentry-native")
|
|
||||||
|
|
||||||
# ------------------------ C++ SETUP ---------------------------------
|
### SETTINGS ###
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
if (MSVC)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
# ------------------------ DEPENDENCIES ------------------------------
|
# add all headers (.h, .hpp) to this
|
||||||
message(STATUS "Adding local source dependencies")
|
set(PRJ_HEADERS
|
||||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
include/ArgsParser.h
|
||||||
add_subdirectory(deps)
|
|
||||||
|
|
||||||
# ------------------------ VARIABLES ---------------------------------
|
|
||||||
|
|
||||||
include(FindLua)
|
|
||||||
include(FindOpenSSL)
|
|
||||||
include(FindThreads)
|
|
||||||
include(FindZLIB)
|
|
||||||
|
|
||||||
find_package(Boost 1.70 REQUIRED COMPONENTS system)
|
|
||||||
|
|
||||||
set(BeamMP_Sources
|
|
||||||
include/TConsole.h src/TConsole.cpp
|
|
||||||
include/TServer.h src/TServer.cpp
|
|
||||||
include/Compat.h src/Compat.cpp
|
|
||||||
include/Common.h src/Common.cpp
|
|
||||||
include/Client.h src/Client.cpp
|
|
||||||
include/VehicleData.h src/VehicleData.cpp
|
|
||||||
include/TConfig.h src/TConfig.cpp
|
|
||||||
include/TLuaEngine.h src/TLuaEngine.cpp
|
|
||||||
include/TLuaPlugin.h src/TLuaPlugin.cpp
|
|
||||||
include/TResourceManager.h src/TResourceManager.cpp
|
|
||||||
include/THeartbeatThread.h src/THeartbeatThread.cpp
|
|
||||||
include/Http.h src/Http.cpp
|
|
||||||
include/TSentry.h src/TSentry.cpp
|
|
||||||
include/TPPSMonitor.h src/TPPSMonitor.cpp
|
|
||||||
include/TNetwork.h src/TNetwork.cpp
|
|
||||||
include/LuaAPI.h src/LuaAPI.cpp
|
|
||||||
include/TScopedTimer.h src/TScopedTimer.cpp
|
|
||||||
include/SignalHandling.h src/SignalHandling.cpp
|
|
||||||
include/ArgsParser.h src/ArgsParser.cpp
|
|
||||||
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
|
||||||
include/Environment.h
|
|
||||||
include/BoostAliases.h
|
include/BoostAliases.h
|
||||||
|
include/Common.h
|
||||||
|
include/Compat.h
|
||||||
|
include/Cryptography.h
|
||||||
|
include/CustomAssert.h
|
||||||
|
include/Defer.h
|
||||||
|
include/Environment.h
|
||||||
|
include/Http.h
|
||||||
|
include/IThreaded.h
|
||||||
|
include/Json.h
|
||||||
|
include/LuaAPI.h
|
||||||
|
include/RWMutex.h
|
||||||
|
include/SignalHandling.h
|
||||||
|
include/TConfig.h
|
||||||
|
include/TConsole.h
|
||||||
|
include/THeartbeatThread.h
|
||||||
|
include/TLuaEngine.h
|
||||||
|
include/TLuaPlugin.h
|
||||||
|
include/TPluginMonitor.h
|
||||||
|
include/TScopedTimer.h
|
||||||
|
include/VehicleData.h
|
||||||
|
include/Env.h
|
||||||
|
include/Network.h
|
||||||
|
)
|
||||||
|
# add all source files (.cpp) to this, except the one with main()
|
||||||
|
set(PRJ_SOURCES
|
||||||
|
src/ArgsParser.cpp
|
||||||
|
src/Common.cpp
|
||||||
|
src/Compat.cpp
|
||||||
|
src/Http.cpp
|
||||||
|
src/LuaAPI.cpp
|
||||||
|
src/SignalHandling.cpp
|
||||||
|
src/TConfig.cpp
|
||||||
|
src/TConsole.cpp
|
||||||
|
src/THeartbeatThread.cpp
|
||||||
|
src/TLuaEngine.cpp
|
||||||
|
src/TLuaPlugin.cpp
|
||||||
|
src/TPluginMonitor.cpp
|
||||||
|
src/TScopedTimer.cpp
|
||||||
|
src/VehicleData.cpp
|
||||||
|
src/Env.cpp
|
||||||
|
src/Network.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
set(BeamMP_Includes
|
find_package(Lua REQUIRED)
|
||||||
${LUA_INCLUDE_DIR}
|
|
||||||
${CURL_INCLUDE_DIRS}
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps"
|
|
||||||
)
|
|
||||||
|
|
||||||
set(BeamMP_Definitions
|
# set the source file containing main()
|
||||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
set(PRJ_MAIN src/main.cpp)
|
||||||
)
|
# set the source file containing the test's main
|
||||||
|
set(PRJ_TEST_MAIN test/test_main.cpp)
|
||||||
if (WIN32)
|
# set include paths not part of libraries
|
||||||
list(APPEND BeamMP_Definitions _WIN32_WINNT=0x0601)
|
set(PRJ_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
|
||||||
list(APPEND BeamMP_Definitions _CRT_SECURE_NO_WARNINGS)
|
# set compile features (e.g. standard version)
|
||||||
endif()
|
set(PRJ_COMPILE_FEATURES cxx_std_20)
|
||||||
if (UNIX)
|
# set #defines (test enable/disable not included here)
|
||||||
set(BeamMP_CompileOptions
|
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||||
-Wall
|
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||||
-Wextra
|
set(PRJ_LIBRARIES
|
||||||
-Wpedantic
|
|
||||||
|
|
||||||
-Werror=uninitialized
|
|
||||||
-Werror=float-equal
|
|
||||||
-Werror=pointer-arith
|
|
||||||
-Werror=double-promotion
|
|
||||||
-Werror=write-strings
|
|
||||||
-Werror=cast-qual
|
|
||||||
-Werror=init-self
|
|
||||||
-Werror=cast-align
|
|
||||||
-Werror=unreachable-code
|
|
||||||
-Werror=strict-aliasing -fstrict-aliasing
|
|
||||||
-Werror=redundant-decls
|
|
||||||
-Werror=missing-declarations
|
|
||||||
-Werror=missing-field-initializers
|
|
||||||
-Werror=write-strings
|
|
||||||
-Werror=ctor-dtor-privacy
|
|
||||||
-Werror=switch-enum
|
|
||||||
-Werror=switch-default
|
|
||||||
-Werror=old-style-cast
|
|
||||||
-Werror=overloaded-virtual
|
|
||||||
-Werror=overloaded-virtual
|
|
||||||
-Werror=missing-include-dirs
|
|
||||||
-Werror=unused-result
|
|
||||||
|
|
||||||
-fstack-protector
|
|
||||||
-Wzero-as-null-pointer-constant
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
set(BeamMP_Libraries
|
|
||||||
Boost::boost
|
|
||||||
Boost::system
|
|
||||||
doctest::doctest
|
|
||||||
OpenSSL::SSL
|
|
||||||
OpenSSL::Crypto
|
|
||||||
sol2::sol2
|
|
||||||
fmt::fmt
|
fmt::fmt
|
||||||
|
doctest::doctest
|
||||||
Threads::Threads
|
Threads::Threads
|
||||||
ZLIB::ZLIB
|
commandline_static
|
||||||
|
toml11::toml11
|
||||||
|
rapidjson
|
||||||
|
sol2
|
||||||
|
httplib::httplib
|
||||||
|
libzip::zip
|
||||||
|
OpenSSL::SSL OpenSSL::Crypto
|
||||||
|
protocol
|
||||||
${LUA_LIBRARIES}
|
${LUA_LIBRARIES}
|
||||||
commandline
|
zstd::libzstd_static
|
||||||
sentry
|
Boost::thread
|
||||||
|
glm::glm
|
||||||
)
|
)
|
||||||
|
|
||||||
if (WIN32)
|
# add dependency find_package calls and similar here
|
||||||
set(BeamMP_PlatformLibs wsock32 ws2_32)
|
find_package(fmt CONFIG REQUIRED)
|
||||||
endif ()
|
find_package(OpenSSL REQUIRED)
|
||||||
|
find_package(doctest CONFIG REQUIRED)
|
||||||
|
find_package(Boost REQUIRED COMPONENTS thread)
|
||||||
|
find_package(httplib CONFIG REQUIRED)
|
||||||
|
find_package(libzip CONFIG REQUIRED)
|
||||||
|
find_package(RapidJSON CONFIG REQUIRED)
|
||||||
|
find_package(sol2 CONFIG REQUIRED)
|
||||||
|
find_package(toml11 CONFIG REQUIRED)
|
||||||
|
find_package(zstd CONFIG REQUIRED)
|
||||||
|
find_package(glm CONFIG REQUIRED)
|
||||||
|
|
||||||
# ------------------------ BEAMMP SERVER -----------------------------
|
include_directories(include)
|
||||||
|
|
||||||
add_executable(BeamMP-Server
|
# to enable multithreading and the Threads::Threads dependency
|
||||||
src/main.cpp
|
include(FindThreads)
|
||||||
${BeamMP_Sources}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_compile_definitions(BeamMP-Server PRIVATE
|
### END SETTINGS ###
|
||||||
${BeamMP_Definitions}
|
|
||||||
DOCTEST_CONFIG_DISABLE
|
|
||||||
)
|
|
||||||
|
|
||||||
target_compile_options(BeamMP-Server PRIVATE
|
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||||
${BeamMP_CompileOptions}
|
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server PRIVATE
|
####################
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server SYSTEM PRIVATE
|
|
||||||
${BeamMP_Includes}
|
|
||||||
)
|
|
||||||
|
|
||||||
target_link_libraries(BeamMP-Server
|
# enables compile_commands.json for clang-related tools (such as the clang LS)
|
||||||
${BeamMP_Libraries}
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
${BeamMP_PlatformLibs}
|
|
||||||
)
|
|
||||||
|
|
||||||
# ------------------------ BEAMMP SERVER TESTS -----------------------
|
# build release builds by default (if not specified otherwise)
|
||||||
|
if(NOT DEFINED CMAKE_BUILD_TYPE)
|
||||||
option(BUILD_TESTS "Build BeamMP-Server tests" ON)
|
message(NOTICE "No build type specified, defaulting to 'Release'")
|
||||||
|
set(CMAKE_BUILD_TYPE "Release")
|
||||||
if(BUILD_TESTS)
|
endif()
|
||||||
add_executable(BeamMP-Server-tests
|
|
||||||
test/test_main.cpp
|
if(UNIX)
|
||||||
${BeamMP_Sources}
|
# this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
|
||||||
)
|
add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
|
||||||
|
endif(UNIX)
|
||||||
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
|
||||||
${BeamMP_Definitions}
|
if (WIN32)
|
||||||
)
|
add_compile_options("-D_WIN32_WINNT=0x0601")
|
||||||
|
endif(WIN32)
|
||||||
target_compile_options(BeamMP-Server-tests PRIVATE
|
|
||||||
${BeamMP_CompileOptions}
|
|
||||||
)
|
include(cmake/CompilerWarnings.cmake)
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server-tests PRIVATE
|
# set MT library for msvc - this is required (says documentation)
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
# linux/mac/etc should simply ignore this by default.
|
||||||
)
|
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||||
|
|
||||||
target_include_directories(BeamMP-Server-tests SYSTEM PRIVATE
|
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
||||||
${BeamMP_Includes}
|
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||||
)
|
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||||
|
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||||
target_link_libraries(BeamMP-Server-tests
|
)
|
||||||
${BeamMP_Libraries}
|
|
||||||
${BeamMP_PlatformLibs}
|
# build commandline manually for funky windows flags to carry over without a custom toolchain file
|
||||||
)
|
add_library(commandline_static
|
||||||
|
deps/commandline/src/impls.h
|
||||||
|
deps/commandline/src/windows_impl.cpp
|
||||||
|
deps/commandline/src/linux_impl.cpp
|
||||||
|
deps/commandline/src/backends/InteractiveBackend.cpp
|
||||||
|
deps/commandline/src/backends/InteractiveBackend.h
|
||||||
|
deps/commandline/src/backends/Backend.cpp
|
||||||
|
deps/commandline/src/backends/Backend.h
|
||||||
|
deps/commandline/src/commandline.h
|
||||||
|
deps/commandline/src/commandline.cpp
|
||||||
|
deps/commandline/src/backends/BufferedBackend.cpp
|
||||||
|
deps/commandline/src/backends/BufferedBackend.h
|
||||||
|
)
|
||||||
|
if (WIN32)
|
||||||
|
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
|
||||||
|
else ()
|
||||||
|
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_LINUX=1)
|
||||||
|
endif ()
|
||||||
|
target_include_directories(commandline_static PUBLIC "deps/commandline/src")
|
||||||
|
target_link_libraries(commandline_static Threads::Threads)
|
||||||
|
# end of commandline custom build
|
||||||
|
|
||||||
|
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
|
||||||
|
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||||
|
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
||||||
|
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
||||||
|
MACOSX_BUNDLE TRUE
|
||||||
|
WIN32_EXECUTABLE TRUE
|
||||||
|
)
|
||||||
|
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||||
|
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
|
||||||
|
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||||
|
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
|
||||||
|
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
|
||||||
|
)
|
||||||
|
|
||||||
|
if(MSVC)
|
||||||
|
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
|
endif(MSVC)
|
||||||
|
|
||||||
|
# setup all warnings (from cmake/CompilerWarnings.cmake)
|
||||||
|
set_project_warnings(${PROJECT_NAME})
|
||||||
|
|
||||||
|
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
|
||||||
|
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
|
||||||
|
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
|
||||||
|
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||||
|
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
|
||||||
|
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||||
|
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
|
||||||
|
set_project_warnings(${PROJECT_NAME}-tests)
|
||||||
|
if(MSVC)
|
||||||
|
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||||
|
endif(MSVC)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|||||||
-149
@@ -1,149 +0,0 @@
|
|||||||
|
|
||||||
# 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
|
|
||||||
@@ -6,13 +6,12 @@
|
|||||||
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, listed below under "[prerequisites](#prerequisites)".**
|
**For Linux, you __need__ the runtime dependencies, which are listed below under [Runtime Dependencies](#runtime-dependencies)**
|
||||||
|
|
||||||
## 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)
|
||||||
|
|
||||||
@@ -43,7 +42,7 @@ We only allow building unmodified (original) source code for public use. `master
|
|||||||
|
|
||||||
## Supported Operating Systems
|
## Supported Operating Systems
|
||||||
|
|
||||||
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and sometimes Linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
|
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
|
||||||
|
|
||||||
Recommended compilers: MSVC, GCC, CLANG.
|
Recommended compilers: MSVC, GCC, CLANG.
|
||||||
|
|
||||||
@@ -51,128 +50,37 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__**
|
On Linux, you need some dependencies to **build** the server (on Windows, you don't):
|
||||||
|
|
||||||
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:
|
|
||||||
```
|
```
|
||||||
lua zlib rapidjson openssl websocketpp curl
|
liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||||
```
|
```
|
||||||
The triplet we use for releases is `x64-windows-static`.
|
|
||||||
|
|
||||||
#### Linux
|
You can install these with your distribution's package manager. You will need sudo or need root for ONLY this step.
|
||||||
|
|
||||||
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).
|
The names of each package may change depending on your platform.
|
||||||
|
|
||||||
##### Runtime Dependencies
|
If you are building for ARM (like aarch64), you need to run `export VCPKG_FORCE_SYSTEM_BINARIES=1` before the following commands.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
<details>
|
Debian, Ubuntu and friends: `liblua5.3-0`
|
||||||
<summary>
|
|
||||||
Ubuntu 22.04
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
`apt-get install` the following libraries:
|
Other Linux distros: `liblua` of *some kind*.
|
||||||
```
|
|
||||||
liblua5.3-0
|
|
||||||
libssl3
|
|
||||||
curl
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
Windows: No libraries.
|
||||||
<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
|
|
||||||
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++
|
|
||||||
cmake
|
|
||||||
zlib
|
|
||||||
boost
|
|
||||||
websocketpp
|
|
||||||
```
|
|
||||||
</details>
|
|
||||||
|
|
||||||
#### macOS
|
|
||||||
|
|
||||||
Dependencies for **macOS** can be installed with homebrew.
|
|
||||||
```
|
|
||||||
brew install lua@5.3 rapidjson websocketpp cmake openssl@1.1
|
|
||||||
```
|
|
||||||
Some packages are included in **macOS** but you might want to install homebrew versions.
|
|
||||||
```
|
|
||||||
brew install curl zlib git make
|
|
||||||
```
|
|
||||||
|
|
||||||
### How to build
|
|
||||||
|
|
||||||
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.
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# from here:
|
||||||
|
#
|
||||||
|
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
||||||
|
# Courtesy of Jason Turner
|
||||||
|
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
||||||
|
#
|
||||||
|
# This version has been modified by the owners of the current respository.
|
||||||
|
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||||
|
# strictly required.
|
||||||
|
|
||||||
|
function(set_project_warnings project_name)
|
||||||
|
set(MSVC_WARNINGS
|
||||||
|
/W4 # Baseline reasonable warnings
|
||||||
|
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
|
||||||
|
# of data
|
||||||
|
/w14254 # 'operator': conversion from 'type1:field_bits' to
|
||||||
|
# 'type2:field_bits', possible loss of data
|
||||||
|
/w14263 # 'function': member function does not override any base class
|
||||||
|
# virtual member function
|
||||||
|
/w14265 # 'classname': class has virtual functions, but destructor is not
|
||||||
|
# virtual instances of this class may not be destructed correctly
|
||||||
|
/w14287 # 'operator': unsigned/negative constant mismatch
|
||||||
|
/we4289 # nonstandard extension used: 'variable': loop control variable
|
||||||
|
# declared in the for-loop is used outside the for-loop scope
|
||||||
|
/w14296 # 'operator': expression is always 'boolean_value'
|
||||||
|
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
|
||||||
|
/w14545 # expression before comma evaluates to a function which is missing
|
||||||
|
# an argument list
|
||||||
|
/w14546 # function call before comma missing argument list
|
||||||
|
/w14547 # 'operator': operator before comma has no effect; expected
|
||||||
|
# operator with side-effect
|
||||||
|
/w14549 # 'operator': operator before comma has no effect; did you intend
|
||||||
|
# 'operator'?
|
||||||
|
/w14555 # expression has no effect; expected expression with side- effect
|
||||||
|
/w14619 # pragma warning: there is no warning number 'number'
|
||||||
|
/w14640 # Enable warning on thread un-safe static member initialization
|
||||||
|
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
|
||||||
|
# cause unexpected runtime behavior.
|
||||||
|
/w14905 # wide string literal cast to 'LPSTR'
|
||||||
|
/w14906 # string literal cast to 'LPWSTR'
|
||||||
|
/w14928 # illegal copy-initialization; more than one user-defined
|
||||||
|
# conversion has been implicitly applied
|
||||||
|
/permissive- # standards conformance mode for MSVC compiler.
|
||||||
|
)
|
||||||
|
|
||||||
|
set(CLANG_WARNINGS
|
||||||
|
-Wall
|
||||||
|
-Wextra # reasonable and standard
|
||||||
|
-Wshadow # warn the user if a variable declaration shadows one from a
|
||||||
|
# parent context
|
||||||
|
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
|
||||||
|
# non-virtual destructor. This helps catch hard to
|
||||||
|
# track down memory errors
|
||||||
|
-Wold-style-cast # warn for c-style casts
|
||||||
|
-Wcast-align # warn for potential performance problem casts
|
||||||
|
-Wunused # warn on anything being unused
|
||||||
|
-Woverloaded-virtual # warn if you overload (not override) a virtual
|
||||||
|
# function
|
||||||
|
-Wpedantic # warn if non-standard C++ is used
|
||||||
|
-Wconversion # warn on type conversions that may lose data
|
||||||
|
-Wsign-conversion # warn on sign conversions
|
||||||
|
-Wnull-dereference # warn if a null dereference is detected
|
||||||
|
-Wdouble-promotion # warn if float is implicit promoted to double
|
||||||
|
-Wformat=2 # warn on security issues around functions that format output
|
||||||
|
# (ie printf)
|
||||||
|
# modified; added more errors / warnings
|
||||||
|
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
|
||||||
|
# (see below) should still be used in strict pipelines.
|
||||||
|
-Werror=uninitialized
|
||||||
|
-Werror=float-equal
|
||||||
|
-Werror=write-strings
|
||||||
|
-Werror=strict-aliasing -fstrict-aliasing
|
||||||
|
-Werror=missing-declarations
|
||||||
|
-Werror=ctor-dtor-privacy
|
||||||
|
-Wno-missing-field-initializers
|
||||||
|
-Wswitch-default
|
||||||
|
-Werror=unused-result
|
||||||
|
-Werror=implicit-fallthrough
|
||||||
|
-Werror=return-type
|
||||||
|
-Wmissing-include-dirs
|
||||||
|
)
|
||||||
|
|
||||||
|
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
|
||||||
|
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
|
||||||
|
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(GCC_WARNINGS
|
||||||
|
${CLANG_WARNINGS}
|
||||||
|
-Wmisleading-indentation # warn if indentation implies blocks where blocks
|
||||||
|
# do not exist
|
||||||
|
-Wduplicated-cond # warn if if / else chain has duplicated conditions
|
||||||
|
-Wduplicated-branches # warn if if / else branches have duplicated code
|
||||||
|
-Wlogical-op # warn about logical operations being used where bitwise were
|
||||||
|
# probably wanted
|
||||||
|
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
|
||||||
|
)
|
||||||
|
|
||||||
|
if(MSVC)
|
||||||
|
set(PRJ_WARNINGS ${MSVC_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
|
||||||
|
set(PRJ_WARNINGS ${CLANG_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||||
|
set(PRJ_WARNINGS ${GCC_WARNINGS})
|
||||||
|
else()
|
||||||
|
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
|
||||||
|
|
||||||
|
if(NOT TARGET ${project_name})
|
||||||
|
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
find_package(Git)
|
||||||
|
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
|
||||||
|
if(Git_FOUND)
|
||||||
|
message(STATUS "Git found, submodule update and init")
|
||||||
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
message(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(Git_FOUND)
|
||||||
|
|
||||||
|
else()
|
||||||
|
message(STATUS "Git not found - the version will not include a git hash.")
|
||||||
|
set(PRJ_GIT_HASH "unknown")
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
|
||||||
|
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
|
||||||
|
# TODO Implement code coverage
|
||||||
|
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
|
||||||
|
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
|
||||||
|
|
||||||
|
# Generate compile_commands.json for clang based tools
|
||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
# Export all symbols when building a shared library
|
||||||
|
if(BUILD_SHARED_LIBS)
|
||||||
|
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
|
||||||
|
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
||||||
|
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF)
|
||||||
|
if(${PROJECT_NAME}_ENABLE_LTO)
|
||||||
|
include(CheckIPOSupported)
|
||||||
|
check_ipo_supported(RESULT result OUTPUT output)
|
||||||
|
if(result)
|
||||||
|
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "IPO is not supported: ${output}.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
|
||||||
|
find_program(CCACHE_FOUND ccache)
|
||||||
|
if(CCACHE_FOUND)
|
||||||
|
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
|
||||||
|
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
|
||||||
|
if(${PROJECT_NAME}_ENABLE_SANITIZER)
|
||||||
|
add_compile_options(-fsanitize=address,undefined)
|
||||||
|
add_link_options(-fsanitize=address,undefined)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
|
||||||
|
find_program(CLANGTIDY clang-tidy)
|
||||||
|
if(CLANGTIDY)
|
||||||
|
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
|
||||||
|
message("Clang-Tidy finished setting up.")
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
|
||||||
|
find_program(CPPCHECK cppcheck)
|
||||||
|
if(CPPCHECK)
|
||||||
|
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
|
||||||
|
--inline-suppr --inconclusive)
|
||||||
|
message("Cppcheck finished setting up.")
|
||||||
|
else()
|
||||||
|
message(SEND_ERROR "Cppcheck requested but executable not found.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
|
||||||
|
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||||
|
find_package(Git)
|
||||||
|
if(Git_FOUND)
|
||||||
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive vcpkg
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||||
|
endif()
|
||||||
|
|
||||||
+1
Submodule deps/BeamMP-Protocol added at 8eda5714c0
Vendored
-6
@@ -1,6 +0,0 @@
|
|||||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
|
||||||
|
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
|
||||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
|
|
||||||
Vendored
-1
Submodule deps/asio deleted from 4915cfd8a1
Vendored
+1
-1
Submodule deps/commandline updated: 470cf2df4a...b2a29733f9
Vendored
-1
Submodule deps/cpp-httplib deleted from d92c314466
Vendored
-1
Submodule deps/doctest deleted from b7c21ec5ce
Vendored
-1
Submodule deps/fmt deleted from c4ee726532
Vendored
-1
Submodule deps/json deleted from 69d744867f
Vendored
-1
Submodule deps/libzip deleted from 5532f9baa0
Vendored
-1
Submodule deps/rapidjson deleted from 00dbcf2c6e
Vendored
-1
Submodule deps/sentry-native deleted from 28be51f5e3
Vendored
-1
Submodule deps/sol2 deleted from eba86625b7
Vendored
-1
Submodule deps/toml11 deleted from c7627ff6a1
@@ -1,116 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <memory>
|
|
||||||
#include <optional>
|
|
||||||
#include <queue>
|
|
||||||
#include <string>
|
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "Compat.h"
|
|
||||||
#include "VehicleData.h"
|
|
||||||
|
|
||||||
class TServer;
|
|
||||||
|
|
||||||
#ifdef BEAMMP_WINDOWS
|
|
||||||
// for socklen_t
|
|
||||||
#include <WS2tcpip.h>
|
|
||||||
#endif // WINDOWS
|
|
||||||
|
|
||||||
struct TConnection final {
|
|
||||||
ip::tcp::socket Socket;
|
|
||||||
ip::tcp::endpoint SockAddr;
|
|
||||||
};
|
|
||||||
|
|
||||||
class TClient final {
|
|
||||||
public:
|
|
||||||
using TSetOfVehicleData = std::vector<TVehicleData>;
|
|
||||||
|
|
||||||
struct TVehicleDataLockPair {
|
|
||||||
TSetOfVehicleData* VehicleData;
|
|
||||||
std::unique_lock<std::mutex> Lock;
|
|
||||||
};
|
|
||||||
|
|
||||||
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
|
||||||
TClient(const TClient&) = delete;
|
|
||||||
~TClient();
|
|
||||||
TClient& operator=(const TClient&) = delete;
|
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
|
||||||
void SetCarData(int Ident, const std::string& Data);
|
|
||||||
void SetCarPosition(int Ident, const std::string& Data);
|
|
||||||
TVehicleDataLockPair GetAllCars();
|
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
|
||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
|
||||||
std::string GetCarData(int Ident);
|
|
||||||
std::string GetCarPositionRaw(int Ident);
|
|
||||||
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
|
||||||
void 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
|
|
||||||
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 GetCarCount() const;
|
|
||||||
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);
|
|
||||||
[[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;
|
|
||||||
void UpdatePingTime();
|
|
||||||
int SecondsSinceLastPing();
|
|
||||||
|
|
||||||
private:
|
|
||||||
void InsertVehicle(int ID, const std::string& Data);
|
|
||||||
|
|
||||||
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::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
|
||||||
+8
-62
@@ -1,8 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "TSentry.h"
|
|
||||||
extern TSentry Sentry;
|
|
||||||
|
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -46,9 +43,11 @@ 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 {};
|
||||||
|
std::string Password{};
|
||||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||||
bool HTTPServerEnabled { false };
|
bool HTTPServerEnabled { false };
|
||||||
@@ -77,7 +76,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; }
|
||||||
@@ -103,9 +102,7 @@ public:
|
|||||||
static void SleepSafeSeconds(size_t Seconds);
|
static void SleepSafeSeconds(size_t Seconds);
|
||||||
|
|
||||||
static void InitializeConsole() {
|
static void InitializeConsole() {
|
||||||
if (!mConsole) {
|
mConsole.InitializeCommandline();
|
||||||
mConsole = std::make_unique<TConsole>();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum class Status {
|
enum class Status {
|
||||||
@@ -131,15 +128,17 @@ 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 std::unique_ptr<TConsole> mConsole;
|
static inline 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, 1, 0 };
|
static inline Version mVersion { 3, 2, 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__)
|
||||||
@@ -192,7 +191,6 @@ void RegisterThread(const std::string& str);
|
|||||||
#define beammp_error(x) \
|
#define beammp_error(x) \
|
||||||
do { \
|
do { \
|
||||||
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
||||||
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_lua_error(x) \
|
#define beammp_lua_error(x) \
|
||||||
do { \
|
do { \
|
||||||
@@ -267,57 +265,5 @@ void RegisterThread(const std::string& str);
|
|||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|
||||||
#define Biggest 30000
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
inline T Comp(const T& Data) {
|
|
||||||
std::array<char, Biggest> C {};
|
|
||||||
// obsolete
|
|
||||||
C.fill(0);
|
|
||||||
z_stream defstream;
|
|
||||||
defstream.zalloc = nullptr;
|
|
||||||
defstream.zfree = nullptr;
|
|
||||||
defstream.opaque = nullptr;
|
|
||||||
defstream.avail_in = uInt(Data.size());
|
|
||||||
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
|
||||||
defstream.avail_out = Biggest;
|
|
||||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
|
||||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
|
||||||
deflate(&defstream, Z_SYNC_FLUSH);
|
|
||||||
deflate(&defstream, Z_FINISH);
|
|
||||||
deflateEnd(&defstream);
|
|
||||||
size_t TotalOut = defstream.total_out;
|
|
||||||
T Ret;
|
|
||||||
Ret.resize(TotalOut);
|
|
||||||
std::fill(Ret.begin(), Ret.end(), 0);
|
|
||||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
|
||||||
return Ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename T>
|
|
||||||
inline T DeComp(const T& Compressed) {
|
|
||||||
std::array<char, Biggest> C {};
|
|
||||||
// not needed
|
|
||||||
C.fill(0);
|
|
||||||
z_stream infstream;
|
|
||||||
infstream.zalloc = nullptr;
|
|
||||||
infstream.zfree = nullptr;
|
|
||||||
infstream.opaque = nullptr;
|
|
||||||
infstream.avail_in = Biggest;
|
|
||||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
|
||||||
infstream.avail_out = Biggest;
|
|
||||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
|
||||||
inflateInit(&infstream);
|
|
||||||
inflate(&infstream, Z_SYNC_FLUSH);
|
|
||||||
inflate(&infstream, Z_FINISH);
|
|
||||||
inflateEnd(&infstream);
|
|
||||||
size_t TotalOut = infstream.total_out;
|
|
||||||
T Ret;
|
|
||||||
Ret.resize(TotalOut);
|
|
||||||
std::fill(Ret.begin(), Ret.end(), 0);
|
|
||||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
|
||||||
return Ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string GetPlatformAgnosticErrorString();
|
std::string GetPlatformAgnosticErrorString();
|
||||||
#define S_DSN SU_RAW
|
#define S_DSN SU_RAW
|
||||||
|
|||||||
@@ -63,12 +63,10 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
bool result = (cond); \
|
bool result = (cond); \
|
||||||
if (!result) { \
|
if (!result) { \
|
||||||
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
||||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define beammp_assert_not_reachable() \
|
#define beammp_assert_not_reachable() \
|
||||||
do { \
|
do { \
|
||||||
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
|
||||||
} while (false)
|
} while (false)
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#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);
|
||||||
|
|
||||||
|
}
|
||||||
+5
-6
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
// pure virtual class to be inherited from by classes which intend to be threaded
|
// pure virtual class to be inherited from by classes which intend to be threaded
|
||||||
@@ -8,17 +9,15 @@ public:
|
|||||||
IThreaded()
|
IThreaded()
|
||||||
// invokes operator() on this object
|
// invokes operator() on this object
|
||||||
: mThread() { }
|
: mThread() { }
|
||||||
~IThreaded() noexcept {
|
virtual ~IThreaded() noexcept {
|
||||||
if (mThread.joinable()) {
|
mThread.interrupt();
|
||||||
mThread.join();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
virtual void Start() final {
|
virtual void Start() final {
|
||||||
mThread = std::thread([this] { (*this)(); });
|
mThread = boost::scoped_thread<>([this] { (*this)(); });
|
||||||
}
|
}
|
||||||
virtual void operator()() = 0;
|
virtual void operator()() = 0;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
std::thread mThread;
|
boost::scoped_thread<> mThread {};
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ namespace MP {
|
|||||||
std::tuple<int, int, int> GetServerVersion();
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
inline size_t GetPlayerCount() { return Engine->Network()->authenticated_client_count(); }
|
||||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Common.h"
|
||||||
|
#include "Packet.h"
|
||||||
|
#include "State.h"
|
||||||
|
#include "Sync.h"
|
||||||
|
#include "Transport.h"
|
||||||
|
#include "Util.h"
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/asio/execution_context.hpp>
|
||||||
|
#include <boost/asio/thread_pool.hpp>
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
|
#include <boost/thread/synchronized_value.hpp>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <glm/detail/qualifier.hpp>
|
||||||
|
#include <glm/vec3.hpp>
|
||||||
|
#include <glm/vec4.hpp>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
#include <optional>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using ClientID = uint32_t;
|
||||||
|
using VehicleID = uint16_t;
|
||||||
|
|
||||||
|
using namespace boost::asio;
|
||||||
|
|
||||||
|
struct Client : std::enable_shared_from_this<Client> {
|
||||||
|
using StrandPtr = std::shared_ptr<boost::asio::strand<ip::tcp::socket::executor_type>>;
|
||||||
|
using Ptr = std::shared_ptr<Client>;
|
||||||
|
|
||||||
|
ClientID id;
|
||||||
|
Sync<bmp::State> state { bmp::State::None };
|
||||||
|
|
||||||
|
Sync<std::string> name;
|
||||||
|
Sync<std::string> role;
|
||||||
|
Sync<bool> is_guest;
|
||||||
|
Sync<std::unordered_map<std::string /* identifier */, std::string /* value */>> identifiers;
|
||||||
|
/// Writes the packet to the TCP stream. Blocks all other writes.
|
||||||
|
void tcp_write(bmp::Packet& packet);
|
||||||
|
/// Writes the specified to the TCP stream without a header or any metadata - use in
|
||||||
|
/// conjunction with something else. Blocks other writes.
|
||||||
|
void tcp_write_file_raw(const std::filesystem::path& path);
|
||||||
|
|
||||||
|
/// Ensures no client is ever created as a non-shared-ptr, so that enable_shared_from_this works.
|
||||||
|
static Client::Ptr make_ptr(ClientID new_id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||||
|
~Client();
|
||||||
|
|
||||||
|
ip::tcp::socket& tcp_socket() { return m_tcp_socket; }
|
||||||
|
|
||||||
|
void start_tcp();
|
||||||
|
|
||||||
|
/// Used to associate the udp socket with this client.
|
||||||
|
/// This isn't very secure and still allows spoofing of the UDP connection (technically),
|
||||||
|
/// but better than simply using the ID like the old protocol.
|
||||||
|
const uint64_t udp_magic;
|
||||||
|
|
||||||
|
const ip::udp::endpoint& udp_endpoint() const { return m_udp_endpoint; }
|
||||||
|
void set_udp_endpoint(const ip::udp::endpoint& ep) { m_udp_endpoint = ep; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
/// Ctor must be private to ensure all clients are constructed as shared_ptr to enable_shared_from_this.
|
||||||
|
Client(ClientID id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||||
|
/// Call this when the client seems to have timed out. Will send a ping and set a flag.
|
||||||
|
/// Returns true if try-again, false if the connection was closed.
|
||||||
|
[[nodiscard]] bool handle_timeout();
|
||||||
|
bool m_timed_out { false };
|
||||||
|
|
||||||
|
/// Timeout used for typical tcp reads.
|
||||||
|
boost::posix_time::milliseconds m_read_timeout { 5000 };
|
||||||
|
/// Timeout used for typical tcp writes. Specified in milliseconds per byte.
|
||||||
|
/// For example, 10 mbit/s works out to 1250 B/ms, so a value of 1250 here would
|
||||||
|
/// cause clients with >10 mbit/s download speed to usually not time out.
|
||||||
|
/// This is done because a write is considered completed when all data is written,
|
||||||
|
/// and worst-case this could mean that we're limited by their download speed.
|
||||||
|
/// We're setting it to 50, which will drop clients who are below a download speed + ping
|
||||||
|
/// combination of 0.4 mbit/s.
|
||||||
|
double m_write_byte_timeout { 0.01 };
|
||||||
|
/// Timeout used for mod download tcp writes.
|
||||||
|
/// This is typically orders of magnitude larger
|
||||||
|
/// to allow for slow downloads.
|
||||||
|
boost::posix_time::milliseconds m_download_write_timeout { 60000 };
|
||||||
|
|
||||||
|
std::mutex m_tcp_read_mtx;
|
||||||
|
std::mutex m_tcp_write_mtx;
|
||||||
|
std::mutex m_udp_read_mtx;
|
||||||
|
|
||||||
|
ip::tcp::socket m_tcp_socket;
|
||||||
|
|
||||||
|
boost::scoped_thread<> m_tcp_thread;
|
||||||
|
|
||||||
|
std::vector<uint8_t> m_header { bmp::Header::SERIALIZED_SIZE };
|
||||||
|
bmp::Packet m_packet {};
|
||||||
|
|
||||||
|
ip::udp::endpoint m_udp_endpoint;
|
||||||
|
|
||||||
|
class Network& m_network;
|
||||||
|
|
||||||
|
StrandPtr m_tcp_strand;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Vehicle {
|
||||||
|
using Ptr = std::shared_ptr<Vehicle>;
|
||||||
|
Sync<ClientID> owner;
|
||||||
|
Sync<std::vector<uint8_t>> data;
|
||||||
|
|
||||||
|
Vehicle(std::span<uint8_t> raw_data)
|
||||||
|
: data(std::vector<uint8_t>(raw_data.begin(), raw_data.end())) {
|
||||||
|
reset_status(data.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets all status fields to zero and reads any statuses present in the data into the fields.
|
||||||
|
void reset_status(std::span<const uint8_t> status_data);
|
||||||
|
|
||||||
|
struct Status {
|
||||||
|
glm::vec3 rvel {};
|
||||||
|
glm::vec4 rot {};
|
||||||
|
glm::vec3 vel {};
|
||||||
|
glm::vec3 pos {};
|
||||||
|
float time {};
|
||||||
|
};
|
||||||
|
|
||||||
|
Status get_status();
|
||||||
|
|
||||||
|
void update_status(std::span<const uint8_t> raw_packet);
|
||||||
|
|
||||||
|
const std::vector<uint8_t>& get_raw_status() const { return m_status_data; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::recursive_mutex m_mtx;
|
||||||
|
|
||||||
|
/// Holds pos, rvel, vel, etc. raw, updated every time
|
||||||
|
/// such a packet arrives.
|
||||||
|
std::vector<uint8_t> m_status_data;
|
||||||
|
|
||||||
|
/// Parses the status_data on request sets needs_refresh = false.
|
||||||
|
void refresh_cache(std::unique_lock<std::recursive_mutex>& lock);
|
||||||
|
|
||||||
|
bool m_needs_refresh = false;
|
||||||
|
glm::vec3 m_rvel {};
|
||||||
|
glm::vec4 m_rot {};
|
||||||
|
glm::vec3 m_vel {};
|
||||||
|
glm::vec3 m_pos {};
|
||||||
|
float m_time {};
|
||||||
|
};
|
||||||
|
|
||||||
|
class Network {
|
||||||
|
public:
|
||||||
|
Network();
|
||||||
|
~Network();
|
||||||
|
|
||||||
|
friend Client;
|
||||||
|
|
||||||
|
void disconnect(ClientID id, const std::string& msg);
|
||||||
|
|
||||||
|
void send_to(ClientID id, bmp::Packet& packet);
|
||||||
|
|
||||||
|
/// Returns a map of <id, client> containing only clients which are
|
||||||
|
/// fully connected, i.e. who have mods downloaded and everything spawned in.
|
||||||
|
/// If you're unsure which to use, use this one.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> playing_clients() const;
|
||||||
|
/// Returns a map of <id, client> containing only clients who are authenticated.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> authenticated_clients() const;
|
||||||
|
/// Returns all clients, including non-authenticated clients. Use only for debugging,
|
||||||
|
/// information, stats, status.
|
||||||
|
std::unordered_map<ClientID, Client::Ptr> all_clients() const;
|
||||||
|
|
||||||
|
std::optional<Client::Ptr> get_client(ClientID id, bmp::State min_state) const;
|
||||||
|
|
||||||
|
std::unordered_map<VehicleID, Vehicle::Ptr> get_vehicles_owned_by(ClientID id);
|
||||||
|
|
||||||
|
std::optional<Vehicle::Ptr> get_vehicle(VehicleID id);
|
||||||
|
|
||||||
|
/// Builds the SessionSetup.PlayersInfo json which contains all player info and all vehicles.
|
||||||
|
nlohmann::json build_players_info();
|
||||||
|
|
||||||
|
size_t authenticated_client_count() const;
|
||||||
|
|
||||||
|
size_t clients_in_state_count(bmp::State state) const;
|
||||||
|
|
||||||
|
size_t guest_count() const;
|
||||||
|
|
||||||
|
size_t vehicle_count() const;
|
||||||
|
|
||||||
|
/// Creates a Playing state packet from uncompressed data.
|
||||||
|
bmp::Packet make_playing_packet(bmp::Purpose purpose, ClientID from_id, VehicleID veh_id, const std::vector<uint8_t>& data);
|
||||||
|
|
||||||
|
/// Sends a <System> or <Server> chat message to all or only one client(s).
|
||||||
|
void send_system_chat_message(const std::string& msg, ClientID to = 0xffffffff);
|
||||||
|
|
||||||
|
/// To be called by accept() async handler once an accept() is completed.
|
||||||
|
void accept();
|
||||||
|
|
||||||
|
/// Gets the async i/o context of the network - can be used to "schedule" tasks on it.
|
||||||
|
boost::asio::thread_pool& context() {
|
||||||
|
return m_threadpool;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void handle_packet(ClientID id, const bmp::Packet& packet);
|
||||||
|
|
||||||
|
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
|
||||||
|
bmp::Packet udp_read(ip::udp::endpoint& out_ep);
|
||||||
|
/// Sends a packet to the specified UDP endpoint via the UDP socket.
|
||||||
|
void udp_write(bmp::Packet& packet, const ip::udp::endpoint& ep);
|
||||||
|
|
||||||
|
void udp_read_main();
|
||||||
|
void tcp_listen_main();
|
||||||
|
|
||||||
|
/// Handles all packets which are allowed during the Identification state.
|
||||||
|
void handle_identification(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the Authentication state.
|
||||||
|
void handle_authentication(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the ModDownload state.
|
||||||
|
void handle_mod_download(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the SessionSetup state.
|
||||||
|
void handle_session_setup(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
/// Handles all packets which are allowed during the Playing state.
|
||||||
|
void handle_playing(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||||
|
|
||||||
|
/// On failure, throws an exception with the error for the client.
|
||||||
|
static void authenticate_user(const std::string& public_key, std::shared_ptr<Client>& client);
|
||||||
|
|
||||||
|
/// Called by accept() once completed (completion handler).
|
||||||
|
void handle_accept(const boost::system::error_code& ec);
|
||||||
|
|
||||||
|
Sync<std::unordered_map<ClientID, Client::Ptr>> m_clients {};
|
||||||
|
Sync<std::unordered_map<VehicleID, Vehicle::Ptr>> m_vehicles {};
|
||||||
|
Sync<std::unordered_map<uint64_t, ClientID>> m_client_magics {};
|
||||||
|
Sync<std::unordered_map<ip::udp::endpoint, ClientID>> m_udp_endpoints {};
|
||||||
|
|
||||||
|
ClientID new_client_id();
|
||||||
|
VehicleID new_vehicle_id();
|
||||||
|
|
||||||
|
thread_pool m_threadpool { std::thread::hardware_concurrency() };
|
||||||
|
Sync<bool> m_shutdown { false };
|
||||||
|
|
||||||
|
ip::udp::socket m_udp_socket { m_threadpool };
|
||||||
|
|
||||||
|
ip::tcp::socket m_tcp_listener { m_threadpool };
|
||||||
|
ip::tcp::acceptor m_tcp_acceptor { m_threadpool };
|
||||||
|
/// This socket gets accepted into, and is then moved.
|
||||||
|
ip::tcp::socket m_temp_socket { m_threadpool };
|
||||||
|
|
||||||
|
boost::scoped_thread<> m_tcp_listen_thread;
|
||||||
|
boost::scoped_thread<> m_udp_read_thread;
|
||||||
|
};
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/thread/synchronized_value.hpp>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
/// This header provides convenience aliases for synchronization primitives.
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
||||||
|
|
||||||
+5
-4
@@ -6,7 +6,7 @@
|
|||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
|
||||||
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
||||||
#include <toml11/toml.hpp> // header-only version of TOML++
|
#include <toml.hpp> // header-only version of TOML++
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
@@ -22,11 +22,12 @@ private:
|
|||||||
void CreateConfigFile();
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void PrintDebug();
|
void PrintDebug();
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
|
||||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
|
std::string TagsAsPrettyArray() const;
|
||||||
bool IsDefault();
|
bool IsDefault();
|
||||||
bool mFailed { false };
|
bool mFailed { false };
|
||||||
std::string mConfigFileName;
|
std::string mConfigFileName;
|
||||||
|
|||||||
+32
-2
@@ -1,14 +1,40 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Cryptography.h"
|
#include "Cryptography.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include "commandline.h"
|
#include "commandline.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <mutex>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#include <boost/container/deque.hpp>
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
|
#include <boost/thread/synchronized_value.hpp>
|
||||||
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
|
#include <span>
|
||||||
|
#include <spdlog/details/null_mutex.h>
|
||||||
|
#include <spdlog/sinks/base_sink.h>
|
||||||
|
#include <spdlog/sinks/sink.h>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
class TConsole;
|
||||||
|
|
||||||
|
class ConsoleSink : public spdlog::sinks::base_sink<spdlog::details::null_mutex> {
|
||||||
|
public:
|
||||||
|
ConsoleSink(TConsole& console);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void sink_it_(const spdlog::details::log_msg& msg) override;
|
||||||
|
void flush_() override;
|
||||||
|
|
||||||
|
TConsole* m_console;
|
||||||
|
};
|
||||||
|
|
||||||
class TLuaEngine;
|
class TLuaEngine;
|
||||||
|
|
||||||
@@ -16,12 +42,15 @@ 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);
|
||||||
@@ -55,7 +84,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
|
||||||
};
|
};
|
||||||
|
|
||||||
Commandline mCommandline;
|
std::unique_ptr<Commandline> mCommandline { nullptr };
|
||||||
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 };
|
||||||
@@ -65,4 +94,5 @@ private:
|
|||||||
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
||||||
std::ofstream mLogFileStream;
|
std::ofstream mLogFileStream;
|
||||||
std::mutex mLogFileStreamMtx;
|
std::mutex mLogFileStreamMtx;
|
||||||
|
TScopedTimer mUptimeTimer{};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,12 +2,11 @@
|
|||||||
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "IThreaded.h"
|
#include "IThreaded.h"
|
||||||
#include "TResourceManager.h"
|
#include "Network.h"
|
||||||
#include "TServer.h"
|
|
||||||
|
|
||||||
class THeartbeatThread : public IThreaded {
|
class THeartbeatThread : public IThreaded {
|
||||||
public:
|
public:
|
||||||
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server);
|
THeartbeatThread(std::shared_ptr<Network> network);
|
||||||
//~THeartbeatThread();
|
//~THeartbeatThread();
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
@@ -15,6 +14,5 @@ private:
|
|||||||
std::string GenerateCall();
|
std::string GenerateCall();
|
||||||
std::string GetPlayers();
|
std::string GetPlayers();
|
||||||
|
|
||||||
TResourceManager& mResourceManager;
|
std::shared_ptr<Network> m_network;
|
||||||
TServer& mServer;
|
|
||||||
};
|
};
|
||||||
|
|||||||
+29
-21
@@ -1,8 +1,10 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "TNetwork.h"
|
#include "Common.h"
|
||||||
#include "TServer.h"
|
#include "IThreaded.h"
|
||||||
|
#include "Network.h"
|
||||||
#include <any>
|
#include <any>
|
||||||
|
#include <boost/thread/scoped_thread.hpp>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <initializer_list>
|
#include <initializer_list>
|
||||||
@@ -13,7 +15,7 @@
|
|||||||
#include <queue>
|
#include <queue>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <toml11/toml.hpp>
|
#include <toml.hpp>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -41,7 +43,14 @@ struct TLuaResult {
|
|||||||
sol::object Result { sol::lua_nil };
|
sol::object Result { sol::lua_nil };
|
||||||
TLuaStateId StateId;
|
TLuaStateId StateId;
|
||||||
std::string Function;
|
std::string Function;
|
||||||
// TODO: Add condition_variable
|
std::shared_ptr<std::mutex> ReadyMutex {
|
||||||
|
std::make_shared<std::mutex>()
|
||||||
|
};
|
||||||
|
std::shared_ptr<std::condition_variable> ReadyCondition {
|
||||||
|
std::make_shared<std::condition_variable>()
|
||||||
|
};
|
||||||
|
|
||||||
|
void MarkAsReady();
|
||||||
void WaitUntilReady();
|
void WaitUntilReady();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,7 +70,7 @@ struct TLuaChunk {
|
|||||||
std::string PluginPath;
|
std::string PluginPath;
|
||||||
};
|
};
|
||||||
|
|
||||||
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
|
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine> {
|
||||||
public:
|
public:
|
||||||
enum CallStrategy : int {
|
enum CallStrategy : int {
|
||||||
BestEffort,
|
BestEffort,
|
||||||
@@ -76,17 +85,15 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
TLuaEngine();
|
TLuaEngine();
|
||||||
~TLuaEngine() noexcept {
|
virtual ~TLuaEngine() noexcept {
|
||||||
beammp_debug("Lua Engine terminated");
|
beammp_debug("Lua Engine terminated");
|
||||||
}
|
}
|
||||||
|
|
||||||
void operator()() override;
|
void Start();
|
||||||
|
|
||||||
TNetwork& Network() { return *mNetwork; }
|
std::shared_ptr<::Network> Network() { return mNetwork; }
|
||||||
TServer& Server() { return *mServer; }
|
|
||||||
|
|
||||||
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
|
void SetNetwork(const std::shared_ptr<::Network>& network) { mNetwork = network; }
|
||||||
void SetServer(TServer* Server) { mServer = Server; }
|
|
||||||
|
|
||||||
size_t GetResultsToCheckSize() {
|
size_t GetResultsToCheckSize() {
|
||||||
std::unique_lock Lock(mResultsToCheckMutex);
|
std::unique_lock Lock(mResultsToCheckMutex);
|
||||||
@@ -98,8 +105,8 @@ public:
|
|||||||
return mLuaStates.size();
|
return mLuaStates.size();
|
||||||
}
|
}
|
||||||
std::vector<std::string> GetLuaStateNames() {
|
std::vector<std::string> GetLuaStateNames() {
|
||||||
std::vector<std::string> names{};
|
std::vector<std::string> names {};
|
||||||
for(auto const& [stateId, _ ] : mLuaStates) {
|
for (auto const& [stateId, _] : mLuaStates) {
|
||||||
names.push_back(stateId);
|
names.push_back(stateId);
|
||||||
}
|
}
|
||||||
return names;
|
return names;
|
||||||
@@ -194,17 +201,17 @@ private:
|
|||||||
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||||
size_t CalculateMemoryUsage();
|
size_t CalculateMemoryUsage();
|
||||||
|
|
||||||
class StateThreadData : IThreaded {
|
class StateThreadData {
|
||||||
public:
|
public:
|
||||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||||
StateThreadData(const StateThreadData&) = delete;
|
StateThreadData(const StateThreadData&) = delete;
|
||||||
~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||||
void operator()() override;
|
void Start();
|
||||||
sol::state_view State() { return sol::state_view(mState); }
|
sol::state_view State() { return sol::state_view(mState); }
|
||||||
|
|
||||||
std::vector<std::string> GetStateGlobalKeys();
|
std::vector<std::string> GetStateGlobalKeys();
|
||||||
@@ -214,6 +221,8 @@ 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);
|
||||||
@@ -221,9 +230,8 @@ private:
|
|||||||
sol::table Lua_GetPlayers();
|
sol::table Lua_GetPlayers();
|
||||||
std::string Lua_GetPlayerName(int ID);
|
std::string Lua_GetPlayerName(int ID);
|
||||||
sol::table Lua_GetPlayerVehicles(int ID);
|
sol::table Lua_GetPlayerVehicles(int ID);
|
||||||
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
|
std::pair<sol::table, std::string> Lua_GetVehicleStatus(int VID);
|
||||||
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
||||||
sol::table Lua_JsonDecode(const std::string& str);
|
|
||||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||||
sol::table Lua_FS_ListFiles(const std::string& Path);
|
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||||
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||||
@@ -231,7 +239,6 @@ private:
|
|||||||
std::string mName;
|
std::string mName;
|
||||||
TLuaStateId mStateId;
|
TLuaStateId mStateId;
|
||||||
lua_State* mState;
|
lua_State* mState;
|
||||||
std::thread mThread;
|
|
||||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||||
std::recursive_mutex mStateExecuteQueueMutex;
|
std::recursive_mutex mStateExecuteQueueMutex;
|
||||||
std::vector<QueuedFunction> mStateFunctionQueue;
|
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||||
@@ -243,6 +250,7 @@ private:
|
|||||||
std::recursive_mutex mPathsMutex;
|
std::recursive_mutex mPathsMutex;
|
||||||
std::mt19937 mMersenneTwister;
|
std::mt19937 mMersenneTwister;
|
||||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||||
|
boost::scoped_thread<> mThread;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct TimedEvent {
|
struct TimedEvent {
|
||||||
@@ -255,8 +263,7 @@ private:
|
|||||||
void Reset();
|
void Reset();
|
||||||
};
|
};
|
||||||
|
|
||||||
TNetwork* mNetwork;
|
std::shared_ptr<::Network> mNetwork;
|
||||||
TServer* mServer;
|
|
||||||
const fs::path mResourceServerPath;
|
const fs::path mResourceServerPath;
|
||||||
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
||||||
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
||||||
@@ -268,6 +275,7 @@ private:
|
|||||||
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
||||||
std::mutex mResultsToCheckMutex;
|
std::mutex mResultsToCheckMutex;
|
||||||
std::condition_variable mResultsToCheckCond;
|
std::condition_variable mResultsToCheckCond;
|
||||||
|
boost::scoped_thread<> mThread;
|
||||||
};
|
};
|
||||||
|
|
||||||
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
#include "Compat.h"
|
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <boost/asio/io_context.hpp>
|
|
||||||
#include <boost/asio/ip/udp.hpp>
|
|
||||||
|
|
||||||
struct TConnection;
|
|
||||||
|
|
||||||
class TNetwork {
|
|
||||||
public:
|
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
|
||||||
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
|
||||||
std::vector<uint8_t> TCPRcv(TClient& c);
|
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
|
||||||
void Identify(TConnection&& client);
|
|
||||||
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
|
||||||
void SyncResources(TClient& c);
|
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
|
||||||
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
|
||||||
void UpdatePlayer(TClient& Client);
|
|
||||||
|
|
||||||
private:
|
|
||||||
void UDPServerMain();
|
|
||||||
void TCPServerMain();
|
|
||||||
|
|
||||||
TServer& mServer;
|
|
||||||
TPPSMonitor& mPPSMonitor;
|
|
||||||
ip::udp::socket mUDPSock;
|
|
||||||
TResourceManager& mResourceManager;
|
|
||||||
std::thread mUDPThread;
|
|
||||||
std::thread mTCPThread;
|
|
||||||
|
|
||||||
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
|
||||||
void HandleDownload(TConnection&& TCPSock);
|
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
|
||||||
int OpenID();
|
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
|
||||||
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
|
||||||
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
|
||||||
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
|
||||||
};
|
|
||||||
|
|
||||||
std::vector<uint8_t> StringToVector(const std::string& Str);
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "Common.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
class TNetwork;
|
|
||||||
|
|
||||||
class TPPSMonitor : public IThreaded {
|
|
||||||
public:
|
|
||||||
explicit TPPSMonitor(TServer& Server);
|
|
||||||
|
|
||||||
void operator()() override;
|
|
||||||
|
|
||||||
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
|
|
||||||
void IncrementInternalPPS() { ++mInternalPPS; }
|
|
||||||
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
|
|
||||||
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
|
|
||||||
|
|
||||||
private:
|
|
||||||
TNetwork& Network() { return mNetwork->get(); }
|
|
||||||
|
|
||||||
TServer& mServer;
|
|
||||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
|
||||||
int mInternalPPS { 0 };
|
|
||||||
};
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "Common.h"
|
|
||||||
|
|
||||||
class TResourceManager {
|
|
||||||
public:
|
|
||||||
TResourceManager();
|
|
||||||
|
|
||||||
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
|
|
||||||
[[nodiscard]] std::string FileList() const { return mFileList; }
|
|
||||||
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
|
||||||
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
|
||||||
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
size_t mMaxModSize = 0;
|
|
||||||
std::string mFileSizes;
|
|
||||||
std::string mFileList;
|
|
||||||
std::string mTrimmedList;
|
|
||||||
int mModsLoaded = 0;
|
|
||||||
};
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#ifndef SENTRY_H
|
|
||||||
#define SENTRY_H
|
|
||||||
|
|
||||||
#include <mutex>
|
|
||||||
#include <string>
|
|
||||||
#include <unordered_map>
|
|
||||||
enum class SentryLevel {
|
|
||||||
Debug = -1,
|
|
||||||
Info = 0,
|
|
||||||
Warning = 1,
|
|
||||||
Error = 2,
|
|
||||||
Fatal = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
// singleton, dont make this twice
|
|
||||||
class TSentry final {
|
|
||||||
public:
|
|
||||||
TSentry();
|
|
||||||
~TSentry();
|
|
||||||
|
|
||||||
void PrintWelcome();
|
|
||||||
void SetupUser();
|
|
||||||
void Log(SentryLevel level, const std::string& logger, const std::string& text);
|
|
||||||
void LogError(const std::string& text, const std::string& file, const std::string& line);
|
|
||||||
void SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map);
|
|
||||||
void LogException(const std::exception& e, const std::string& file, const std::string& line);
|
|
||||||
void LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function);
|
|
||||||
void AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line);
|
|
||||||
// cleared when Logged
|
|
||||||
void SetTransaction(const std::string& id);
|
|
||||||
[[nodiscard]] std::unique_lock<std::mutex> CreateExclusiveContext();
|
|
||||||
|
|
||||||
private:
|
|
||||||
bool mValid { true };
|
|
||||||
std::mutex mMutex;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // SENTRY_H
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "IThreaded.h"
|
|
||||||
#include "RWMutex.h"
|
|
||||||
#include "TScopedTimer.h"
|
|
||||||
#include <functional>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <unordered_set>
|
|
||||||
|
|
||||||
#include "BoostAliases.h"
|
|
||||||
|
|
||||||
class TClient;
|
|
||||||
class TNetwork;
|
|
||||||
class TPPSMonitor;
|
|
||||||
|
|
||||||
class TServer final {
|
|
||||||
public:
|
|
||||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
|
||||||
|
|
||||||
TServer(const std::vector<std::string_view>& Arguments);
|
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
|
||||||
// in Fn, return true to continue, return false to break
|
|
||||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
|
||||||
size_t ClientCount() const;
|
|
||||||
|
|
||||||
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);
|
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
|
||||||
|
|
||||||
const TScopedTimer UptimeTimer;
|
|
||||||
|
|
||||||
// asio io context
|
|
||||||
io_context& IoCtx() { return mIoCtx; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
io_context mIoCtx {};
|
|
||||||
TClientSet mClients;
|
|
||||||
mutable RWMutex mClientsMutex;
|
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
|
||||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
|
||||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
|
||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
|
||||||
static void HandlePosition(TClient& c, const std::string& Packet);
|
|
||||||
};
|
|
||||||
|
|
||||||
struct BufferView {
|
|
||||||
uint8_t* Data { nullptr };
|
|
||||||
size_t Size { 0 };
|
|
||||||
const uint8_t* data() const { return Data; }
|
|
||||||
uint8_t* data() { return Data; }
|
|
||||||
size_t size() const { return Size; }
|
|
||||||
};
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/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
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/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
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/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
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
git config --global --add safe.directory $(pwd)
|
||||||
|
git config --global --add safe.directory $(pwd)/vcpkg
|
||||||
|
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
./vcpkg/bootstrap-vcpkg.sh
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/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
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
apt-get update -y
|
||||||
|
|
||||||
|
apt-get install -y liblua5.3-0 curl
|
||||||
|
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
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
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake --build bin --parallel -t BeamMP-Server --config Release
|
||||||
-152
@@ -1,152 +0,0 @@
|
|||||||
#include "Client.h"
|
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
#include <memory>
|
|
||||||
#include <optional>
|
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
|
||||||
return Ident == elem.ID();
|
|
||||||
});
|
|
||||||
if (iter != mVehicleData.end()) {
|
|
||||||
mVehicleData.erase(iter);
|
|
||||||
} else {
|
|
||||||
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::ClearCars() {
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
mVehicleData.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
int TClient::GetOpenCarID() const {
|
|
||||||
int OpenID = 0;
|
|
||||||
bool found;
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
do {
|
|
||||||
found = true;
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == OpenID) {
|
|
||||||
OpenID++;
|
|
||||||
found = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} while (!found);
|
|
||||||
return OpenID;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::AddNewCar(int Ident, const std::string& Data) {
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
mVehicleData.emplace_back(Ident, Data);
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|
||||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
try {
|
|
||||||
return mVehiclePosition.at(Ident);
|
|
||||||
} catch (const std::out_of_range& oor) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::Disconnect(std::string_view Reason) {
|
|
||||||
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
|
||||||
boost::system::error_code ec;
|
|
||||||
mSocket.shutdown(socket_base::shutdown_both, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
mSocket.close(ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("Failed to close client socket: {}", ec.message());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
|
||||||
std::unique_lock lock(mVehiclePositionMutex);
|
|
||||||
mVehiclePosition[Ident] = Data;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TClient::GetCarData(int Ident) {
|
|
||||||
{ // lock
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == Ident) {
|
|
||||||
return v.Data();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // unlock
|
|
||||||
DeleteCar(Ident);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::SetCarData(int Ident, const std::string& Data) {
|
|
||||||
{ // lock
|
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
|
||||||
for (auto& v : mVehicleData) {
|
|
||||||
if (v.ID() == Ident) {
|
|
||||||
v.SetData(Data);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // unlock
|
|
||||||
DeleteCar(Ident);
|
|
||||||
}
|
|
||||||
|
|
||||||
int TClient::GetCarCount() const {
|
|
||||||
return int(mVehicleData.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
TServer& TClient::Server() const {
|
|
||||||
return mServer;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
|
||||||
mPacketsSync.push(Packet);
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
|
||||||
: mServer(Server)
|
|
||||||
, mSocket(std::move(Socket))
|
|
||||||
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
|
||||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
|
||||||
}
|
|
||||||
|
|
||||||
TClient::~TClient() {
|
|
||||||
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
|
||||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
|
||||||
}
|
|
||||||
int TClient::SecondsSinceLastPing() {
|
|
||||||
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
|
||||||
std::chrono::high_resolution_clock::now() - mLastPingTime)
|
|
||||||
.count();
|
|
||||||
return int(seconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
|
||||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
|
||||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
|
||||||
ReadLock Lock(Server.GetClientMutex());
|
|
||||||
if (!CPtr.expired()) {
|
|
||||||
auto C = CPtr.lock();
|
|
||||||
if (C->GetID() == ID) {
|
|
||||||
MaybeClient = CPtr;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return MaybeClient;
|
|
||||||
}
|
|
||||||
+18
-8
@@ -1,8 +1,10 @@
|
|||||||
#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>
|
||||||
@@ -13,9 +15,6 @@
|
|||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
// global, yes, this is ugly, no, it cant be done another way
|
|
||||||
TSentry Sentry {};
|
|
||||||
|
|
||||||
Application::TSettings Application::Settings = {};
|
Application::TSettings Application::Settings = {};
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
@@ -204,8 +203,11 @@ 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 = RemoteVersion.AsString();
|
std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
|
||||||
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));
|
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
|
||||||
|
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
|
||||||
|
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!");
|
||||||
@@ -217,9 +219,6 @@ void Application::CheckForUpdates() {
|
|||||||
if (FirstTime) {
|
if (FirstTime) {
|
||||||
beammp_debug("Failed to fetch version from: " + url);
|
beammp_debug("Failed to fetch version from: " + url);
|
||||||
beammp_trace("got " + Response);
|
beammp_trace("got " + Response);
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("get-response", { { "response", Response } });
|
|
||||||
Sentry.LogError("failed to get server version", _file_basename, _line);
|
|
||||||
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -354,3 +353,14 @@ 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
@@ -0,0 +1,20 @@
|
|||||||
|
#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 "";
|
||||||
|
}
|
||||||
+3
-4
@@ -1,6 +1,5 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
@@ -15,7 +14,7 @@
|
|||||||
using json = nlohmann::json;
|
using json = nlohmann::json;
|
||||||
|
|
||||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||||
httplib::SSLClient client(host, port);
|
static thread_local httplib::SSLClient client(host, port);
|
||||||
client.enable_server_certificate_verification(false);
|
client.enable_server_certificate_verification(false);
|
||||||
client.set_address_family(AF_INET);
|
client.set_address_family(AF_INET);
|
||||||
auto res = client.Get(target.c_str());
|
auto res = client.Get(target.c_str());
|
||||||
@@ -30,7 +29,7 @@ std::string Http::GET(const std::string& host, int port, const std::string& targ
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
||||||
httplib::SSLClient client(host, port);
|
static thread_local httplib::SSLClient client(host, port);
|
||||||
client.set_read_timeout(std::chrono::seconds(10));
|
client.set_read_timeout(std::chrono::seconds(10));
|
||||||
beammp_assert(client.is_valid());
|
beammp_assert(client.is_valid());
|
||||||
client.enable_server_certificate_verification(false);
|
client.enable_server_certificate_verification(false);
|
||||||
@@ -181,7 +180,7 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.set_content(
|
res.set_content(
|
||||||
json {
|
nlohmann::json {
|
||||||
{ "ok", SystemsBad == 0 },
|
{ "ok", SystemsBad == 0 },
|
||||||
}
|
}
|
||||||
.dump(),
|
.dump(),
|
||||||
|
|||||||
+49
-33
@@ -1,5 +1,4 @@
|
|||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
@@ -114,24 +113,26 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||||
std::string Packet = "E:" + EventName + ":" + Data;
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
if (PlayerID == -1) {
|
/*
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
return { true, "" };
|
if (PlayerID == -1) {
|
||||||
} else {
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
return { true, "" };
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
} else {
|
||||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
return { false, "Invalid Player ID" };
|
if (!MaybeClient) {
|
||||||
}
|
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||||
auto c = MaybeClient.value().lock();
|
return { false, "Invalid Player ID" };
|
||||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
}
|
||||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
auto c = MaybeClient.value();
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
return { false, "Respond failed, dropping client" };
|
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||||
}
|
LuaAPI::MP::Engine->Network().Disconnect(*c);
|
||||||
return { true, "" };
|
return { false, "Respond failed, dropping client" };
|
||||||
}
|
}
|
||||||
|
return { true, "" };
|
||||||
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||||
@@ -140,17 +141,22 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient) {
|
||||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||||
return { false, "Player does not exist" };
|
return { false, "Player does not exist" };
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||||
return { true, "" };
|
return { true, "" };
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
std::pair<bool, std::string> Result;
|
std::pair<bool, std::string> Result;
|
||||||
std::string Packet = "C:Server: " + Message;
|
std::string Packet = "C:Server: " + Message;
|
||||||
if (ID == -1) {
|
if (ID == -1) {
|
||||||
@@ -159,17 +165,18 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
if (!c->IsSynced()) {
|
if (!c->IsSynced) {
|
||||||
Result.first = false;
|
Result.first = false;
|
||||||
Result.second = "Player still syncing data";
|
Result.second = "Player still syncing data";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message);
|
||||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||||
// TODO: should we return an error here?
|
beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get());
|
||||||
|
Engine->Network().Disconnect(c);
|
||||||
}
|
}
|
||||||
Result.first = true;
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
@@ -180,18 +187,21 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
std::pair<bool, std::string> Result;
|
std::pair<bool, std::string> Result;
|
||||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient) {
|
||||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||||
Result.first = false;
|
Result.first = false;
|
||||||
Result.second = "Invalid Player ID";
|
Result.second = "Invalid Player ID";
|
||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value();
|
||||||
if (!c->GetCarData(VID).empty()) {
|
if (!c->GetCarData(VID).empty()) {
|
||||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
@@ -202,6 +212,7 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
|||||||
Result.second = "Vehicle does not exist";
|
Result.second = "Vehicle does not exist";
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||||
@@ -273,21 +284,26 @@ void LuaAPI::MP::Sleep(size_t Ms) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
return MaybeClient.value().lock()->IsConnected();
|
return MaybeClient.value()->IsConnected.get();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
return MaybeClient.value().lock()->IsGuest();
|
return MaybeClient.value()->IsGuest.get();
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||||
|
|||||||
+1251
File diff suppressed because it is too large
Load Diff
+72
-50
@@ -1,6 +1,7 @@
|
|||||||
#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>
|
||||||
@@ -8,30 +9,36 @@
|
|||||||
|
|
||||||
// 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";
|
||||||
|
|
||||||
// Misc
|
// Misc
|
||||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
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);
|
||||||
@@ -55,7 +62,6 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -101,32 +107,26 @@ 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;
|
||||||
|
// 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(), " You can turn on/off the SendErrors message you get on startup here");
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
// 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://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
|
||||||
<< data;
|
<< data;
|
||||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||||
if (!File) {
|
if (!File) {
|
||||||
@@ -156,19 +156,38 @@ void TConfig::CreateConfigFile() {
|
|||||||
FlushToFile();
|
FlushToFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, 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, bool& OutValue) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, 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, int& OutValue) {
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
|
||||||
|
if (!Env.empty()) {
|
||||||
|
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||||
|
OutValue = int(std::strtol(envp, nullptr, 10));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
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());
|
||||||
}
|
}
|
||||||
@@ -178,28 +197,23 @@ void TConfig::ParseFromFile(std::string_view name) {
|
|||||||
try {
|
try {
|
||||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
// GENERAL
|
// GENERAL
|
||||||
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
|
||||||
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
|
||||||
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
|
||||||
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
|
||||||
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
|
||||||
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
|
||||||
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
|
||||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
|
||||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
|
||||||
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
|
||||||
|
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
|
||||||
|
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;
|
||||||
@@ -232,14 +246,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"));
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseOldFormat() {
|
void TConfig::ParseOldFormat() {
|
||||||
@@ -294,3 +306,13 @@ 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;
|
||||||
|
}
|
||||||
|
|||||||
+63
-80
@@ -2,12 +2,12 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
|
#include <mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||||
@@ -51,17 +51,6 @@ 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);
|
||||||
@@ -156,13 +145,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,9 +163,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,10 +187,10 @@ bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min,
|
|||||||
return EnsureArgsCount(args, min);
|
return EnsureArgsCount(args, min);
|
||||||
} else {
|
} else {
|
||||||
if (args.size() > max) {
|
if (args.size() > max) {
|
||||||
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
} else if (args.size() < min) {
|
} else if (args.size() < min) {
|
||||||
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -256,7 +245,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) {
|
||||||
@@ -276,17 +265,15 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
|
|||||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||||
};
|
};
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
if (!Client.expired()) {
|
/*mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||||
auto locked = Client.lock();
|
if (NameCompare(Client->Name.get(), Name)) {
|
||||||
if (NameCompare(locked->GetName(), Name)) {
|
mLuaEngine->Network().ClientKick(*Client, Reason);
|
||||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
|
||||||
Kicked = true;
|
Kicked = true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});*/
|
||||||
if (!Kicked) {
|
if (!Kicked) {
|
||||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||||
} else {
|
} else {
|
||||||
@@ -350,7 +337,7 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
if (!EnsureArgsCount(args, 0)) {
|
if (!EnsureArgsCount(args, 1, 2)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -369,23 +356,24 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
|
|||||||
if (!EnsureArgsCount(args, 0)) {
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Implement once running
|
||||||
|
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||||
|
/*
|
||||||
if (mLuaEngine->Server().ClientCount() == 0) {
|
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||||
Application::Console().WriteRaw("No players online.");
|
Application::Console().WriteRaw("No players online.");
|
||||||
} else {
|
} else {
|
||||||
std::stringstream ss;
|
std::stringstream ss;
|
||||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||||
if (!Client.expired()) {
|
ss << std::left << std::setw(25) << Client->Name.get()
|
||||||
auto locked = Client.lock();
|
<< std::setw(6) << Client->ID.get()
|
||||||
ss << std::left << std::setw(25) << locked->GetName()
|
<< std::setw(6) << Client->GetCarCount() << "\n";
|
||||||
<< std::setw(6) << locked->GetID()
|
|
||||||
<< std::setw(6) << locked->GetCarCount() << "\n";
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
auto Str = ss.str();
|
auto Str = ss.str();
|
||||||
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||||
@@ -394,29 +382,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
}
|
}
|
||||||
std::stringstream Status;
|
std::stringstream Status;
|
||||||
|
|
||||||
size_t CarCount = 0;
|
|
||||||
size_t ConnectedCount = 0;
|
|
||||||
size_t GuestCount = 0;
|
|
||||||
size_t SyncedCount = 0;
|
|
||||||
size_t SyncingCount = 0;
|
|
||||||
size_t MissedPacketQueueSum = 0;
|
|
||||||
int LargestSecondsSinceLastPing = 0;
|
|
||||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
|
||||||
if (!Client.expired()) {
|
|
||||||
auto Locked = Client.lock();
|
|
||||||
CarCount += Locked->GetCarCount();
|
|
||||||
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
|
||||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
|
||||||
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
|
||||||
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
|
||||||
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
|
||||||
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
|
||||||
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
size_t SystemsStarting = 0;
|
size_t SystemsStarting = 0;
|
||||||
size_t SystemsGood = 0;
|
size_t SystemsGood = 0;
|
||||||
size_t SystemsBad = 0;
|
size_t SystemsBad = 0;
|
||||||
@@ -461,15 +426,21 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
||||||
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||||
|
|
||||||
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
auto ElapsedTime = mUptimeTimer.GetElapsedTime();
|
||||||
|
|
||||||
|
auto network = mLuaEngine->Network();
|
||||||
|
auto clients = network->all_clients();
|
||||||
|
|
||||||
Status << "BeamMP-Server Status:\n"
|
Status << "BeamMP-Server Status:\n"
|
||||||
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
<< "\tTotal Players: " << clients.size() << "\n"
|
||||||
<< "\tSyncing Players: " << SyncingCount << "\n"
|
<< "\tPlayers identifying: " << network->clients_in_state_count(bmp::State::Identification) << "\n"
|
||||||
<< "\tSynced Players: " << SyncedCount << "\n"
|
<< "\tPlayers authenticating: " << network->clients_in_state_count(bmp::State::Authentication) << "\n"
|
||||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
<< "\tPlayers downloading mods: " << network->clients_in_state_count(bmp::State::ModDownload) << "\n"
|
||||||
<< "\tGuests: " << GuestCount << "\n"
|
<< "\tPlayers spawning in: " << network->clients_in_state_count(bmp::State::SessionSetup) << "\n"
|
||||||
<< "\tCars: " << CarCount << "\n"
|
<< "\tPlayers playing: " << network->clients_in_state_count(bmp::State::Playing) << "\n"
|
||||||
|
<< "\tPlayers leaving: " << network->clients_in_state_count(bmp::State::Leaving) << "\n"
|
||||||
|
<< "\tGuests: " << network->guest_count() << "\n"
|
||||||
|
<< "\tVehicles: " << network->vehicle_count() << "\n"
|
||||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||||
<< "\tLua:\n"
|
<< "\tLua:\n"
|
||||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||||
@@ -478,12 +449,12 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
||||||
<< "\tSubsystems:\n"
|
<< "\tSubsystems:\n"
|
||||||
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
||||||
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
||||||
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
||||||
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
||||||
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
||||||
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
||||||
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||||
<< "";
|
<< "";
|
||||||
|
|
||||||
Application::Console().WriteRaw(Status.str());
|
Application::Console().WriteRaw(Status.str());
|
||||||
@@ -588,16 +559,20 @@ Commands
|
|||||||
}
|
}
|
||||||
|
|
||||||
TConsole::TConsole() {
|
TConsole::TConsole() {
|
||||||
mCommandline.enable_history();
|
}
|
||||||
mCommandline.set_history_limit(20);
|
|
||||||
mCommandline.set_prompt("> ");
|
void TConsole::InitializeCommandline() {
|
||||||
|
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");
|
||||||
@@ -605,9 +580,7 @@ TConsole::TConsole() {
|
|||||||
HandleLuaInternalCommand(cmd.substr(1));
|
HandleLuaInternalCommand(cmd.substr(1));
|
||||||
} else {
|
} else {
|
||||||
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
||||||
while (!Future->Ready) {
|
Future->WaitUntilReady();
|
||||||
std::this_thread::yield(); // TODO: Add a timeout
|
|
||||||
}
|
|
||||||
if (Future->Error) {
|
if (Future->Error) {
|
||||||
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||||
}
|
}
|
||||||
@@ -634,7 +607,7 @@ TConsole::TConsole() {
|
|||||||
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
|
||||||
@@ -704,11 +677,21 @@ TConsole::TConsole() {
|
|||||||
|
|
||||||
void TConsole::Write(const std::string& str) {
|
void TConsole::Write(const std::string& str) {
|
||||||
auto ToWrite = GetDate() + str;
|
auto ToWrite = GetDate() + str;
|
||||||
mCommandline.write(ToWrite);
|
// allows writing to stdout without an initialized console
|
||||||
|
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) {
|
||||||
mCommandline.write(str);
|
// allows writing to stdout without an initialized console
|
||||||
|
if (mCommandline) {
|
||||||
|
mCommandline->write(str);
|
||||||
|
} else {
|
||||||
|
std::cout << str << std::endl;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
||||||
|
|||||||
+17
-38
@@ -1,8 +1,7 @@
|
|||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
//#include "SocketIO.h"
|
// #include "SocketIO.h"
|
||||||
#include <rapidjson/document.h>
|
#include <rapidjson/document.h>
|
||||||
#include <rapidjson/rapidjson.h>
|
#include <rapidjson/rapidjson.h>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
@@ -40,16 +39,6 @@ void THeartbeatThread::operator()() {
|
|||||||
Body += "&ip=" + Application::Settings.CustomIP;
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("heartbeat",
|
|
||||||
{ { "response-body", T },
|
|
||||||
{ "request-body", Body } });
|
|
||||||
Sentry.SetTransaction(transaction);
|
|
||||||
beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
|
|
||||||
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
|
|
||||||
};
|
|
||||||
|
|
||||||
auto Target = "/heartbeat";
|
auto Target = "/heartbeat";
|
||||||
unsigned int ResponseCode = 0;
|
unsigned int ResponseCode = 0;
|
||||||
|
|
||||||
@@ -63,10 +52,8 @@ void THeartbeatThread::operator()() {
|
|||||||
beammp_trace("Backend response failed to parse as valid json");
|
beammp_trace("Backend response failed to parse as valid json");
|
||||||
beammp_trace("Response was: `" + T + "`");
|
beammp_trace("Response was: `" + T + "`");
|
||||||
}
|
}
|
||||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
|
||||||
SentryReportError(Url + Target, ResponseCode);
|
|
||||||
} else if (ResponseCode != 200) {
|
} else if (ResponseCode != 200) {
|
||||||
SentryReportError(Url + Target, ResponseCode);
|
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
|
||||||
} else {
|
} else {
|
||||||
// all ok
|
// all ok
|
||||||
Ok = true;
|
Ok = true;
|
||||||
@@ -85,24 +72,20 @@ void THeartbeatThread::operator()() {
|
|||||||
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
||||||
Status = Doc[StatusKey].GetString();
|
Status = Doc[StatusKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Sentry.SetContext("JSON Response", { { StatusKey, "invalid string / missing" } });
|
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||||
Code = Doc[CodeKey].GetString();
|
Code = Doc[CodeKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Sentry.SetContext("JSON Response", { { CodeKey, "invalid string / missing" } });
|
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||||
Message = Doc[MessageKey].GetString();
|
Message = Doc[MessageKey].GetString();
|
||||||
} else {
|
} else {
|
||||||
Sentry.SetContext("JSON Response", { { MessageKey, "invalid string / missing" } });
|
|
||||||
Ok = false;
|
Ok = false;
|
||||||
}
|
}
|
||||||
if (!Ok) {
|
if (!Ok) {
|
||||||
beammp_error("Missing/invalid json members in backend response");
|
beammp_error("Missing/invalid json members in backend response");
|
||||||
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!Application::Settings.Private) {
|
if (!Application::Settings.Private) {
|
||||||
@@ -137,7 +120,7 @@ std::string THeartbeatThread::GenerateCall() {
|
|||||||
std::stringstream Ret;
|
std::stringstream Ret;
|
||||||
|
|
||||||
Ret << "uuid=" << Application::Settings.Key
|
Ret << "uuid=" << Application::Settings.Key
|
||||||
<< "&players=" << mServer.ClientCount()
|
<< "&players=" << m_network->authenticated_client_count()
|
||||||
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||||
<< "&port=" << Application::Settings.Port
|
<< "&port=" << Application::Settings.Port
|
||||||
<< "&map=" << Application::Settings.MapName
|
<< "&map=" << Application::Settings.MapName
|
||||||
@@ -145,16 +128,17 @@ 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
|
||||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
<< "&tags=" << Application::Settings.ServerTags
|
||||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
<< "&modlist=" << "-"//mResourceManager.TrimmedList()
|
||||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
<< "&modstotalsize=" << 0 //mResourceManager.MaxModSize()
|
||||||
|
<< "&modstotal=" << 0 // mResourceManager.ModsLoaded()
|
||||||
<< "&playerslist=" << GetPlayers()
|
<< "&playerslist=" << GetPlayers()
|
||||||
<< "&desc=" << Application::Settings.ServerDesc;
|
<< "&desc=" << Application::Settings.ServerDesc
|
||||||
|
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||||
return Ret.str();
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
|
||||||
: mResourceManager(ResourceManager)
|
: m_network(std::move(network)) {
|
||||||
, mServer(Server) {
|
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||||
@@ -166,15 +150,10 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
|
|||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
std::string THeartbeatThread::GetPlayers() {
|
std::string THeartbeatThread::GetPlayers() {
|
||||||
std::string Return;
|
std::string players;
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
for (const auto& [id, client] : m_network->authenticated_clients()) {
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
players += client->name.get() + ";";
|
||||||
if (!ClientPtr.expired()) {
|
}
|
||||||
Return += ClientPtr.lock()->GetName() + ";";
|
return players;
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return Return;
|
|
||||||
}
|
}
|
||||||
/*THeartbeatThread::~THeartbeatThread() {
|
|
||||||
}*/
|
|
||||||
|
|||||||
+76
-84
@@ -1,5 +1,4 @@
|
|||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "Client.h"
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
@@ -32,7 +31,7 @@ TLuaEngine::TLuaEngine()
|
|||||||
}
|
}
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
IThreaded::Start();
|
mThread = boost::scoped_thread<>(&TLuaEngine::Start, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_CASE("TLuaEngine ctor & dtor") {
|
TEST_CASE("TLuaEngine ctor & dtor") {
|
||||||
@@ -41,7 +40,7 @@ TEST_CASE("TLuaEngine ctor & dtor") {
|
|||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::operator()() {
|
void TLuaEngine::Start() {
|
||||||
RegisterThread("LuaEngine");
|
RegisterThread("LuaEngine");
|
||||||
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
|
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
|
||||||
// lua engine main thread
|
// lua engine main thread
|
||||||
@@ -286,6 +285,7 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
|
|||||||
bool Cancelled = false;
|
bool Cancelled = false;
|
||||||
size_t ms = 0;
|
size_t ms = 0;
|
||||||
std::set<std::string> WarnedResults;
|
std::set<std::string> WarnedResults;
|
||||||
|
|
||||||
while (!Result->Ready && !Cancelled) {
|
while (!Result->Ready && !Cancelled) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
ms += 10;
|
ms += 10;
|
||||||
@@ -300,6 +300,7 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Cancelled) {
|
if (Cancelled) {
|
||||||
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
|
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
|
||||||
LuaAPI::MP::Engine->ReportErrors({ Result });
|
LuaAPI::MP::Engine->ReportErrors({ Result });
|
||||||
@@ -425,7 +426,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
||||||
}
|
}
|
||||||
Result->Ready = true;
|
Result->MarkAsReady();
|
||||||
Return.push_back(Result);
|
Return.push_back(Result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -477,14 +478,14 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
|
|||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto MaybeClient = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient) {
|
||||||
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
|
auto IDs = MaybeClient.value()->identifiers.synchronize();
|
||||||
if (IDs.empty()) {
|
if (IDs->empty()) {
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
sol::table Result = mStateView.create_table();
|
sol::table Result = mStateView.create_table();
|
||||||
for (const auto& Pair : IDs) {
|
for (const auto& Pair : *IDs) {
|
||||||
Result[Pair.first] = Pair.second;
|
Result[Pair.first] = Pair.second;
|
||||||
}
|
}
|
||||||
return Result;
|
return Result;
|
||||||
@@ -494,30 +495,22 @@ 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([&](std::weak_ptr<TClient> Client) -> bool {
|
auto clients = mEngine->Network()->authenticated_clients();
|
||||||
if (!Client.expired()) {
|
for (const auto& [id, client] : clients) {
|
||||||
auto locked = Client.lock();
|
result[client->id] = client->name.get();
|
||||||
Result[locked->GetID()] = locked->GetName();
|
}
|
||||||
}
|
return result;
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
|
||||||
int Id = -1;
|
auto clients = mEngine->Network()->authenticated_clients();
|
||||||
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
|
for (const auto& [id, client] : clients) {
|
||||||
if (!Client.expired()) {
|
if (client->name.get() == Name) {
|
||||||
auto locked = Client.lock();
|
return int(client->id);
|
||||||
if (locked->GetName() == Name) {
|
|
||||||
Id = locked->GetID();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return true;
|
}
|
||||||
});
|
return -1;
|
||||||
return Id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
|
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
|
||||||
@@ -547,60 +540,51 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto maybe_client = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (maybe_client) {
|
||||||
return MaybeClient.value().lock()->GetName();
|
return maybe_client.value()->name.get();
|
||||||
} else {
|
} else {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), ID);
|
auto vehicles = mEngine->Network()->get_vehicles_owned_by(ClientID(ID));
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (vehicles.empty()) {
|
||||||
auto Client = MaybeClient.value().lock();
|
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
|
||||||
{ // Vehicle Data Lock Scope
|
|
||||||
auto LockedData = Client->GetAllCars();
|
|
||||||
VehicleData = *LockedData.VehicleData;
|
|
||||||
} // End Vehicle Data Lock Scope
|
|
||||||
if (VehicleData.empty()) {
|
|
||||||
return sol::lua_nil;
|
|
||||||
}
|
|
||||||
sol::state_view StateView(mState);
|
|
||||||
sol::table Result = StateView.create_table();
|
|
||||||
for (const auto& v : VehicleData) {
|
|
||||||
Result[v.ID()] = v.Data().substr(3);
|
|
||||||
}
|
|
||||||
return Result;
|
|
||||||
} else
|
|
||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
|
}
|
||||||
|
sol::state_view state_view(mState);
|
||||||
|
sol::table result = state_view.create_table();
|
||||||
|
for (const auto& [vid, vehicle] : vehicles) {
|
||||||
|
result[vid] = vehicle->data.get();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
|
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetVehicleStatus(int VID) {
|
||||||
std::pair<sol::table, std::string> Result;
|
auto maybe_vehicle = mEngine->Network()->get_vehicle(VehicleID(VID));
|
||||||
auto MaybeClient = GetClient(mEngine->Server(), PID);
|
if (maybe_vehicle) {
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
sol::state_view state_view(mState);
|
||||||
auto Client = MaybeClient.value().lock();
|
sol::table result = state_view.create_table();
|
||||||
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
auto veh = maybe_vehicle.value();
|
||||||
|
auto status = veh->get_status();
|
||||||
if (VehiclePos.empty()) {
|
result["pos"]["x"] = status.pos.x;
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
result["pos"]["y"] = status.pos.y;
|
||||||
Result.second = "Vehicle not found";
|
result["pos"]["z"] = status.pos.z;
|
||||||
return Result;
|
result["vel"]["x"] = status.vel.x;
|
||||||
}
|
result["vel"]["y"] = status.vel.y;
|
||||||
|
result["vel"]["z"] = status.vel.z;
|
||||||
sol::table t = Lua_JsonDecode(VehiclePos);
|
result["rvel"]["x"] = status.rvel.x;
|
||||||
if (t == sol::lua_nil) {
|
result["rvel"]["y"] = status.rvel.y;
|
||||||
Result.second = "Packet decode failed";
|
result["rvel"]["z"] = status.rvel.z;
|
||||||
}
|
result["rot"]["x"] = status.rot.x;
|
||||||
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
result["rot"]["y"] = status.rot.y;
|
||||||
Result.first = t;
|
result["rot"]["z"] = status.rot.z;
|
||||||
return Result;
|
result["rot"]["w"] = status.rot.w;
|
||||||
|
result["time"] = status.time;
|
||||||
|
return { result, "" };
|
||||||
} else {
|
} else {
|
||||||
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
return { sol::lua_nil, fmt::format("Vehicle {} not found", VID) };
|
||||||
Result.second = "Client expired";
|
|
||||||
return Result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -762,8 +746,8 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
||||||
return Lua_GetPlayerVehicles(ID);
|
return Lua_GetPlayerVehicles(ID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> {
|
MPTable.set_function("GetVehicleStatus", [&](int VID) -> std::pair<sol::table, std::string> {
|
||||||
return Lua_GetPositionRaw(PID, VID);
|
return Lua_GetVehicleStatus(VID);
|
||||||
});
|
});
|
||||||
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
||||||
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
||||||
@@ -864,7 +848,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
|||||||
FSTable.set_function("ListDirectories", [this](const std::string& Path) {
|
FSTable.set_function("ListDirectories", [this](const std::string& Path) {
|
||||||
return Lua_FS_ListDirectories(Path);
|
return Lua_FS_ListDirectories(Path);
|
||||||
});
|
});
|
||||||
Start();
|
mThread = boost::scoped_thread<>(&StateThreadData::Start, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
|
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
|
||||||
@@ -910,7 +894,7 @@ void TLuaEngine::StateThreadData::RegisterEvent(const std::string& EventName, co
|
|||||||
mEngine->RegisterEvent(EventName, mStateId, FunctionName);
|
mEngine->RegisterEvent(EventName, mStateId, FunctionName);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaEngine::StateThreadData::operator()() {
|
void TLuaEngine::StateThreadData::Start() {
|
||||||
RegisterThread("Lua:" + mStateId);
|
RegisterThread("Lua:" + mStateId);
|
||||||
while (!Application::IsShuttingDown()) {
|
while (!Application::IsShuttingDown()) {
|
||||||
{ // StateExecuteQueue Scope
|
{ // StateExecuteQueue Scope
|
||||||
@@ -955,7 +939,7 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
S.second->ErrorMessage = Err.what();
|
S.second->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
S.second->Ready = true;
|
S.second->MarkAsReady();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{ // StateFunctionQueue Scope
|
{ // StateFunctionQueue Scope
|
||||||
@@ -1016,11 +1000,11 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
Result->ErrorMessage = Err.what();
|
Result->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
Result->Ready = true;
|
Result->MarkAsReady();
|
||||||
} else {
|
} else {
|
||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
||||||
Result->Ready = true;
|
Result->MarkAsReady();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1070,11 +1054,19 @@ void TLuaEngine::StateThreadData::AddPath(const fs::path& Path) {
|
|||||||
mPaths.push(Path);
|
mPaths.push(Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaResult::WaitUntilReady() {
|
void TLuaResult::MarkAsReady() {
|
||||||
while (!Ready) {
|
{
|
||||||
std::this_thread::yield();
|
std::lock_guard<std::mutex> readyLock(*this->ReadyMutex);
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
this->Ready = true;
|
||||||
}
|
}
|
||||||
|
this->ReadyCondition->notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TLuaResult::WaitUntilReady() {
|
||||||
|
std::unique_lock readyLock(*this->ReadyMutex);
|
||||||
|
// wait if not ready yet
|
||||||
|
if (!this->Ready)
|
||||||
|
this->ReadyCondition->wait(readyLock);
|
||||||
}
|
}
|
||||||
|
|
||||||
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
|
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
|
||||||
|
|||||||
@@ -1,932 +0,0 @@
|
|||||||
#include "TNetwork.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "LuaAPI.h"
|
|
||||||
#include "TLuaEngine.h"
|
|
||||||
#include "nlohmann/json.hpp"
|
|
||||||
#include <CustomAssert.h>
|
|
||||||
#include <Http.h>
|
|
||||||
#include <array>
|
|
||||||
#include <boost/asio/ip/address.hpp>
|
|
||||||
#include <boost/asio/ip/address_v4.hpp>
|
|
||||||
#include <cstring>
|
|
||||||
|
|
||||||
std::vector<uint8_t> StringToVector(const std::string& Str) {
|
|
||||||
return std::vector<uint8_t>(Str.data(), Str.data() + Str.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
static void CompressProperly(std::vector<uint8_t>& Data) {
|
|
||||||
constexpr std::string_view ABG = "ABG:";
|
|
||||||
auto CombinedData = std::vector<uint8_t>(ABG.begin(), ABG.end());
|
|
||||||
auto CompData = Comp(Data);
|
|
||||||
CombinedData.resize(ABG.size() + CompData.size());
|
|
||||||
std::copy(CompData.begin(), CompData.end(), CombinedData.begin() + ABG.size());
|
|
||||||
Data = CombinedData;
|
|
||||||
}
|
|
||||||
|
|
||||||
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
|
|
||||||
: mServer(Server)
|
|
||||||
, mPPSMonitor(PPSMonitor)
|
|
||||||
, mUDPSock(Server.IoCtx())
|
|
||||||
, mResourceManager(ResourceManager) {
|
|
||||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting);
|
|
||||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
|
|
||||||
Application::RegisterShutdownHandler([&] {
|
|
||||||
beammp_debug("Kicking all players due to shutdown");
|
|
||||||
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
|
|
||||||
if (!client.expired()) {
|
|
||||||
ClientKick(*client.lock(), "Server shutdown");
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Application::RegisterShutdownHandler([&] {
|
|
||||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown);
|
|
||||||
if (mUDPThread.joinable()) {
|
|
||||||
mUDPThread.detach();
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Shutdown);
|
|
||||||
});
|
|
||||||
Application::RegisterShutdownHandler([&] {
|
|
||||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::ShuttingDown);
|
|
||||||
if (mTCPThread.joinable()) {
|
|
||||||
mTCPThread.detach();
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Shutdown);
|
|
||||||
});
|
|
||||||
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
|
|
||||||
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::UDPServerMain() {
|
|
||||||
RegisterThread("UDPServer");
|
|
||||||
ip::udp::endpoint UdpListenEndpoint(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
|
|
||||||
boost::system::error_code ec;
|
|
||||||
mUDPSock.open(UdpListenEndpoint.protocol(), ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_error("open() failed: " + ec.message());
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
|
||||||
Application::GracefullyShutdown();
|
|
||||||
}
|
|
||||||
mUDPSock.bind(UdpListenEndpoint, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_error("bind() failed: " + ec.message());
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
|
||||||
Application::GracefullyShutdown();
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good);
|
|
||||||
beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
|
|
||||||
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
|
|
||||||
while (!Application::IsShuttingDown()) {
|
|
||||||
try {
|
|
||||||
ip::udp::endpoint client {};
|
|
||||||
std::vector<uint8_t> Data = UDPRcvFromClient(client); // Receives any data from Socket
|
|
||||||
auto Pos = std::find(Data.begin(), Data.end(), ':');
|
|
||||||
if (Data.empty() || Pos > Data.begin() + 2)
|
|
||||||
continue;
|
|
||||||
uint8_t ID = uint8_t(Data.at(0)) - 1;
|
|
||||||
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> Client;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
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;
|
|
||||||
});
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_error(("fatal: ") + std::string(e.what()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::TCPServerMain() {
|
|
||||||
RegisterThread("TCPServer");
|
|
||||||
|
|
||||||
ip::tcp::endpoint ListenEp(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
|
|
||||||
ip::tcp::socket Listener(mServer.IoCtx());
|
|
||||||
boost::system::error_code ec;
|
|
||||||
Listener.open(ListenEp.protocol(), ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("Failed to open socket: {}", ec.message());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
socket_base::linger LingerOpt {};
|
|
||||||
LingerOpt.enabled(false);
|
|
||||||
Listener.set_option(LingerOpt, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("Failed to set up listening socket to not linger / reuse address. "
|
|
||||||
"This may cause the socket to refuse to bind(). Error: {}",
|
|
||||||
ec.message());
|
|
||||||
}
|
|
||||||
|
|
||||||
ip::tcp::acceptor Acceptor(mServer.IoCtx(), ListenEp);
|
|
||||||
Acceptor.listen(socket_base::max_listen_connections, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("listen() failed, which is needed for the server to operate. "
|
|
||||||
"Shutting down. Error: {}",
|
|
||||||
ec.message());
|
|
||||||
Application::GracefullyShutdown();
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
|
||||||
beammp_info("Vehicle event network online");
|
|
||||||
do {
|
|
||||||
try {
|
|
||||||
if (Application::IsShuttingDown()) {
|
|
||||||
beammp_debug("shutdown during TCP wait for accept loop");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ip::tcp::endpoint ClientEp;
|
|
||||||
ip::tcp::socket ClientSocket = Acceptor.accept(ClientEp, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("failed to accept: {}", ec.message());
|
|
||||||
}
|
|
||||||
TConnection Conn { std::move(ClientSocket), ClientEp };
|
|
||||||
std::thread ID(&TNetwork::Identify, this, std::move(Conn));
|
|
||||||
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_error("fatal: " + std::string(e.what()));
|
|
||||||
}
|
|
||||||
} while (!Application::IsShuttingDown());
|
|
||||||
}
|
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
|
||||||
|
|
||||||
#include "Json.h"
|
|
||||||
namespace json = rapidjson;
|
|
||||||
|
|
||||||
void TNetwork::Identify(TConnection&& RawConnection) {
|
|
||||||
RegisterThreadAuto();
|
|
||||||
char Code;
|
|
||||||
|
|
||||||
boost::system::error_code ec;
|
|
||||||
read(RawConnection.Socket, buffer(&Code, 1), ec);
|
|
||||||
if (ec) {
|
|
||||||
// TODO: is this right?!
|
|
||||||
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::shared_ptr<TClient> Client { nullptr };
|
|
||||||
if (Code == 'C') {
|
|
||||||
Client = Authentication(std::move(RawConnection));
|
|
||||||
} else if (Code == 'D') {
|
|
||||||
HandleDownload(std::move(RawConnection));
|
|
||||||
} else if (Code == 'P') {
|
|
||||||
boost::system::error_code ec;
|
|
||||||
write(RawConnection.Socket, buffer("P"), ec);
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
beammp_errorf("Invalid code got in Identify: '{}'", Code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::HandleDownload(TConnection&& Conn) {
|
|
||||||
char D;
|
|
||||||
boost::system::error_code ec;
|
|
||||||
read(Conn.Socket, buffer(&D, 1), ec);
|
|
||||||
if (ec) {
|
|
||||||
Conn.Socket.shutdown(socket_base::shutdown_both, ec);
|
|
||||||
// ignore ec
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto ID = uint8_t(D);
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
auto c = ClientPtr.lock();
|
|
||||||
if (c->GetID() == ID) {
|
|
||||||
c->SetDownSock(std::move(Conn.Socket));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
|
|
||||||
auto Client = CreateClient(std::move(RawConnection.Socket));
|
|
||||||
Client->SetIdentifier("ip", RawConnection.SockAddr.address().to_string());
|
|
||||||
beammp_tracef("This thread is ip {}", RawConnection.SockAddr.address().to_string());
|
|
||||||
|
|
||||||
beammp_info("Identifying new ClientConnection...");
|
|
||||||
|
|
||||||
auto Data = TCPRcv(*Client);
|
|
||||||
|
|
||||||
constexpr std::string_view VC = "VC";
|
|
||||||
if (Data.size() > 3 && std::equal(Data.begin(), Data.begin() + VC.size(), VC.begin(), VC.end())) {
|
|
||||||
std::string ClientVersionStr(reinterpret_cast<const char*>(Data.data() + 2), Data.size() - 2);
|
|
||||||
Version ClientVersion = Application::VersionStrToInts(ClientVersionStr + ".0");
|
|
||||||
if (ClientVersion.major != Application::ClientMajorVersion()) {
|
|
||||||
beammp_errorf("Client tried to connect with version '{}', but only versions '{}.x.x' is allowed",
|
|
||||||
ClientVersion.AsString(), Application::ClientMajorVersion());
|
|
||||||
ClientKick(*Client, "Outdated Version!");
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ClientKick(*Client, fmt::format("Invalid version header: '{}' ({})", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()), Data.size()));
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
if (!TCPSend(*Client, StringToVector("S"))) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
|
|
||||||
Data = TCPRcv(*Client);
|
|
||||||
|
|
||||||
if (Data.size() > 50) {
|
|
||||||
ClientKick(*Client, "Invalid Key (too long)!");
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
nlohmann::json AuthReq {
|
|
||||||
{ "key", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()) }
|
|
||||||
};
|
|
||||||
auto Target = "/pkToUser";
|
|
||||||
unsigned int ResponseCode = 0;
|
|
||||||
const auto AuthResStr = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, AuthReq.dump(), "application/json", &ResponseCode);
|
|
||||||
|
|
||||||
try {
|
|
||||||
nlohmann::json AuthRes = nlohmann::json::parse(AuthResStr);
|
|
||||||
|
|
||||||
if (AuthRes["username"].is_string() && AuthRes["roles"].is_string()
|
|
||||||
&& AuthRes["guest"].is_boolean() && AuthRes["identifiers"].is_array()) {
|
|
||||||
|
|
||||||
Client->SetName(AuthRes["username"]);
|
|
||||||
Client->SetRoles(AuthRes["roles"]);
|
|
||||||
Client->SetIsGuest(AuthRes["guest"]);
|
|
||||||
for (const auto& ID : AuthRes["identifiers"]) {
|
|
||||||
auto Raw = std::string(ID);
|
|
||||||
auto SepIndex = Raw.find(':');
|
|
||||||
Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
beammp_error("Invalid authentication data received from authentication backend");
|
|
||||||
ClientKick(*Client, "Invalid authentication data!");
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_errorf("Client sent invalid key. Error was: {}", e.what());
|
|
||||||
// TODO: we should really clarify that this was a backend response or parsing error
|
|
||||||
ClientKick(*Client, "Invalid key! Please restart your game.");
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> Cl;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
Cl = ClientPtr.lock();
|
|
||||||
} else
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (Cl->GetName() == Client->GetName() && Cl->IsGuest() == Client->IsGuest()) {
|
|
||||||
Cl->Disconnect("Stale Client (not a real player)");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers());
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
|
||||||
return !Result->Error && Result->Result.is<int>() && bool(Result->Result.as<int>());
|
|
||||||
});
|
|
||||||
std::string Reason;
|
|
||||||
bool NotAllowedWithReason = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[&Reason](const std::shared_ptr<TLuaResult>& Result) -> bool {
|
|
||||||
if (!Result->Error && Result->Result.is<std::string>()) {
|
|
||||||
Reason = Result->Result.as<std::string>();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (NotAllowed) {
|
|
||||||
ClientKick(*Client, "you are not allowed on the server!");
|
|
||||||
return {};
|
|
||||||
} else if (NotAllowedWithReason) {
|
|
||||||
ClientKick(*Client, Reason);
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
|
|
||||||
beammp_info("Identification success");
|
|
||||||
mServer.InsertClient(Client);
|
|
||||||
TCPClient(Client);
|
|
||||||
} else {
|
|
||||||
ClientKick(*Client, "Server full!");
|
|
||||||
}
|
|
||||||
return Client;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
|
|
||||||
auto c = std::make_shared<TClient>(mServer, std::move(TCPSock));
|
|
||||||
return c;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) {
|
|
||||||
if (!IsSync) {
|
|
||||||
if (c.IsSyncing()) {
|
|
||||||
if (!Data.empty()) {
|
|
||||||
if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') {
|
|
||||||
c.EnqueuePacket(Data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
auto& Sock = c.GetTCPSock();
|
|
||||||
|
|
||||||
/*
|
|
||||||
* our TCP protocol sends a header of 4 bytes, followed by the data.
|
|
||||||
*
|
|
||||||
* [][][][][][]...[]
|
|
||||||
* ^------^^---...-^
|
|
||||||
* size data
|
|
||||||
*/
|
|
||||||
|
|
||||||
const auto Size = int32_t(Data.size());
|
|
||||||
std::vector<uint8_t> ToSend;
|
|
||||||
ToSend.resize(Data.size() + sizeof(Size));
|
|
||||||
std::memcpy(ToSend.data(), &Size, sizeof(Size));
|
|
||||||
std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size());
|
|
||||||
boost::system::error_code ec;
|
|
||||||
write(Sock, buffer(ToSend), ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("write(): {}", ec.message());
|
|
||||||
c.Disconnect("write() failed");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
c.UpdatePingTime();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
|
|
||||||
if (c.IsDisconnected()) {
|
|
||||||
beammp_error("Client disconnected, cancelling TCPRcv");
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
int32_t Header {};
|
|
||||||
auto& Sock = c.GetTCPSock();
|
|
||||||
|
|
||||||
boost::system::error_code ec;
|
|
||||||
std::array<uint8_t, sizeof(Header)> HeaderData;
|
|
||||||
read(Sock, buffer(HeaderData), ec);
|
|
||||||
if (ec) {
|
|
||||||
// TODO: handle this case (read failed)
|
|
||||||
beammp_debugf("TCPRcv: Reading header failed: {}", ec.message());
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
Header = *reinterpret_cast<int32_t*>(HeaderData.data());
|
|
||||||
|
|
||||||
std::vector<uint8_t> Data;
|
|
||||||
// TODO: This is arbitrary, this needs to be handled another way
|
|
||||||
if (Header < int32_t(100 * MB)) {
|
|
||||||
Data.resize(Header);
|
|
||||||
} else {
|
|
||||||
ClientKick(c, "Header size limit exceeded");
|
|
||||||
beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
auto N = read(Sock, buffer(Data), ec);
|
|
||||||
if (ec) {
|
|
||||||
// TODO: handle this case properly
|
|
||||||
beammp_debugf("TCPRcv: Reading data failed: {}", ec.message());
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (N != Header) {
|
|
||||||
beammp_errorf("Expected to read {} bytes, instead got {}", Header, N);
|
|
||||||
}
|
|
||||||
|
|
||||||
constexpr std::string_view ABG = "ABG:";
|
|
||||||
if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
|
||||||
Data.erase(Data.begin(), Data.begin() + ABG.size());
|
|
||||||
return DeComp(Data);
|
|
||||||
} else {
|
|
||||||
return Data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
|
||||||
beammp_info("Client kicked: " + R);
|
|
||||||
if (!TCPSend(c, StringToVector("K" + R))) {
|
|
||||||
beammp_debugf("tried to kick player '{}' (id {}), but was already connected", c.GetName(), c.GetID());
|
|
||||||
}
|
|
||||||
c.Disconnect("Kicked");
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
|
||||||
RegisterThreadAuto();
|
|
||||||
while (!c.expired()) {
|
|
||||||
auto Client = c.lock();
|
|
||||||
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 {};
|
|
||||||
{ // locked context
|
|
||||||
std::unique_lock lock(Client->MissedPacketQueueMutex());
|
|
||||||
if (Client->MissedPacketQueueSize() <= 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
QData = Client->MissedPacketQueue().front();
|
|
||||||
Client->MissedPacketQueue().pop();
|
|
||||||
} // end locked context
|
|
||||||
// beammp_debug("sending a missed packet: " + QData);
|
|
||||||
if (!TCPSend(*Client, QData, true)) {
|
|
||||||
Client->Disconnect("Failed to TCPSend while clearing the missed packet queue");
|
|
||||||
std::unique_lock lock(Client->MissedPacketQueueMutex());
|
|
||||||
while (!Client->MissedPacketQueue().empty()) {
|
|
||||||
Client->MissedPacketQueue().pop();
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
RegisterThread("(" + std::to_string(c.lock()->GetID()) + ") \"" + c.lock()->GetName() + "\"");
|
|
||||||
|
|
||||||
std::thread QueueSync(&TNetwork::Looper, this, c);
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
if (c.expired())
|
|
||||||
break;
|
|
||||||
auto Client = c.lock();
|
|
||||||
if (Client->IsDisconnected()) {
|
|
||||||
beammp_debug("client status < 0, breaking client loop");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto res = TCPRcv(*Client);
|
|
||||||
if (res.empty()) {
|
|
||||||
beammp_debug("TCPRcv empty");
|
|
||||||
Client->Disconnect("TCPRcv failed");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (QueueSync.joinable())
|
|
||||||
QueueSync.join();
|
|
||||||
|
|
||||||
if (!c.expired()) {
|
|
||||||
auto Client = c.lock();
|
|
||||||
OnDisconnect(c);
|
|
||||||
} else {
|
|
||||||
beammp_warn("client expired in TCPClient, should never happen");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::UpdatePlayer(TClient& Client) {
|
|
||||||
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
auto c = ClientPtr.lock();
|
|
||||||
Packet += c->GetName() + ",";
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
Packet = Packet.substr(0, Packet.length() - 1);
|
|
||||||
Client.EnqueuePacket(StringToVector(Packet));
|
|
||||||
//(void)Respond(Client, Packet, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) {
|
|
||||||
beammp_assert(!ClientPtr.expired());
|
|
||||||
auto LockedClientPtr = ClientPtr.lock();
|
|
||||||
TClient& c = *LockedClientPtr;
|
|
||||||
beammp_info(c.GetName() + (" Connection Terminated"));
|
|
||||||
std::string Packet;
|
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
|
||||||
{ // Vehicle Data Lock Scope
|
|
||||||
auto LockedData = c.GetAllCars();
|
|
||||||
VehicleData = *LockedData.VehicleData;
|
|
||||||
} // End Vehicle Data Lock Scope
|
|
||||||
for (auto& v : VehicleData) {
|
|
||||||
Packet = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(v.ID());
|
|
||||||
SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
}
|
|
||||||
Packet = ("L") + c.GetName() + (" left the server!");
|
|
||||||
SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
Packet.clear();
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", c.GetID());
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(Futures);
|
|
||||||
c.Disconnect("Already Disconnected (OnDisconnect)");
|
|
||||||
mServer.RemoveClient(ClientPtr);
|
|
||||||
}
|
|
||||||
|
|
||||||
int TNetwork::OpenID() {
|
|
||||||
int ID = 0;
|
|
||||||
bool found;
|
|
||||||
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) {
|
|
||||||
beammp_assert(!c.expired());
|
|
||||||
beammp_info("Client connected");
|
|
||||||
auto LockedClient = c.lock();
|
|
||||||
LockedClient->SetID(OpenID());
|
|
||||||
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID()));
|
|
||||||
SyncResources(*LockedClient);
|
|
||||||
if (LockedClient->IsDisconnected())
|
|
||||||
return;
|
|
||||||
(void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
|
|
||||||
beammp_info(LockedClient->GetName() + " : Connected");
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::SyncResources(TClient& c) {
|
|
||||||
if (!TCPSend(c, StringToVector("P" + std::to_string(c.GetID())))) {
|
|
||||||
// TODO handle
|
|
||||||
}
|
|
||||||
std::vector<uint8_t> Data;
|
|
||||||
while (!c.IsDisconnected()) {
|
|
||||||
Data = TCPRcv(c);
|
|
||||||
if (Data.empty()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
constexpr std::string_view Done = "Done";
|
|
||||||
if (std::equal(Data.begin(), Data.end(), Done.begin(), Done.end()))
|
|
||||||
break;
|
|
||||||
Parse(c, Data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
|
|
||||||
if (Packet.empty())
|
|
||||||
return;
|
|
||||||
char Code = Packet.at(0), SubCode = 0;
|
|
||||||
if (Packet.size() > 1)
|
|
||||||
SubCode = Packet.at(1);
|
|
||||||
switch (Code) {
|
|
||||||
case 'f':
|
|
||||||
SendFile(c, std::string(reinterpret_cast<const char*>(Packet.data() + 1), Packet.size() - 1));
|
|
||||||
return;
|
|
||||||
case 'S':
|
|
||||||
if (SubCode == 'R') {
|
|
||||||
beammp_debug("Sending Mod Info");
|
|
||||||
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
|
|
||||||
if (ToSend.empty())
|
|
||||||
ToSend = "-";
|
|
||||||
if (!TCPSend(c, StringToVector(ToSend))) {
|
|
||||||
// TODO: error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
default:
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|
||||||
beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
|
|
||||||
|
|
||||||
if (!fs::path(UnsafeName).has_filename()) {
|
|
||||||
if (!TCPSend(c, StringToVector("CO"))) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
beammp_warn("File " + UnsafeName + " is not a file!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto FileName = fs::path(UnsafeName).filename().string();
|
|
||||||
FileName = Application::Settings.Resource + "/Client/" + FileName;
|
|
||||||
|
|
||||||
if (!std::filesystem::exists(FileName)) {
|
|
||||||
if (!TCPSend(c, StringToVector("CO"))) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
beammp_warn("File " + UnsafeName + " could not be accessed!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!TCPSend(c, StringToVector("AG"))) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait for connections
|
|
||||||
int T = 0;
|
|
||||||
while (!c.GetDownSock().is_open() && T < 50) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
||||||
T++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!c.GetDownSock().is_open()) {
|
|
||||||
beammp_error("Client doesn't have a download socket!");
|
|
||||||
if (!c.IsDisconnected())
|
|
||||||
c.Disconnect("Missing download socket");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t Size = size_t(std::filesystem::file_size(FileName)), MSize = Size / 2;
|
|
||||||
|
|
||||||
std::thread SplitThreads[2] {
|
|
||||||
std::thread([&] {
|
|
||||||
RegisterThread("SplitLoad_0");
|
|
||||||
SplitLoad(c, 0, MSize, false, FileName);
|
|
||||||
}),
|
|
||||||
std::thread([&] {
|
|
||||||
RegisterThread("SplitLoad_1");
|
|
||||||
SplitLoad(c, MSize, Size, true, FileName);
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
for (auto& SplitThread : SplitThreads) {
|
|
||||||
if (SplitThread.joinable()) {
|
|
||||||
SplitThread.join();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::pair<size_t /* count */, size_t /* last chunk */> SplitIntoChunks(size_t FullSize, size_t ChunkSize) {
|
|
||||||
if (FullSize < ChunkSize) {
|
|
||||||
return { 0, FullSize };
|
|
||||||
}
|
|
||||||
size_t Count = FullSize / (FullSize / ChunkSize);
|
|
||||||
size_t LastChunkSize = FullSize - (Count * ChunkSize);
|
|
||||||
return { Count, LastChunkSize };
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("SplitIntoChunks") {
|
|
||||||
size_t FullSize;
|
|
||||||
size_t ChunkSize;
|
|
||||||
SUBCASE("Normal case") {
|
|
||||||
FullSize = 1234567;
|
|
||||||
ChunkSize = 1234;
|
|
||||||
}
|
|
||||||
SUBCASE("Zero original size") {
|
|
||||||
FullSize = 0;
|
|
||||||
ChunkSize = 100;
|
|
||||||
}
|
|
||||||
SUBCASE("Equal full size and chunk size") {
|
|
||||||
FullSize = 125;
|
|
||||||
ChunkSize = 125;
|
|
||||||
}
|
|
||||||
SUBCASE("Even split") {
|
|
||||||
FullSize = 10000;
|
|
||||||
ChunkSize = 100;
|
|
||||||
}
|
|
||||||
SUBCASE("Odd split") {
|
|
||||||
FullSize = 13;
|
|
||||||
ChunkSize = 2;
|
|
||||||
}
|
|
||||||
SUBCASE("Large sizes") {
|
|
||||||
FullSize = 10 * GB;
|
|
||||||
ChunkSize = 125 * MB;
|
|
||||||
}
|
|
||||||
auto [Count, LastSize] = SplitIntoChunks(FullSize, ChunkSize);
|
|
||||||
CHECK((Count * ChunkSize) + LastSize == FullSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
const uint8_t* /* end ptr */ TNetwork::SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size) {
|
|
||||||
if (TCPSendRaw(c, Socket, DataPtr, Size)) {
|
|
||||||
return DataPtr + Size;
|
|
||||||
} else {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
|
||||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
|
||||||
uint32_t Split = 125 * MB;
|
|
||||||
std::vector<uint8_t> Data;
|
|
||||||
if (Size > Split)
|
|
||||||
Data.resize(Split);
|
|
||||||
else
|
|
||||||
Data.resize(Size);
|
|
||||||
ip::tcp::socket* TCPSock { nullptr };
|
|
||||||
if (D)
|
|
||||||
TCPSock = &c.GetDownSock();
|
|
||||||
else
|
|
||||||
TCPSock = &c.GetTCPSock();
|
|
||||||
while (!c.IsDisconnected() && Sent < Size) {
|
|
||||||
size_t Diff = Size - Sent;
|
|
||||||
if (Diff > Split) {
|
|
||||||
f.seekg(Sent, std::ios_base::beg);
|
|
||||||
f.read(reinterpret_cast<char*>(Data.data()), Split);
|
|
||||||
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
|
|
||||||
if (!c.IsDisconnected())
|
|
||||||
c.Disconnect("TCPSendRaw failed in mod download (1)");
|
|
||||||
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())
|
|
||||||
c.Disconnect("TCPSendRaw failed in mod download (2)");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Sent += Diff;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size) {
|
|
||||||
boost::system::error_code ec;
|
|
||||||
write(socket, buffer(Data, Size), ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("Failed to send raw data to client: {}", ec.message());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
C.UpdatePingTime();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync) {
|
|
||||||
if (Data.size() > 400) {
|
|
||||||
CompressProperly(Data);
|
|
||||||
}
|
|
||||||
return TCPSend(c, Data, isSync);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync) {
|
|
||||||
char C = MSG.at(0);
|
|
||||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
|
||||||
if (C == 'O' || C == 'T' || MSG.size() > 1000) {
|
|
||||||
return SendLarge(c, MSG, isSync);
|
|
||||||
} else {
|
|
||||||
return TCPSend(c, MSG, isSync);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return UDPSend(c, MSG);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
|
|
||||||
if (c.expired()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
auto LockedClient = c.lock();
|
|
||||||
if (LockedClient->IsSynced())
|
|
||||||
return true;
|
|
||||||
// Syncing, later set isSynced
|
|
||||||
// after syncing is done, we apply all packets they missed
|
|
||||||
if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->GetName()), true)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// ignore error
|
|
||||||
(void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->GetName() + "!"), false, true);
|
|
||||||
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID()));
|
|
||||||
LockedClient->SetIsSyncing(true);
|
|
||||||
bool Return = false;
|
|
||||||
bool res = true;
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> client;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
client = ClientPtr.lock();
|
|
||||||
} else
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
|
||||||
{ // 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()) {
|
|
||||||
Return = true;
|
|
||||||
res = false;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
res = Respond(*LockedClient, StringToVector(v.Data()), true, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
LockedClient->SetIsSyncing(false);
|
|
||||||
if (Return) {
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
LockedClient->SetIsSynced(true);
|
|
||||||
beammp_info(LockedClient->GetName() + (" is now synced!"));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) {
|
|
||||||
if (!Self)
|
|
||||||
beammp_assert(c);
|
|
||||||
char C = Data.at(0);
|
|
||||||
bool ret = true;
|
|
||||||
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> Client;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
Client = ClientPtr.lock();
|
|
||||||
} else
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (Self || Client.get() != c) {
|
|
||||||
if (Client->IsSynced() || Client->IsSyncing()) {
|
|
||||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
|
||||||
if (C == 'O' || C == 'T' || Data.size() > 1000) {
|
|
||||||
if (Data.size() > 400) {
|
|
||||||
auto CompressedData = Data;
|
|
||||||
CompressProperly(CompressedData);
|
|
||||||
Client->EnqueuePacket(CompressedData);
|
|
||||||
} else {
|
|
||||||
Client->EnqueuePacket(Data);
|
|
||||||
}
|
|
||||||
// ret = SendLarge(*Client, Data);
|
|
||||||
} else {
|
|
||||||
Client->EnqueuePacket(Data);
|
|
||||||
// ret = TCPSend(*Client, Data);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ret = UDPSend(*Client, Data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
if (!ret) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
|
|
||||||
if (!Client.IsConnected() || Client.IsDisconnected()) {
|
|
||||||
// this can happen if we try to send a packet to a client that is either
|
|
||||||
// 1. not yet fully connected, or
|
|
||||||
// 2. disconnected and not yet fully removed
|
|
||||||
// this is fine can can be ignored :^)
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const auto Addr = Client.GetUDPAddr();
|
|
||||||
if (Data.size() > 400) {
|
|
||||||
CompressProperly(Data);
|
|
||||||
}
|
|
||||||
boost::system::error_code ec;
|
|
||||||
mUDPSock.send_to(buffer(Data), Addr, 0, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_debugf("UDP sendto() failed: {}", ec.message());
|
|
||||||
if (!Client.IsDisconnected())
|
|
||||||
Client.Disconnect("UDP send failed");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<uint8_t> TNetwork::UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint) {
|
|
||||||
std::array<char, 1024> Ret {};
|
|
||||||
boost::system::error_code ec;
|
|
||||||
const auto Rcv = mUDPSock.receive_from(mutable_buffer(Ret.data(), Ret.size()), ClientEndpoint, 0, ec);
|
|
||||||
if (ec) {
|
|
||||||
beammp_errorf("UDP recvfrom() failed: {}", ec.message());
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
beammp_assert(Rcv <= Ret.size());
|
|
||||||
return std::vector<uint8_t>(Ret.begin(), Ret.begin() + Rcv);
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
#include "TPPSMonitor.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "TNetwork.h"
|
|
||||||
|
|
||||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
|
||||||
: mServer(Server) {
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
|
||||||
Application::SetPPS("-");
|
|
||||||
Application::RegisterShutdownHandler([&] {
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
|
||||||
if (mThread.joinable()) {
|
|
||||||
beammp_debug("shutting down PPSMonitor");
|
|
||||||
mThread.join();
|
|
||||||
beammp_debug("shut down PPSMonitor");
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
|
||||||
});
|
|
||||||
Start();
|
|
||||||
}
|
|
||||||
void TPPSMonitor::operator()() {
|
|
||||||
RegisterThread("PPSMonitor");
|
|
||||||
while (!mNetwork) {
|
|
||||||
// hard(-ish) spin
|
|
||||||
std::this_thread::yield();
|
|
||||||
}
|
|
||||||
beammp_debug("PPSMonitor starting");
|
|
||||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
|
||||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
|
||||||
while (!Application::IsShuttingDown()) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
|
||||||
int C = 0, V = 0;
|
|
||||||
if (mServer.ClientCount() == 0) {
|
|
||||||
Application::SetPPS("-");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> c;
|
|
||||||
{
|
|
||||||
ReadLock Lock(mServer.GetClientMutex());
|
|
||||||
if (!ClientPtr.expired()) {
|
|
||||||
c = ClientPtr.lock();
|
|
||||||
} else
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (c->GetCarCount() > 0) {
|
|
||||||
C++;
|
|
||||||
V += c->GetCarCount();
|
|
||||||
}
|
|
||||||
// kick on "no ping"
|
|
||||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
|
||||||
beammp_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);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
for (auto& ClientToKick : TimedOutClients) {
|
|
||||||
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
|
||||||
}
|
|
||||||
TimedOutClients.clear();
|
|
||||||
if (C == 0 || mInternalPPS == 0) {
|
|
||||||
Application::SetPPS("-");
|
|
||||||
} else {
|
|
||||||
int R = (mInternalPPS / C) / V;
|
|
||||||
Application::SetPPS(std::to_string(R));
|
|
||||||
}
|
|
||||||
mInternalPPS = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#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)
|
||||||
@@ -9,7 +10,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)) {
|
for (const auto& Entry : fs::recursive_directory_iterator(mPath, fs::directory_options::follow_directory_symlink)) {
|
||||||
// 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());
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
#include "TResourceManager.h"
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
|
||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
|
||||||
std::string Path = Application::Settings.Resource + "/Client";
|
|
||||||
if (!fs::exists(Path))
|
|
||||||
fs::create_directories(Path);
|
|
||||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
|
||||||
std::string File(entry.path().string());
|
|
||||||
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
|
||||||
if (File.length() - pos == 4) {
|
|
||||||
std::replace(File.begin(), File.end(), '\\', '/');
|
|
||||||
mFileList += File + ';';
|
|
||||||
if (auto i = File.find_last_of('/'); i != std::string::npos) {
|
|
||||||
++i;
|
|
||||||
File = File.substr(i, pos - i);
|
|
||||||
}
|
|
||||||
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
|
||||||
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
|
||||||
mMaxModSize += size_t(fs::file_size(entry.path()));
|
|
||||||
mModsLoaded++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mModsLoaded) {
|
|
||||||
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
|
||||||
}
|
|
||||||
|
|
||||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
|
||||||
}
|
|
||||||
-138
@@ -1,138 +0,0 @@
|
|||||||
#include "TSentry.h"
|
|
||||||
#include "Common.h"
|
|
||||||
|
|
||||||
#include <cstring>
|
|
||||||
#include <sentry.h>
|
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
TSentry::TSentry() {
|
|
||||||
if (std::strlen(S_DSN) == /* DISABLES CODE */ (0)) {
|
|
||||||
mValid = false;
|
|
||||||
} else {
|
|
||||||
mValid = true;
|
|
||||||
sentry_options_t* options = sentry_options_new();
|
|
||||||
sentry_options_set_dsn(options, S_DSN);
|
|
||||||
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersionString();
|
|
||||||
sentry_options_set_symbolize_stacktraces(options, true);
|
|
||||||
sentry_options_set_release(options, ReleaseString.c_str());
|
|
||||||
sentry_options_set_max_breadcrumbs(options, 10);
|
|
||||||
sentry_init(options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TSentry::~TSentry() {
|
|
||||||
if (mValid) {
|
|
||||||
sentry_close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::PrintWelcome() {
|
|
||||||
if (mValid) {
|
|
||||||
if (!Application::Settings.SendErrors) {
|
|
||||||
mValid = false;
|
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
|
||||||
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
|
||||||
} else {
|
|
||||||
beammp_info("Sentry disabled");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
|
||||||
beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
|
|
||||||
} else {
|
|
||||||
beammp_info("Sentry started");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
|
||||||
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
|
||||||
} else {
|
|
||||||
beammp_info("Sentry disabled in unofficial build");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetupUser() {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
|
||||||
sentry_value_t user = sentry_value_new_object();
|
|
||||||
if (Application::Settings.Key.size() == 36) {
|
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
|
||||||
} else {
|
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
|
|
||||||
}
|
|
||||||
sentry_set_user(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::Log(SentryLevel level, const std::string& logger, const std::string& text) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
|
||||||
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
|
||||||
sentry_capture_event(Msg);
|
|
||||||
sentry_set_transaction(nullptr);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line);
|
|
||||||
Log(SentryLevel::Error, "default", file + ": " + text);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto ctx = sentry_value_new_object();
|
|
||||||
for (const auto& pair : map) {
|
|
||||||
std::string key = pair.first;
|
|
||||||
if (key == "type") {
|
|
||||||
// `type` is reserved
|
|
||||||
key = "_type";
|
|
||||||
}
|
|
||||||
sentry_value_set_by_key(ctx, key.c_str(), sentry_value_new_string(pair.second.c_str()));
|
|
||||||
}
|
|
||||||
sentry_set_context(context_name.c_str(), ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogException(const std::exception& e, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line);
|
|
||||||
Log(SentryLevel::Fatal, "exceptions", std::string(e.what()) + " @ " + file + ":" + line);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
SetTransaction(file + ":" + line + ":" + function);
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << "\"" << condition_string << "\" failed @ " << file << ":" << line;
|
|
||||||
Log(SentryLevel::Fatal, "asserts", ss.str());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto crumb = sentry_value_new_breadcrumb("default", (msg + " @ " + file + ":" + line).c_str());
|
|
||||||
sentry_value_set_by_key(crumb, "level", sentry_value_new_string("error"));
|
|
||||||
sentry_add_breadcrumb(crumb);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TSentry::SetTransaction(const std::string& id) {
|
|
||||||
if (!mValid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sentry_set_transaction(id.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unique_lock<std::mutex> TSentry::CreateExclusiveContext() {
|
|
||||||
return std::unique_lock<std::mutex>(mMutex);
|
|
||||||
}
|
|
||||||
-448
@@ -1,448 +0,0 @@
|
|||||||
#include "TServer.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "TNetwork.h"
|
|
||||||
#include "TPPSMonitor.h"
|
|
||||||
#include <TLuaPlugin.h>
|
|
||||||
#include <algorithm>
|
|
||||||
#include <any>
|
|
||||||
#include <sstream>
|
|
||||||
|
|
||||||
#include <nlohmann/json.hpp>
|
|
||||||
|
|
||||||
#include "LuaAPI.h"
|
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
|
||||||
|
|
||||||
#include "Json.h"
|
|
||||||
|
|
||||||
static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
|
|
||||||
auto IDSep = str.find('-');
|
|
||||||
std::string pid = str.substr(0, IDSep);
|
|
||||||
std::string vid = str.substr(IDSep + 1);
|
|
||||||
|
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
|
||||||
try {
|
|
||||||
int PID = stoi(pid);
|
|
||||||
int VID = stoi(vid);
|
|
||||||
return { { PID, VID } };
|
|
||||||
} catch (const std::exception&) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE("GetPidVid") {
|
|
||||||
SUBCASE("Valid singledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-1");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 0);
|
|
||||||
CHECK_EQ(vid, 1);
|
|
||||||
}
|
|
||||||
SUBCASE("Valid doubledigit") {
|
|
||||||
const auto MaybePidVid = GetPidVid("10-12");
|
|
||||||
CHECK(MaybePidVid);
|
|
||||||
auto [pid, vid] = MaybePidVid.value();
|
|
||||||
|
|
||||||
CHECK_EQ(pid, 10);
|
|
||||||
CHECK_EQ(vid, 12);
|
|
||||||
}
|
|
||||||
SUBCASE("Empty string") {
|
|
||||||
const auto MaybePidVid = GetPidVid("");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid separator") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0x0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Missing vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid pid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("x-0");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
SUBCASE("Invalid vid") {
|
|
||||||
const auto MaybePidVid = GetPidVid("0-x");
|
|
||||||
CHECK(!MaybePidVid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
|
||||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
|
||||||
if (Arguments.size() > 1) {
|
|
||||||
Application::Settings.CustomIP = Arguments[0];
|
|
||||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
|
||||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
|
||||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
|
||||||
Application::Settings.CustomIP.clear();
|
|
||||||
beammp_warn("IP Specified is invalid! Ignoring");
|
|
||||||
} else {
|
|
||||||
beammp_info("server started with custom IP");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
|
||||||
if (!WeakClientPtr.expired()) {
|
|
||||||
TClient& Client = *WeakClientPtr.lock();
|
|
||||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
|
||||||
Client.ClearCars();
|
|
||||||
WriteLock Lock(mClientsMutex);
|
|
||||||
mClients.erase(WeakClientPtr.lock());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
|
||||||
decltype(mClients) Clients;
|
|
||||||
{
|
|
||||||
ReadLock lock(mClientsMutex);
|
|
||||||
Clients = mClients;
|
|
||||||
}
|
|
||||||
for (auto& Client : Clients) {
|
|
||||||
if (!Fn(Client)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t TServer::ClientCount() const {
|
|
||||||
ReadLock Lock(mClientsMutex);
|
|
||||||
return mClients.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
|
||||||
constexpr std::string_view ABG = "ABG:";
|
|
||||||
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
|
||||||
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
|
||||||
Packet = DeComp(Packet);
|
|
||||||
}
|
|
||||||
if (Packet.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Client.expired()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto LockedClient = Client.lock();
|
|
||||||
|
|
||||||
std::any Res;
|
|
||||||
char Code = Packet.at(0);
|
|
||||||
|
|
||||||
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
|
||||||
|
|
||||||
// V to Y
|
|
||||||
if (Code <= 89 && Code >= 86) {
|
|
||||||
PPSMonitor.IncrementInternalPPS();
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
switch (Code) {
|
|
||||||
case 'H': // initial connection
|
|
||||||
if (!Network.SyncClient(Client)) {
|
|
||||||
// TODO handle
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'p':
|
|
||||||
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
|
||||||
// failed to send
|
|
||||||
LockedClient->Disconnect("Failed to send ping");
|
|
||||||
} else {
|
|
||||||
Network.UpdatePlayer(*LockedClient);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'O':
|
|
||||||
if (Packet.size() > 1000) {
|
|
||||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
|
||||||
}
|
|
||||||
ParseVehicle(*LockedClient, StringPacket, Network);
|
|
||||||
return;
|
|
||||||
case 'J':
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
|
||||||
return;
|
|
||||||
case 'C': {
|
|
||||||
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
|
||||||
break;
|
|
||||||
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), PacketAsString.substr(PacketAsString.find(':', 3) + 2));
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
|
||||||
if (std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
|
||||||
return !Elem->Error
|
|
||||||
&& Elem->Result.is<int>()
|
|
||||||
&& bool(Elem->Result.as<int>());
|
|
||||||
})) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'E':
|
|
||||||
HandleEvent(*LockedClient, StringPacket);
|
|
||||||
return;
|
|
||||||
case 'N':
|
|
||||||
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
|
||||||
return;
|
|
||||||
case 'Z': // position packet
|
|
||||||
PPSMonitor.IncrementInternalPPS();
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
|
||||||
|
|
||||||
HandlePosition(*LockedClient, StringPacket);
|
|
||||||
default:
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
|
||||||
// E:Name:Data
|
|
||||||
// Data is allowed to have ':'
|
|
||||||
auto NameDataSep = RawData.find(':', 2);
|
|
||||||
if (NameDataSep == std::string::npos) {
|
|
||||||
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
|
||||||
}
|
|
||||||
std::string Name = RawData.substr(2, NameDataSep - 2);
|
|
||||||
std::string Data = RawData.substr(NameDataSep + 1);
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
|
||||||
try {
|
|
||||||
auto Car = nlohmann::json::parse(CarJson);
|
|
||||||
const std::string jbm = "jbm";
|
|
||||||
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
|
||||||
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
|
|
||||||
c.SetUnicycleID(ID);
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return c.GetCarCount() < Application::Settings.MaxCars;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
|
||||||
if (Pckt.length() < 6)
|
|
||||||
return;
|
|
||||||
std::string Packet = Pckt;
|
|
||||||
char Code = Packet.at(1);
|
|
||||||
int PID = -1;
|
|
||||||
int VID = -1;
|
|
||||||
std::string Data = Packet.substr(3), pid, vid;
|
|
||||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
|
||||||
case 's':
|
|
||||||
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
|
||||||
if (Data.at(0) == '0') {
|
|
||||||
int CarID = c.GetOpenCarID();
|
|
||||||
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
|
||||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
|
||||||
c.AddNewCar(CarID, Packet);
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
|
||||||
} else {
|
|
||||||
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
|
||||||
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
case 'c': {
|
|
||||||
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
|
||||||
TLuaEngine::WaitForAll(Futures);
|
|
||||||
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
|
||||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
|
||||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
|
||||||
});
|
|
||||||
|
|
||||||
auto FoundPos = Packet.find('{');
|
|
||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
|
||||||
&& !ShouldntAllow) {
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
Apply(c, VID, Packet);
|
|
||||||
} else {
|
|
||||||
if (c.GetUnicycleID() == VID) {
|
|
||||||
c.SetUnicycleID(-1);
|
|
||||||
}
|
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
|
||||||
c.DeleteCar(VID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'd': {
|
|
||||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
if (c.GetUnicycleID() == VID) {
|
|
||||||
c.SetUnicycleID(-1);
|
|
||||||
}
|
|
||||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
|
||||||
// TODO: should this trigger on all vehicle deletions?
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
|
||||||
c.DeleteCar(VID);
|
|
||||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 'r': {
|
|
||||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
|
||||||
if (MaybePidVid) {
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
|
||||||
Data = Data.substr(Data.find('{'));
|
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
case 't':
|
|
||||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
|
||||||
return;
|
|
||||||
case 'm':
|
|
||||||
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
|
||||||
return;
|
|
||||||
default:
|
|
||||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|
||||||
auto FoundPos = pckt.find('{');
|
|
||||||
if (FoundPos == std::string::npos) {
|
|
||||||
beammp_error("Malformed packet received, no '{' found");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string Packet = pckt.substr(FoundPos);
|
|
||||||
std::string VD = c.GetCarData(VID);
|
|
||||||
if (VD.empty()) {
|
|
||||||
beammp_error("Tried to apply change to vehicle that does not exist");
|
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("vehicle-change",
|
|
||||||
{ { "packet", Packet },
|
|
||||||
{ "vehicle-id", std::to_string(VID) },
|
|
||||||
{ "client-car-count", std::to_string(c.GetCarCount()) } });
|
|
||||||
Sentry.LogError("attempt to apply change to nonexistent vehicle", _file_basename, _line);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string Header = VD.substr(0, VD.find('{'));
|
|
||||||
|
|
||||||
FoundPos = VD.find('{');
|
|
||||||
if (FoundPos == std::string::npos) {
|
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("vehicle-change-packet",
|
|
||||||
{ { "packet", VD } });
|
|
||||||
Sentry.LogError("malformed packet", _file_basename, _line);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
VD = VD.substr(FoundPos);
|
|
||||||
rapidjson::Document Veh, Pack;
|
|
||||||
Veh.Parse(VD.c_str());
|
|
||||||
if (Veh.HasParseError()) {
|
|
||||||
beammp_error("Could not get vehicle config!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Pack.Parse(Packet.c_str());
|
|
||||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
|
||||||
beammp_error("Could not get active vehicle config!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (auto& M : Pack.GetObject()) {
|
|
||||||
if (Veh[M.name].IsNull()) {
|
|
||||||
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
|
|
||||||
} else {
|
|
||||||
Veh[M.name] = Pack[M.name];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rapidjson::StringBuffer Buffer;
|
|
||||||
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
|
|
||||||
Veh.Accept(writer);
|
|
||||||
c.SetCarData(VID, Header + Buffer.GetString());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
|
||||||
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
|
||||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
|
||||||
(void)mClients.insert(NewClient);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
|
||||||
if (Packet.size() < 3) {
|
|
||||||
// invalid packet
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Zp:serverVehicleID:data
|
|
||||||
// Zp:0:data
|
|
||||||
std::string withoutCode = Packet.substr(3);
|
|
||||||
auto NameDataSep = withoutCode.find(':', 2);
|
|
||||||
if (NameDataSep == std::string::npos || NameDataSep < 2) {
|
|
||||||
// invalid packet
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// FIXME: ensure that -2 does what it should... it seems weird.
|
|
||||||
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
|
||||||
if (NameDataSep + 1 > withoutCode.size()) {
|
|
||||||
// invalid packet
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string Data = withoutCode.substr(NameDataSep + 1);
|
|
||||||
|
|
||||||
// parse veh ID
|
|
||||||
auto MaybePidVid = GetPidVid(ServerVehicleID);
|
|
||||||
if (MaybePidVid) {
|
|
||||||
int PID = -1;
|
|
||||||
int VID = -1;
|
|
||||||
// FIXME: check that the VID and PID are valid, so that we don't waste memory
|
|
||||||
std::tie(PID, VID) = MaybePidVid.value();
|
|
||||||
|
|
||||||
c.SetCarPosition(VID, Data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+49
-32
@@ -1,5 +1,3 @@
|
|||||||
#include "TSentry.h"
|
|
||||||
|
|
||||||
#include "ArgsParser.h"
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
@@ -8,13 +6,13 @@
|
|||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "TNetwork.h"
|
|
||||||
#include "TPPSMonitor.h"
|
|
||||||
#include "TPluginMonitor.h"
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <spdlog/sinks/rotating_file_sink.h>
|
||||||
|
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||||
|
#include <spdlog/spdlog.h>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
static const std::string sCommandlineArguments = R"(
|
static const std::string sCommandlineArguments = R"(
|
||||||
@@ -64,15 +62,38 @@ int main(int argc, char** argv) {
|
|||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
||||||
beammp_error(e.what());
|
beammp_error(e.what());
|
||||||
Sentry.LogException(e, _file_basename, _line);
|
|
||||||
MainRet = -1;
|
MainRet = -1;
|
||||||
}
|
}
|
||||||
std::exit(MainRet);
|
std::exit(MainRet);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static std::shared_ptr<spdlog::logger> default_logger;
|
||||||
|
|
||||||
|
static void setup_logger() {
|
||||||
|
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||||
|
console_sink->set_pattern("[%H:%M:%S] [%^%l%$] %v");
|
||||||
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
|
console_sink->set_level(spdlog::level::debug);
|
||||||
|
} else {
|
||||||
|
console_sink->set_level(spdlog::level::info);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("Launcher.log", 1024 * 1024, 3, true);
|
||||||
|
file_sink->set_level(spdlog::level::trace);
|
||||||
|
file_sink->set_pattern("[%H:%M:%S.%e] [%t] [%l] %v");
|
||||||
|
|
||||||
|
default_logger = std::make_shared<spdlog::logger>(spdlog::logger("default", { console_sink, file_sink }));
|
||||||
|
|
||||||
|
default_logger->set_level(spdlog::level::trace);
|
||||||
|
default_logger->flush_on(spdlog::level::trace);
|
||||||
|
|
||||||
|
spdlog::set_default_logger(default_logger);
|
||||||
|
|
||||||
|
spdlog::debug("Logger initialized");
|
||||||
|
}
|
||||||
|
|
||||||
int BeamMPServerMain(MainArguments Arguments) {
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
setlocale(LC_ALL, "C");
|
setlocale(LC_ALL, "C");
|
||||||
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);
|
||||||
@@ -83,24 +104,26 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// badly seed C's rng - this is only because rand() is used here and there for unimportant stuff
|
||||||
|
std::srand(std::time(0));
|
||||||
|
|
||||||
std::string ConfigPath = "ServerConfig.toml";
|
std::string ConfigPath = "ServerConfig.toml";
|
||||||
if (Parser.FoundArgument({ "config" })) {
|
if (Parser.FoundArgument({ "config" })) {
|
||||||
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||||
if (MaybeConfigPath.has_value()) {
|
if (MaybeConfigPath.has_value()) {
|
||||||
ConfigPath = MaybeConfigPath.value();
|
ConfigPath = MaybeConfigPath.value();
|
||||||
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
// beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
setup_logger();
|
||||||
if (Parser.FoundArgument({ "working-directory" })) {
|
if (Parser.FoundArgument({ "working-directory" })) {
|
||||||
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
||||||
if (MaybeWorkingDirectory.has_value()) {
|
if (MaybeWorkingDirectory.has_value()) {
|
||||||
@@ -113,10 +136,21 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
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::Console().StartLoggingToFile();
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||||
|
|
||||||
SetupSignalHandlers();
|
SetupSignalHandlers();
|
||||||
|
|
||||||
bool Shutdown = false;
|
bool Shutdown = false;
|
||||||
@@ -130,32 +164,15 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||||
});
|
});
|
||||||
|
|
||||||
TServer Server(Arguments.List);
|
|
||||||
TConfig Config(ConfigPath);
|
|
||||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
LuaEngine->SetServer(&Server);
|
|
||||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
if (Config.Failed()) {
|
|
||||||
beammp_info("Closing in 10 seconds");
|
|
||||||
// loop to make it possible to ctrl+c instead
|
|
||||||
for (size_t i = 0; i < 20; ++i) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
RegisterThread("Main");
|
RegisterThread("Main");
|
||||||
|
|
||||||
beammp_trace("Running in debug mode on a debug build");
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
Sentry.SetupUser();
|
std::shared_ptr<Network> network = std::make_shared<Network>();
|
||||||
Sentry.PrintWelcome();
|
THeartbeatThread Heartbeat(network);
|
||||||
TResourceManager ResourceManager;
|
LuaEngine->SetNetwork(network);
|
||||||
TPPSMonitor PPSMonitor(Server);
|
|
||||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
|
||||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
|
||||||
LuaEngine->SetNetwork(&Network);
|
|
||||||
PPSMonitor.SetNetwork(Network);
|
|
||||||
Application::CheckForUpdates();
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||||
|
|||||||
Submodule
+1
Submodule vcpkg added at 8397227251
+24
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"version-string": "0.1.0",
|
||||||
|
"dependencies": [
|
||||||
|
"boost-asio",
|
||||||
|
"boost-spirit",
|
||||||
|
"boost-uuid",
|
||||||
|
"boost-variant",
|
||||||
|
"boost-iostreams",
|
||||||
|
"cpp-httplib",
|
||||||
|
"doctest",
|
||||||
|
"fmt",
|
||||||
|
"nlohmann-json",
|
||||||
|
"openssl",
|
||||||
|
"rapidjson",
|
||||||
|
"sol2",
|
||||||
|
"toml11",
|
||||||
|
"zstd",
|
||||||
|
"glm",
|
||||||
|
"libzip",
|
||||||
|
"spdlog",
|
||||||
|
"readline"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user