mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
199 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9b9d4642a | |||
| b4d6f90012 | |||
| 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 | |||
| aa185afabf | |||
| e8caeb9126 | |||
| fa1944dbef | |||
| 093f905fd8 | |||
| 2a45d2282d | |||
| aeb024953a | |||
| 12a0ab7fdd | |||
| 917c501faf | |||
| 340933bbb3 | |||
| a63359479e | |||
| bdf2da758c | |||
| 88c0ed56e4 | |||
| 4256977400 | |||
| 309a9d1fa9 | |||
| ad860835ca | |||
| c6c2efb0b1 | |||
| c4c3b03b7a | |||
| fd51336a91 | |||
| 466845b314 | |||
| 92632b53b5 | |||
| 331a597ec7 | |||
| 87965433c2 | |||
| 75ff9f7571 | |||
| 94c0547a35 | |||
| 98f77e157f | |||
| 54730d2baf | |||
| 064e71e59f | |||
| 2678234d67 | |||
| 4320a91e5c | |||
| 7d1318653c | |||
| 67d02d4cf2 | |||
| 93b2559120 | |||
| ed872f730d | |||
| b25f4a875c | |||
| cc6b7846b2 | |||
| 88f5db514f | |||
| e595192829 | |||
| c69418ea5e | |||
| 917e3f98ab | |||
| c42a523532 | |||
| 95ae0f5d03 | |||
| fc0a509bd9 | |||
| 6249397fb5 | |||
| 231b13a0e7 | |||
| 7d2e4d4581 | |||
| 7446526a19 | |||
| 6e97a3cd6e | |||
| 30482d290a | |||
| 5f1d003077 | |||
| 5d3dff3c88 | |||
| cb0cb30797 | |||
| 1f14de2e71 | |||
| 658b37acac | |||
| d63c84286e | |||
| 9c6127a105 | |||
| a1d99c0203 | |||
| 10dff185e0 | |||
| dd17b95427 | |||
| 1a9872db00 | |||
| dbb01998ea | |||
| 3c4737a145 | |||
| 36e8ba1614 | |||
| 988f19fd00 | |||
| fdf24815bb | |||
| b145c8159e | |||
| ae517b30c0 | |||
| e638c25f70 | |||
| 24c98eb2b2 | |||
| 501fddadc6 | |||
| 6da9a921d0 | |||
| a8333359ce | |||
| b71aa2db04 | |||
| 78f7cdc17a | |||
| 36a1da3218 | |||
| 23e9941704 | |||
| 469eb78c80 | |||
| af5658d0e1 | |||
| 1062e29582 | |||
| ec9a280d30 | |||
| 784bbd4f6b | |||
| bc6b4e40e1 | |||
| 071ba08dfe | |||
| 023738c41b | |||
| 6a166110f6 | |||
| 71fbf7b7cc | |||
| 4b242c26fc | |||
| a84d042a8a | |||
| 44b94c9e58 | |||
| 660f94b691 | |||
| a7c4103f7c | |||
| 0932078e4b | |||
| 54e02abad1 | |||
| e4cbba59ef | |||
| e4db66782e | |||
| b443bec72e | |||
| 76a8f231ac | |||
| 398f8d3fa4 | |||
| 60dd1e2472 | |||
| e634b4b6b7 | |||
| 1caa5e3517 | |||
| b009a37f35 | |||
| a28b3e1532 | |||
| b01bed2996 | |||
| 7bdc2b304b | |||
| b19bca4c82 | |||
| 708848f275 | |||
| d6625187d1 |
@@ -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-20.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
|
|
||||||
|
|
||||||
- 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-20.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 openssl
|
|
||||||
|
|
||||||
- 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: 'a106de33bbee694e3be6243718aa2a549a692832'
|
|
||||||
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,123 @@
|
|||||||
|
name: Linux
|
||||||
|
|
||||||
|
on: [push]
|
||||||
|
|
||||||
|
env:
|
||||||
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
|
CMAKE_BUILD_TYPE: "Release"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
debian-11-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: debian:11
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/debian-11/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-debian
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-debian.debug
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/debian-11/3-build-tests.sh
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
run: bash ./scripts/debian-11/4-install-runtime-deps.sh
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: ./bin/BeamMP-Server-tests
|
||||||
|
|
||||||
|
ubuntu-22-04-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: ubuntu:22.04
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||||
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-ubuntu
|
||||||
|
path: ./bin/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive server debug info artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-ubuntu.debug
|
||||||
|
path: ./bin/BeamMP-Server.debug
|
||||||
|
|
||||||
|
- name: Build Tests
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/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-latest
|
|
||||||
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
|
|
||||||
|
|
||||||
- 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: 'a106de33bbee694e3be6243718aa2a549a692832'
|
|
||||||
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,191 @@
|
|||||||
|
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"
|
||||||
|
|
||||||
|
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. You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this.
|
||||||
|
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`.
|
||||||
|
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
|
||||||
|
|
||||||
|
upload-release-files-debian-11:
|
||||||
|
name: Build and upload Debian 11 Release Files
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
needs: create-release
|
||||||
|
container:
|
||||||
|
image: debian:11
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Setup vcpkg
|
||||||
|
uses: lukka/run-vcpkg@v11
|
||||||
|
with:
|
||||||
|
runVcpkgInstall: true
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/debian-11/3-build.sh
|
||||||
|
|
||||||
|
- name: Upload Release Asset
|
||||||
|
id: upload-release-asset
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_name: BeamMP-Server-debian
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- name: Upload Debug Info
|
||||||
|
id: upload-debug-info
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server.debug
|
||||||
|
asset_name: debuginfo-debian.debug
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
upload-release-files-ubuntu-22-04:
|
||||||
|
name: Build and upload Ubuntu 22.04 Release Files
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
needs: create-release
|
||||||
|
container:
|
||||||
|
image: ubuntu:22.04
|
||||||
|
steps:
|
||||||
|
- name: Export GitHub Actions cache environment variables
|
||||||
|
uses: actions/github-script@v6
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||||
|
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||||
|
|
||||||
|
- name: Install git
|
||||||
|
run: |
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y git
|
||||||
|
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
|
||||||
|
- name: Git config safe directory
|
||||||
|
shell: bash
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||||
|
|
||||||
|
- name: Install Dependencies
|
||||||
|
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||||
|
|
||||||
|
- name: Create Build Environment
|
||||||
|
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||||
|
|
||||||
|
- name: Build Server
|
||||||
|
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||||
|
|
||||||
|
- name: Upload Release Asset
|
||||||
|
id: upload-release-asset
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server
|
||||||
|
asset_name: BeamMP-Server-ubuntu
|
||||||
|
asset_content_type: application/x-elf
|
||||||
|
|
||||||
|
- name: Upload Debug Info
|
||||||
|
id: upload-debug-info
|
||||||
|
uses: actions/upload-release-asset@v1
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||||
|
asset_path: ./bin/BeamMP-Server.debug
|
||||||
|
asset_name: debuginfo-ubuntu.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
|
||||||
|
|
||||||
+3
-30
@@ -1,33 +1,6 @@
|
|||||||
[submodule "deps/commandline"]
|
[submodule "deps/commandline"]
|
||||||
path = deps/commandline
|
path = deps/commandline
|
||||||
url = https://github.com/lionkor/commandline
|
url = https://github.com/lionkor/commandline
|
||||||
[submodule "deps/asio"]
|
[submodule "vcpkg"]
|
||||||
path = deps/asio
|
path = vcpkg
|
||||||
url = https://github.com/chriskohlhoff/asio
|
url = https://github.com/Microsoft/vcpkg.git
|
||||||
[submodule "deps/rapidjson"]
|
|
||||||
path = deps/rapidjson
|
|
||||||
url = https://github.com/Tencent/rapidjson
|
|
||||||
[submodule "deps/toml11"]
|
|
||||||
path = deps/toml11
|
|
||||||
url = https://github.com/ToruNiina/toml11
|
|
||||||
[submodule "deps/sentry-native"]
|
|
||||||
path = deps/sentry-native
|
|
||||||
url = https://github.com/getsentry/sentry-native
|
|
||||||
[submodule "deps/sol2"]
|
|
||||||
path = deps/sol2
|
|
||||||
url = https://github.com/ThePhD/sol2
|
|
||||||
[submodule "deps/libzip"]
|
|
||||||
path = deps/libzip
|
|
||||||
url = https://github.com/nih-at/libzip
|
|
||||||
[submodule "deps/cpp-httplib"]
|
|
||||||
path = deps/cpp-httplib
|
|
||||||
url = https://github.com/yhirose/cpp-httplib
|
|
||||||
[submodule "deps/json"]
|
|
||||||
path = deps/json
|
|
||||||
url = https://github.com/nlohmann/json
|
|
||||||
[submodule "deps/fmt"]
|
|
||||||
path = deps/fmt
|
|
||||||
url = https://github.com/fmtlib/fmt
|
|
||||||
[submodule "deps/doctest"]
|
|
||||||
path = deps/doctest
|
|
||||||
url = https://github.com/doctest/doctest
|
|
||||||
|
|||||||
+209
-194
@@ -1,198 +1,213 @@
|
|||||||
# 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 \
|
|
||||||
https://github.com/BeamMP/BeamMP-Server")
|
|
||||||
|
|
||||||
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()
|
|
||||||
|
|
||||||
|
|
||||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
|
||||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
|
||||||
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/websocketpp")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include")
|
|
||||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps")
|
|
||||||
|
|
||||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
|
||||||
|
|
||||||
# ------------------------ APPLE ---------------------------------
|
|
||||||
if(APPLE)
|
|
||||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
|
||||||
set(LUA_LIBRARIES lua)
|
|
||||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
|
||||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
|
||||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
|
||||||
# ------------------------ WINDOWS ---------------------------------
|
|
||||||
elseif (WIN32)
|
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
|
||||||
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})
|
|
||||||
# ------------------------ LINUX ---------------------------------
|
|
||||||
elseif (UNIX)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++ -static-libgcc")
|
|
||||||
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=undefined,thread")
|
|
||||||
endif (SANITIZE)
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
include_directories("include/sentry-native/include")
|
|
||||||
set(BUILD_SHARED_LIBS OFF)
|
|
||||||
# ------------------------ SENTRY ---------------------------------
|
|
||||||
message(STATUS "Checking for Sentry URL")
|
|
||||||
# this is set by the build system.
|
|
||||||
# IMPORTANT: if you're building from source, just leave this empty
|
|
||||||
if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
|
|
||||||
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
|
|
||||||
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
|
|
||||||
set(BEAMMP_SECRET_SENTRY_URL "")
|
|
||||||
set(SENTRY_BACKEND none)
|
|
||||||
else()
|
|
||||||
set(SENTRY_BACKEND breakpad)
|
|
||||||
endif()
|
|
||||||
add_subdirectory("deps/sentry-native")
|
|
||||||
|
|
||||||
# ------------------------ C++ SETUP ---------------------------------
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
if (MSVC)
|
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
|
||||||
endif ()
|
|
||||||
|
|
||||||
# ------------------------ DEPENDENCIES ------------------------------
|
|
||||||
message(STATUS "Adding local source dependencies")
|
|
||||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
|
||||||
add_subdirectory(deps)
|
|
||||||
|
|
||||||
# ------------------------ VARIABLES ---------------------------------
|
|
||||||
|
|
||||||
include(FindLua)
|
|
||||||
include(FindOpenSSL)
|
|
||||||
include(FindThreads)
|
|
||||||
include(FindZLIB)
|
|
||||||
|
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
set(BeamMP_Includes
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
|
|
||||||
${LUA_INCLUDE_DIR}
|
|
||||||
${CURL_INCLUDE_DIRS}
|
|
||||||
"include/tomlplusplus"
|
|
||||||
"include/sentry-native/include"
|
|
||||||
"include/curl/include"
|
|
||||||
)
|
|
||||||
|
|
||||||
set(BeamMP_Definitions
|
|
||||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
|
||||||
)
|
|
||||||
|
|
||||||
set(BeamMP_Libraries
|
|
||||||
doctest::doctest
|
|
||||||
OpenSSL::SSL
|
|
||||||
OpenSSL::Crypto
|
|
||||||
sol2::sol2
|
|
||||||
fmt::fmt
|
|
||||||
Threads::Threads
|
|
||||||
ZLIB::ZLIB
|
|
||||||
${LUA_LIBRARIES}
|
|
||||||
commandline
|
|
||||||
sentry
|
|
||||||
)
|
|
||||||
|
|
||||||
if (WIN32)
|
if (WIN32)
|
||||||
set(BeamMP_PlatformLibs wsock32 ws2_32)
|
set(VCPKG_TARGET_TRIPLET x64-windows-static)
|
||||||
endif ()
|
endif()
|
||||||
|
|
||||||
# ------------------------ BEAMMP SERVER -----------------------------
|
include(cmake/Vcpkg.cmake) # needs to happen before project()
|
||||||
|
|
||||||
add_executable(BeamMP-Server
|
project(
|
||||||
src/main.cpp
|
"BeamMP-Server" # replace this
|
||||||
${BeamMP_Sources}
|
VERSION 3.3.0
|
||||||
)
|
)
|
||||||
|
|
||||||
target_compile_definitions(BeamMP-Server PRIVATE
|
include(cmake/StandardSettings.cmake)
|
||||||
${BeamMP_Definitions}
|
include(cmake/StaticAnalyzers.cmake)
|
||||||
DOCTEST_CONFIG_DISABLE
|
include(cmake/Git.cmake)
|
||||||
)
|
|
||||||
|
# below are options which should be changed
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
|
||||||
${BeamMP_Includes}
|
### SETTINGS ###
|
||||||
)
|
|
||||||
|
# add all headers (.h, .hpp) to this
|
||||||
target_link_libraries(BeamMP-Server
|
set(PRJ_HEADERS
|
||||||
${BeamMP_Libraries}
|
include/ArgsParser.h
|
||||||
${BeamMP_PlatformLibs}
|
include/BoostAliases.h
|
||||||
)
|
include/Client.h
|
||||||
|
include/Common.h
|
||||||
# ------------------------ BEAMMP SERVER TESTS -----------------------
|
include/Compat.h
|
||||||
|
include/Cryptography.h
|
||||||
option(BUILD_TESTS "Build BeamMP-Server tests" ON)
|
include/CustomAssert.h
|
||||||
|
include/Defer.h
|
||||||
if(BUILD_TESTS)
|
include/Environment.h
|
||||||
add_executable(BeamMP-Server-tests
|
include/Http.h
|
||||||
test/test_main.cpp
|
include/IThreaded.h
|
||||||
${BeamMP_Sources}
|
include/Json.h
|
||||||
)
|
include/LuaAPI.h
|
||||||
|
include/RWMutex.h
|
||||||
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
include/SignalHandling.h
|
||||||
${BeamMP_Definitions}
|
include/TConfig.h
|
||||||
)
|
include/TConsole.h
|
||||||
|
include/THeartbeatThread.h
|
||||||
target_include_directories(BeamMP-Server-tests PUBLIC
|
include/TLuaEngine.h
|
||||||
${BeamMP_Includes}
|
include/TLuaPlugin.h
|
||||||
)
|
include/TNetwork.h
|
||||||
|
include/TPluginMonitor.h
|
||||||
target_link_libraries(BeamMP-Server-tests
|
include/TPPSMonitor.h
|
||||||
${BeamMP_Libraries}
|
include/TResourceManager.h
|
||||||
${BeamMP_PlatformLibs}
|
include/TScopedTimer.h
|
||||||
)
|
include/TServer.h
|
||||||
|
include/VehicleData.h
|
||||||
|
)
|
||||||
|
# add all source files (.cpp) to this, except the one with main()
|
||||||
|
set(PRJ_SOURCES
|
||||||
|
src/ArgsParser.cpp
|
||||||
|
src/Client.cpp
|
||||||
|
src/Common.cpp
|
||||||
|
src/Compat.cpp
|
||||||
|
src/Http.cpp
|
||||||
|
src/LuaAPI.cpp
|
||||||
|
src/SignalHandling.cpp
|
||||||
|
src/TConfig.cpp
|
||||||
|
src/TConsole.cpp
|
||||||
|
src/THeartbeatThread.cpp
|
||||||
|
src/TLuaEngine.cpp
|
||||||
|
src/TLuaPlugin.cpp
|
||||||
|
src/TNetwork.cpp
|
||||||
|
src/TPluginMonitor.cpp
|
||||||
|
src/TPPSMonitor.cpp
|
||||||
|
src/TResourceManager.cpp
|
||||||
|
src/TScopedTimer.cpp
|
||||||
|
src/TServer.cpp
|
||||||
|
src/VehicleData.cpp
|
||||||
|
)
|
||||||
|
|
||||||
|
find_package(Lua REQUIRED)
|
||||||
|
|
||||||
|
# set the source file containing main()
|
||||||
|
set(PRJ_MAIN src/main.cpp)
|
||||||
|
# set the source file containing the test's main
|
||||||
|
set(PRJ_TEST_MAIN test/test_main.cpp)
|
||||||
|
# set include paths not part of libraries
|
||||||
|
set(PRJ_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
|
||||||
|
# set compile features (e.g. standard version)
|
||||||
|
set(PRJ_COMPILE_FEATURES cxx_std_20)
|
||||||
|
# set #defines (test enable/disable not included here)
|
||||||
|
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
|
||||||
|
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||||
|
set(PRJ_LIBRARIES
|
||||||
|
fmt::fmt
|
||||||
|
doctest::doctest
|
||||||
|
Threads::Threads
|
||||||
|
commandline_static
|
||||||
|
toml11::toml11
|
||||||
|
rapidjson
|
||||||
|
sol2
|
||||||
|
httplib::httplib
|
||||||
|
libzip::zip
|
||||||
|
OpenSSL::SSL OpenSSL::Crypto
|
||||||
|
${LUA_LIBRARIES}
|
||||||
|
)
|
||||||
|
|
||||||
|
# add dependency find_package calls and similar here
|
||||||
|
find_package(fmt CONFIG REQUIRED)
|
||||||
|
find_package(OpenSSL REQUIRED)
|
||||||
|
find_package(doctest CONFIG REQUIRED)
|
||||||
|
find_package(Boost REQUIRED)
|
||||||
|
find_package(httplib CONFIG REQUIRED)
|
||||||
|
find_package(libzip CONFIG REQUIRED)
|
||||||
|
find_package(RapidJSON CONFIG REQUIRED)
|
||||||
|
find_package(sol2 CONFIG REQUIRED)
|
||||||
|
find_package(toml11 CONFIG REQUIRED)
|
||||||
|
|
||||||
|
include_directories(include)
|
||||||
|
|
||||||
|
# to enable multithreading and the Threads::Threads dependency
|
||||||
|
include(FindThreads)
|
||||||
|
|
||||||
|
### END SETTINGS ###
|
||||||
|
|
||||||
|
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||||
|
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
||||||
|
|
||||||
|
####################
|
||||||
|
|
||||||
|
|
||||||
|
# enables compile_commands.json for clang-related tools (such as the clang LS)
|
||||||
|
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||||
|
|
||||||
|
# build release builds by default (if not specified otherwise)
|
||||||
|
if(NOT DEFINED CMAKE_BUILD_TYPE)
|
||||||
|
message(NOTICE "No build type specified, defaulting to 'Release'")
|
||||||
|
set(CMAKE_BUILD_TYPE "Release")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(UNIX)
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
if (WIN32)
|
||||||
|
add_compile_options("-D_WIN32_WINNT=0x0601")
|
||||||
|
endif(WIN32)
|
||||||
|
|
||||||
|
|
||||||
|
include(cmake/CompilerWarnings.cmake)
|
||||||
|
|
||||||
|
# set MT library for msvc - this is required (says documentation)
|
||||||
|
# linux/mac/etc should simply ignore this by default.
|
||||||
|
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||||
|
|
||||||
|
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
||||||
|
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||||
|
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||||
|
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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()
|
||||||
|
|
||||||
|
|||||||
+111
@@ -0,0 +1,111 @@
|
|||||||
|
# Contributing to BeamMP-Server
|
||||||
|
|
||||||
|
Unlike other parts of BeamMP, the BeamMP-Server does not have any dependency to the BeamNG.drive game.
|
||||||
|
|
||||||
|
To contribute *C++ code*, you'll need a MacOS, Linux or Windows PC, and intermediate to advanced knowledge of C++.
|
||||||
|
For reference, you should know be reasonably comfortable with the STL, the concept of RAII, templates, and generally know how to read & write post-C++17 code. To contribute anything else, you won't need most of this (though it'd be helpful to have some vocabulary about computers).
|
||||||
|
|
||||||
|
# Ways to Contribute
|
||||||
|
|
||||||
|
## Bug Reports
|
||||||
|
|
||||||
|
If you work with BeamMP-Server, either by simply using it, or even writing plugins for it, and you run into any issues, we definitely want to know about it. Please use [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues) and select the "Bug" template, read it, and fill it out accordingly.
|
||||||
|
|
||||||
|
## Bug Fixes
|
||||||
|
|
||||||
|
If you are interested in fixing bugs, check out the [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues). There, you can pick any issue that has nobody assigned to it. For example, some bugs which we definitely need some help with are marked with the "help wanted" tag.
|
||||||
|
|
||||||
|
Once you picked a bug, you need to reproduce it. Start by following the instructions in the bug report, and don't be afraid to ask for more information or clarification on the issue itself.
|
||||||
|
|
||||||
|
Refer to [getting started with the codebase](#getting-started-with-the-codebase) for more information on how to build the server. You can also ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
If you want to add new features, please make an issue for it first or ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||||
|
|
||||||
|
You need to make sure the feature isn't being worked on by someone else, and aligns with the vision we have for the server.
|
||||||
|
|
||||||
|
# Git Guidelines
|
||||||
|
|
||||||
|
**Read this carefully. Failing to follow these rules results in your changes not being accepted**. This applies for outside contributors, members of the BeamMP development team ("BeamMP Developers"), project owners, maintainers, frequent contributors, and literally everyone else. **It applies to everyone**.
|
||||||
|
|
||||||
|
## How to Commit
|
||||||
|
|
||||||
|
Commit messages **MUST** (mandatory):
|
||||||
|
|
||||||
|
- start with a **lower case action verb in present tense**, for example `add`, `fix`, `implement`, `refactor`, `remove`, `rename`. *Counter examples (these are bad): ~~`Fixed`, `fixing`, `added`, `removing`~~*.
|
||||||
|
- not have a first line much longer than 70 characters.
|
||||||
|
- explain briefly the changes made.
|
||||||
|
- reference the issue by number, if there is an issue the commit addresses, like so: `#<number>`. Example: `#123`.
|
||||||
|
|
||||||
|
If any of these are not followed, **your changes will not be accepted.**
|
||||||
|
|
||||||
|
Commit messages **SHOULD** (optional, "nice to have"):
|
||||||
|
|
||||||
|
- only address one "atomic" change.
|
||||||
|
- have an empty second line, and the subsequent lines explaining the changes in more detail (if more detail is available).
|
||||||
|
|
||||||
|
Commits may be squashed (via a Git "interactive rebase") in order to satisfy these rules, but history that is >1h old should not be rewritten if possible. Force pushes are ugly ;)
|
||||||
|
|
||||||
|
## Pulling, Merging
|
||||||
|
|
||||||
|
Do **NOT** pull with merge. This is the default git behavior for `git pull`, but creates ugly and unnecessary commit messages like `"merge origin/master into master"`. Instead, pull with rebase, for example via `git pull -r`. If you get conflicts, resolve them properly.
|
||||||
|
|
||||||
|
The only acceptable merge commits are those which actually merge functionally different branches into each other, for example for merging one feature branch into another.
|
||||||
|
|
||||||
|
## Branches
|
||||||
|
|
||||||
|
### Which branch should I base my work on?
|
||||||
|
|
||||||
|
Each *feature* or *bug-fix* is implemented on a new Git branch, branched off of the branch it should be based on. The `master` branch is usually stable, so we don't do development on it. It is always a safe bet to branch off of `master`, but it may be more work to merge later. Branches to base your work on are usually branches like `rc-v3.3.0`, when the latest public version is `3.2.0`, for example. These can often be found in Pull-Requests on GitHub which are tagged `Release Candidate`.
|
||||||
|
|
||||||
|
## Unit tests & CI/CD
|
||||||
|
|
||||||
|
We use GitHub Actions, which runs our unit-tests. PR's which fail these tests, or even fail any of our actions (which run automatically), will not be merged and require further changes until they compile, link, and all tests pass properly. If you have issues with this, feel free to ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`)
|
||||||
|
|
||||||
|
### What should I call by branch?
|
||||||
|
|
||||||
|
Keep branch names **unique**, **descriptive**, and **shorter than 30 characters**. Names must be in present-tense, such as `fix-xyz`, **not** ~~`fixing-xyz`~~.
|
||||||
|
|
||||||
|
We generally use *feature branches*, so we keep one branch per feature or fix.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
- You want to fix issue number #123? You could call the branch `fix-123`.
|
||||||
|
- You want to add a feature described in issue #456? You could call the branch `implement-456`.
|
||||||
|
- You want to add a feature or fix a bug that has no issue? You should probably make an issue for it first! Or, if you're not ready for that yet, you could call it by the feature name or bug description, for example for a bug that makes cars disappear: `fix-disappearing-cars`.
|
||||||
|
|
||||||
|
## Pull Requests, Code Review
|
||||||
|
|
||||||
|
Once you are ready to show what you did, and get feedback on it, you open a Pull-Request on GitHub. Please make sure to pick the right branches, and a descriptive title. Mention any related issues with `#<issue number>`, for example `#123`.
|
||||||
|
|
||||||
|
Make sure to explain what the PR does, what it fixes, and what needs to still be done (if anything).
|
||||||
|
|
||||||
|
A BeamMP-Developer must review your code in detail, and leave a review. If this takes too long, feel free to @ a maintainer/developer, or leave another comment on the PR. It helps to say something like "Ready for review", for example.
|
||||||
|
|
||||||
|
# Getting Started with the Codebase
|
||||||
|
|
||||||
|
1. Look at current Pull-Requests, look at the git branches, or ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`), in order to find out which branch you should work on to minimize conflict. See [this section on branches](#branches) for more info.
|
||||||
|
2. Fork the repository (with that branch) on GitHub. GitHub, by default, gives you only the `master` branch when forking, so make sure you fork with other branches enabled when you want to work on a branch that isn't master (it's a checkbox when you fork).
|
||||||
|
3. Clone the fork to your local machine.
|
||||||
|
4. Check out the branch you want to work on (see 1.).
|
||||||
|
5. Run `git submodule update --init --recursive`.
|
||||||
|
6. Make a new branch for your feature or fix from the branch you are on. You can do this via `git checkout -b <branch name>`. See [this section on branches](#branches) for more info on branch naming.
|
||||||
|
7. Install all dependencies. Those are usually listed in the `README.md` in the branch you're in, or, more reliably, in one of the files in `.github/workflows` (if you can read `yaml`).
|
||||||
|
8. Run CMake to configure the project. You can find tutorials on this online. You will want to tell CMake to build with `CMAKE_BUILD_TYPE=Debug`, for example by passing it to CMake via the commandline switch `-DCMAKE_BUILD_TYPE=Debug`. You may also want to turn off sentry by setting `SENTRY_BACKEND=none` (for example via commandline switch `-DSENTRY_BACKEND=none`). An example invocation on Linux with GNU make would be
|
||||||
|
`cmake . -DCMAKE_BUILD_TYPE=Debug -DSENTRY_BACKEND=none` .
|
||||||
|
9. Build the `BeamMP-Server` target to build the BeamMP-Server, or the `BeamMP-Server-tests` target to build the unit-tests (does not include a working server). In the example from 8. (on Linux), you could build with `make BeamMP-Server`, `make -j BeamMP-Server` or `cmake --build . --parallel --target BeamMP-Server` . Or, on Windows, (in Visual Studio), you would just press some big green "run" or "debug" button.
|
||||||
|
10. When making changes, refer to [this section on how to commit properly](#how-to-commit). Not following those guidelines will result in your changes being rejected, so please take a look.
|
||||||
|
11. Make sure to add Unit-tests with `doctest` if you build new stuff. You can find examples all over the latest version of the codebase (search for `TEST_CASE`).
|
||||||
|
|
||||||
|
# Code Guidelines
|
||||||
|
|
||||||
|
## Formatting
|
||||||
|
|
||||||
|
1. Use `clang-format` to format your code before committig. A `.clang-format` file is provided in the root of the repository.
|
||||||
|
2. All identifiers, type names, function names, etc. should be `PascalCase`. Type names may also have the `T` prefix, although this is not enforced (for example `TNetwork`).
|
||||||
|
|
||||||
|
## Modular code
|
||||||
|
|
||||||
|
Write code that is modular and testable. Generally, if you can write a good unit-test for it, it's modular. If you can't, it's not.
|
||||||
|
|
||||||
|
Don't overdo it though - sometimes its okay to just write code, do the job, be done with it. You'll get feedback on this in the code review for your PR.
|
||||||
-139
@@ -1,139 +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 MP.JsonEncode() and MP.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
|
|
||||||
- FIXED `ip` in MP.GetIdentifiers
|
|
||||||
- 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
|
|
||||||
|
|
||||||
# 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
|
|
||||||
@@ -4,16 +4,16 @@
|
|||||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
||||||
|
|
||||||
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 throug which all clients communicate. You can write lua mods for the server, 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".**
|
**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)
|
||||||
|
|
||||||
## Minimum Requirements
|
## Minimum Requirements
|
||||||
|
|
||||||
@@ -28,21 +28,21 @@ These values are guesstimated and are subject to change with each release.
|
|||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column.
|
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" or "good first issue" label or with nobody assigned.
|
||||||
|
|
||||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) and at the [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer). Any issues that have the "help wanted" label or don't have anyone assigned and any trello cards that aren't assigned or in the "In-Progress" section are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||||
|
|
||||||
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
||||||
|
|
||||||
If you need support with understanding the codebase, please write us in the discord. You'll need to be proficient in modern C++.
|
If you need support with understanding the codebase, please write us in the Discord. You'll need to be proficient in modern C++.
|
||||||
|
|
||||||
## About Building from Source
|
## About Building from Source
|
||||||
|
|
||||||
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`.
|
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.1.0`.
|
||||||
|
|
||||||
## Supported Operating Systems
|
## Supported Operating Systems
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
@@ -50,71 +50,38 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
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)).
|
For Debian, Ubuntu and others you can find scripts that do this in `scripts/`.
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
#### 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
|
liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||||
zlib
|
|
||||||
rapidjson
|
|
||||||
openssl
|
|
||||||
websocketpp
|
|
||||||
curl
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Linux
|
The names of each package may change depending on your platform. See in `scripts/` or use a search engine to find out what they're called for you.
|
||||||
|
|
||||||
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
You can build on **Windows, Linux** or other platforms by following these steps:
|
||||||
|
|
||||||
Runtime dependencies for **linux** are (debian/ubuntu):
|
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
||||||
```
|
2. Go into the directory `cd BeamMP-Server`.
|
||||||
libz-dev
|
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.
|
||||||
rapidjson-dev
|
4. Build via `cmake --build bin --parallel -t BeamMP-Server`.
|
||||||
liblua5.3
|
5. Your executable can be found in `bin/`.
|
||||||
libssl-dev
|
|
||||||
libwebsocketpp-dev
|
|
||||||
libcurl4-openssl-dev
|
|
||||||
```
|
|
||||||
|
|
||||||
Build-time dependencies for **linux** are:
|
When you make changes to the code, you only have to run step 4 again.
|
||||||
```
|
|
||||||
git
|
|
||||||
make
|
|
||||||
cmake
|
|
||||||
g++
|
|
||||||
```
|
|
||||||
|
|
||||||
For other distributions (e.g. Arch) you want to find packages for:
|
### Runtime Dependencies
|
||||||
- libz
|
|
||||||
- rapidjson
|
|
||||||
- lua5.3
|
|
||||||
- ssl / openssl
|
|
||||||
- websocketpp
|
|
||||||
- curl (with ssl support)
|
|
||||||
- \+ the build time dependencies from above
|
|
||||||
|
|
||||||
### How to build
|
These are needed to *run* the server.
|
||||||
|
|
||||||
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
Debian, Ubuntu and friends: `liblua5.3-0`
|
||||||
|
|
||||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
Other Linux distros: `liblua` of *some kind*.
|
||||||
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
|
||||||
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
|
||||||
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v3.0.1` for version 3.0.1. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
|
||||||
5. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
|
||||||
6. Run `make`
|
|
||||||
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) 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 &`*.*
|
Windows: No libraries.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
## Copyright
|
## Copyright
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# from here:
|
||||||
|
#
|
||||||
|
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
||||||
|
# Courtesy of Jason Turner
|
||||||
|
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
||||||
|
#
|
||||||
|
# This version has been modified by the owners of the current respository.
|
||||||
|
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||||
|
# strictly required.
|
||||||
|
|
||||||
|
function(set_project_warnings project_name)
|
||||||
|
set(MSVC_WARNINGS
|
||||||
|
/W4 # Baseline reasonable warnings
|
||||||
|
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
|
||||||
|
# of data
|
||||||
|
/w14254 # 'operator': conversion from 'type1:field_bits' to
|
||||||
|
# 'type2:field_bits', possible loss of data
|
||||||
|
/w14263 # 'function': member function does not override any base class
|
||||||
|
# virtual member function
|
||||||
|
/w14265 # 'classname': class has virtual functions, but destructor is not
|
||||||
|
# virtual instances of this class may not be destructed correctly
|
||||||
|
/w14287 # 'operator': unsigned/negative constant mismatch
|
||||||
|
/we4289 # nonstandard extension used: 'variable': loop control variable
|
||||||
|
# declared in the for-loop is used outside the for-loop scope
|
||||||
|
/w14296 # 'operator': expression is always 'boolean_value'
|
||||||
|
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
|
||||||
|
/w14545 # expression before comma evaluates to a function which is missing
|
||||||
|
# an argument list
|
||||||
|
/w14546 # function call before comma missing argument list
|
||||||
|
/w14547 # 'operator': operator before comma has no effect; expected
|
||||||
|
# operator with side-effect
|
||||||
|
/w14549 # 'operator': operator before comma has no effect; did you intend
|
||||||
|
# 'operator'?
|
||||||
|
/w14555 # expression has no effect; expected expression with side- effect
|
||||||
|
/w14619 # pragma warning: there is no warning number 'number'
|
||||||
|
/w14640 # Enable warning on thread un-safe static member initialization
|
||||||
|
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
|
||||||
|
# cause unexpected runtime behavior.
|
||||||
|
/w14905 # wide string literal cast to 'LPSTR'
|
||||||
|
/w14906 # string literal cast to 'LPWSTR'
|
||||||
|
/w14928 # illegal copy-initialization; more than one user-defined
|
||||||
|
# conversion has been implicitly applied
|
||||||
|
/permissive- # standards conformance mode for MSVC compiler.
|
||||||
|
)
|
||||||
|
|
||||||
|
set(CLANG_WARNINGS
|
||||||
|
-Wall
|
||||||
|
-Wextra # reasonable and standard
|
||||||
|
-Wshadow # warn the user if a variable declaration shadows one from a
|
||||||
|
# parent context
|
||||||
|
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
|
||||||
|
# non-virtual destructor. This helps catch hard to
|
||||||
|
# track down memory errors
|
||||||
|
-Wold-style-cast # warn for c-style casts
|
||||||
|
-Wcast-align # warn for potential performance problem casts
|
||||||
|
-Wunused # warn on anything being unused
|
||||||
|
-Woverloaded-virtual # warn if you overload (not override) a virtual
|
||||||
|
# function
|
||||||
|
-Wpedantic # warn if non-standard C++ is used
|
||||||
|
-Wconversion # warn on type conversions that may lose data
|
||||||
|
-Wsign-conversion # warn on sign conversions
|
||||||
|
-Wnull-dereference # warn if a null dereference is detected
|
||||||
|
-Wdouble-promotion # warn if float is implicit promoted to double
|
||||||
|
-Wformat=2 # warn on security issues around functions that format output
|
||||||
|
# (ie printf)
|
||||||
|
# modified; added more errors / warnings
|
||||||
|
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
|
||||||
|
# (see below) should still be used in strict pipelines.
|
||||||
|
-Werror=uninitialized
|
||||||
|
-Werror=float-equal
|
||||||
|
-Werror=write-strings
|
||||||
|
-Werror=strict-aliasing -fstrict-aliasing
|
||||||
|
-Werror=missing-declarations
|
||||||
|
-Werror=missing-field-initializers
|
||||||
|
-Werror=ctor-dtor-privacy
|
||||||
|
-Werror=switch-enum
|
||||||
|
-Wswitch-default
|
||||||
|
-Werror=unused-result
|
||||||
|
-Werror=implicit-fallthrough
|
||||||
|
-Werror=return-type
|
||||||
|
-Wmissing-include-dirs
|
||||||
|
)
|
||||||
|
|
||||||
|
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
|
||||||
|
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
|
||||||
|
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(GCC_WARNINGS
|
||||||
|
${CLANG_WARNINGS}
|
||||||
|
-Wmisleading-indentation # warn if indentation implies blocks where blocks
|
||||||
|
# do not exist
|
||||||
|
-Wduplicated-cond # warn if if / else chain has duplicated conditions
|
||||||
|
-Wduplicated-branches # warn if if / else branches have duplicated code
|
||||||
|
-Wlogical-op # warn about logical operations being used where bitwise were
|
||||||
|
# probably wanted
|
||||||
|
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
|
||||||
|
)
|
||||||
|
|
||||||
|
if(MSVC)
|
||||||
|
set(PRJ_WARNINGS ${MSVC_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
|
||||||
|
set(PRJ_WARNINGS ${CLANG_WARNINGS})
|
||||||
|
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||||
|
set(PRJ_WARNINGS ${GCC_WARNINGS})
|
||||||
|
else()
|
||||||
|
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
|
||||||
|
|
||||||
|
if(NOT TARGET ${project_name})
|
||||||
|
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
@@ -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()
|
||||||
|
|
||||||
Vendored
-7
@@ -1,7 +0,0 @@
|
|||||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
|
||||||
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
|
||||||
|
|
||||||
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 d038fb3c2f
Vendored
+1
-1
Submodule deps/commandline updated: d6b1c32c8a...b2a29733f9
Vendored
-1
Submodule deps/cpp-httplib deleted from 47044c05a8
Vendored
-1
Submodule deps/doctest deleted from 7b98851331
Vendored
-1
Submodule deps/fmt deleted from ce246aaf74
Vendored
-1
Submodule deps/json deleted from ede6667858
Vendored
-1
Submodule deps/libzip deleted from 76df02f86b
Vendored
-1
Submodule deps/rapidjson deleted from 00dbcf2c6e
Vendored
-1
Submodule deps/sentry-native deleted from 90966cc102
Vendored
-1
Submodule deps/sol2 deleted from c068aefbed
Vendored
-1
Submodule deps/toml11 deleted from 1400dd223f
@@ -0,0 +1,6 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <boost/asio.hpp>
|
||||||
|
#include <boost/system/error_code.hpp>
|
||||||
|
|
||||||
|
using namespace boost::asio;
|
||||||
+27
-19
@@ -7,6 +7,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "VehicleData.h"
|
#include "VehicleData.h"
|
||||||
@@ -19,9 +20,8 @@ class TServer;
|
|||||||
#endif // WINDOWS
|
#endif // WINDOWS
|
||||||
|
|
||||||
struct TConnection final {
|
struct TConnection final {
|
||||||
SOCKET Socket;
|
ip::tcp::socket Socket;
|
||||||
struct sockaddr SockAddr;
|
ip::tcp::endpoint SockAddr;
|
||||||
socklen_t SockAddrLen;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class TClient final {
|
class TClient final {
|
||||||
@@ -33,27 +33,34 @@ public:
|
|||||||
std::unique_lock<std::mutex> Lock;
|
std::unique_lock<std::mutex> Lock;
|
||||||
};
|
};
|
||||||
|
|
||||||
explicit TClient(TServer& Server);
|
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
||||||
TClient(const TClient&) = delete;
|
TClient(const TClient&) = delete;
|
||||||
|
~TClient();
|
||||||
TClient& operator=(const TClient&) = delete;
|
TClient& operator=(const TClient&) = delete;
|
||||||
|
|
||||||
void AddNewCar(int Ident, const std::string& Data);
|
void AddNewCar(int Ident, const std::string& Data);
|
||||||
void SetCarData(int Ident, const std::string& Data);
|
void SetCarData(int Ident, const std::string& Data);
|
||||||
|
void SetCarPosition(int Ident, const std::string& Data);
|
||||||
TVehicleDataLockPair GetAllCars();
|
TVehicleDataLockPair GetAllCars();
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
void SetName(const std::string& Name) { mName = Name; }
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||||
std::string GetCarData(int Ident);
|
std::string GetCarData(int Ident);
|
||||||
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
std::string GetCarPositionRaw(int Ident);
|
||||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
||||||
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
||||||
void SetStatus(int Status) { mStatus = Status; }
|
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
||||||
|
void Disconnect(std::string_view Reason);
|
||||||
|
bool IsDisconnected() const { return !mSocket.is_open(); }
|
||||||
// locks
|
// locks
|
||||||
void DeleteCar(int Ident);
|
void DeleteCar(int Ident);
|
||||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||||
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
||||||
|
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
||||||
|
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
||||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||||
[[nodiscard]] std::string GetName() const { return mName; }
|
[[nodiscard]] std::string GetName() const { return mName; }
|
||||||
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
void SetUnicycleID(int ID) { mUnicycleID = ID; }
|
||||||
@@ -61,7 +68,6 @@ public:
|
|||||||
[[nodiscard]] int GetOpenCarID() const;
|
[[nodiscard]] int GetOpenCarID() const;
|
||||||
[[nodiscard]] int GetCarCount() const;
|
[[nodiscard]] int GetCarCount() const;
|
||||||
void ClearCars();
|
void ClearCars();
|
||||||
[[nodiscard]] int GetStatus() const { return mStatus; }
|
|
||||||
[[nodiscard]] int GetID() const { return mID; }
|
[[nodiscard]] int GetID() const { return mID; }
|
||||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||||
@@ -71,9 +77,9 @@ public:
|
|||||||
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
|
||||||
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
|
||||||
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
|
||||||
void EnqueuePacket(const std::string& Packet);
|
void EnqueuePacket(const std::vector<uint8_t>& Packet);
|
||||||
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
|
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
||||||
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
|
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
||||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||||
@@ -89,18 +95,20 @@ private:
|
|||||||
bool mIsSynced = false;
|
bool mIsSynced = false;
|
||||||
bool mIsSyncing = false;
|
bool mIsSyncing = false;
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
mutable std::mutex mMissedPacketsMutex;
|
||||||
std::queue<std::string> mPacketsSync;
|
std::queue<std::vector<uint8_t>> mPacketsSync;
|
||||||
std::unordered_map<std::string, std::string> mIdentifiers;
|
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||||
bool mIsGuest = false;
|
bool mIsGuest = false;
|
||||||
mutable std::mutex mVehicleDataMutex;
|
mutable std::mutex mVehicleDataMutex;
|
||||||
|
mutable std::mutex mVehiclePositionMutex;
|
||||||
TSetOfVehicleData mVehicleData;
|
TSetOfVehicleData mVehicleData;
|
||||||
|
SparseArray<std::string> mVehiclePosition;
|
||||||
std::string mName = "Unknown Client";
|
std::string mName = "Unknown Client";
|
||||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
ip::tcp::socket mSocket;
|
||||||
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
ip::tcp::socket mDownSocket;
|
||||||
|
ip::udp::endpoint mUDPAddress {};
|
||||||
int mUnicycleID = -1;
|
int mUnicycleID = -1;
|
||||||
std::string mRole;
|
std::string mRole;
|
||||||
std::string mDID;
|
std::string mDID;
|
||||||
int mStatus = 0;
|
|
||||||
int mID = -1;
|
int mID = -1;
|
||||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||||
};
|
};
|
||||||
|
|||||||
+23
-25
@@ -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>
|
||||||
@@ -14,14 +11,13 @@ extern TSentry Sentry;
|
|||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <shared_mutex>
|
#include <shared_mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
#include <unordered_map>
|
||||||
#include <zlib.h>
|
#include <zlib.h>
|
||||||
|
|
||||||
#include <doctest/doctest.h>
|
#include <doctest/doctest.h>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
#include "Compat.h"
|
|
||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
struct Version {
|
struct Version {
|
||||||
@@ -33,6 +29,9 @@ struct Version {
|
|||||||
std::string AsString();
|
std::string AsString();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
using SparseArray = std::unordered_map<size_t, T>;
|
||||||
|
|
||||||
// static class handling application start, shutdown, etc.
|
// static class handling application start, shutdown, etc.
|
||||||
// yes, static classes, singletons, globals are all pretty
|
// yes, static classes, singletons, globals are all pretty
|
||||||
// bad idioms. In this case we need a central way to access
|
// bad idioms. In this case we need a central way to access
|
||||||
@@ -44,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 };
|
||||||
@@ -75,10 +76,10 @@ 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 std::string ClientVersionString() { return "2.0"; }
|
static uint8_t ClientMajorVersion() { return 2; }
|
||||||
static std::string PPS() { return mPPS; }
|
static std::string PPS() { return mPPS; }
|
||||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||||
|
|
||||||
@@ -101,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 {
|
||||||
@@ -129,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, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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__)
|
||||||
@@ -190,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 { \
|
||||||
@@ -273,11 +273,11 @@ inline T Comp(const T& Data) {
|
|||||||
// obsolete
|
// obsolete
|
||||||
C.fill(0);
|
C.fill(0);
|
||||||
z_stream defstream;
|
z_stream defstream;
|
||||||
defstream.zalloc = Z_NULL;
|
defstream.zalloc = nullptr;
|
||||||
defstream.zfree = Z_NULL;
|
defstream.zfree = nullptr;
|
||||||
defstream.opaque = Z_NULL;
|
defstream.opaque = nullptr;
|
||||||
defstream.avail_in = (uInt)Data.size();
|
defstream.avail_in = uInt(Data.size());
|
||||||
defstream.next_in = (Bytef*)&Data[0];
|
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
||||||
defstream.avail_out = Biggest;
|
defstream.avail_out = Biggest;
|
||||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||||
@@ -298,13 +298,13 @@ inline T DeComp(const T& Compressed) {
|
|||||||
// not needed
|
// not needed
|
||||||
C.fill(0);
|
C.fill(0);
|
||||||
z_stream infstream;
|
z_stream infstream;
|
||||||
infstream.zalloc = Z_NULL;
|
infstream.zalloc = nullptr;
|
||||||
infstream.zfree = Z_NULL;
|
infstream.zfree = nullptr;
|
||||||
infstream.opaque = Z_NULL;
|
infstream.opaque = nullptr;
|
||||||
infstream.avail_in = Biggest;
|
infstream.avail_in = Biggest;
|
||||||
infstream.next_in = (Bytef*)(&Compressed[0]);
|
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||||
infstream.avail_out = Biggest;
|
infstream.avail_out = Biggest;
|
||||||
infstream.next_out = (Bytef*)(C.data());
|
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
||||||
inflateInit(&infstream);
|
inflateInit(&infstream);
|
||||||
inflate(&infstream, Z_SYNC_FLUSH);
|
inflate(&infstream, Z_SYNC_FLUSH);
|
||||||
inflate(&infstream, Z_FINISH);
|
inflate(&infstream, Z_FINISH);
|
||||||
@@ -319,5 +319,3 @@ inline T DeComp(const T& Compressed) {
|
|||||||
|
|
||||||
std::string GetPlatformAgnosticErrorString();
|
std::string GetPlatformAgnosticErrorString();
|
||||||
#define S_DSN SU_RAW
|
#define S_DSN SU_RAW
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
|
||||||
|
|||||||
@@ -5,54 +5,23 @@
|
|||||||
// ======================= UNIX ========================
|
// ======================= UNIX ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_LINUX
|
#ifdef BEAMMP_LINUX
|
||||||
#include <arpa/inet.h>
|
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
using SOCKET = int;
|
|
||||||
using DWORD = unsigned long;
|
|
||||||
using PDWORD = unsigned long*;
|
|
||||||
using LPDWORD = unsigned long*;
|
|
||||||
char _getch();
|
char _getch();
|
||||||
inline void CloseSocketProper(int TheSocket) {
|
|
||||||
shutdown(TheSocket, SHUT_RDWR);
|
|
||||||
close(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= APPLE ========================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
#ifdef BEAMMP_APPLE
|
#ifdef BEAMMP_APPLE
|
||||||
#include <arpa/inet.h>
|
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
using SOCKET = int;
|
|
||||||
using DWORD = unsigned long;
|
|
||||||
using PDWORD = unsigned long*;
|
|
||||||
using LPDWORD = unsigned long*;
|
|
||||||
char _getch();
|
char _getch();
|
||||||
inline void CloseSocketProper(int TheSocket) {
|
|
||||||
shutdown(TheSocket, SHUT_RDWR);
|
|
||||||
close(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= WINDOWS =======================
|
// ======================= WINDOWS =======================
|
||||||
|
|
||||||
#ifdef BEAMMP_WINDOWS
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <conio.h>
|
#include <conio.h>
|
||||||
#include <winsock2.h>
|
|
||||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
|
||||||
shutdown(TheSocket, 2); // 2 == SD_BOTH
|
|
||||||
closesocket(TheSocket);
|
|
||||||
}
|
|
||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
#ifdef INVALID_SOCKET
|
|
||||||
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
|
|
||||||
#else
|
|
||||||
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
|
|
||||||
#endif
|
|
||||||
|
|||||||
+9
-10
@@ -58,16 +58,15 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||||
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||||
#else
|
#else
|
||||||
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
#define beammp_assert(cond) \
|
||||||
#define beammp_assert(cond) \
|
do { \
|
||||||
do { \
|
bool result = (cond); \
|
||||||
bool result = (cond); \
|
if (!result) { \
|
||||||
if (!result) { \
|
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 { \
|
||||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||||
} while (false)
|
} while (false)
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
#if defined(BEAMMP_LINUX)
|
#if defined(BEAMMP_LINUX)
|
||||||
#pragma GCC diagnostic push
|
#pragma GCC diagnostic push
|
||||||
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||||
|
#pragma GCC diagnostic ignored "-Wcast-qual"
|
||||||
|
#pragma GCC diagnostic ignored "-Wold-style-cast"
|
||||||
#endif
|
#endif
|
||||||
#include <httplib.h>
|
#include <httplib.h>
|
||||||
#if defined(BEAMMP_LINUX)
|
#if defined(BEAMMP_LINUX)
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ public:
|
|||||||
IThreaded()
|
IThreaded()
|
||||||
// invokes operator() on this object
|
// invokes operator() on this object
|
||||||
: mThread() { }
|
: mThread() { }
|
||||||
~IThreaded() noexcept {
|
virtual ~IThreaded() noexcept {
|
||||||
if (mThread.joinable()) {
|
if (mThread.joinable()) {
|
||||||
mThread.join();
|
mThread.join();
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -12,12 +12,12 @@ namespace MP {
|
|||||||
|
|
||||||
std::string GetOSName();
|
std::string GetOSName();
|
||||||
std::tuple<int, int, int> GetServerVersion();
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
bool 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);
|
||||||
bool 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->Server().ClientCount(); }
|
||||||
void DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
void SendChatMessage(int ID, const std::string& Message);
|
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||||
void RemoveVehicle(int PlayerID, int VehicleID);
|
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||||
void Set(int ConfigID, sol::object NewValue);
|
void Set(int ConfigID, sol::object NewValue);
|
||||||
bool IsPlayerGuest(int ID);
|
bool IsPlayerGuest(int ID);
|
||||||
bool IsPlayerConnected(int ID);
|
bool IsPlayerConnected(int ID);
|
||||||
|
|||||||
+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;
|
||||||
|
|||||||
+6
-2
@@ -5,6 +5,7 @@
|
|||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
|
#include <mutex>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
@@ -16,12 +17,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 +59,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 };
|
||||||
|
|||||||
+23
-5
@@ -13,7 +13,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>
|
||||||
|
|
||||||
@@ -25,11 +25,12 @@ namespace fs = std::filesystem;
|
|||||||
/**
|
/**
|
||||||
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
||||||
*/
|
*/
|
||||||
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>;
|
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
|
||||||
static constexpr size_t TLuaArgTypes_String = 0;
|
static constexpr size_t TLuaArgTypes_String = 0;
|
||||||
static constexpr size_t TLuaArgTypes_Int = 1;
|
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||||
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||||
static constexpr size_t TLuaArgTypes_Bool = 3;
|
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||||
|
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||||
|
|
||||||
class TLuaPlugin;
|
class TLuaPlugin;
|
||||||
|
|
||||||
@@ -40,7 +41,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();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -75,7 +83,7 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
TLuaEngine();
|
TLuaEngine();
|
||||||
~TLuaEngine() noexcept {
|
virtual ~TLuaEngine() noexcept {
|
||||||
beammp_debug("Lua Engine terminated");
|
beammp_debug("Lua Engine terminated");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +104,13 @@ public:
|
|||||||
std::unique_lock Lock(mLuaStatesMutex);
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
return mLuaStates.size();
|
return mLuaStates.size();
|
||||||
}
|
}
|
||||||
|
std::vector<std::string> GetLuaStateNames() {
|
||||||
|
std::vector<std::string> names {};
|
||||||
|
for (auto const& [stateId, _] : mLuaStates) {
|
||||||
|
names.push_back(stateId);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
size_t GetTimedEventsCount() {
|
size_t GetTimedEventsCount() {
|
||||||
std::unique_lock Lock(mTimedEventsMutex);
|
std::unique_lock Lock(mTimedEventsMutex);
|
||||||
return mTimedEvents.size();
|
return mTimedEvents.size();
|
||||||
@@ -172,6 +187,7 @@ public:
|
|||||||
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
||||||
|
|
||||||
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
||||||
|
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
|
||||||
|
|
||||||
// Debugging functions (slow)
|
// Debugging functions (slow)
|
||||||
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||||
@@ -189,7 +205,7 @@ private:
|
|||||||
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);
|
||||||
@@ -199,6 +215,7 @@ private:
|
|||||||
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();
|
||||||
|
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
|
||||||
|
|
||||||
// Debug functions, slow
|
// Debug functions, slow
|
||||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||||
@@ -211,6 +228,7 @@ 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);
|
||||||
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);
|
sol::table Lua_JsonDecode(const std::string& str);
|
||||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||||
|
|||||||
+22
-17
@@ -1,8 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
#include <boost/asio/io_context.hpp>
|
||||||
|
#include <boost/asio/ip/udp.hpp>
|
||||||
|
|
||||||
struct TConnection;
|
struct TConnection;
|
||||||
|
|
||||||
@@ -10,19 +13,18 @@ class TNetwork {
|
|||||||
public:
|
public:
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||||
|
|
||||||
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
|
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
||||||
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
|
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
||||||
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
|
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
||||||
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
|
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
||||||
std::string TCPRcv(TClient& c);
|
std::vector<uint8_t> TCPRcv(TClient& c);
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
void ClientKick(TClient& c, const std::string& R);
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||||
void Identify(const TConnection& client);
|
void Identify(TConnection&& client);
|
||||||
void Authentication(const TConnection& ClientConnection);
|
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
||||||
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
|
||||||
void SyncResources(TClient& c);
|
void SyncResources(TClient& c);
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
||||||
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
|
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
||||||
void UpdatePlayer(TClient& Client);
|
void UpdatePlayer(TClient& Client);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -31,21 +33,24 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
TPPSMonitor& mPPSMonitor;
|
TPPSMonitor& mPPSMonitor;
|
||||||
SOCKET mUDPSock {};
|
ip::udp::socket mUDPSock;
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
std::thread mUDPThread;
|
std::thread mUDPThread;
|
||||||
std::thread mTCPThread;
|
std::thread mTCPThread;
|
||||||
|
|
||||||
std::string UDPRcvFromClient(sockaddr_in& client) const;
|
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
||||||
void HandleDownload(SOCKET TCPSock);
|
void HandleDownload(TConnection&& TCPSock);
|
||||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||||
void Looper(const std::weak_ptr<TClient>& c);
|
void Looper(const std::weak_ptr<TClient>& c);
|
||||||
int OpenID();
|
int OpenID();
|
||||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
|
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
||||||
void Parse(TClient& c, const std::string& Packet);
|
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
||||||
void SendFile(TClient& c, const std::string& Name);
|
void SendFile(TClient& c, const std::string& Name);
|
||||||
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||||
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
|
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
std::string HashPassword(const std::string& str);
|
||||||
|
std::vector<uint8_t> StringToVector(const std::string& Str);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ class TNetwork;
|
|||||||
class TPPSMonitor : public IThreaded {
|
class TPPSMonitor : public IThreaded {
|
||||||
public:
|
public:
|
||||||
explicit TPPSMonitor(TServer& Server);
|
explicit TPPSMonitor(TServer& Server);
|
||||||
|
virtual ~TPPSMonitor() {}
|
||||||
|
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
|
||||||
+17
-3
@@ -8,6 +8,8 @@
|
|||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
|
|
||||||
|
#include "BoostAliases.h"
|
||||||
|
|
||||||
class TClient;
|
class TClient;
|
||||||
class TNetwork;
|
class TNetwork;
|
||||||
class TPPSMonitor;
|
class TPPSMonitor;
|
||||||
@@ -19,23 +21,35 @@ public:
|
|||||||
TServer(const std::vector<std::string_view>& Arguments);
|
TServer(const std::vector<std::string_view>& Arguments);
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||||
std::weak_ptr<TClient> InsertNewClient();
|
|
||||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||||
// in Fn, return true to continue, return false to break
|
// in Fn, return true to continue, return false to break
|
||||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||||
size_t ClientCount() const;
|
size_t ClientCount() const;
|
||||||
|
|
||||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||||
static void HandleEvent(TClient& c, const std::string& Data);
|
static void HandleEvent(TClient& c, const std::string& Data);
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||||
|
|
||||||
|
|
||||||
const TScopedTimer UptimeTimer;
|
const TScopedTimer UptimeTimer;
|
||||||
|
|
||||||
|
// asio io context
|
||||||
|
io_context& IoCtx() { return mIoCtx; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
io_context mIoCtx {};
|
||||||
TClientSet mClients;
|
TClientSet mClients;
|
||||||
mutable RWMutex mClientsMutex;
|
mutable RWMutex mClientsMutex;
|
||||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
||||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
||||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||||
|
static 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++
|
||||||
@@ -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
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
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++
|
||||||
@@ -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
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||||
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
|
||||||
+37
-2
@@ -6,6 +6,7 @@
|
|||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
void TClient::DeleteCar(int Ident) {
|
||||||
|
// TODO: Send delete packets
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
||||||
return Ident == elem.ID();
|
return Ident == elem.ID();
|
||||||
@@ -47,6 +48,34 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
|||||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string TClient::GetCarPositionRaw(int Ident) {
|
||||||
|
std::unique_lock lock(mVehiclePositionMutex);
|
||||||
|
try {
|
||||||
|
return mVehiclePosition.at(size_t(Ident));
|
||||||
|
} catch (const std::out_of_range& oor) {
|
||||||
|
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[size_t(Ident)] = Data;
|
||||||
|
}
|
||||||
|
|
||||||
std::string TClient::GetCarData(int Ident) {
|
std::string TClient::GetCarData(int Ident) {
|
||||||
{ // lock
|
{ // lock
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
@@ -81,16 +110,22 @@ TServer& TClient::Server() const {
|
|||||||
return mServer;
|
return mServer;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TClient::EnqueuePacket(const std::string& Packet) {
|
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
||||||
std::unique_lock Lock(mMissedPacketsMutex);
|
std::unique_lock Lock(mMissedPacketsMutex);
|
||||||
mPacketsSync.push(Packet);
|
mPacketsSync.push(Packet);
|
||||||
}
|
}
|
||||||
|
|
||||||
TClient::TClient(TServer& Server)
|
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
||||||
: mServer(Server)
|
: mServer(Server)
|
||||||
|
, mSocket(std::move(Socket))
|
||||||
|
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
||||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TClient::~TClient() {
|
||||||
|
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
||||||
|
}
|
||||||
|
|
||||||
void TClient::UpdatePingTime() {
|
void TClient::UpdatePingTime() {
|
||||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-7
@@ -9,12 +9,10 @@
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
|
#include "Compat.h"
|
||||||
#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) {
|
||||||
@@ -170,6 +168,8 @@ void Application::SetSubsystemStatus(const std::string& Subsystem, Status status
|
|||||||
case Status::Shutdown:
|
case Status::Shutdown:
|
||||||
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
||||||
break;
|
break;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
std::unique_lock Lock(mSystemStatusMapMutex);
|
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||||
mSystemStatusMap[Subsystem] = status;
|
mSystemStatusMap[Subsystem] = status;
|
||||||
@@ -195,7 +195,7 @@ void Application::CheckForUpdates() {
|
|||||||
// checks current version against latest version
|
// checks current version against latest version
|
||||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||||
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/v/s");
|
auto Response = Http::GET(url, 443, "/v/s");
|
||||||
bool Matches = std::regex_match(Response, VersionRegex);
|
bool Matches = std::regex_match(Response, VersionRegex);
|
||||||
if (Matches) {
|
if (Matches) {
|
||||||
auto MyVersion = ServerVersion();
|
auto MyVersion = ServerVersion();
|
||||||
@@ -214,9 +214,6 @@ void Application::CheckForUpdates() {
|
|||||||
if (FirstTime) {
|
if (FirstTime) {
|
||||||
beammp_debug("Failed to fetch version from: " + url);
|
beammp_debug("Failed to fetch version from: " + url);
|
||||||
beammp_trace("got " + Response);
|
beammp_trace("got " + Response);
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("get-response", { { "response", Response } });
|
|
||||||
Sentry.LogError("failed to get server version", _file_basename, _line);
|
|
||||||
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -347,5 +344,18 @@ std::string GetPlatformAgnosticErrorString() {
|
|||||||
}
|
}
|
||||||
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
return std::strerror(errno);
|
return std::strerror(errno);
|
||||||
|
#else
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+14
-5
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
static struct termios old, current;
|
static struct termios old, current;
|
||||||
|
|
||||||
void initTermios(int echo) {
|
static void initTermios(int echo) {
|
||||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||||
current = old; /* make new settings same as old settings */
|
current = old; /* make new settings same as old settings */
|
||||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||||
@@ -19,7 +19,7 @@ void initTermios(int echo) {
|
|||||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||||
}
|
}
|
||||||
|
|
||||||
void resetTermios(void) {
|
static void resetTermios(void) {
|
||||||
tcsetattr(0, TCSANOW, &old);
|
tcsetattr(0, TCSANOW, &old);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,14 +36,23 @@ TEST_CASE("init and reset termios") {
|
|||||||
resetTermios();
|
resetTermios();
|
||||||
struct termios current;
|
struct termios current;
|
||||||
tcgetattr(0, ¤t);
|
tcgetattr(0, ¤t);
|
||||||
CHECK(std::memcmp(&original, ¤t, sizeof(struct termios)) == 0);
|
CHECK_EQ(std::memcmp(¤t.c_cc, &original.c_cc, sizeof(current.c_cc)), 0);
|
||||||
|
CHECK_EQ(current.c_cflag, original.c_cflag);
|
||||||
|
CHECK_EQ(current.c_iflag, original.c_iflag);
|
||||||
|
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
||||||
|
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||||
|
CHECK_EQ(current.c_line, original.c_line);
|
||||||
|
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||||
|
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
char getch_(int echo) {
|
static char getch_(int echo) {
|
||||||
char ch;
|
char ch;
|
||||||
initTermios(echo);
|
initTermios(echo);
|
||||||
read(STDIN_FILENO, &ch, 1);
|
if (read(STDIN_FILENO, &ch, 1) < 0) {
|
||||||
|
// ignore, not much we can do
|
||||||
|
}
|
||||||
resetTermios();
|
resetTermios();
|
||||||
return ch;
|
return ch;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -4,7 +4,6 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "httplib.h"
|
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
@@ -177,6 +176,8 @@ void Http::Server::THttpServerInstance::operator()() try {
|
|||||||
case Application::Status::Bad:
|
case Application::Status::Bad:
|
||||||
SystemsBad++;
|
SystemsBad++;
|
||||||
break;
|
break;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res.set_content(
|
res.set_content(
|
||||||
|
|||||||
+55
-25
@@ -1,6 +1,7 @@
|
|||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
@@ -74,8 +75,10 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
|
|||||||
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||||
return ss.str();
|
return ss.str();
|
||||||
}
|
}
|
||||||
|
case sol::type::poly:
|
||||||
|
return "<poly>";
|
||||||
default:
|
default:
|
||||||
return "((unprintable type))";
|
return "<unprintable type>";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,72 +113,95 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
|||||||
CHECK(pa == real.patch);
|
CHECK(pa == real.patch);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline bool InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||||
std::string Packet = "E:" + EventName + ":" + Data;
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
if (PlayerID == -1)
|
if (PlayerID == -1) {
|
||||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
else {
|
return { true, "" };
|
||||||
|
} else {
|
||||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||||
return false;
|
return { false, "Invalid Player ID" };
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||||
return false;
|
return { false, "Respond failed, dropping client" };
|
||||||
}
|
}
|
||||||
|
return { true, "" };
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool 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) {
|
||||||
std::string Data = DataObj.as<std::string>();
|
std::string Data = DataObj.as<std::string>();
|
||||||
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
beammp_lua_error("Tried to drop client with id " + std::to_string(ID) + ", who doesn't exist");
|
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||||
return;
|
return { false, "Player does not exist" };
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||||
|
return { true, "" };
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
std::string Packet = "C:Server: " + Message;
|
std::string Packet = "C:Server: " + Message;
|
||||||
if (ID == -1) {
|
if (ID == -1) {
|
||||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||||
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
if (!c->IsSynced())
|
if (!c->IsSynced()) {
|
||||||
return;
|
Result.first = false;
|
||||||
|
Result.second = "Player still syncing data";
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||||
Engine->Network().Respond(*c, Packet, true);
|
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||||
|
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||||
|
// TODO: should we return an error here?
|
||||||
|
}
|
||||||
|
Result.first = true;
|
||||||
} else {
|
} else {
|
||||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||||
|
Result.first = false;
|
||||||
|
Result.second = "Invalid Player ID";
|
||||||
}
|
}
|
||||||
|
return Result;
|
||||||
}
|
}
|
||||||
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||||
return;
|
Result.first = false;
|
||||||
|
Result.second = "Invalid Player ID";
|
||||||
|
return Result;
|
||||||
}
|
}
|
||||||
auto c = MaybeClient.value().lock();
|
auto c = MaybeClient.value().lock();
|
||||||
if (!c->GetCarData(VID).empty()) {
|
if (!c->GetCarData(VID).empty()) {
|
||||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||||
Engine->Network().SendToAll(nullptr, Destroy, true, true);
|
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
c->DeleteCar(VID);
|
c->DeleteCar(VID);
|
||||||
|
Result.first = true;
|
||||||
|
} else {
|
||||||
|
Result.first = false;
|
||||||
|
Result.second = "Vehicle does not exist";
|
||||||
}
|
}
|
||||||
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||||
@@ -500,7 +526,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string key;
|
std::string key {};
|
||||||
switch (left.get_type()) {
|
switch (left.get_type()) {
|
||||||
case sol::type::lua_nil:
|
case sol::type::lua_nil:
|
||||||
case sol::type::none:
|
case sol::type::none:
|
||||||
@@ -519,6 +545,8 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
case sol::type::number:
|
case sol::type::number:
|
||||||
key = std::to_string(left.as<double>());
|
key = std::to_string(left.as<double>());
|
||||||
break;
|
break;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
nlohmann::json value;
|
nlohmann::json value;
|
||||||
switch (right.get_type()) {
|
switch (right.get_type()) {
|
||||||
@@ -561,6 +589,8 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
if (is_array) {
|
if (is_array) {
|
||||||
json.push_back(value);
|
json.push_back(value);
|
||||||
@@ -645,6 +675,6 @@ std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
|||||||
return nlohmann::json::parse(json).unflatten().dump(-1);
|
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||||
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-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);
|
||||||
@@ -44,7 +51,10 @@ TEST_CASE("TConfig::TConfig") {
|
|||||||
{
|
{
|
||||||
buf.resize(fs::file_size(CfgFile));
|
buf.resize(fs::file_size(CfgFile));
|
||||||
auto fp = std::fopen(CfgFile.c_str(), "r");
|
auto fp = std::fopen(CfgFile.c_str(), "r");
|
||||||
std::fread(buf.data(), 1, buf.size(), fp);
|
auto res = std::fread(buf.data(), 1, buf.size(), fp);
|
||||||
|
if (res != buf.size()) {
|
||||||
|
// IGNORE?
|
||||||
|
}
|
||||||
std::fclose(fp);
|
std::fclose(fp);
|
||||||
}
|
}
|
||||||
INFO("file contents are:", buf);
|
INFO("file contents are:", buf);
|
||||||
@@ -52,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);
|
||||||
}
|
}
|
||||||
@@ -98,11 +107,15 @@ 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.");
|
||||||
@@ -110,20 +123,10 @@ void TConfig::FlushToFile() {
|
|||||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
// 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) {
|
||||||
@@ -153,21 +156,40 @@ 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 = Table[Category.c_str()][Key.data()].as_integer();
|
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,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;
|
||||||
@@ -229,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() {
|
||||||
@@ -291,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;
|
||||||
|
}
|
||||||
|
|||||||
+90
-47
@@ -8,6 +8,7 @@
|
|||||||
#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,7 +52,7 @@ TEST_CASE("TrimString") {
|
|||||||
CHECK(TrimString("") == "");
|
CHECK(TrimString("") == "");
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
auto local_tm = std::localtime(&tt);
|
auto local_tm = std::localtime(&tt);
|
||||||
@@ -144,14 +145,14 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
|||||||
mStateId = LuaStateId;
|
mStateId = 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 `:detach`");
|
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 `:detach`");
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,9 +164,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,10 +188,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -245,7 +246,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) {
|
||||||
@@ -259,9 +260,10 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
|
|||||||
}
|
}
|
||||||
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||||
bool Kicked = false;
|
bool Kicked = false;
|
||||||
|
// TODO: this sucks, tolower is locale-dependent.
|
||||||
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||||
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(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 {
|
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
@@ -320,7 +322,9 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
|||||||
}
|
}
|
||||||
++Ptr;
|
++Ptr;
|
||||||
}
|
}
|
||||||
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
// this is required, otherwise we get negative int to unsigned cast in the next operations
|
||||||
|
beammp_assert(PrevPtr <= Ptr);
|
||||||
|
Arg = std::string(PrevPtr, std::string::size_type(Ptr - PrevPtr));
|
||||||
// remove quotes if enclosed in quotes
|
// remove quotes if enclosed in quotes
|
||||||
for (char Quote : { '"', '\'', '`' }) {
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||||
@@ -336,7 +340,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -436,6 +440,8 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
SystemsShutdown++;
|
SystemsShutdown++;
|
||||||
SystemsShutdownList += NameStatusPair.first + ", ";
|
SystemsShutdownList += NameStatusPair.first + ", ";
|
||||||
break;
|
break;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// remove ", " at the end
|
// remove ", " at the end
|
||||||
@@ -454,7 +460,7 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
|||||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
<< "\tConnected Players: " << ConnectedCount << "\n"
|
||||||
<< "\tGuests: " << GuestCount << "\n"
|
<< "\tGuests: " << GuestCount << "\n"
|
||||||
<< "\tCars: " << CarCount << "\n"
|
<< "\tCars: " << CarCount << "\n"
|
||||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(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"
|
||||||
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||||
@@ -462,12 +468,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());
|
||||||
@@ -572,16 +578,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");
|
||||||
@@ -589,9 +599,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);
|
||||||
}
|
}
|
||||||
@@ -618,56 +626,91 @@ 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 {
|
||||||
auto cmd = TrimString(stub);
|
|
||||||
// beammp_error("yes 1");
|
|
||||||
// beammp_error(stub);
|
|
||||||
if (mIsLuaConsole) { // if lua
|
if (mIsLuaConsole) { // if lua
|
||||||
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");
|
||||||
} else {
|
} else {
|
||||||
std::string prefix {};
|
std::string prefix {}; // stores non-table part of input
|
||||||
for (size_t i = stub.length(); i > 0; i--) {
|
for (size_t i = stub.length(); i > 0; i--) { // separate table from input
|
||||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') {
|
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
|
||||||
prefix = stub.substr(0, i);
|
prefix = stub.substr(0, i);
|
||||||
stub = stub.substr(i);
|
stub = stub.substr(i);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
|
|
||||||
for (const auto& key : keys) {
|
// turn string into vector of keys
|
||||||
std::string::size_type n = key.find(stub);
|
std::vector<std::string> tablekeys;
|
||||||
|
|
||||||
|
SplitString(stub, '.', tablekeys);
|
||||||
|
|
||||||
|
// remove last key if incomplete
|
||||||
|
if (stub.rfind('.') != stub.size() - 1 && !tablekeys.empty()) {
|
||||||
|
tablekeys.pop_back();
|
||||||
|
}
|
||||||
|
|
||||||
|
auto keys = mLuaEngine->GetStateTableKeysForState(mStateId, tablekeys);
|
||||||
|
|
||||||
|
for (const auto& key : keys) { // go through each bottom-level key
|
||||||
|
auto last_dot = stub.rfind('.');
|
||||||
|
std::string last_atom;
|
||||||
|
if (last_dot != std::string::npos) {
|
||||||
|
last_atom = stub.substr(last_dot + 1);
|
||||||
|
}
|
||||||
|
std::string before_last_atom = stub.substr(0, last_dot + 1); // get last confirmed key
|
||||||
|
auto last = stub.substr(stub.rfind('.') + 1);
|
||||||
|
std::string::size_type n = key.find(last);
|
||||||
if (n == 0) {
|
if (n == 0) {
|
||||||
suggestions.push_back(prefix + key);
|
suggestions.push_back(prefix + before_last_atom + key);
|
||||||
// beammp_warn(cmd_name);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else { // if not lua
|
} else { // if not lua
|
||||||
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
|
||||||
std::string::size_type n = cmd_name.find(stub);
|
std::string after_prefix = TrimString(stub.substr(3));
|
||||||
if (n == 0) {
|
auto stateNames = mLuaEngine->GetLuaStateNames();
|
||||||
suggestions.push_back(cmd_name);
|
|
||||||
// beammp_warn(cmd_name);
|
for (const auto& name : stateNames) {
|
||||||
|
if (name.find(after_prefix) == 0) {
|
||||||
|
suggestions.push_back("lua " + name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||||
|
if (cmd_name.find(stub) == 0) {
|
||||||
|
suggestions.push_back(cmd_name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
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.");
|
||||||
}
|
}
|
||||||
|
std::sort(suggestions.begin(), suggestions.end());
|
||||||
return suggestions;
|
return suggestions;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
|
|||||||
@@ -40,20 +40,6 @@ void THeartbeatThread::operator()() {
|
|||||||
Body += "&ip=" + Application::Settings.CustomIP;
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
}
|
}
|
||||||
|
|
||||||
Body += "&pps=" + Application::PPS();
|
|
||||||
|
|
||||||
beammp_trace("heartbeat body: '" + Body + "'");
|
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
@@ -61,17 +47,14 @@ void THeartbeatThread::operator()() {
|
|||||||
bool Ok = false;
|
bool Ok = false;
|
||||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
beammp_trace(T);
|
|
||||||
Doc.Parse(T.data(), T.size());
|
Doc.Parse(T.data(), T.size());
|
||||||
if (Doc.HasParseError() || !Doc.IsObject()) {
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
if (!Application::Settings.Private) {
|
if (!Application::Settings.Private) {
|
||||||
beammp_error("Backend response failed to parse as valid json");
|
beammp_trace("Backend response failed to parse as valid json");
|
||||||
beammp_trace("Response was: `" + T + "`");
|
beammp_trace("Response was: `" + T + "`");
|
||||||
}
|
}
|
||||||
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
|
||||||
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;
|
||||||
@@ -90,24 +73,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) {
|
||||||
@@ -148,13 +127,15 @@ std::string THeartbeatThread::GenerateCall() {
|
|||||||
<< "&map=" << Application::Settings.MapName
|
<< "&map=" << Application::Settings.MapName
|
||||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||||
<< "&version=" << Application::ServerVersionString()
|
<< "&version=" << Application::ServerVersionString()
|
||||||
<< "&clientversion=" << Application::ClientVersionString()
|
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||||
<< "&name=" << Application::Settings.ServerName
|
<< "&name=" << Application::Settings.ServerName
|
||||||
|
<< "&tags=" << Application::Settings.ServerTags
|
||||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||||
<< "&playerslist=" << GetPlayers()
|
<< "&playerslist=" << GetPlayers()
|
||||||
<< "&desc=" << Application::Settings.ServerDesc;
|
<< "&desc=" << Application::Settings.ServerDesc
|
||||||
|
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||||
return Ret.str();
|
return Ret.str();
|
||||||
}
|
}
|
||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||||
|
|||||||
+120
-9
@@ -4,10 +4,10 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "TLuaPlugin.h"
|
#include "TLuaPlugin.h"
|
||||||
|
#include "sol/object.hpp"
|
||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <condition_variable>
|
#include <condition_variable>
|
||||||
#include <httplib.h>
|
|
||||||
#include <nlohmann/json.hpp>
|
#include <nlohmann/json.hpp>
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
@@ -221,11 +221,72 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
|
|||||||
return Result;
|
return Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> TLuaEngine::GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys) {
|
||||||
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
|
auto Result = mLuaStates.at(StateId)->GetStateTableKeys(keys);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const std::vector<std::string>& keys) {
|
||||||
|
auto globals = mStateView.globals();
|
||||||
|
|
||||||
|
sol::table current = globals;
|
||||||
|
std::vector<std::string> Result {};
|
||||||
|
|
||||||
|
for (const auto& [key, value] : current) {
|
||||||
|
std::string s = key.as<std::string>();
|
||||||
|
if (value.get_type() == sol::type::function) {
|
||||||
|
s += "(";
|
||||||
|
}
|
||||||
|
Result.push_back(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!keys.empty()) {
|
||||||
|
Result.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (size_t i = 0; i < keys.size(); ++i) {
|
||||||
|
auto obj = current.get<sol::object>(keys.at(i));
|
||||||
|
if (obj.get_type() == sol::type::nil) {
|
||||||
|
// error
|
||||||
|
break;
|
||||||
|
} else if (i == keys.size() - 1) {
|
||||||
|
if (obj.get_type() == sol::type::table) {
|
||||||
|
for (const auto& [key, value] : obj.as<sol::table>()) {
|
||||||
|
std::string s = key.as<std::string>();
|
||||||
|
if (value.get_type() == sol::type::function) {
|
||||||
|
s += "(";
|
||||||
|
}
|
||||||
|
Result.push_back(s);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Result = { obj.as<std::string>() };
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (obj.get_type() == sol::type::table) {
|
||||||
|
current = obj;
|
||||||
|
} else {
|
||||||
|
// error
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
|
||||||
|
_G.a.b.c.d.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
|
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
|
||||||
for (const auto& Result : Results) {
|
for (const auto& Result : Results) {
|
||||||
bool Cancelled = false;
|
bool Cancelled = false;
|
||||||
size_t ms = 0;
|
size_t ms = 0;
|
||||||
std::set<std::string> WarnedResults;
|
std::set<std::string> WarnedResults;
|
||||||
|
|
||||||
while (!Result->Ready && !Cancelled) {
|
while (!Result->Ready && !Cancelled) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
ms += 10;
|
ms += 10;
|
||||||
@@ -240,6 +301,7 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Cancelled) {
|
if (Cancelled) {
|
||||||
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
|
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
|
||||||
LuaAPI::MP::Engine->ReportErrors({ Result });
|
LuaAPI::MP::Engine->ReportErrors({ Result });
|
||||||
@@ -358,7 +420,6 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
if (Fn.valid()) {
|
if (Fn.valid()) {
|
||||||
auto LuaResult = Fn(EventArgs);
|
auto LuaResult = Fn(EventArgs);
|
||||||
auto Result = std::make_shared<TLuaResult>();
|
auto Result = std::make_shared<TLuaResult>();
|
||||||
Result->Ready = true;
|
|
||||||
if (LuaResult.valid()) {
|
if (LuaResult.valid()) {
|
||||||
Result->Error = false;
|
Result->Error = false;
|
||||||
Result->Result = LuaResult;
|
Result->Result = LuaResult;
|
||||||
@@ -366,6 +427,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
|
|||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
|
||||||
}
|
}
|
||||||
|
Result->MarkAsReady();
|
||||||
Return.push_back(Result);
|
Return.push_back(Result);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -517,6 +579,33 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
|||||||
return sol::lua_nil;
|
return sol::lua_nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
|
||||||
|
std::pair<sol::table, std::string> Result;
|
||||||
|
auto MaybeClient = GetClient(mEngine->Server(), PID);
|
||||||
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
|
auto Client = MaybeClient.value().lock();
|
||||||
|
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
||||||
|
|
||||||
|
if (VehiclePos.empty()) {
|
||||||
|
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
||||||
|
Result.second = "Vehicle not found";
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
sol::table t = Lua_JsonDecode(VehiclePos);
|
||||||
|
if (t == sol::lua_nil) {
|
||||||
|
Result.second = "Packet decode failed";
|
||||||
|
}
|
||||||
|
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
||||||
|
Result.first = t;
|
||||||
|
return Result;
|
||||||
|
} else {
|
||||||
|
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
||||||
|
Result.second = "Client expired";
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
||||||
auto table = mStateView.create_table();
|
auto table = mStateView.create_table();
|
||||||
constexpr const char* InternalClient = "__InternalClient";
|
constexpr const char* InternalClient = "__InternalClient";
|
||||||
@@ -590,6 +679,8 @@ static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, c
|
|||||||
return;
|
return;
|
||||||
case nlohmann::detail::value_t::discarded:
|
case nlohmann::detail::value_t::discarded:
|
||||||
return;
|
return;
|
||||||
|
default:
|
||||||
|
beammp_assert_not_reachable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -673,6 +764,9 @@ 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> {
|
||||||
|
return Lua_GetPositionRaw(PID, 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 {
|
||||||
return Lua_GetPlayers();
|
return Lua_GetPlayers();
|
||||||
@@ -855,7 +949,6 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
}
|
}
|
||||||
sol::state_view StateView(mState);
|
sol::state_view StateView(mState);
|
||||||
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
|
||||||
S.second->Ready = true;
|
|
||||||
if (Res.valid()) {
|
if (Res.valid()) {
|
||||||
S.second->Error = false;
|
S.second->Error = false;
|
||||||
S.second->Result = std::move(Res);
|
S.second->Result = std::move(Res);
|
||||||
@@ -864,6 +957,7 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
S.second->ErrorMessage = Err.what();
|
S.second->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
|
S.second->MarkAsReady();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{ // StateFunctionQueue Scope
|
{ // StateFunctionQueue Scope
|
||||||
@@ -901,6 +995,15 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
case TLuaArgTypes_Bool:
|
case TLuaArgTypes_Bool:
|
||||||
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
|
||||||
break;
|
break;
|
||||||
|
case TLuaArgTypes_StringStringMap: {
|
||||||
|
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
|
||||||
|
auto Table = StateView.create_table();
|
||||||
|
for (const auto& [k, v] : Map) {
|
||||||
|
Table[k] = v;
|
||||||
|
}
|
||||||
|
LuaArgs.push_back(sol::make_object(StateView, Table));
|
||||||
|
break;
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
beammp_error("Unknown argument type, passed as nil");
|
beammp_error("Unknown argument type, passed as nil");
|
||||||
break;
|
break;
|
||||||
@@ -915,11 +1018,11 @@ void TLuaEngine::StateThreadData::operator()() {
|
|||||||
sol::error Err = Res;
|
sol::error Err = Res;
|
||||||
Result->ErrorMessage = Err.what();
|
Result->ErrorMessage = Err.what();
|
||||||
}
|
}
|
||||||
Result->Ready = true;
|
Result->MarkAsReady();
|
||||||
} else {
|
} else {
|
||||||
Result->Error = true;
|
Result->Error = true;
|
||||||
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
|
||||||
Result->Ready = true;
|
Result->MarkAsReady();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -969,11 +1072,19 @@ void TLuaEngine::StateThreadData::AddPath(const fs::path& Path) {
|
|||||||
mPaths.push(Path);
|
mPaths.push(Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLuaResult::WaitUntilReady() {
|
void TLuaResult::MarkAsReady() {
|
||||||
while (!Ready) {
|
{
|
||||||
std::this_thread::yield();
|
std::lock_guard<std::mutex> readyLock(*this->ReadyMutex);
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
this->Ready = true;
|
||||||
}
|
}
|
||||||
|
this->ReadyCondition->notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TLuaResult::WaitUntilReady() {
|
||||||
|
std::unique_lock readyLock(*this->ReadyMutex);
|
||||||
|
// wait if not ready yet
|
||||||
|
if(!this->Ready)
|
||||||
|
this->ReadyCondition->wait(readyLock);
|
||||||
}
|
}
|
||||||
|
|
||||||
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
|
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
|
||||||
|
|||||||
+377
-428
File diff suppressed because it is too large
Load Diff
@@ -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());
|
||||||
|
|||||||
-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) == 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);
|
|
||||||
}
|
|
||||||
+176
-98
@@ -1,9 +1,11 @@
|
|||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include <TLuaPlugin.h>
|
#include <TLuaPlugin.h>
|
||||||
|
#include <algorithm>
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
@@ -15,38 +17,87 @@
|
|||||||
|
|
||||||
#include "Json.h"
|
#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) {
|
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||||
if (Arguments.size() > 1) {
|
|
||||||
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);
|
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||||
if (!WeakClientPtr.expired()) {
|
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
||||||
TClient& Client = *WeakClientPtr.lock();
|
try {
|
||||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
LockedClientPtr = WeakClientPtr.lock();
|
||||||
Client.ClearCars();
|
} catch (const std::exception&) {
|
||||||
WriteLock Lock(mClientsMutex);
|
// silently fail, as there's nothing to do
|
||||||
mClients.erase(WeakClientPtr.lock());
|
return;
|
||||||
}
|
}
|
||||||
}
|
beammp_assert(LockedClientPtr != nullptr);
|
||||||
|
TClient& Client = *LockedClientPtr;
|
||||||
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||||
beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
// TODO: Send delete packets for all cars
|
||||||
|
Client.ClearCars();
|
||||||
WriteLock Lock(mClientsMutex);
|
WriteLock Lock(mClientsMutex);
|
||||||
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
mClients.erase(WeakClientPtr.lock());
|
||||||
return *Iter;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||||
@@ -67,12 +118,11 @@ size_t TServer::ClientCount() const {
|
|||||||
return mClients.size();
|
return mClients.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
constexpr std::string_view ABG = "ABG:";
|
||||||
// abort();
|
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
||||||
}
|
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
||||||
if (Packet.substr(0, 4) == "ABG:") {
|
Packet = DeComp(Packet);
|
||||||
Packet = DeComp(Packet.substr(4));
|
|
||||||
}
|
}
|
||||||
if (Packet.empty()) {
|
if (Packet.empty()) {
|
||||||
return;
|
return;
|
||||||
@@ -86,46 +136,50 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
std::any Res;
|
std::any Res;
|
||||||
char Code = Packet.at(0);
|
char Code = Packet.at(0);
|
||||||
|
|
||||||
// V to Z
|
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
if (Code <= 90 && Code >= 86) {
|
|
||||||
|
// V to Y
|
||||||
|
if (Code <= 89 && Code >= 86) {
|
||||||
PPSMonitor.IncrementInternalPPS();
|
PPSMonitor.IncrementInternalPPS();
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
switch (Code) {
|
switch (Code) {
|
||||||
case 'H': // initial connection
|
case 'H': // initial connection
|
||||||
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
|
||||||
if (!Network.SyncClient(Client)) {
|
if (!Network.SyncClient(Client)) {
|
||||||
// TODO handle
|
// TODO handle
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'p':
|
case 'p':
|
||||||
if (!Network.Respond(*LockedClient, ("p"), false)) {
|
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
||||||
// failed to send
|
// failed to send
|
||||||
if (LockedClient->GetStatus() > -1) {
|
LockedClient->Disconnect("Failed to send ping");
|
||||||
LockedClient->SetStatus(-1);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Network.UpdatePlayer(*LockedClient);
|
Network.UpdatePlayer(*LockedClient);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'O':
|
case 'O':
|
||||||
if (Packet.length() > 1000) {
|
if (Packet.size() > 1000) {
|
||||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
||||||
}
|
}
|
||||||
ParseVehicle(*LockedClient, Packet, Network);
|
ParseVehicle(*LockedClient, StringPacket, Network);
|
||||||
return;
|
|
||||||
case 'J':
|
|
||||||
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
|
||||||
return;
|
return;
|
||||||
case 'C': {
|
case 'C': {
|
||||||
beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
||||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
|
||||||
break;
|
break;
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||||
|
std::string Message = "";
|
||||||
|
const auto ColonPos = PacketAsString.find(':', 3);
|
||||||
|
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
|
||||||
|
Message = PacketAsString.substr(ColonPos + 2);
|
||||||
|
}
|
||||||
|
if (Message.empty()) {
|
||||||
|
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
|
||||||
TLuaEngine::WaitForAll(Futures);
|
TLuaEngine::WaitForAll(Futures);
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1));
|
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
||||||
if (std::any_of(Futures.begin(), Futures.end(),
|
if (std::any_of(Futures.begin(), Futures.end(),
|
||||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||||
return !Elem->Error
|
return !Elem->Error
|
||||||
@@ -134,17 +188,21 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
})) {
|
})) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
||||||
|
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'E':
|
case 'E':
|
||||||
beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
HandleEvent(*LockedClient, StringPacket);
|
||||||
HandleEvent(*LockedClient, Packet);
|
|
||||||
return;
|
return;
|
||||||
case 'N':
|
case 'N':
|
||||||
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
|
case 'Z': // position packet
|
||||||
|
PPSMonitor.IncrementInternalPPS();
|
||||||
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
|
HandlePosition(*LockedClient, StringPacket);
|
||||||
default:
|
default:
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -153,6 +211,10 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||||
// E:Name:Data
|
// E:Name:Data
|
||||||
// Data is allowed to have ':'
|
// Data is allowed to have ':'
|
||||||
|
if (RawData.size() < 2) {
|
||||||
|
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
|
||||||
|
return;
|
||||||
|
}
|
||||||
auto NameDataSep = RawData.find(':', 2);
|
auto NameDataSep = RawData.find(':', 2);
|
||||||
if (NameDataSep == std::string::npos) {
|
if (NameDataSep == std::string::npos) {
|
||||||
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||||
@@ -170,7 +232,7 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
|
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -185,19 +247,19 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||||
if (Pckt.length() < 4)
|
if (Pckt.length() < 6)
|
||||||
return;
|
return;
|
||||||
std::string Packet = Pckt;
|
std::string Packet = Pckt;
|
||||||
char Code = Packet.at(1);
|
char Code = Packet.at(1);
|
||||||
int PID = -1;
|
int PID = -1;
|
||||||
int VID = -1, Pos;
|
int VID = -1;
|
||||||
std::string Data = Packet.substr(3), pid, vid;
|
std::string Data = Packet.substr(3), pid, vid;
|
||||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||||
case 's':
|
case 's':
|
||||||
beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
||||||
if (Data.at(0) == '0') {
|
if (Data.at(0) == '0') {
|
||||||
int CarID = c.GetOpenCarID();
|
int CarID = c.GetOpenCarID();
|
||||||
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
std::string CarJson = Packet.substr(5);
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||||
@@ -210,26 +272,24 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||||
c.AddNewCar(CarID, Packet);
|
c.AddNewCar(CarID, Packet);
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
} else {
|
} else {
|
||||||
if (!Network.Respond(c, Packet, true)) {
|
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||||
if (!Network.Respond(c, Destroy, true)) {
|
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'c':
|
case 'c': {
|
||||||
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Data.find('-'));
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
if (MaybePidVid) {
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
PID = stoi(pid);
|
|
||||||
VID = stoi(vid);
|
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||||
@@ -243,62 +303,57 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||||
&& !ShouldntAllow) {
|
&& !ShouldntAllow) {
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
Apply(c, VID, Packet);
|
Apply(c, VID, Packet);
|
||||||
} else {
|
} else {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||||
if (!Network.Respond(c, Destroy, true)) {
|
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||||
// TODO: handle
|
|
||||||
}
|
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'd':
|
}
|
||||||
|
case 'd': {
|
||||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Data.find('-'));
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
vid = Data.substr(Data.find('-') + 1);
|
if (MaybePidVid) {
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
PID = stoi(pid);
|
|
||||||
VID = stoi(vid);
|
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
if (c.GetUnicycleID() == VID) {
|
if (c.GetUnicycleID() == VID) {
|
||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||||
// TODO: should this trigger on all vehicle deletions?
|
// TODO: should this trigger on all vehicle deletions?
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'r':
|
}
|
||||||
|
case 'r': {
|
||||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Pos = int(Data.find('-'));
|
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||||
pid = Data.substr(0, Pos++);
|
if (MaybePidVid) {
|
||||||
vid = Data.substr(Pos, Data.find(':') - Pos);
|
std::tie(PID, VID) = MaybePidVid.value();
|
||||||
|
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
|
||||||
PID = stoi(pid);
|
|
||||||
VID = stoi(vid);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
Data = Data.substr(Data.find('{'));
|
Data = Data.substr(Data.find('{'));
|
||||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
case 't':
|
case 't':
|
||||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||||
return;
|
return;
|
||||||
case 'm':
|
case 'm':
|
||||||
Network.SendToAll(&c, Packet, true, true);
|
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||||
@@ -316,23 +371,13 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|||||||
std::string VD = c.GetCarData(VID);
|
std::string VD = c.GetCarData(VID);
|
||||||
if (VD.empty()) {
|
if (VD.empty()) {
|
||||||
beammp_error("Tried to apply change to vehicle that does not exist");
|
beammp_error("Tried to apply change to vehicle that does not exist");
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("vehicle-change",
|
|
||||||
{ { "packet", Packet },
|
|
||||||
{ "vehicle-id", std::to_string(VID) },
|
|
||||||
{ "client-car-count", std::to_string(c.GetCarCount()) } });
|
|
||||||
Sentry.LogError("attempt to apply change to nonexistent vehicle", _file_basename, _line);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string Header = VD.substr(0, VD.find('{'));
|
std::string Header = VD.substr(0, VD.find('{'));
|
||||||
|
|
||||||
FoundPos = VD.find('{');
|
FoundPos = VD.find('{');
|
||||||
if (FoundPos == std::string::npos) {
|
if (FoundPos == std::string::npos) {
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
return;
|
||||||
Sentry.SetContext("vehicle-change-packet",
|
|
||||||
{ { "packet", VD } });
|
|
||||||
Sentry.LogError("malformed packet", _file_basename, _line);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
VD = VD.substr(FoundPos);
|
VD = VD.substr(FoundPos);
|
||||||
rapidjson::Document Veh, Pack;
|
rapidjson::Document Veh, Pack;
|
||||||
@@ -365,3 +410,36 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
|||||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||||
(void)mClients.insert(NewClient);
|
(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+15
-23
@@ -1,8 +1,5 @@
|
|||||||
#include "TSentry.h"
|
|
||||||
|
|
||||||
#include "ArgsParser.h"
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
#include "LuaAPI.h"
|
#include "LuaAPI.h"
|
||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
@@ -13,7 +10,6 @@
|
|||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include "TPluginMonitor.h"
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TScopedTimer.h"
|
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
@@ -56,7 +52,7 @@ int BeamMPServerMain(MainArguments Arguments);
|
|||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
MainArguments Args { argc, argv, {}, argv[0] };
|
MainArguments Args { argc, argv, {}, argv[0] };
|
||||||
Args.List.reserve(argc);
|
Args.List.reserve(size_t(argc));
|
||||||
for (int i = 1; i < argc; ++i) {
|
for (int i = 1; i < argc; ++i) {
|
||||||
Args.List.push_back(argv[i]);
|
Args.List.push_back(argv[i]);
|
||||||
}
|
}
|
||||||
@@ -66,7 +62,6 @@ int main(int argc, char** argv) {
|
|||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
||||||
beammp_error(e.what());
|
beammp_error(e.what());
|
||||||
Sentry.LogException(e, _file_basename, _line);
|
|
||||||
MainRet = -1;
|
MainRet = -1;
|
||||||
}
|
}
|
||||||
std::exit(MainRet);
|
std::exit(MainRet);
|
||||||
@@ -74,7 +69,6 @@ int main(int argc, char** argv) {
|
|||||||
|
|
||||||
int BeamMPServerMain(MainArguments Arguments) {
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
setlocale(LC_ALL, "C");
|
setlocale(LC_ALL, "C");
|
||||||
Application::InitializeConsole();
|
|
||||||
ArgsParser Parser;
|
ArgsParser Parser;
|
||||||
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||||
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||||
@@ -85,12 +79,10 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -114,11 +106,22 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TConfig Config(ConfigPath);
|
||||||
|
|
||||||
|
if (Config.Failed()) {
|
||||||
|
beammp_info("Closing in 10 seconds");
|
||||||
|
// loop to make it possible to ctrl+c instead
|
||||||
|
for (size_t i = 0; i < 20; ++i) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
Application::InitializeConsole();
|
||||||
|
Application::Console().StartLoggingToFile();
|
||||||
|
|
||||||
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||||
|
|
||||||
Application::Console().StartLoggingToFile();
|
|
||||||
|
|
||||||
SetupSignalHandlers();
|
SetupSignalHandlers();
|
||||||
|
|
||||||
bool Shutdown = false;
|
bool Shutdown = false;
|
||||||
@@ -133,25 +136,14 @@ int BeamMPServerMain(MainArguments Arguments) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
TServer Server(Arguments.List);
|
TServer Server(Arguments.List);
|
||||||
TConfig Config(ConfigPath);
|
|
||||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
LuaEngine->SetServer(&Server);
|
LuaEngine->SetServer(&Server);
|
||||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
if (Config.Failed()) {
|
|
||||||
beammp_info("Closing in 10 seconds");
|
|
||||||
// loop to make it possible to ctrl+c instead
|
|
||||||
for (size_t i = 0; i < 20; ++i) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
RegisterThread("Main");
|
RegisterThread("Main");
|
||||||
|
|
||||||
beammp_trace("Running in debug mode on a debug build");
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
Sentry.SetupUser();
|
|
||||||
Sentry.PrintWelcome();
|
|
||||||
TResourceManager ResourceManager;
|
TResourceManager ResourceManager;
|
||||||
TPPSMonitor PPSMonitor(Server);
|
TPPSMonitor PPSMonitor(Server);
|
||||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
THeartbeatThread Heartbeat(ResourceManager, Server);
|
||||||
|
|||||||
Submodule
+1
Submodule vcpkg added at 72010900b7
+19
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"version-string": "0.1.0",
|
||||||
|
"dependencies": [
|
||||||
|
"fmt",
|
||||||
|
"doctest",
|
||||||
|
"boost-asio",
|
||||||
|
"boost-variant",
|
||||||
|
"boost-spirit",
|
||||||
|
"boost-uuid",
|
||||||
|
"cpp-httplib",
|
||||||
|
"toml11",
|
||||||
|
"libzip",
|
||||||
|
"rapidjson",
|
||||||
|
"nlohmann-json",
|
||||||
|
"openssl",
|
||||||
|
"sol2"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user