mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 10:13:42 +00:00
Compare commits
413 Commits
master
...
add-region-tld
| Author | SHA1 | Date | |
|---|---|---|---|
| 8239a31e4b | |||
| 088c99beb7 | |||
| a65b8b8e4c | |||
| 58aedfb9bf | |||
| 0432309e4a | |||
| e393239fdc | |||
| 54f49d81e2 | |||
| 9bc22de9b0 | |||
| 24c83bfb40 | |||
| a008e1edc6 | |||
| 4104dc1f18 | |||
| 57fe7cb055 | |||
| 7c6acfdc86 | |||
| 06bd719dbf | |||
| 4045727c8b | |||
| c97d7b1b73 | |||
| dd6d90a986 | |||
| 8f2b8b25e8 | |||
| f820d75851 | |||
| 9ca12fc7a6 | |||
| 98fb12bbcc | |||
| 3e12e487ab | |||
| b3e8d86cef | |||
| 0c864665bb | |||
| 4bb7232a41 | |||
| 58d9f2e980 | |||
| 66f5f2b8b6 | |||
| e260de55af | |||
| 7096fe058a | |||
| 7089e5da9a | |||
| e9ce71d39a | |||
| d26e53a975 | |||
| 4da5a7440a | |||
| b1946ef1d9 | |||
| c08eefdf69 | |||
| be0d8d5334 | |||
| 1f55c35f2b | |||
| a3cfe47e78 | |||
| 58e5317687 | |||
| be6f3a2fd1 | |||
| 0ac5da2366 | |||
| b5642247a6 | |||
| a46f2d3204 | |||
| a59f7296d0 | |||
| 87e9db5382 | |||
| 7c7b7477eb | |||
| 6fca901aa2 | |||
| 7925caf1a2 | |||
| 8cdee376c6 | |||
| d56d9892c4 | |||
| 82102fcd4b | |||
| 66884920db | |||
| 5c2a0db7ef | |||
| b139a6aaad | |||
| 75e9c52ce8 | |||
| b4b262196b | |||
| 4af0e4ccac | |||
| 5d2b198fb8 | |||
| 89392a67c2 | |||
| 86a1c50c8b | |||
| d97010c8ca | |||
| 8a613e0b16 | |||
| 48d721f602 | |||
| f38797a9ab | |||
| da0089fb2e | |||
| 3befc84f00 | |||
| 595247d51d | |||
| 48a77e9ea6 | |||
| f9c85a1f35 | |||
| 168a410129 | |||
| 4926e1aebd | |||
| 1e2d8688a8 | |||
| 6f196aca64 | |||
| 99476a2c77 | |||
| 9fa9974159 | |||
| 3ef816845d | |||
| 6ec4106ec7 | |||
| b094e35f8c | |||
| 83afafc0c3 | |||
| 31122abe10 | |||
| 0615b57a37 | |||
| 4a8378427a | |||
| b74f0c7ca8 | |||
| 420c64f6cf | |||
| add45c085b | |||
| 372076a4ef | |||
| eb2deb73c1 | |||
| 21874afb87 | |||
| 184d50bf8c | |||
| c4c894c1f7 | |||
| 039a44bba5 | |||
| add0b86b37 | |||
| 403c1d5f78 | |||
| 6318ca79e7 | |||
| 2bd4ee9321 | |||
| 22c0a966bb | |||
| 731599f16e | |||
| 38c6766b2b | |||
| bcb035bafc | |||
| 068f553fa9 | |||
| ca11f353b0 | |||
| b7cf304d49 | |||
| 03d3b873c4 | |||
| ea9c808233 | |||
| 40bd050ca6 | |||
| a0d75c01f0 | |||
| 8098431fad | |||
| 40c8c0c5c2 | |||
| cd39f387c2 | |||
| a5ca50866f | |||
| 10ea0cf59e | |||
| 7db40e068e | |||
| 6053aa6192 | |||
| 0bb18de9f6 | |||
| 7a439bb5b9 | |||
| 6c3174ac08 | |||
| 73e9595d14 | |||
| 3f7cf7a258 | |||
| 093310c124 | |||
| 6286457fa4 | |||
| 71b8a61c97 | |||
| f0141e4fd3 | |||
| 00560f7646 | |||
| 27d50fc2b5 | |||
| 52a1d9a99e | |||
| 2f577a2358 | |||
| 6014536f52 | |||
| fbce8a946e | |||
| bd9b6212e2 | |||
| b112ee20d8 | |||
| 8593aeb21d | |||
| 840f9b9f9d | |||
| ec21cbbe86 | |||
| e90f1af109 | |||
| c78775bfd8 | |||
| 9c3042280d | |||
| 4f2ef3c3a7 | |||
| 6a2ee052ba | |||
| 2658d0f785 | |||
| a7eeda0569 | |||
| cd29f25435 | |||
| 7c864d94b3 | |||
| 26f1be0a51 | |||
| d7e75ae0c7 | |||
| 1d90f53527 | |||
| 7dd6b41642 | |||
| d7f3bc8b9f | |||
| 687a988701 | |||
| 9046b5a4d3 | |||
| b4d4967529 | |||
| 51c24b82fe | |||
| 5e13f9dd2d | |||
| f8d66c4336 | |||
| 9875defe86 | |||
| fc208770dd | |||
| 99a51808a0 | |||
| 1c07cf83b2 | |||
| 99136f133a | |||
| 6c9d58582b | |||
| 4edae00998 | |||
| 17e9c05f46 | |||
| 71e3cb83ae | |||
| fb2e26bd28 | |||
| 976ab68ca3 | |||
| 58a76e1df2 | |||
| c696276fc3 | |||
| 6ce0608bb3 | |||
| 52ad237419 | |||
| 71038dc617 | |||
| dc3bb517a3 | |||
| 7b2c48c8d4 | |||
| ef557ebfc4 | |||
| b2e953b92a | |||
| 576d765557 | |||
| e3416804e4 | |||
| 9ad4f61209 | |||
| aed6311146 | |||
| 5e41cefa87 | |||
| b1710ee826 | |||
| 03b0bd4d2c | |||
| 5179ac1fdc | |||
| 54e31ce2ec | |||
| 4abe9b8636 | |||
| 956d6f50e1 | |||
| 6aeb2eb736 | |||
| f40d4c1ddd | |||
| 4f052a3e0a | |||
| 2bf9e7d916 | |||
| 89c906232d | |||
| c39beb5b72 | |||
| 7dd2d89ad9 | |||
| 3403c8acba | |||
| 0a6eecee69 | |||
| cf3985ce00 | |||
| b04c5068ea | |||
| 077bb6b1cd | |||
| 0850cde1fb | |||
| 611e53b484 | |||
| f039f57f11 | |||
| 5d34090952 | |||
| 88ca17236a | |||
| a4b62d013c | |||
| 9a0270cb09 | |||
| 55f1a3c734 | |||
| bb3c762d68 | |||
| 3ade7f5743 | |||
| 9d44c2063c | |||
| 17185da53b | |||
| 623dfa17d5 | |||
| 7f69e336a9 | |||
| f08dfc0585 | |||
| a9dee2bec5 | |||
| 5319c2878a | |||
| 73f494041a | |||
| caafb216c9 | |||
| 530d605bc1 | |||
| 63b2a8e4a3 | |||
| a7a19d9a30 | |||
| 3068a0e5c4 | |||
| f70514a021 | |||
| 94768c916d | |||
| 86b37e8ae1 | |||
| 8f9db10474 | |||
| afa5a04043 | |||
| 4444be0af9 | |||
| 5f7207bc52 | |||
| 9927d2befb | |||
| 60f88916a9 | |||
| 0cc73e70c9 | |||
| bfb2086e05 | |||
| 9d67838f8f | |||
| bbfb85155e | |||
| ce5f2e666d | |||
| e076197ab2 | |||
| ee03afb9a1 | |||
| f775678e2e | |||
| 45bb6ca6f3 | |||
| f5f6b8534d | |||
| f3627ce0bf | |||
| e1aaaf5e63 | |||
| a147edd31a | |||
| 214096409d | |||
| 4a062e5aa0 | |||
| ba723ee106 | |||
| 49ed82bea1 | |||
| 0d848fda7c | |||
| a0040d8c57 | |||
| baa2c86e25 | |||
| 0950d367d4 | |||
| 8b21b6cef3 | |||
| 82a6d4af60 | |||
| 8b753ab6ea | |||
| b097acfd4a | |||
| 5baeaa72c2 | |||
| bd76e28ca6 | |||
| 012ce08b91 | |||
| 9db3619cd8 | |||
| 6f4c3f0ceb | |||
| 4fad047bf4 | |||
| 5502c74229 | |||
| eaedeb5324 | |||
| 72022e3349 | |||
| 08374b1398 | |||
| 29f4d0d286 | |||
| 3c80bcbf01 | |||
| 5919fc6f47 | |||
| 461fb5d896 | |||
| 6731b3e977 | |||
| e7c7f45039 | |||
| 0748267fab | |||
| 8c32d760be | |||
| 7919f81927 | |||
| 26ef39827e | |||
| 2451e08b01 | |||
| 25739cb1bd | |||
| 814927d0a1 | |||
| 6c0a8d1d62 | |||
| 0d3256c429 | |||
| 509225f151 | |||
| 73ecef1a87 | |||
| 28a9690a64 | |||
| 07a8d49046 | |||
| bfb0675efa | |||
| 105fd6d4c9 | |||
| a9385c47e1 | |||
| 1e9c4e357c | |||
| a998a7c091 | |||
| 277036fc52 | |||
| e776848a76 | |||
| 63fa65e9a7 | |||
| c07baeed1a | |||
| 33b5384398 | |||
| e94cfd641d | |||
| 6e590ff18a | |||
| 91bc7dea79 | |||
| 8b94b1f0ef | |||
| 5dab48af92 | |||
| f3060f5247 | |||
| c61816dfeb | |||
| 2fcb53530a | |||
| cee039d922 | |||
| 566f0b55f7 | |||
| 58a7e39419 | |||
| bf7f1ef1a5 | |||
| e35bf4fe15 | |||
| 419a951c29 | |||
| 135008a73c | |||
| 29c3fed374 | |||
| 93192fd9b5 | |||
| eea041e8eb | |||
| a3670bff4a | |||
| 1b60e89f26 | |||
| 06e5805428 | |||
| 04e8d00daa | |||
| d30dccc94a | |||
| 84f5f95e54 | |||
| 67db9358e1 | |||
| fd2f713485 | |||
| c880460a55 | |||
| 7f54bcfaec | |||
| 785c5343cd | |||
| 40e5496819 | |||
| 4c9fbc250a | |||
| 31ce0cc7de | |||
| 3a8f4ded29 | |||
| f567645db6 | |||
| 3609fd77ec | |||
| a5e3fc8fb9 | |||
| bcd4b5a235 | |||
| 8c15b87628 | |||
| 13e641b3a3 | |||
| 5f9726f10f | |||
| fcd408970b | |||
| cf5ebcbd1a | |||
| c9d926f9e3 | |||
| 9f47978f0f | |||
| a0f649288e | |||
| b995a222ff | |||
| c5dff8b913 | |||
| 0c740ccedf | |||
| b0cf5c7838 | |||
| 586510041d | |||
| 1794c3fe45 | |||
| ee599e970d | |||
| 40158dc252 | |||
| 5ece60574a | |||
| ff812429ed | |||
| 639c46ad36 | |||
| 158875a962 | |||
| c6dac55679 | |||
| 37109ae3f1 | |||
| d6b78b9683 | |||
| f5e2f7425f | |||
| 8693b8a2b0 | |||
| 3989961ff9 | |||
| a357ff8ca3 | |||
| 86f0052e07 | |||
| 89034a64e0 | |||
| 55f5437618 | |||
| c605498a2d | |||
| 4d7967d5d9 | |||
| 5dd4c97ed1 | |||
| 13390c5388 | |||
| 2f995a71ae | |||
| 3b5c6491a3 | |||
| db8719b5cd | |||
| a3c4b82a5d | |||
| 3b0e49fb06 | |||
| cf8f10b949 | |||
| 6f50cad76b | |||
| 03d91b1f4d | |||
| e407d246e2 | |||
| 234bdf5877 | |||
| c3b4528c89 | |||
| 5cf6d1d228 | |||
| 65017d0834 | |||
| 1237e7e533 | |||
| d81087b5af | |||
| 7e1f86478d | |||
| c85e026c2d | |||
| e4826e8bf1 | |||
| 590b159f14 | |||
| 40533c04bc | |||
| 946c1362e1 | |||
| 4347cb4af2 | |||
| 88721d4f7f | |||
| 7deea900fb | |||
| cbc1483537 | |||
| e2d7721438 | |||
| 0146a1cbe8 | |||
| 352a3aa536 | |||
| ac8c386c61 | |||
| d1fb15fc9a | |||
| f376d9f7be | |||
| 2f3dcfeb5a | |||
| 913ba1c793 | |||
| 9a0c9d3ce4 | |||
| a0d9be18b7 | |||
| 87d2e3355a | |||
| afb3763eab | |||
| 9de5a08b0c | |||
| bef623a281 | |||
| e852245bae | |||
| 5f5af9b0a7 | |||
| 64f2e08ed2 | |||
| 707682f4a8 | |||
| 913674740d | |||
| 1c575ff1bc | |||
| e72c217e63 | |||
| 75bae8ee5a | |||
| acc2dd29e9 | |||
| 39badf432d | |||
| 03307e71fb |
@@ -0,0 +1 @@
|
||||
patreon: BeamMP
|
||||
@@ -0,0 +1,6 @@
|
||||
Please replace this text <-> with your PR description and leave the below declarations intact.
|
||||
|
||||
---
|
||||
|
||||
By creating this pull request, I understand that code that is AI generated or otherwise automatically generated may be rejected without further discussion.
|
||||
I declare that I fully understand all code I pushed into this PR, and wrote all this code myself and own the rights to this code.
|
||||
+24
-19
@@ -1,9 +1,13 @@
|
||||
name: Linux
|
||||
|
||||
on: [push]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "develop"
|
||||
- "minor"
|
||||
pull_request:
|
||||
|
||||
|
||||
env:
|
||||
env:
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
@@ -15,20 +19,20 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- distro: debian
|
||||
version: 11
|
||||
- distro: debian
|
||||
version: 12
|
||||
- distro: debian
|
||||
version: 13
|
||||
- distro: ubuntu
|
||||
version: 22.04
|
||||
- distro: ubuntu
|
||||
version: 20.04
|
||||
version: 24.04
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -43,7 +47,8 @@ jobs:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
submodules: "recursive"
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
@@ -59,13 +64,13 @@ jobs:
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
path: ./bin/BeamMP-Server
|
||||
|
||||
- name: Archive server debug info artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
path: ./bin/BeamMP-Server.debug
|
||||
@@ -80,26 +85,26 @@ jobs:
|
||||
run: ./bin/BeamMP-Server-tests
|
||||
|
||||
arm64-matrix:
|
||||
runs-on: [Linux, ARM64]
|
||||
runs-on: ubuntu-22.04-arm
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- distro: debian
|
||||
version: 11
|
||||
- distro: debian
|
||||
version: 12
|
||||
- distro: debian
|
||||
version: 13
|
||||
- distro: ubuntu
|
||||
version: 22.04
|
||||
- distro: ubuntu
|
||||
version: 20.04
|
||||
version: 24.04
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -114,7 +119,8 @@ jobs:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
submodules: "recursive"
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
@@ -130,13 +136,13 @@ jobs:
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
path: ./bin/BeamMP-Server
|
||||
|
||||
- name: Archive server debug info artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
path: ./bin/BeamMP-Server.debug
|
||||
@@ -149,4 +155,3 @@ jobs:
|
||||
|
||||
- name: Test
|
||||
run: ./bin/BeamMP-Server-tests
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ on:
|
||||
push:
|
||||
# Sequence of patterns matched against refs/tags
|
||||
tags:
|
||||
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||
- "v*" # Push events to matching v*, i.e. v1.0, v20.15.10
|
||||
|
||||
env:
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
@@ -14,8 +14,8 @@ jobs:
|
||||
create-release:
|
||||
runs-on: ubuntu-latest
|
||||
name: Create Release
|
||||
outputs:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
outputs:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
steps:
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
@@ -38,20 +38,20 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- distro: debian
|
||||
version: 11
|
||||
- distro: debian
|
||||
version: 12
|
||||
- distro: debian
|
||||
version: 13
|
||||
- distro: ubuntu
|
||||
version: 22.04
|
||||
- distro: ubuntu
|
||||
version: 20.04
|
||||
version: 24.04
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -66,7 +66,8 @@ jobs:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
submodules: "recursive"
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
@@ -82,7 +83,7 @@ jobs:
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -104,19 +105,19 @@ jobs:
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
arm64-matrix:
|
||||
runs-on: [Linux, ARM64]
|
||||
runs-on: ubuntu-22.04-arm
|
||||
needs: create-release
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- distro: debian
|
||||
version: 11
|
||||
- distro: debian
|
||||
version: 12
|
||||
- distro: debian
|
||||
version: 13
|
||||
- distro: ubuntu
|
||||
version: 22.04
|
||||
- distro: ubuntu
|
||||
version: 20.04
|
||||
version: 24.04
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
|
||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||
@@ -125,7 +126,7 @@ jobs:
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -140,7 +141,8 @@ jobs:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
submodules: "recursive"
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
@@ -156,7 +158,7 @@ jobs:
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -193,7 +195,8 @@ jobs:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
submodules: "recursive"
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Create Build Environment
|
||||
shell: bash
|
||||
@@ -204,7 +207,7 @@ jobs:
|
||||
run: bash ./scripts/windows/2-build.sh
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
id: upload-release-asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
name: Windows
|
||||
|
||||
on: [push]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'develop'
|
||||
- 'minor'
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||
@@ -21,6 +26,7 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
@@ -36,7 +42,7 @@ jobs:
|
||||
run: bash ./scripts/windows/2-build.sh
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BeamMP-Server-windows
|
||||
path: ./bin/Release/BeamMP-Server.exe
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.idea/
|
||||
.sentry-native/
|
||||
*.orig
|
||||
*.toml
|
||||
boost_*
|
||||
|
||||
@@ -4,3 +4,6 @@
|
||||
[submodule "vcpkg"]
|
||||
path = vcpkg
|
||||
url = https://github.com/Microsoft/vcpkg.git
|
||||
[submodule "deps/toml11"]
|
||||
path = deps/toml11
|
||||
url = https://github.com/ToruNiina/toml11
|
||||
|
||||
+31
-8
@@ -8,7 +8,7 @@ include(cmake/Vcpkg.cmake) # needs to happen before project()
|
||||
|
||||
project(
|
||||
"BeamMP-Server" # replace this
|
||||
VERSION 3.3.0
|
||||
VERSION 3.9.3
|
||||
)
|
||||
|
||||
include(cmake/StandardSettings.cmake)
|
||||
@@ -20,7 +20,7 @@ include(cmake/Git.cmake)
|
||||
### SETTINGS ###
|
||||
|
||||
# add all headers (.h, .hpp) to this
|
||||
set(PRJ_HEADERS
|
||||
set(PRJ_HEADERS
|
||||
include/ArgsParser.h
|
||||
include/BoostAliases.h
|
||||
include/Client.h
|
||||
@@ -39,6 +39,7 @@ set(PRJ_HEADERS
|
||||
include/TConfig.h
|
||||
include/TConsole.h
|
||||
include/THeartbeatThread.h
|
||||
include/TIoPollThread.h
|
||||
include/TLuaEngine.h
|
||||
include/TLuaPlugin.h
|
||||
include/TNetwork.h
|
||||
@@ -49,6 +50,12 @@ set(PRJ_HEADERS
|
||||
include/TServer.h
|
||||
include/VehicleData.h
|
||||
include/Env.h
|
||||
include/Settings.h
|
||||
include/Profiling.h
|
||||
include/ChronoWrapper.h
|
||||
include/TConnectionLimiter.h
|
||||
include/TLuaResult.h
|
||||
include/RegionHandler.h
|
||||
)
|
||||
# add all source files (.cpp) to this, except the one with main()
|
||||
set(PRJ_SOURCES
|
||||
@@ -62,6 +69,7 @@ set(PRJ_SOURCES
|
||||
src/TConfig.cpp
|
||||
src/TConsole.cpp
|
||||
src/THeartbeatThread.cpp
|
||||
src/TIoPollThread.cpp
|
||||
src/TLuaEngine.cpp
|
||||
src/TLuaPlugin.cpp
|
||||
src/TNetwork.cpp
|
||||
@@ -72,6 +80,12 @@ set(PRJ_SOURCES
|
||||
src/TServer.cpp
|
||||
src/VehicleData.cpp
|
||||
src/Env.cpp
|
||||
src/Settings.cpp
|
||||
src/Profiling.cpp
|
||||
src/ChronoWrapper.cpp
|
||||
src/TConnectionLimiter.cpp
|
||||
src/TLuaResult.cpp
|
||||
src/RegionHandler.cpp
|
||||
)
|
||||
|
||||
find_package(Lua REQUIRED)
|
||||
@@ -87,7 +101,7 @@ 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
|
||||
set(PRJ_LIBRARIES
|
||||
fmt::fmt
|
||||
doctest::doctest
|
||||
Threads::Threads
|
||||
@@ -98,6 +112,7 @@ set(PRJ_LIBRARIES
|
||||
httplib::httplib
|
||||
libzip::zip
|
||||
OpenSSL::SSL OpenSSL::Crypto
|
||||
CURL::libcurl
|
||||
${LUA_LIBRARIES}
|
||||
)
|
||||
|
||||
@@ -110,7 +125,8 @@ find_package(httplib CONFIG REQUIRED)
|
||||
find_package(libzip CONFIG REQUIRED)
|
||||
find_package(RapidJSON CONFIG REQUIRED)
|
||||
find_package(sol2 CONFIG REQUIRED)
|
||||
find_package(toml11 CONFIG REQUIRED)
|
||||
find_package(CURL CONFIG REQUIRED)
|
||||
add_subdirectory("deps/toml11")
|
||||
|
||||
include_directories(include)
|
||||
|
||||
@@ -119,7 +135,7 @@ include(FindThreads)
|
||||
|
||||
### END SETTINGS ###
|
||||
|
||||
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||
# 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.
|
||||
|
||||
####################
|
||||
@@ -140,7 +156,9 @@ if(UNIX)
|
||||
endif(UNIX)
|
||||
|
||||
if (WIN32)
|
||||
add_compile_options("-D_WIN32_WINNT=0x0601")
|
||||
add_compile_definitions(_WIN32_WINNT=0x0A00)
|
||||
|
||||
add_compile_options("/bigobj")
|
||||
endif(WIN32)
|
||||
|
||||
|
||||
@@ -157,7 +175,7 @@ set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
||||
)
|
||||
|
||||
# build commandline manually for funky windows flags to carry over without a custom toolchain file
|
||||
add_library(commandline_static
|
||||
add_library(commandline_static
|
||||
deps/commandline/src/impls.h
|
||||
deps/commandline/src/windows_impl.cpp
|
||||
deps/commandline/src/linux_impl.cpp
|
||||
@@ -170,6 +188,11 @@ add_library(commandline_static
|
||||
deps/commandline/src/backends/BufferedBackend.cpp
|
||||
deps/commandline/src/backends/BufferedBackend.h
|
||||
)
|
||||
|
||||
# Ensure the commandline library uses C++11
|
||||
set_target_properties(commandline_static PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED YES)
|
||||
|
||||
|
||||
if (WIN32)
|
||||
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
|
||||
else ()
|
||||
@@ -194,6 +217,7 @@ target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARN
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(${PROJECT_NAME} PUBLIC "/bigobj")
|
||||
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||
endif(MSVC)
|
||||
|
||||
@@ -212,4 +236,3 @@ if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
|
||||
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
|
||||
endif(MSVC)
|
||||
endif()
|
||||
|
||||
|
||||
+22
-5
@@ -53,11 +53,28 @@ Do **NOT** pull with merge. This is the default git behavior for `git pull`, but
|
||||
|
||||
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.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Making an issue and fixing it
|
||||
|
||||
1. Create an issue detailing the feature or bug.
|
||||
2. Assign a milestone to the issue, or wait for a maintainer to add a milestone to your issue.
|
||||
3. Fork the repository and base your work on the branch mentioned in the milestone attached to your issue (e.g. `v3.0.0 (develop)` -> `develop`).
|
||||
4. Program your feature or bug fix.
|
||||
5. Open a PR that references the issue by number in the format: `#12345`.
|
||||
6. Someone will review your PR and merge it, or ask for changes.
|
||||
|
||||
### Fixing an existing issue
|
||||
|
||||
1. Fork the repository and base your work on the branch mentioned in the milestone attached to your issue (e.g. `v3.0.0 (develop)` -> `develop`).
|
||||
2. Program your feature or bug fix.
|
||||
3. Open a PR that references the issue by number in the format: `#12345`.
|
||||
4. Someone will review your PR and merge it, or ask for changes.
|
||||
|
||||
## 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`.
|
||||
- `minor`: Minor releases, like `v1.2.3` -> `v1.3.0` or `v1.2.3` -> `v1.2.4`.
|
||||
- `develop`: Major releases, like `v1.2.3` -> `v2.0.0`, and larger feature/minor releases.
|
||||
|
||||
## Unit tests & CI/CD
|
||||
|
||||
@@ -91,8 +108,8 @@ A BeamMP-Developer must review your code in detail, and leave a review. If this
|
||||
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` .
|
||||
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`. An example invocation on Linux with GNU make would be
|
||||
`cmake . -DCMAKE_BUILD_TYPE=Debug` .
|
||||
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`).
|
||||
|
||||
@@ -19,7 +19,7 @@ Feel free to ask any questions via the following channels:
|
||||
|
||||
These values are guesstimated and are subject to change with each release.
|
||||
|
||||
* RAM: 50+ MiB usable (not counting OS overhead)
|
||||
* RAM: 30-100 MiB usable (not counting OS overhead)
|
||||
* CPU: >1GHz, preferably multicore
|
||||
* OS: Windows, Linux (theoretically any POSIX)
|
||||
* GPU: None
|
||||
@@ -38,7 +38,7 @@ If you need support with understanding the codebase, please write us in the Disc
|
||||
|
||||
## 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 `v3.1.0`.
|
||||
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.4.1`. See [the tags](https://github.com/BeamMP/BeamMP-Server/tags) for possible versions/tags, as well as [the releases](https://github.com/BeamMP/BeamMP-Server/releases) to check which version is marked as a release/prerelease. We recommend using the [latest release](https://github.com/BeamMP/BeamMP-Server/releases/latest).
|
||||
|
||||
## Supported Operating Systems
|
||||
|
||||
@@ -66,9 +66,10 @@ You can build on **Windows, Linux** or other platforms by following these steps:
|
||||
|
||||
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
||||
2. Go into the directory `cd BeamMP-Server`.
|
||||
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
|
||||
4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
|
||||
5. Your executable can be found in `bin/`.
|
||||
3. Specify the server version to build by checking out a tag: `git checkout tags/v3.4.1` - [Possible versions/tags](https://github.com/BeamMP/BeamMP-Server/tags)
|
||||
4. 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.
|
||||
5. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
|
||||
6. Your executable can be found in `bin/`.
|
||||
|
||||
When you make changes to the code, you only have to run step 4 again.
|
||||
### Building for FreeBSD
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
# 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
|
||||
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||
# strictly required.
|
||||
|
||||
function(set_project_warnings project_name)
|
||||
@@ -73,7 +73,6 @@ function(set_project_warnings project_name)
|
||||
-Werror=missing-declarations
|
||||
-Werror=missing-field-initializers
|
||||
-Werror=ctor-dtor-privacy
|
||||
-Werror=switch-enum
|
||||
-Wswitch-default
|
||||
-Werror=unused-result
|
||||
-Werror=implicit-fallthrough
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ 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
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
|
||||
@@ -15,3 +15,5 @@ if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
|
||||
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||
endif()
|
||||
|
||||
# ensure SOL2 safeties are all ON
|
||||
add_compile_definitions(SOL_ALL_SAFETIES_ON=1)
|
||||
|
||||
Vendored
+1
-1
Submodule deps/commandline updated: b2a29733f9...04952e4811
+1
Submodule deps/toml11 added at f33ca743fb
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace ChronoWrapper {
|
||||
std::chrono::high_resolution_clock::duration TimeFromStringWithLiteral(const std::string& time_str);
|
||||
}
|
||||
+25
-13
@@ -18,12 +18,14 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include "BoostAliases.h"
|
||||
#include "Common.h"
|
||||
@@ -56,27 +58,27 @@ public:
|
||||
~TClient();
|
||||
TClient& operator=(const TClient&) = delete;
|
||||
|
||||
void AddNewCar(int Ident, const std::string& Data);
|
||||
void SetCarData(int Ident, const std::string& Data);
|
||||
void AddNewCar(int Ident, const nlohmann::json& Data);
|
||||
void SetCarData(int Ident, const nlohmann::json& Data);
|
||||
void SetCarPosition(int Ident, const std::string& Data);
|
||||
TVehicleDataLockPair GetAllCars();
|
||||
void SetName(const std::string& Name) { mName = Name; }
|
||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||
std::string GetCarData(int Ident);
|
||||
nlohmann::json GetCarData(int Ident);
|
||||
std::string GetCarPositionRaw(int Ident);
|
||||
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
||||
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
||||
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
||||
void Disconnect(std::string_view Reason);
|
||||
bool IsDisconnected() const { return !mSocket.is_open(); }
|
||||
// Returns true only for the thread that actually performs socket shutdown/close.
|
||||
[[nodiscard]] bool Disconnect(std::string_view Reason);
|
||||
bool IsDisconnected() const {
|
||||
return mDisconnectState.load(std::memory_order_acquire) != EDisconnectState::Connected;
|
||||
}
|
||||
// locks
|
||||
void DeleteCar(int Ident);
|
||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
||||
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
||||
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
||||
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
||||
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
||||
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||
@@ -88,7 +90,7 @@ public:
|
||||
void ClearCars();
|
||||
[[nodiscard]] int GetID() const { return mID; }
|
||||
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
|
||||
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
|
||||
[[nodiscard]] bool IsUDPConnected() const { return mIsUDPConnected; }
|
||||
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
|
||||
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
|
||||
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
|
||||
@@ -100,16 +102,24 @@ public:
|
||||
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
|
||||
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
|
||||
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
|
||||
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
|
||||
void SetIsUDPConnected(bool NewIsConnected) { mIsUDPConnected = NewIsConnected; }
|
||||
[[nodiscard]] TServer& Server() const;
|
||||
void UpdatePingTime();
|
||||
int SecondsSinceLastPing();
|
||||
void SetMagic(std::vector<uint8_t> magic) { mMagic = std::move(magic); }
|
||||
[[nodiscard]] const std::vector<uint8_t>& GetMagic() const { return mMagic; }
|
||||
|
||||
private:
|
||||
enum class EDisconnectState {
|
||||
Connected,
|
||||
Disconnecting,
|
||||
Disconnected
|
||||
};
|
||||
|
||||
void InsertVehicle(int ID, const std::string& Data);
|
||||
|
||||
TServer& mServer;
|
||||
bool mIsConnected = false;
|
||||
bool mIsUDPConnected = false;
|
||||
bool mIsSynced = false;
|
||||
bool mIsSyncing = false;
|
||||
mutable std::mutex mMissedPacketsMutex;
|
||||
@@ -121,14 +131,16 @@ private:
|
||||
TSetOfVehicleData mVehicleData;
|
||||
SparseArray<std::string> mVehiclePosition;
|
||||
std::string mName = "Unknown Client";
|
||||
// Once disconnect starts, this client is terminal and its socket must be treated as dead.
|
||||
std::atomic<EDisconnectState> mDisconnectState { EDisconnectState::Connected };
|
||||
ip::tcp::socket mSocket;
|
||||
ip::tcp::socket mDownSocket;
|
||||
ip::udp::endpoint mUDPAddress {};
|
||||
int mUnicycleID = -1;
|
||||
std::string mRole;
|
||||
std::string mDID;
|
||||
int mID = -1;
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||
std::vector<uint8_t> mMagic;
|
||||
};
|
||||
|
||||
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
||||
|
||||
+39
-98
@@ -18,6 +18,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
@@ -28,6 +29,7 @@
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <span>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <zlib.h>
|
||||
@@ -36,6 +38,7 @@
|
||||
#include <filesystem>
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
#include "Settings.h"
|
||||
#include "TConsole.h"
|
||||
|
||||
struct Version {
|
||||
@@ -58,32 +61,6 @@ using SparseArray = std::unordered_map<size_t, T>;
|
||||
class Application final {
|
||||
public:
|
||||
// types
|
||||
struct TSettings {
|
||||
std::string ServerName { "BeamMP Server" };
|
||||
std::string ServerDesc { "BeamMP Default Description" };
|
||||
std::string ServerTags { "Freeroam" };
|
||||
std::string Resource { "Resources" };
|
||||
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||
std::string Key {};
|
||||
std::string Password{};
|
||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||
bool HTTPServerEnabled { false };
|
||||
int MaxPlayers { 8 };
|
||||
bool Private { true };
|
||||
int MaxCars { 1 };
|
||||
bool DebugModeEnabled { false };
|
||||
int Port { 30814 };
|
||||
std::string CustomIP {};
|
||||
bool LogChat { true };
|
||||
bool SendErrors { true };
|
||||
bool SendErrorsMessageEnabled { true };
|
||||
int HTTPServerPort { 8080 };
|
||||
std::string HTTPServerIP { "127.0.0.1" };
|
||||
bool HTTPServerUseSSL { false };
|
||||
bool HideUpdateMessages { false };
|
||||
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||
};
|
||||
|
||||
using TShutdownHandler = std::function<void()>;
|
||||
|
||||
@@ -97,22 +74,18 @@ public:
|
||||
static TConsole& Console() { return mConsole; }
|
||||
static std::string ServerVersionString();
|
||||
static const Version& ServerVersion() { return mVersion; }
|
||||
static uint8_t ClientMajorVersion() { return 2; }
|
||||
static Version ClientMinimumVersion() { return Version { 2, 7, 0 }; }
|
||||
static std::string PPS() { return mPPS; }
|
||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||
|
||||
static TSettings Settings;
|
||||
static inline struct Settings Settings { };
|
||||
|
||||
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||
return {
|
||||
"backend.beammp.com",
|
||||
"backup1.beammp.com",
|
||||
"backup2.beammp.com"
|
||||
};
|
||||
}
|
||||
static std::vector<std::string> GetBackendUrlsInOrder();
|
||||
|
||||
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
||||
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
||||
static std::string GetServerCheckUrl();
|
||||
|
||||
static std::string GetBackendUrlForAuth();
|
||||
static std::string GetBackendUrlForSocketIO();
|
||||
static void CheckForUpdates();
|
||||
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
||||
static bool IsOutdated(const Version& Current, const Version& Newest);
|
||||
@@ -151,11 +124,18 @@ private:
|
||||
static inline bool mShutdown { false };
|
||||
static inline std::mutex mShutdownHandlersMutex {};
|
||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||
static inline int mTLDIndex { 0 };
|
||||
static inline std::vector<std::string> mValidTLDs {"beammp.com", "beammp.ru"};
|
||||
|
||||
static inline Version mVersion { 3, 2, 2 };
|
||||
static inline Version mVersion { 3, 9, 3 };
|
||||
};
|
||||
|
||||
/// Used to static_assert in std::visit
|
||||
template<class>
|
||||
inline constexpr bool AlwaysFalseV = false;
|
||||
|
||||
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
|
||||
std::string LowerString(std::string str);
|
||||
|
||||
std::string ThreadName(bool DebugModeOverride = false);
|
||||
void RegisterThread(const std::string& str);
|
||||
@@ -164,7 +144,6 @@ void RegisterThread(const std::string& str);
|
||||
#define KB 1024llu
|
||||
#define MB (KB * 1024llu)
|
||||
#define GB (MB * 1024llu)
|
||||
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||
|
||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||
#define _line std::to_string(__LINE__)
|
||||
@@ -187,13 +166,13 @@ void RegisterThread(const std::string& str);
|
||||
#else
|
||||
#define _function_name std::string(__func__)
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef NDEBUG
|
||||
#define DEBUG
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(DEBUG)
|
||||
|
||||
|
||||
// if this is defined, we will show the full function signature infront of
|
||||
// each info/debug/warn... call instead of the 'filename:line' format.
|
||||
#if defined(BMP_FULL_FUNCTION_NAMES)
|
||||
@@ -203,7 +182,7 @@ void RegisterThread(const std::string& str);
|
||||
#endif
|
||||
|
||||
#endif // defined(DEBUG)
|
||||
|
||||
|
||||
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
||||
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
||||
#define beammp_error(x) \
|
||||
@@ -214,6 +193,10 @@ void RegisterThread(const std::string& str);
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
||||
} while (false)
|
||||
#define beammp_lua_log(level, plugin, x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + fmt::format("[{}] [{}] ", plugin, level) + (x)); \
|
||||
} while (false)
|
||||
#define beammp_lua_warn(x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||
@@ -221,13 +204,13 @@ void RegisterThread(const std::string& str);
|
||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||
#define beammp_debug(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
#define beammp_event(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
||||
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
@@ -235,14 +218,14 @@ void RegisterThread(const std::string& str);
|
||||
#if defined(DEBUG)
|
||||
#define beammp_trace(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) { \
|
||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
#else
|
||||
#define beammp_trace(x)
|
||||
#endif // defined(DEBUG)
|
||||
|
||||
|
||||
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||
@@ -269,6 +252,7 @@ void RegisterThread(const std::string& str);
|
||||
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_log(level, plugin, x) /* x */
|
||||
|
||||
#endif // DOCTEST_CONFIG_DISABLE
|
||||
|
||||
@@ -283,57 +267,14 @@ void RegisterThread(const std::string& str);
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||
|
||||
#define Biggest 30000
|
||||
|
||||
template <typename T>
|
||||
inline T Comp(const T& Data) {
|
||||
std::array<char, Biggest> C {};
|
||||
// obsolete
|
||||
C.fill(0);
|
||||
z_stream defstream;
|
||||
defstream.zalloc = nullptr;
|
||||
defstream.zfree = nullptr;
|
||||
defstream.opaque = nullptr;
|
||||
defstream.avail_in = uInt(Data.size());
|
||||
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
size_t TotalOut = defstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T DeComp(const T& Compressed) {
|
||||
std::array<char, Biggest> C {};
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = nullptr;
|
||||
infstream.zfree = nullptr;
|
||||
infstream.opaque = nullptr;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
size_t TotalOut = infstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
std::vector<uint8_t> Comp(std::span<const uint8_t> input);
|
||||
std::vector<uint8_t> DeComp(std::span<const uint8_t> input);
|
||||
|
||||
std::string GetPlatformAgnosticErrorString();
|
||||
#define S_DSN SU_RAW
|
||||
|
||||
class InvalidDataError : std::runtime_error {
|
||||
public:
|
||||
InvalidDataError() : std::runtime_error("Invalid data") {
|
||||
}
|
||||
};
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
#include <thread>
|
||||
|
||||
#include "Common.h"
|
||||
#include "Compat.h"
|
||||
|
||||
static const char* const ANSI_RESET = "\u001b[0m";
|
||||
|
||||
@@ -56,7 +57,7 @@ static const char* const ANSI_WHITE_BOLD = "\u001b[37;1m";
|
||||
static const char* const ANSI_BOLD = "\u001b[1m";
|
||||
static const char* const ANSI_UNDERLINE = "\u001b[4m";
|
||||
|
||||
#ifdef DEBUG
|
||||
#if defined(DEBUG) && !defined(BEAMMP_FREEBSD)
|
||||
#include <iostream>
|
||||
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
|
||||
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
|
||||
@@ -81,8 +82,8 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
||||
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
||||
} \
|
||||
} while (false)
|
||||
#define beammp_assert_not_reachable() \
|
||||
do { \
|
||||
#define beammp_assert_not_reachable() \
|
||||
do { \
|
||||
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||
} while (false)
|
||||
#endif // DEBUG
|
||||
|
||||
@@ -25,6 +25,10 @@ namespace Env {
|
||||
enum class Key {
|
||||
// provider settings
|
||||
PROVIDER_UPDATE_MESSAGE,
|
||||
PROVIDER_DISABLE_CONFIG,
|
||||
PROVIDER_DISABLE_MP_SET,
|
||||
PROVIDER_PORT_ENV,
|
||||
PROVIDER_IP_ENV
|
||||
};
|
||||
|
||||
std::optional<std::string> Get(Key key);
|
||||
|
||||
+3
-2
@@ -23,6 +23,7 @@
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <curl/curl.h>
|
||||
|
||||
#if defined(BEAMMP_LINUX)
|
||||
#pragma GCC diagnostic push
|
||||
@@ -38,8 +39,8 @@
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Http {
|
||||
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
||||
std::string POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const httplib::Headers& headers = {});
|
||||
std::string GET(const std::string& url, unsigned int* status = nullptr);
|
||||
std::string POST(const std::string& url, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const std::map<std::string, std::string>& headers = {});
|
||||
namespace Status {
|
||||
std::string ToString(int code);
|
||||
}
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
#include "rapidjson/prettywriter.h"
|
||||
#include "rapidjson/document.h"
|
||||
#include "rapidjson/prettywriter.h"
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
#include "rapidjson/writer.h"
|
||||
|
||||
+4
-1
@@ -34,9 +34,12 @@ namespace MP {
|
||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message, const bool& LogChat = true);
|
||||
std::pair<bool, std::string> SendNotification(int ID, const std::string& Message, const std::string& Icon, const std::string& Category);
|
||||
std::pair<bool, std::string> ConfirmationDialog(int ID, const std::string& Title, const std::string& Body, const sol::table& buttons, const std::string& InteractionID, const bool& warning = false, const bool& reportToServer = true, const bool& reportToExtensions = true);
|
||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||
void Set(int ConfigID, sol::object NewValue);
|
||||
TLuaValue Get(int ConfigID);
|
||||
bool IsPlayerGuest(int ID);
|
||||
bool IsPlayerConnected(int ID);
|
||||
void Sleep(size_t Ms);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <unordered_map>
|
||||
|
||||
#undef max
|
||||
#undef min
|
||||
|
||||
namespace prof {
|
||||
|
||||
using Duration = std::chrono::duration<double, std::milli>;
|
||||
using TimePoint = std::chrono::high_resolution_clock::time_point;
|
||||
|
||||
/// Returns the current time.
|
||||
TimePoint now();
|
||||
|
||||
/// Returns a sub-millisecond resolution duration between start and end.
|
||||
Duration duration(const TimePoint& start, const TimePoint& end);
|
||||
|
||||
struct Stats {
|
||||
double mean;
|
||||
double stdev;
|
||||
double min;
|
||||
double max;
|
||||
size_t n;
|
||||
};
|
||||
|
||||
/// Calculates and stores the moving average over K samples of execution time data
|
||||
/// for some single unit of code. Threadsafe.
|
||||
struct UnitExecutionTime {
|
||||
UnitExecutionTime();
|
||||
|
||||
/// Adds a sample to the collection, overriding the oldest sample if needed.
|
||||
void add_sample(const Duration& dur);
|
||||
|
||||
/// Calculates the mean duration over the `measurement_count()` measurements,
|
||||
/// as well as the standard deviation.
|
||||
Stats stats() const;
|
||||
|
||||
/// Returns the number of elements the moving average is calculated over.
|
||||
size_t measurement_count() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex m_mtx {};
|
||||
size_t m_total_calls {};
|
||||
double m_sum {};
|
||||
// sum of measurements squared (for running stdev)
|
||||
double m_measurement_sqr_sum {};
|
||||
double m_min { std::numeric_limits<double>::max() };
|
||||
double m_max { std::numeric_limits<double>::min() };
|
||||
};
|
||||
|
||||
/// Holds profiles for multiple units by name. Threadsafe.
|
||||
struct UnitProfileCollection {
|
||||
/// Adds a sample to the collection, overriding the oldest sample if needed.
|
||||
void add_sample(const std::string& unit, const Duration& duration);
|
||||
|
||||
/// Calculates the mean duration over the `measurement_count()` measurements,
|
||||
/// as well as the standard deviation.
|
||||
Stats stats(const std::string& unit);
|
||||
|
||||
/// Returns the number of elements the moving average is calculated over.
|
||||
size_t measurement_count(const std::string& unit);
|
||||
|
||||
/// Returns the stats for all stored units.
|
||||
std::unordered_map<std::string, Stats> all_stats();
|
||||
|
||||
private:
|
||||
boost::synchronized_value<std::unordered_map<std::string, UnitExecutionTime>> m_map;
|
||||
};
|
||||
|
||||
}
|
||||
+1
-1
@@ -23,8 +23,8 @@
|
||||
* and write locks and read locks are mutually exclusive.
|
||||
*/
|
||||
|
||||
#include <shared_mutex>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
|
||||
// Use ReadLock(m) and WriteLock(m) to lock it.
|
||||
using RWMutex = std::shared_mutex;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <array>
|
||||
|
||||
class RegionHandler final {
|
||||
public:
|
||||
RegionHandler() = delete;
|
||||
static void TopLevelDomainFailed();
|
||||
static std::string RegionToTopLevelDomain();
|
||||
private:
|
||||
static inline unsigned int mRegionIndex { 0 };
|
||||
const static inline std::array<std::string, 2> mValidTLDs {"beammp.com", "beammp.ru"};
|
||||
};
|
||||
@@ -0,0 +1,145 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
#include "Sync.h"
|
||||
#include <concepts>
|
||||
#include <cstdint>
|
||||
#include <doctest/doctest.h>
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/format.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
|
||||
struct ComposedKey {
|
||||
std::string Category;
|
||||
std::string Key;
|
||||
|
||||
bool operator==(const ComposedKey& rhs) const {
|
||||
return (this->Category == rhs.Category && this->Key == rhs.Key);
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct fmt::formatter<ComposedKey> : formatter<std::string> {
|
||||
auto format(ComposedKey key, format_context& ctx) const;
|
||||
};
|
||||
|
||||
inline auto fmt::formatter<ComposedKey>::format(ComposedKey key, fmt::format_context& ctx) const {
|
||||
std::string key_metadata = fmt::format("{}::{}", key.Category, key.Key);
|
||||
return formatter<std::string>::format(key_metadata, ctx);
|
||||
}
|
||||
|
||||
namespace std {
|
||||
template <>
|
||||
class hash<ComposedKey> {
|
||||
public:
|
||||
std::uint64_t operator()(const ComposedKey& key) const {
|
||||
std::hash<std::string> hash_fn;
|
||||
return hash_fn(key.Category + key.Key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
struct Settings {
|
||||
using SettingsTypeVariant = std::variant<std::string, bool, int>;
|
||||
|
||||
Settings();
|
||||
|
||||
enum Key {
|
||||
// Keys that correspond to the keys set in TOML
|
||||
// Keys have their TOML section name as prefix
|
||||
|
||||
// [Misc]
|
||||
Misc_ImScaredOfUpdates,
|
||||
Misc_UpdateReminderTime,
|
||||
|
||||
// [General]
|
||||
General_Description,
|
||||
General_Tags,
|
||||
General_MaxPlayers,
|
||||
General_Name,
|
||||
General_Map,
|
||||
General_AuthKey,
|
||||
General_Private,
|
||||
General_IP,
|
||||
General_Port,
|
||||
General_MaxCars,
|
||||
General_LogChat,
|
||||
General_ResourceFolder,
|
||||
General_Debug,
|
||||
General_AllowGuests,
|
||||
General_InformationPacket,
|
||||
General_Region,
|
||||
};
|
||||
|
||||
Sync<std::unordered_map<Key, SettingsTypeVariant>> SettingsMap;
|
||||
enum SettingsAccessMask {
|
||||
READ_ONLY, // Value can be read from console
|
||||
READ_WRITE, // Value can be read and written to from console
|
||||
NO_ACCESS // Value is inaccessible from console (no read OR write)
|
||||
};
|
||||
|
||||
using SettingsAccessControl = std::pair<
|
||||
Key, // The Key's corresponding enum encoding
|
||||
SettingsAccessMask // Console read/write permissions
|
||||
>;
|
||||
|
||||
Sync<std::unordered_map<ComposedKey, SettingsAccessControl>> InputAccessMapping;
|
||||
std::string getAsString(Key key);
|
||||
|
||||
int getAsInt(Key key);
|
||||
|
||||
bool getAsBool(Key key);
|
||||
|
||||
SettingsTypeVariant get(Key key);
|
||||
|
||||
void set(Key key, const std::string& value);
|
||||
|
||||
template <typename Integer, std::enable_if_t<std::is_same_v<Integer, int>, bool> = true>
|
||||
void set(Key key, Integer value) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(int)" };
|
||||
}
|
||||
if (!std::holds_alternative<int>(map->at(key))) {
|
||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(int): index {}", map->at(key).index()) };
|
||||
}
|
||||
map->at(key) = value;
|
||||
}
|
||||
template <typename Boolean, std::enable_if_t<std::is_same_v<bool, Boolean>, bool> = true>
|
||||
void set(Key key, Boolean value) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(bool)" };
|
||||
}
|
||||
if (!std::holds_alternative<bool>(map->at(key))) {
|
||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(bool): index {}", map->at(key).index()) };
|
||||
}
|
||||
map->at(key) = value;
|
||||
}
|
||||
|
||||
const std::unordered_map<ComposedKey, SettingsAccessControl> getAccessControlMap() const;
|
||||
SettingsAccessControl getConsoleInputAccessMapping(const ComposedKey& keyName);
|
||||
|
||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, const std::string& value);
|
||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, int value);
|
||||
void setConsoleInputAccessMapping(const ComposedKey& keyName, bool value);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <mutex>
|
||||
|
||||
/// This header provides convenience aliases for synchronization primitives.
|
||||
|
||||
template <typename T>
|
||||
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
||||
+4
-4
@@ -19,6 +19,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "Settings.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
@@ -35,18 +36,17 @@ public:
|
||||
[[nodiscard]] bool Failed() const { return mFailed; }
|
||||
|
||||
void FlushToFile();
|
||||
void PrintDebug();
|
||||
|
||||
private:
|
||||
void CreateConfigFile();
|
||||
void ParseFromFile(std::string_view name);
|
||||
void PrintDebug();
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, Settings::Key key);
|
||||
|
||||
void ParseOldFormat();
|
||||
std::string TagsAsPrettyArray() const;
|
||||
bool IsDefault();
|
||||
bool mFailed { false };
|
||||
bool mDisableConfig { false };
|
||||
std::string mConfigFileName;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2026 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
class TConnectionLimiter {
|
||||
public:
|
||||
struct TStats {
|
||||
size_t CurrentGlobal = 0;
|
||||
size_t MaxGlobal = 0;
|
||||
size_t ActiveIpBuckets = 0;
|
||||
size_t CurrentMaxPerIp = 0;
|
||||
size_t MaxPerIp = 0;
|
||||
size_t SaturatedIpBuckets = 0;
|
||||
};
|
||||
|
||||
class TGuard {
|
||||
public:
|
||||
TGuard() = default;
|
||||
TGuard(TConnectionLimiter* owner, std::string ip);
|
||||
|
||||
TGuard(const TGuard&) = delete;
|
||||
TGuard& operator=(const TGuard&) = delete;
|
||||
|
||||
~TGuard() { Release(); }
|
||||
|
||||
// not threadsafe
|
||||
TGuard(TGuard&& other) noexcept { *this = std::move(other); }
|
||||
// not threadsafe
|
||||
TGuard& operator=(TGuard&& other) noexcept;
|
||||
|
||||
private:
|
||||
friend class TConnectionLimiter;
|
||||
|
||||
// not threadsafe
|
||||
void Release();
|
||||
|
||||
TConnectionLimiter* mOwner { nullptr };
|
||||
std::string mIp;
|
||||
};
|
||||
|
||||
TConnectionLimiter(size_t maxPerIp, size_t maxGlobal);
|
||||
|
||||
[[nodiscard]] std::optional<TGuard> TryAcquire(const std::string& ip);
|
||||
[[nodiscard]] TStats GetStats();
|
||||
|
||||
private:
|
||||
void Release(const std::string& ip) {
|
||||
std::unique_lock Lock { mMutex };
|
||||
auto It = mPerIp.find(ip);
|
||||
if (It != mPerIp.end()) {
|
||||
// this guard exists to avoid underflow in case something goes wrong and this gets called too many times
|
||||
if (It->second > 0)
|
||||
--It->second;
|
||||
if (It->second == 0)
|
||||
mPerIp.erase(It);
|
||||
}
|
||||
// this guard exists to avoid underflow in case something goes wrong and this gets called too many times
|
||||
if (mGlobal > 0)
|
||||
--mGlobal;
|
||||
}
|
||||
|
||||
const size_t mMaxPerIp;
|
||||
const size_t mMaxGlobal;
|
||||
|
||||
std::mutex mMutex { };
|
||||
std::unordered_map<std::string, size_t> mPerIp { };
|
||||
size_t mGlobal = 0;
|
||||
};
|
||||
@@ -58,6 +58,10 @@ private:
|
||||
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
||||
void Command_Version(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_ProtectMod(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_ReloadMods(const std::string& cmd, const std::vector<std::string>& args);
|
||||
void Command_NetTest(const std::string& cmd, const std::vector<std::string>& args);
|
||||
|
||||
void Command_Say(const std::string& FullCommand);
|
||||
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
||||
@@ -75,6 +79,10 @@ private:
|
||||
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
||||
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
|
||||
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||
{ "version", [this](const auto& a, const auto& b) { Command_Version(a, b); } },
|
||||
{ "protectmod", [this](const auto& a, const auto& b) { Command_ProtectMod(a, b); } },
|
||||
{ "reloadmods", [this](const auto& a, const auto& b) { Command_ReloadMods(a, b); } },
|
||||
{ "nettest", [this](const auto& a, const auto& b) { Command_NetTest(a, b); } },
|
||||
};
|
||||
|
||||
std::unique_ptr<Commandline> mCommandline { nullptr };
|
||||
|
||||
@@ -29,6 +29,7 @@ public:
|
||||
//~THeartbeatThread();
|
||||
void operator()() override;
|
||||
|
||||
static inline std::string lastCall = "";
|
||||
private:
|
||||
std::string GenerateCall();
|
||||
std::string GetPlayers();
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/executor_work_guard.hpp>
|
||||
#include <thread>
|
||||
|
||||
class TIoPollThread {
|
||||
public:
|
||||
TIoPollThread();
|
||||
~TIoPollThread();
|
||||
|
||||
boost::asio::io_context& IoCtx() noexcept { return mIoCtx; }
|
||||
|
||||
private:
|
||||
boost::asio::io_context mIoCtx;
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> mWorkGuard;
|
||||
std::jthread mThread;
|
||||
};
|
||||
+38
-40
@@ -18,58 +18,51 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Profiling.h"
|
||||
#include "TLuaResult.h"
|
||||
#include "TNetwork.h"
|
||||
#include "TServer.h"
|
||||
#include <any>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <initializer_list>
|
||||
#include <list>
|
||||
#include <lua.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <sol/forward.hpp>
|
||||
#include <sol/protected_function_result.hpp>
|
||||
#include <toml.hpp>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#define SOL_ALL_SAFETIES_ON 1
|
||||
#define SOL_USER_C_ASSERT SOL_ON
|
||||
#define SOL_C_ASSERT(...) \
|
||||
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__)
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
struct JsonString {
|
||||
std::string value;
|
||||
};
|
||||
|
||||
// value used to keep nils in a table or array, across serialization boundaries like
|
||||
// JsonEncode, so that the nil stays at the same index and isn't treated like a special
|
||||
// value (e.g. one that can be ignored or discarded).
|
||||
const inline std::string BEAMMP_INTERNAL_NIL = "BEAMMP_SERVER_INTERNAL_NIL_VALUE";
|
||||
|
||||
using TLuaStateId = std::string;
|
||||
namespace fs = std::filesystem;
|
||||
/**
|
||||
* 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, std::unordered_map<std::string, std::string>>;
|
||||
static constexpr size_t TLuaArgTypes_String = 0;
|
||||
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||
using TLuaValue = std::variant<std::monostate, std::string, int, JsonString, bool, std::unordered_map<std::string, std::string>, float>;
|
||||
|
||||
class TLuaPlugin;
|
||||
|
||||
struct TLuaResult {
|
||||
bool Ready;
|
||||
bool Error;
|
||||
std::string ErrorMessage;
|
||||
sol::object Result { sol::lua_nil };
|
||||
TLuaStateId StateId;
|
||||
std::string Function;
|
||||
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();
|
||||
};
|
||||
|
||||
struct TLuaPluginConfig {
|
||||
static inline const std::string FileName = "PluginConfig.toml";
|
||||
TLuaStateId StateId;
|
||||
@@ -96,7 +89,7 @@ public:
|
||||
struct QueuedFunction {
|
||||
std::string FunctionName;
|
||||
std::shared_ptr<TLuaResult> Result;
|
||||
std::vector<TLuaArgTypes> Args;
|
||||
std::vector<TLuaValue> Args;
|
||||
std::string EventName; // optional, may be empty
|
||||
};
|
||||
|
||||
@@ -148,8 +141,8 @@ public:
|
||||
const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
|
||||
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
||||
bool HasState(TLuaStateId StateId);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||
[[nodiscard]] std::shared_ptr<TLuaVoidResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName);
|
||||
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||
/**
|
||||
@@ -169,12 +162,12 @@ public:
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
||||
|
||||
for (const auto& Event : mLuaEvents.at(EventName)) {
|
||||
for (const auto& Function : Event.second) {
|
||||
if (Event.first != IgnoreId) {
|
||||
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments));
|
||||
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments, EventName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,10 +181,10 @@ public:
|
||||
return {};
|
||||
}
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
std::vector<TLuaValue> Arguments { TLuaValue { std::forward<ArgsT>(Args) }... };
|
||||
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||
for (const auto& Handler : Handlers) {
|
||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments, EventName));
|
||||
}
|
||||
return Results;
|
||||
}
|
||||
@@ -209,9 +202,9 @@ public:
|
||||
|
||||
// Debugging functions (slow)
|
||||
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaVoidResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
|
||||
std::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
|
||||
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||
std::vector<TLuaResult::DetachedSnapshot> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||
|
||||
private:
|
||||
void CollectAndInitPlugins();
|
||||
@@ -224,9 +217,9 @@ private:
|
||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||
StateThreadData(const StateThreadData&) = delete;
|
||||
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||
[[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> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||
[[nodiscard]] std::shared_ptr<TLuaVoidResult> EnqueueScript(const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaValue>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||
void operator()() override;
|
||||
@@ -236,13 +229,14 @@ private:
|
||||
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
|
||||
|
||||
// Debug functions, slow
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaVoidResult>>> Debug_GetStateExecuteQueue();
|
||||
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
||||
|
||||
private:
|
||||
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_GetPlayerIdentifiers(int ID);
|
||||
std::variant<std::string, sol::nil_t> Lua_GetPlayerRole(int ID);
|
||||
sol::table Lua_GetPlayers();
|
||||
std::string Lua_GetPlayerName(int ID);
|
||||
sol::table Lua_GetPlayerVehicles(int ID);
|
||||
@@ -253,11 +247,14 @@ private:
|
||||
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||
|
||||
prof::UnitProfileCollection mProfile {};
|
||||
std::unordered_map<std::string, prof::TimePoint> mProfileStarts;
|
||||
|
||||
std::string mName;
|
||||
TLuaStateId mStateId;
|
||||
lua_State* mState;
|
||||
std::thread mThread;
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaVoidResult>>> mStateExecuteQueue;
|
||||
std::recursive_mutex mStateExecuteQueueMutex;
|
||||
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||
std::mutex mStateFunctionQueueMutex;
|
||||
@@ -268,6 +265,7 @@ private:
|
||||
std::recursive_mutex mPathsMutex;
|
||||
std::mt19937 mMersenneTwister;
|
||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||
std::vector<sol::object> JsonStringToArray(JsonString Str);
|
||||
};
|
||||
|
||||
struct TimedEvent {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2026 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include <condition_variable>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
using TLuaStateId = std::string;
|
||||
|
||||
struct TDetachedLuaValue {
|
||||
using Ptr = std::shared_ptr<TDetachedLuaValue>;
|
||||
using Array = std::vector<TDetachedLuaValue>;
|
||||
// This weird Ptr indirection is needed because some implementations of libstc++,
|
||||
// like the GCC 11 one shipped with ubuntu 22.04, need to know the size of the second
|
||||
// member of the pairs that make up the elements of such a map. It's fine in vector.
|
||||
using Object = std::unordered_map<std::string, TDetachedLuaValue::Ptr>;
|
||||
std::variant<std::monostate, bool, double, int, std::string, Array, Object> V;
|
||||
};
|
||||
std::ostream& operator<<(std::ostream& os, const TDetachedLuaValue& value);
|
||||
|
||||
/// Result for operations that stay within one Lua state (e.g. script loads).
|
||||
/// This type intentionally does not store any Lua references or serialized Lua values.
|
||||
struct TLuaVoidResult {
|
||||
struct Snapshot {
|
||||
bool Error;
|
||||
bool Ready;
|
||||
std::string ErrorMessage;
|
||||
TLuaStateId StateId;
|
||||
};
|
||||
|
||||
explicit TLuaVoidResult(TLuaStateId StateId)
|
||||
: mStateId(std::move(StateId)) {}
|
||||
|
||||
/// Marks this result as success & sets it as ready, waking all waiting threads.
|
||||
void MarkReadySuccess();
|
||||
/// Marks this result as erroneous & sets it as ready, waking all waiting threads.
|
||||
void MarkReadyError(sol::protected_function_result Res);
|
||||
/// Marks this result as erroneous & sets it as ready, waking all waiting threads.
|
||||
void MarkReadyError(std::string Res);
|
||||
/// Wait (suspend) until this result is ready.
|
||||
void WaitUntilReady();
|
||||
bool IsReady() const;
|
||||
bool IsError() const;
|
||||
Snapshot GetSnapshot() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mMutex {};
|
||||
bool mReady { false };
|
||||
bool mError { false };
|
||||
std::string mErrorMessage;
|
||||
TLuaStateId mStateId;
|
||||
std::condition_variable mReadyCondition {};
|
||||
|
||||
void SetErrorMessageFromResult(sol::protected_function_result& Res) {
|
||||
if (Res.valid()) {
|
||||
beammp_lua_errorf("Error was not an error");
|
||||
}
|
||||
if (Res.get_type() == sol::type::string) {
|
||||
mErrorMessage = Res.get<sol::error>().what();
|
||||
} else {
|
||||
mErrorMessage = "(unknown error; error object is not inspectable)";
|
||||
}
|
||||
}
|
||||
|
||||
void MarkAsReady();
|
||||
};
|
||||
|
||||
struct TLuaResult {
|
||||
struct DetachedSnapshot {
|
||||
bool Error;
|
||||
bool Ready;
|
||||
std::string ErrorMessage;
|
||||
/// Serialized Lua result. Has no reference to the Lua state, and is safe to use
|
||||
/// from any thread that acquires it.
|
||||
TDetachedLuaValue Result;
|
||||
TLuaStateId StateId;
|
||||
std::string Function;
|
||||
};
|
||||
|
||||
|
||||
TLuaResult(TLuaStateId StateId, std::string FunctionName) : mStateId(StateId), mFunction(std::move(FunctionName)) {}
|
||||
|
||||
/// Marks this result as success & sets it as ready, waking all threads waiting on it.
|
||||
void MarkReadySuccess(sol::object Res);
|
||||
/// Marks this result as successful and ready without serializing a Lua value.
|
||||
void MarkReadySuccessNoResult();
|
||||
/// Marks this result as erroneous & sets it as ready, waking all threads waiting on it.
|
||||
void MarkReadyError(sol::protected_function_result Res);
|
||||
/// Marks this result as erroneous & sets it as ready, waking all threads waiting on it.
|
||||
void MarkReadyError(std::string Res);
|
||||
/// Wait (suspend) until this result is ready. Use `GetDetachedSnapshot` to get the result.
|
||||
void WaitUntilReady();
|
||||
bool IsReady() const;
|
||||
bool IsError() const;
|
||||
TLuaStateId OwnerState() const;
|
||||
void SetOwnerState(TLuaStateId StateId);
|
||||
|
||||
/// Returns a snapshot with, if not an error, a serialized version of the result
|
||||
/// object. This never stores or returns raw Lua references and is safe to use
|
||||
/// across threads.
|
||||
DetachedSnapshot GetDetachedSnapshot() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mMutex {};
|
||||
bool mReady { false };
|
||||
bool mError { false };
|
||||
std::string mErrorMessage;
|
||||
TDetachedLuaValue mDetachedResult;
|
||||
TLuaStateId mStateId;
|
||||
std::string mFunction;
|
||||
std::condition_variable mReadyCondition {};
|
||||
|
||||
TDetachedLuaValue Freeze(const sol::object& o, int depth = 0);
|
||||
|
||||
void SetErrorMessageFromResult(sol::protected_function_result& Res) {
|
||||
if (Res.valid()) {
|
||||
beammp_lua_errorf("Error was not an error");
|
||||
}
|
||||
if (Res.get_type() == sol::type::string) {
|
||||
mErrorMessage = Res.get<sol::error>().what();
|
||||
} else {
|
||||
mErrorMessage = "(unknown error; error object is not inspectable)";
|
||||
}
|
||||
}
|
||||
|
||||
void MarkAsReady();
|
||||
};
|
||||
+18
-10
@@ -20,9 +20,9 @@
|
||||
|
||||
#include "BoostAliases.h"
|
||||
#include "Compat.h"
|
||||
#include "TConnectionLimiter.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/ip/udp.hpp>
|
||||
|
||||
struct TConnection;
|
||||
@@ -34,16 +34,23 @@ public:
|
||||
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
||||
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
||||
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
||||
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
||||
std::vector<uint8_t> TCPRcv(TClient& c);
|
||||
std::shared_ptr<TClient> CreateClient(boost::asio::ip::tcp::socket&& TCPSock);
|
||||
std::vector<uint8_t> TCPRcv(TClient& c, bool WithTimeout = false);
|
||||
void ClientKick(TClient& c, const std::string& R);
|
||||
void DisconnectClient(const std::weak_ptr<TClient>& c, const std::string& R);
|
||||
void DisconnectClient(TClient& c, const std::string& R);
|
||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||
void Identify(TConnection&& client);
|
||||
void Identify(TConnection&& client, TConnectionLimiter::TGuard&&);
|
||||
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
||||
void SyncResources(TClient& c);
|
||||
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
||||
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
||||
void UpdatePlayer(TClient& Client);
|
||||
boost::system::error_code ReadWithTimeout(boost::asio::ip::tcp::socket& Socket, void* Buf, size_t Len, std::chrono::steady_clock::duration Timeout);
|
||||
boost::system::error_code ReadWithTimeout(TConnection& Connection, void* Buf, size_t Len, std::chrono::steady_clock::duration Timeout);
|
||||
[[nodiscard]] TConnectionLimiter::TStats GetConnectionLimiterStats() { return mConnectionLimiter.GetStats(); }
|
||||
|
||||
TResourceManager& ResourceManager() const { return mResourceManager; }
|
||||
|
||||
private:
|
||||
void UDPServerMain();
|
||||
@@ -51,13 +58,14 @@ private:
|
||||
|
||||
TServer& mServer;
|
||||
TPPSMonitor& mPPSMonitor;
|
||||
ip::udp::socket mUDPSock;
|
||||
boost::asio::ip::udp::socket mUDPSock;
|
||||
TResourceManager& mResourceManager;
|
||||
std::thread mUDPThread;
|
||||
std::thread mTCPThread;
|
||||
std::mutex mOpenIDMutex;
|
||||
TConnectionLimiter mConnectionLimiter;
|
||||
|
||||
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
||||
void HandleDownload(TConnection&& TCPSock);
|
||||
std::vector<uint8_t> UDPRcvFromClient(boost::asio::ip::udp::endpoint& ClientEndpoint);
|
||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||
void Looper(const std::weak_ptr<TClient>& c);
|
||||
@@ -65,9 +73,9 @@ private:
|
||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
||||
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
||||
void SendFile(TClient& c, const std::string& Name);
|
||||
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||
static bool TCPSendRaw(TClient& C, boost::asio::ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||
void SendFileToClient(TClient& c, size_t Size, const std::string& Name);
|
||||
static const uint8_t* SendSplit(TClient& c, boost::asio::ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||
};
|
||||
|
||||
std::string HashPassword(const std::string& str);
|
||||
|
||||
@@ -27,7 +27,7 @@ class TNetwork;
|
||||
class TPPSMonitor : public IThreaded {
|
||||
public:
|
||||
explicit TPPSMonitor(TServer& Server);
|
||||
virtual ~TPPSMonitor() {}
|
||||
virtual ~TPPSMonitor() { }
|
||||
|
||||
void operator()() override;
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
class TResourceManager {
|
||||
public:
|
||||
@@ -29,6 +30,10 @@ public:
|
||||
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
||||
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
||||
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
||||
[[nodiscard]] nlohmann::json GetMods() const { return mMods; }
|
||||
|
||||
void RefreshFiles();
|
||||
void SetProtected(const std::string& ModName, bool Protected);
|
||||
|
||||
private:
|
||||
size_t mMaxModSize = 0;
|
||||
@@ -36,4 +41,7 @@ private:
|
||||
std::string mFileList;
|
||||
std::string mTrimmedList;
|
||||
int mModsLoaded = 0;
|
||||
|
||||
std::mutex mModsMutex;
|
||||
nlohmann::json mMods = nlohmann::json::array();
|
||||
};
|
||||
|
||||
+4
-4
@@ -20,6 +20,7 @@
|
||||
|
||||
#include "IThreaded.h"
|
||||
#include "RWMutex.h"
|
||||
#include "TIoPollThread.h"
|
||||
#include "TScopedTimer.h"
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
@@ -44,17 +45,16 @@ public:
|
||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||
size_t ClientCount() const;
|
||||
|
||||
void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||
void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network, bool udp);
|
||||
static void HandleEvent(TClient& c, const std::string& Data);
|
||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||
|
||||
const TScopedTimer UptimeTimer;
|
||||
|
||||
// asio io context
|
||||
io_context& IoCtx() { return mIoCtx; }
|
||||
io_context& IoCtx() { return mIoCtxPoller.IoCtx(); }
|
||||
|
||||
private:
|
||||
io_context mIoCtx {};
|
||||
TIoPollThread mIoCtxPoller;
|
||||
TClientSet mClients;
|
||||
mutable RWMutex mClientsMutex;
|
||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||
|
||||
@@ -18,11 +18,12 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
class TVehicleData final {
|
||||
public:
|
||||
TVehicleData(int ID, std::string Data);
|
||||
TVehicleData(int ID, nlohmann::json Data);
|
||||
~TVehicleData();
|
||||
// We cannot delete this, since vector needs to be able to copy when it resizes.
|
||||
// Deleting this causes some wacky template errors which are hard to decipher,
|
||||
@@ -32,14 +33,16 @@ public:
|
||||
[[nodiscard]] bool IsInvalid() const { return mID == -1; }
|
||||
[[nodiscard]] int ID() const { return mID; }
|
||||
|
||||
[[nodiscard]] std::string Data() const { return mData; }
|
||||
void SetData(const std::string& Data) { mData = Data; }
|
||||
[[nodiscard]] nlohmann::json Data() const { return mData; }
|
||||
[[nodiscard]] std::string DataAsPacket(const std::string& Role, const std::string& Name, int ID) const;
|
||||
|
||||
void SetData(const nlohmann::json& Data) { mData = Data; }
|
||||
|
||||
bool operator==(const TVehicleData& v) const { return mID == v.mID; }
|
||||
|
||||
private:
|
||||
int mID { -1 };
|
||||
std::string mData;
|
||||
nlohmann::json mData;
|
||||
};
|
||||
|
||||
// TODO: unused now, remove?
|
||||
|
||||
@@ -4,4 +4,4 @@ set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--export-dynamic" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
|
||||
@@ -4,4 +4,4 @@ set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--export-dynamic" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
|
||||
Executable → Regular
Executable → Regular
+1
-1
@@ -4,4 +4,4 @@ set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--export-dynamic" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
Executable → Regular
Executable → Regular
Executable → Regular
@@ -4,4 +4,4 @@ set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--export-dynamic" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
git config --global --add safe.directory $(pwd)
|
||||
git config --global --add safe.directory $(pwd)/vcpkg
|
||||
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--export-dynamic" -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,23 @@
|
||||
#include "ChronoWrapper.h"
|
||||
#include "Common.h"
|
||||
#include <regex>
|
||||
|
||||
std::chrono::high_resolution_clock::duration ChronoWrapper::TimeFromStringWithLiteral(const std::string& time_str) {
|
||||
// const std::regex time_regex(R"((\d+\.{0,1}\d*)(min|ms|us|ns|[dhs]))"); //i.e one of: "25ns, 6us, 256ms, 2s, 13min, 69h, 356d" will get matched (only available in newer C++ versions)
|
||||
const std::regex time_regex(R"((\d+\.{0,1}\d*)(min|[dhs]))"); // i.e one of: "2.01s, 13min, 69h, 356.69d" will get matched
|
||||
std::smatch match;
|
||||
float time_value;
|
||||
if (!std::regex_search(time_str, match, time_regex))
|
||||
return std::chrono::nanoseconds(0);
|
||||
time_value = stof(match.str(1));
|
||||
if (match.str(2) == "d") {
|
||||
return std::chrono::seconds((uint64_t)(time_value * 86400)); // 86400 seconds in a day
|
||||
} else if (match.str(2) == "h") {
|
||||
return std::chrono::seconds((uint64_t)(time_value * 3600)); // 3600 seconds in an hour
|
||||
} else if (match.str(2) == "min") {
|
||||
return std::chrono::seconds((uint64_t)(time_value * 60));
|
||||
} else if (match.str(2) == "s") {
|
||||
return std::chrono::seconds((uint64_t)time_value);
|
||||
}
|
||||
return std::chrono::nanoseconds(0);
|
||||
}
|
||||
+34
-15
@@ -57,7 +57,7 @@ int TClient::GetOpenCarID() const {
|
||||
return OpenID;
|
||||
}
|
||||
|
||||
void TClient::AddNewCar(int Ident, const std::string& Data) {
|
||||
void TClient::AddNewCar(int Ident, const nlohmann::json& Data) {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
mVehicleData.emplace_back(Ident, Data);
|
||||
}
|
||||
@@ -76,17 +76,30 @@ std::string TClient::GetCarPositionRaw(int Ident) {
|
||||
}
|
||||
}
|
||||
|
||||
void TClient::Disconnect(std::string_view Reason) {
|
||||
bool TClient::Disconnect(std::string_view Reason) {
|
||||
// Do not remove this guard: concurrent close() on the same socket can crash in Asio internals.
|
||||
EDisconnectState Expected = EDisconnectState::Connected;
|
||||
if (!mDisconnectState.compare_exchange_strong(Expected, EDisconnectState::Disconnecting, std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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());
|
||||
if (mSocket.is_open()) {
|
||||
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());
|
||||
}
|
||||
} else {
|
||||
beammp_debug("Socket is already closed.");
|
||||
}
|
||||
// Terminal state: this client must not perform TCP IO after this point.
|
||||
mDisconnectState.store(EDisconnectState::Disconnected, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||
@@ -94,7 +107,7 @@ void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||
mVehiclePosition[size_t(Ident)] = Data;
|
||||
}
|
||||
|
||||
std::string TClient::GetCarData(int Ident) {
|
||||
nlohmann::json TClient::GetCarData(int Ident) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
@@ -104,10 +117,10 @@ std::string TClient::GetCarData(int Ident) {
|
||||
}
|
||||
} // unlock
|
||||
DeleteCar(Ident);
|
||||
return "";
|
||||
return nlohmann::detail::value_t::null;
|
||||
}
|
||||
|
||||
void TClient::SetCarData(int Ident, const std::string& Data) {
|
||||
void TClient::SetCarData(int Ident, const nlohmann::json& Data) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
@@ -121,6 +134,14 @@ void TClient::SetCarData(int Ident, const std::string& Data) {
|
||||
}
|
||||
|
||||
int TClient::GetCarCount() const {
|
||||
// mVechileData holds both unicycle and cars which both count towards the maximum car count
|
||||
// spawning a unicycle meant reaching the max, hence being unable to spawn car. this dirty fixes the problem for now.
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == mUnicycleID) {
|
||||
return int(mVehicleData.size() - 1);
|
||||
}
|
||||
}
|
||||
return int(mVehicleData.size());
|
||||
}
|
||||
|
||||
@@ -136,7 +157,6 @@ void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
||||
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
||||
: mServer(Server)
|
||||
, mSocket(std::move(Socket))
|
||||
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||
}
|
||||
|
||||
@@ -158,8 +178,7 @@ std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
||||
ReadLock Lock(Server.GetClientMutex());
|
||||
if (!CPtr.expired()) {
|
||||
auto C = CPtr.lock();
|
||||
if (auto C = CPtr.lock()) {
|
||||
if (C->GetID() == ID) {
|
||||
MaybeClient = CPtr;
|
||||
return false;
|
||||
|
||||
+105
-11
@@ -22,18 +22,20 @@
|
||||
#include "TConsole.h"
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <fmt/core.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#include "TLuaResult.h"
|
||||
#include "Compat.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Http.h"
|
||||
|
||||
Application::TSettings Application::Settings = {};
|
||||
#include "RegionHandler.h"
|
||||
|
||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||
@@ -72,6 +74,27 @@ std::string Application::ServerVersionString() {
|
||||
return mVersion.AsString();
|
||||
}
|
||||
|
||||
std::vector<std::string> Application::GetBackendUrlsInOrder() {
|
||||
return {
|
||||
"https://backend." + RegionHandler::RegionToTopLevelDomain(),
|
||||
};
|
||||
}
|
||||
|
||||
std::string Application::GetServerCheckUrl()
|
||||
{
|
||||
return "https://check." + RegionHandler::RegionToTopLevelDomain();
|
||||
}
|
||||
|
||||
std::string Application::GetBackendUrlForAuth()
|
||||
{
|
||||
return "https://auth." + RegionHandler::RegionToTopLevelDomain();
|
||||
}
|
||||
|
||||
std::string Application::GetBackendUrlForSocketIO()
|
||||
{
|
||||
return "https://backend." + RegionHandler::RegionToTopLevelDomain();
|
||||
}
|
||||
|
||||
std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
|
||||
std::array<uint8_t, 3> Version;
|
||||
std::stringstream ss(str);
|
||||
@@ -215,14 +238,14 @@ void Application::CheckForUpdates() {
|
||||
// checks current version against latest version
|
||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||
auto Response = Http::GET(url, 443, "/v/s");
|
||||
auto Response = Http::GET(url + "/v/s");
|
||||
bool Matches = std::regex_match(Response, VersionRegex);
|
||||
if (Matches) {
|
||||
auto MyVersion = ServerVersion();
|
||||
auto RemoteVersion = Version(VersionStrToInts(Response));
|
||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
||||
std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
|
||||
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
|
||||
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://docs.beammp.com/server/server-maintenance/#updating-the-server";
|
||||
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
|
||||
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
|
||||
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
|
||||
@@ -256,7 +279,7 @@ static std::mutex ThreadNameMapMutex {};
|
||||
|
||||
std::string ThreadName(bool DebugModeOverride) {
|
||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||
if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
|
||||
if (DebugModeOverride || Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
||||
auto id = std::this_thread::get_id();
|
||||
if (threadNameMap.find(id) != threadNameMap.end()) {
|
||||
// found
|
||||
@@ -268,21 +291,21 @@ std::string ThreadName(bool DebugModeOverride) {
|
||||
|
||||
TEST_CASE("ThreadName") {
|
||||
RegisterThread("MyThread");
|
||||
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
||||
auto OrigDebug = Application::Settings.getAsBool(Settings::Key::General_Debug);
|
||||
|
||||
// ThreadName adds a space at the end, legacy but we need it still
|
||||
SUBCASE("Debug mode enabled") {
|
||||
Application::Settings.DebugModeEnabled = true;
|
||||
Application::Settings.set(Settings::Key::General_Debug, true);
|
||||
CHECK(ThreadName(true) == "MyThread ");
|
||||
CHECK(ThreadName(false) == "MyThread ");
|
||||
}
|
||||
SUBCASE("Debug mode disabled") {
|
||||
Application::Settings.DebugModeEnabled = false;
|
||||
Application::Settings.set(Settings::Key::General_Debug, false);
|
||||
CHECK(ThreadName(true) == "MyThread ");
|
||||
CHECK(ThreadName(false) == "");
|
||||
}
|
||||
// cleanup
|
||||
Application::Settings.DebugModeEnabled = OrigDebug;
|
||||
Application::Settings.set(Settings::Key::General_Debug, OrigDebug);
|
||||
}
|
||||
|
||||
void RegisterThread(const std::string& str) {
|
||||
@@ -296,7 +319,7 @@ void RegisterThread(const std::string& str) {
|
||||
#elif defined(BEAMMP_FREEBSD)
|
||||
ThreadId = std::to_string(getpid());
|
||||
#endif
|
||||
if (Application::Settings.DebugModeEnabled) {
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
||||
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
||||
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
|
||||
}
|
||||
@@ -329,7 +352,7 @@ TEST_CASE("Version::AsString") {
|
||||
}
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||
if (Application::Settings.LogChat) {
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_LogChat)) {
|
||||
std::stringstream ss;
|
||||
ss << ThreadName();
|
||||
ss << "[CHAT] ";
|
||||
@@ -384,3 +407,74 @@ void SplitString(const std::string& str, const char delim, std::vector<std::stri
|
||||
out.push_back(str.substr(start, end - start));
|
||||
}
|
||||
}
|
||||
|
||||
std::string LowerString(std::string str) {
|
||||
std::ranges::transform(str, str.begin(), ::tolower);
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
static constexpr size_t STARTING_MAX_DECOMPRESSION_BUFFER_SIZE = 15 * 1024 * 1024;
|
||||
static constexpr size_t MAX_DECOMPRESSION_BUFFER_SIZE = 30 * 1024 * 1024;
|
||||
|
||||
std::vector<uint8_t> DeComp(std::span<const uint8_t> input) {
|
||||
beammp_debugf("got {} bytes of input data", input.size());
|
||||
|
||||
// start with a decompression buffer of 5x the input size, clamped to a maximum of 15 MB.
|
||||
// this buffer can and will grow, but we don't want to start it too large. A 5x compression ratio
|
||||
// is pretty optimistic.
|
||||
std::vector<uint8_t> output_buffer(std::min<size_t>(input.size() * 5, STARTING_MAX_DECOMPRESSION_BUFFER_SIZE));
|
||||
|
||||
uLongf output_size = output_buffer.size();
|
||||
|
||||
while (true) {
|
||||
int res = uncompress(
|
||||
reinterpret_cast<Bytef*>(output_buffer.data()),
|
||||
&output_size,
|
||||
reinterpret_cast<const Bytef*>(input.data()),
|
||||
static_cast<uLongf>(input.size()));
|
||||
if (res == Z_BUF_ERROR) {
|
||||
// We assume that a reasonable maximum size for decompressed packets exists. We want to avoid
|
||||
// a client effectively "zip bombing" us by sending a lot of small packets which decompress
|
||||
// into huge data.
|
||||
// If this limit were to be an issue, this could be made configurable, however clients have a similar
|
||||
// limit. For that reason, we just reject packets which decompress into too much data.
|
||||
if (output_buffer.size() >= MAX_DECOMPRESSION_BUFFER_SIZE) {
|
||||
throw std::runtime_error(fmt::format("decompressed packet size of {} bytes exceeded", MAX_DECOMPRESSION_BUFFER_SIZE));
|
||||
}
|
||||
// if decompression fails, we double the buffer size (up to the allowed limit) and try again
|
||||
output_buffer.resize(std::max<size_t>(output_buffer.size() * 2, MAX_DECOMPRESSION_BUFFER_SIZE));
|
||||
beammp_warnf("zlib uncompress() failed, trying with a larger buffer size of {}", output_buffer.size());
|
||||
output_size = output_buffer.size();
|
||||
} else if (res != Z_OK) {
|
||||
beammp_error("zlib uncompress() failed: " + std::to_string(res));
|
||||
if (res == Z_DATA_ERROR) {
|
||||
throw InvalidDataError {};
|
||||
} else {
|
||||
throw std::runtime_error("zlib uncompress() failed");
|
||||
}
|
||||
} else if (res == Z_OK) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
output_buffer.resize(output_size);
|
||||
return output_buffer;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> Comp(std::span<const uint8_t> input) {
|
||||
auto max_size = compressBound(input.size());
|
||||
std::vector<uint8_t> output(max_size);
|
||||
uLongf output_size = output.size();
|
||||
int res = compress(
|
||||
reinterpret_cast<Bytef*>(output.data()),
|
||||
&output_size,
|
||||
reinterpret_cast<const Bytef*>(input.data()),
|
||||
static_cast<uLongf>(input.size()));
|
||||
if (res != Z_OK) {
|
||||
beammp_error("zlib compress() failed: " + std::to_string(res));
|
||||
throw std::runtime_error("zlib compress() failed");
|
||||
}
|
||||
beammp_debug("zlib compressed " + std::to_string(input.size()) + " B to " + std::to_string(output_size) + " B");
|
||||
output.resize(output_size);
|
||||
return output;
|
||||
}
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ TEST_CASE("init and reset termios") {
|
||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||
#ifndef BEAMMP_FREEBSD // The 'c_line' attribute seems to only exist on Linux, so we need to omit it on other platforms
|
||||
CHECK_EQ(current.c_line, original.c_line);
|
||||
#endif
|
||||
#endif
|
||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||
}
|
||||
|
||||
+12
@@ -33,6 +33,18 @@ std::string_view Env::ToString(Env::Key key) {
|
||||
case Key::PROVIDER_UPDATE_MESSAGE:
|
||||
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
|
||||
break;
|
||||
case Key::PROVIDER_DISABLE_CONFIG:
|
||||
return "BEAMMP_PROVIDER_DISABLE_CONFIG";
|
||||
break;
|
||||
case Key::PROVIDER_DISABLE_MP_SET:
|
||||
return "BEAMMP_PROVIDER_DISABLE_MP_SET";
|
||||
break;
|
||||
case Key::PROVIDER_PORT_ENV:
|
||||
return "BEAMMP_PROVIDER_PORT_ENV";
|
||||
break;
|
||||
case Key::PROVIDER_IP_ENV:
|
||||
return "BEAMMP_PROVIDER_IP_ENV";
|
||||
break;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
+173
-34
@@ -18,51 +18,195 @@
|
||||
|
||||
#include "Http.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
|
||||
#include <curl/easy.h>
|
||||
#include <map>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
|
||||
// TODO: Add sentry error handling back
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||
httplib::SSLClient client(host, port);
|
||||
client.enable_server_certificate_verification(false);
|
||||
client.set_address_family(AF_INET);
|
||||
auto res = client.Get(target.c_str());
|
||||
if (res) {
|
||||
if (status) {
|
||||
*status = res->status;
|
||||
static size_t CurlWriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
|
||||
std::string* Result = reinterpret_cast<std::string*>(userp);
|
||||
std::string NewContents(reinterpret_cast<char*>(contents), size * nmemb);
|
||||
*Result += NewContents;
|
||||
return size * nmemb;
|
||||
}
|
||||
|
||||
struct CurlDeleter {
|
||||
void operator()(CURL* c) const noexcept {
|
||||
if (c)
|
||||
curl_easy_cleanup(c);
|
||||
}
|
||||
};
|
||||
|
||||
static std::mutex gCurlPoolMutex;
|
||||
static std::map<CURL*, bool> gCurlPool; // false = free, true = in use
|
||||
constexpr size_t MAX_CURL_POOL_SIZE = 128;
|
||||
|
||||
static CURL* AcquireCurl() {
|
||||
std::unique_lock Lock(gCurlPoolMutex);
|
||||
for (auto& [Curl, InUse] : gCurlPool) {
|
||||
if (!InUse) {
|
||||
InUse = true;
|
||||
curl_easy_reset(Curl);
|
||||
return Curl;
|
||||
}
|
||||
return res->body;
|
||||
} else {
|
||||
return Http::ErrorString;
|
||||
}
|
||||
|
||||
// none found, if we're under the limit add one!
|
||||
if (gCurlPool.size() >= MAX_CURL_POOL_SIZE) {
|
||||
beammp_debugf("Ran out of curl handles for network requests, skipping this request");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
CURL* Curl = curl_easy_init();
|
||||
if (!Curl) {
|
||||
// failed, ignore
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
gCurlPool[Curl] = true;
|
||||
return Curl;
|
||||
}
|
||||
|
||||
static void ReleaseCurl(CURL* curl) {
|
||||
if (!curl) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::unique_lock Lock(gCurlPoolMutex);
|
||||
auto It = gCurlPool.find(curl);
|
||||
if (It != gCurlPool.end()) {
|
||||
It->second = false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
||||
httplib::SSLClient client(host, port);
|
||||
client.set_read_timeout(std::chrono::seconds(10));
|
||||
beammp_assert(client.is_valid());
|
||||
client.enable_server_certificate_verification(false);
|
||||
client.set_address_family(AF_INET);
|
||||
auto res = client.Post(target.c_str(), headers, body.c_str(), body.size(), ContentType.c_str());
|
||||
if (res) {
|
||||
if (status) {
|
||||
*status = res->status;
|
||||
/// RAII container for curl handles to ensure correct release
|
||||
class CurlLease {
|
||||
private:
|
||||
CURL* mHandle = nullptr;
|
||||
public:
|
||||
|
||||
CurlLease() : mHandle(AcquireCurl()) {}
|
||||
~CurlLease() {
|
||||
ReleaseCurl(mHandle);
|
||||
}
|
||||
CurlLease(const CurlLease&) = delete;
|
||||
CurlLease& operator=(const CurlLease&) = delete;
|
||||
|
||||
CurlLease(CurlLease&& other) noexcept
|
||||
: mHandle(other.mHandle) {
|
||||
other.mHandle = nullptr;
|
||||
}
|
||||
|
||||
CurlLease& operator=(CurlLease&& other) noexcept {
|
||||
if (this != &other) {
|
||||
ReleaseCurl(mHandle);
|
||||
mHandle = other.mHandle;
|
||||
other.mHandle = nullptr;
|
||||
}
|
||||
return res->body;
|
||||
return *this;
|
||||
}
|
||||
|
||||
CURL* GetHandle() const noexcept {
|
||||
return mHandle;
|
||||
}
|
||||
};
|
||||
|
||||
std::string Http::GET(const std::string& url, unsigned int* status) {
|
||||
std::string Ret;
|
||||
CurlLease Lease{};
|
||||
CURL* curl = Lease.GetHandle();
|
||||
if (curl) {
|
||||
CURLcode res;
|
||||
char errbuf[CURL_ERROR_SIZE];
|
||||
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&Ret));
|
||||
|
||||
// ensure we dont keep connections open for long
|
||||
curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 8L);
|
||||
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
|
||||
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
|
||||
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_MAXAGE_CONN, 60L);
|
||||
curl_easy_setopt(curl, CURLOPT_MAXLIFETIME_CONN, 300L);
|
||||
|
||||
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
|
||||
errbuf[0] = 0;
|
||||
res = curl_easy_perform(curl);
|
||||
if (res != CURLE_OK) {
|
||||
beammp_error("GET to " + url + " failed: " + std::string(curl_easy_strerror(res)));
|
||||
beammp_error("Curl error: " + std::string(errbuf));
|
||||
return Http::ErrorString;
|
||||
}
|
||||
|
||||
if (status) {
|
||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, status);
|
||||
}
|
||||
|
||||
} else {
|
||||
beammp_debug("POST failed: " + httplib::to_string(res.error()));
|
||||
beammp_error("Curl easy init failed");
|
||||
return Http::ErrorString;
|
||||
}
|
||||
return Ret;
|
||||
}
|
||||
|
||||
std::string Http::POST(const std::string& url, const std::string& body, const std::string& ContentType, unsigned int* status, const std::map<std::string, std::string>& headers) {
|
||||
std::string Ret;
|
||||
CurlLease Lease{};
|
||||
CURL* curl = Lease.GetHandle();
|
||||
if (curl) {
|
||||
CURLcode res;
|
||||
char errbuf[CURL_ERROR_SIZE];
|
||||
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&Ret));
|
||||
curl_easy_setopt(curl, CURLOPT_POST, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, body.size());
|
||||
struct curl_slist* list = nullptr;
|
||||
list = curl_slist_append(list, ("Content-Type: " + ContentType).c_str());
|
||||
|
||||
for (auto [header, value] : headers) {
|
||||
list = curl_slist_append(list, (header + ": " + value).c_str());
|
||||
}
|
||||
|
||||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
|
||||
|
||||
// ensure we dont keep connections open for long
|
||||
curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 8L);
|
||||
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
|
||||
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
|
||||
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_MAXAGE_CONN, 60L);
|
||||
curl_easy_setopt(curl, CURLOPT_MAXLIFETIME_CONN, 300L);
|
||||
|
||||
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
|
||||
errbuf[0] = 0;
|
||||
res = curl_easy_perform(curl);
|
||||
curl_slist_free_all(list);
|
||||
if (res != CURLE_OK) {
|
||||
beammp_error("POST to " + url + " failed: " + std::string(curl_easy_strerror(res)));
|
||||
beammp_error("Curl error: " + std::string(errbuf));
|
||||
return Http::ErrorString;
|
||||
}
|
||||
|
||||
if (status) {
|
||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, status);
|
||||
}
|
||||
|
||||
} else {
|
||||
beammp_error("Curl easy init failed");
|
||||
return Http::ErrorString;
|
||||
}
|
||||
return Ret;
|
||||
}
|
||||
|
||||
// RFC 2616, RFC 7231
|
||||
@@ -172,7 +316,6 @@ Http::Server::THttpServerInstance::THttpServerInstance() {
|
||||
}
|
||||
|
||||
void Http::Server::THttpServerInstance::operator()() try {
|
||||
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
|
||||
std::unique_ptr<httplib::Server> HttpLibServerInstance;
|
||||
HttpLibServerInstance = std::make_unique<httplib::Server>();
|
||||
// todo: make this IP agnostic so people can set their own IP
|
||||
@@ -214,10 +357,6 @@ void Http::Server::THttpServerInstance::operator()() try {
|
||||
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
|
||||
});
|
||||
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
|
||||
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
|
||||
if (!ret) {
|
||||
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Failed to start http server. Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it. Error: " + std::string(e.what()));
|
||||
}
|
||||
|
||||
+253
-82
@@ -20,6 +20,7 @@
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Settings.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
@@ -60,7 +61,11 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
|
||||
}
|
||||
case sol::type::number: {
|
||||
std::stringstream ss;
|
||||
ss << Value.as<float>();
|
||||
if (Value.is<int>()) {
|
||||
ss << Value.as<int>();
|
||||
} else {
|
||||
ss << Value.as<float>();
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::lua_nil:
|
||||
@@ -138,17 +143,23 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
|
||||
return { true, "" };
|
||||
} else {
|
||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||
return { false, "Invalid Player ID" };
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
if (!c->IsSyncing() && !c->IsSynced()) {
|
||||
return { false, "Player hasn't joined yet" };
|
||||
}
|
||||
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||
return { false, "Respond failed, dropping client" };
|
||||
}
|
||||
return { true, "" };
|
||||
}
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||
return { false, "Respond failed, dropping client" };
|
||||
}
|
||||
return { true, "" };
|
||||
|
||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||
return { false, "Invalid Player ID" };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,37 +170,48 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
return { false, "Player does not exist" };
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||
return { true, "" };
|
||||
}
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||
return { true, "" };
|
||||
|
||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
return { false, "Player does not exist" };
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message, const bool& LogChat) {
|
||||
std::pair<bool, std::string> Result;
|
||||
std::string Packet = "C:Server: " + Message;
|
||||
if (ID == -1) {
|
||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||
if (LogChat) {
|
||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||
}
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->IsSynced()) {
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player still syncing data";
|
||||
return Result;
|
||||
}
|
||||
if (LogChat) {
|
||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||
}
|
||||
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 {
|
||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Player still syncing data";
|
||||
return Result;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||
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 {
|
||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
@@ -200,24 +222,113 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendNotification(int ID, const std::string& Message, const std::string& Icon, const std::string& Category) {
|
||||
std::pair<bool, std::string> Result;
|
||||
std::string Packet = "n" + Category + ":" + Icon + ":" + Message;
|
||||
if (ID == -1) {
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player is not synced yet";
|
||||
return Result;
|
||||
}
|
||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_errorf("Failed to send notification to player (id {}) - did the player disconnect?", ID);
|
||||
Result.first = false;
|
||||
Result.second = "Failed to send packet";
|
||||
}
|
||||
Result.first = true;
|
||||
} else {
|
||||
beammp_lua_error("SendNotification invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
} else {
|
||||
beammp_lua_error("SendNotification invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::ConfirmationDialog(int ID, const std::string& Title, const std::string& Body, const sol::table& buttons, const std::string& InteractionID, const bool& warning, const bool& reportToServer, const bool& reportToExtensions) {
|
||||
std::pair<bool, std::string> Result;
|
||||
|
||||
const nlohmann::json PacketBody = {
|
||||
{ "title", Title },
|
||||
{ "body", Body },
|
||||
{ "buttons", nlohmann::json::parse(JsonEncode(buttons), nullptr, false) },
|
||||
{ "interactionID", InteractionID },
|
||||
{ "class", warning ? "experimental" : "" },
|
||||
{ "reportToServer", reportToServer },
|
||||
{ "reportToExtensions", reportToExtensions }
|
||||
};
|
||||
|
||||
std::string Packet = "D" + PacketBody.dump();
|
||||
if (ID == -1) {
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player is not synced yet";
|
||||
return Result;
|
||||
}
|
||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_errorf("Failed to send confirmation dialog to player (id {}) - did the player disconnect?", ID);
|
||||
Result.first = false;
|
||||
Result.second = "Failed to send packet";
|
||||
}
|
||||
Result.first = true;
|
||||
} else {
|
||||
beammp_lua_error("ConfirmationDialog invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
} else {
|
||||
beammp_lua_error("ConfirmationDialog invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||
std::pair<bool, std::string> Result;
|
||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
if (c->GetCarData(VID) != nlohmann::detail::value_t::null) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", PID, VID));
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||
c->DeleteCar(VID);
|
||||
Result.first = true;
|
||||
} else {
|
||||
Result.first = false;
|
||||
Result.second = "Vehicle does not exist";
|
||||
}
|
||||
} else {
|
||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
} else {
|
||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
return Result;
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||
c->DeleteCar(VID);
|
||||
Result.first = true;
|
||||
} else {
|
||||
Result.first = false;
|
||||
Result.second = "Vehicle does not exist";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
@@ -226,86 +337,120 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
switch (ConfigID) {
|
||||
case 0: // debug
|
||||
if (NewValue.is<bool>()) {
|
||||
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
Application::Settings.set(Settings::Key::General_Debug, NewValue.as<bool>());
|
||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.getAsBool(Settings::Key::General_Debug) ? "true" : "false"));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 1: // private
|
||||
if (NewValue.is<bool>()) {
|
||||
Application::Settings.Private = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
||||
Application::Settings.set(Settings::Key::General_Private, NewValue.as<bool>());
|
||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false"));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 2: // max cars
|
||||
if (NewValue.is<int>()) {
|
||||
Application::Settings.MaxCars = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
||||
Application::Settings.set(Settings::Key::General_MaxCars, NewValue.as<int>());
|
||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxCars)));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 3: // max players
|
||||
if (NewValue.is<int>()) {
|
||||
Application::Settings.MaxPlayers = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
||||
Application::Settings.set(Settings::Key::General_MaxPlayers, NewValue.as<int>());
|
||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 4: // Map
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.MapName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
||||
Application::Settings.set(Settings::Key::General_Map, NewValue.as<std::string>());
|
||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.getAsString(Settings::Key::General_Map));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 5: // Name
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.ServerName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
||||
Application::Settings.set(Settings::Key::General_Name, NewValue.as<std::string>());
|
||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.getAsString(Settings::Key::General_Name));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 6: // Desc
|
||||
if (NewValue.is<std::string>()) {
|
||||
Application::Settings.ServerDesc = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
||||
Application::Settings.set(Settings::Key::General_Description, NewValue.as<std::string>());
|
||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.getAsString(Settings::Key::General_Description));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 7: // Information packet
|
||||
if (NewValue.is<bool>()) {
|
||||
Application::Settings.set(Settings::Key::General_InformationPacket, NewValue.as<bool>());
|
||||
beammp_info(std::string("Set `InformationPacket` to ") + (Application::Settings.getAsBool(Settings::Key::General_InformationPacket) ? "true" : "false"));
|
||||
} else {
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
TLuaValue LuaAPI::MP::Get(int ConfigID) {
|
||||
switch (ConfigID) {
|
||||
case 0: // debug
|
||||
return Application::Settings.getAsBool(Settings::Key::General_Debug);
|
||||
case 1: // private
|
||||
return Application::Settings.getAsBool(Settings::Key::General_Private);
|
||||
case 2: // max cars
|
||||
return Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
||||
case 3: // max players
|
||||
return Application::Settings.getAsInt(Settings::Key::General_MaxPlayers);
|
||||
case 4: // Map
|
||||
return Application::Settings.getAsString(Settings::Key::General_Map);
|
||||
case 5: // Name
|
||||
return Application::Settings.getAsString(Settings::Key::General_Name);
|
||||
case 6: // Desc
|
||||
return Application::Settings.getAsString(Settings::Key::General_Description);
|
||||
case 7: // Information packet
|
||||
return Application::Settings.getAsBool(Settings::Key::General_InformationPacket);
|
||||
default:
|
||||
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void LuaAPI::MP::Sleep(size_t Ms) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsConnected();
|
||||
} else {
|
||||
return false;
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
return c->IsUDPConnected();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsGuest();
|
||||
} else {
|
||||
return false;
|
||||
if (MaybeClient) {
|
||||
if (auto c = MaybeClient.value().lock()) {
|
||||
return c->IsGuest();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||
@@ -320,7 +465,16 @@ void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||
}
|
||||
|
||||
int LuaAPI::PanicHandler(lua_State* State) {
|
||||
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
||||
// panic path: use raw lua c api only; sol2 conversions can raise lua_error
|
||||
// and re-enter panic recursively.
|
||||
const int ErrorType = lua_type(State, -1);
|
||||
if (ErrorType == LUA_TSTRING) {
|
||||
const char* Message = lua_tostring(State, -1);
|
||||
beammp_lua_error(std::string("PANIC: ") + (Message ? Message : "(null)"));
|
||||
} else {
|
||||
const char* ErrorTypeName = lua_typename(State, ErrorType);
|
||||
beammp_lua_error(std::string("PANIC: non-string error object (") + (ErrorTypeName ? ErrorTypeName : "unknown") + ")");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -561,7 +715,11 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
key = left.as<std::string>();
|
||||
break;
|
||||
case sol::type::number:
|
||||
key = std::to_string(left.as<double>());
|
||||
if (left.is<int>()) {
|
||||
key = std::to_string(left.as<int>());
|
||||
} else {
|
||||
key = std::to_string(left.as<double>());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
@@ -589,21 +747,30 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
case sol::type::string:
|
||||
value = right.as<std::string>();
|
||||
break;
|
||||
case sol::type::number:
|
||||
value = right.as<double>();
|
||||
case sol::type::number: {
|
||||
if (right.is<int>()) {
|
||||
value = right.as<int>();
|
||||
} else {
|
||||
value = right.as<double>();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case sol::type::function:
|
||||
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
|
||||
return;
|
||||
case sol::type::table: {
|
||||
bool local_is_array = true;
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
local_is_array = false;
|
||||
if (right.as<sol::table>().empty()) {
|
||||
value = nlohmann::json::object();
|
||||
} else {
|
||||
bool local_is_array = true;
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
local_is_array = false;
|
||||
}
|
||||
}
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||
}
|
||||
}
|
||||
for (const auto& pair : right.as<sol::table>()) {
|
||||
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -620,14 +787,18 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
||||
nlohmann::json json;
|
||||
// table
|
||||
bool is_array = true;
|
||||
for (const auto& pair : object.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
is_array = false;
|
||||
if (object.as<sol::table>().empty()) {
|
||||
json = nlohmann::json::object();
|
||||
} else {
|
||||
bool is_array = true;
|
||||
for (const auto& pair : object.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
is_array = false;
|
||||
}
|
||||
}
|
||||
for (const auto& entry : object) {
|
||||
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||
}
|
||||
}
|
||||
for (const auto& entry : object) {
|
||||
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||
}
|
||||
return json.dump();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#include "Profiling.h"
|
||||
#include <limits>
|
||||
|
||||
prof::Duration prof::duration(const TimePoint& start, const TimePoint& end) {
|
||||
return end - start;
|
||||
}
|
||||
prof::TimePoint prof::now() {
|
||||
return std::chrono::high_resolution_clock::now();
|
||||
}
|
||||
prof::Stats prof::UnitProfileCollection::stats(const std::string& unit) {
|
||||
return m_map->operator[](unit).stats();
|
||||
}
|
||||
|
||||
size_t prof::UnitProfileCollection::measurement_count(const std::string& unit) {
|
||||
return m_map->operator[](unit).measurement_count();
|
||||
}
|
||||
|
||||
void prof::UnitProfileCollection::add_sample(const std::string& unit, const Duration& duration) {
|
||||
m_map->operator[](unit).add_sample(duration);
|
||||
}
|
||||
|
||||
prof::Stats prof::UnitExecutionTime::stats() const {
|
||||
std::unique_lock lock(m_mtx);
|
||||
Stats result {};
|
||||
// calculate sum
|
||||
result.n = m_total_calls;
|
||||
result.max = m_min;
|
||||
result.min = m_max;
|
||||
// calculate mean: mean = sum_x / n
|
||||
result.mean = m_sum / double(m_total_calls);
|
||||
// calculate stdev: stdev = sqrt((sum_x2 / n) - (mean * mean))
|
||||
result.stdev = std::sqrt((m_measurement_sqr_sum / double(result.n)) - (result.mean * result.mean));
|
||||
return result;
|
||||
}
|
||||
|
||||
void prof::UnitExecutionTime::add_sample(const Duration& dur) {
|
||||
std::unique_lock lock(m_mtx);
|
||||
m_sum += dur.count();
|
||||
m_measurement_sqr_sum += dur.count() * dur.count();
|
||||
m_min = std::min(dur.count(), m_min);
|
||||
m_max = std::max(dur.count(), m_max);
|
||||
++m_total_calls;
|
||||
}
|
||||
|
||||
prof::UnitExecutionTime::UnitExecutionTime() {
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, prof::Stats> prof::UnitProfileCollection::all_stats() {
|
||||
auto map = m_map.synchronize();
|
||||
std::unordered_map<std::string, Stats> result {};
|
||||
for (const auto& [name, time] : *map) {
|
||||
result[name] = time.stats();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
size_t prof::UnitExecutionTime::measurement_count() const {
|
||||
std::unique_lock lock(m_mtx);
|
||||
return m_total_calls;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "RegionHandler.h"
|
||||
#include "Common.h"
|
||||
|
||||
void RegionHandler::TopLevelDomainFailed()
|
||||
{
|
||||
beammp_info("Top level domain of " + mValidTLDs[mRegionIndex % mValidTLDs.size()] + " didn't respond correctly , changing domain to " + mValidTLDs[(mRegionIndex + 1) % mValidTLDs.size()]);
|
||||
mRegionIndex++;
|
||||
}
|
||||
|
||||
std::string RegionHandler::RegionToTopLevelDomain()
|
||||
{
|
||||
static bool isDeveloperRegion = Application::Settings.getAsString(Settings::Key::General_Region) == "Developer";
|
||||
if (isDeveloperRegion) {
|
||||
return "beammp.dev";
|
||||
}
|
||||
return mValidTLDs[mRegionIndex % mValidTLDs.size()]; // Global
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "Settings.h"
|
||||
|
||||
Settings::Settings() {
|
||||
SettingsMap = std::unordered_map<Key, SettingsTypeVariant> {
|
||||
// All entries which contain std::strings must be explicitly constructed, otherwise they become 'bool'
|
||||
{ General_Description, std::string("BeamMP Default Description") },
|
||||
{ General_Tags, std::string("Freeroam") },
|
||||
{ General_MaxPlayers, 8 },
|
||||
{ General_Name, std::string("BeamMP Server") },
|
||||
{ General_Map, std::string("/levels/gridmap_v2/info.json") },
|
||||
{ General_AuthKey, std::string("") },
|
||||
{ General_Private, true },
|
||||
{ General_IP, "::"},
|
||||
{ General_Port, 30814 },
|
||||
{ General_MaxCars, 1 },
|
||||
{ General_LogChat, true },
|
||||
{ General_ResourceFolder, std::string("Resources") },
|
||||
{ General_Debug, false },
|
||||
{ General_AllowGuests, true },
|
||||
{ General_InformationPacket, true },
|
||||
{ General_Region, std::string("")},
|
||||
{ Misc_ImScaredOfUpdates, true },
|
||||
{ Misc_UpdateReminderTime, "30s" }
|
||||
};
|
||||
|
||||
InputAccessMapping = std::unordered_map<ComposedKey, SettingsAccessControl> {
|
||||
{ { "General", "Description" }, { General_Description, READ_WRITE } },
|
||||
{ { "General", "Tags" }, { General_Tags, READ_WRITE } },
|
||||
{ { "General", "MaxPlayers" }, { General_MaxPlayers, READ_WRITE } },
|
||||
{ { "General", "Name" }, { General_Name, READ_WRITE } },
|
||||
{ { "General", "Map" }, { General_Map, READ_WRITE } },
|
||||
{ { "General", "AuthKey" }, { General_AuthKey, NO_ACCESS } },
|
||||
{ { "General", "Private" }, { General_Private, READ_ONLY } },
|
||||
{ { "General", "IP" }, { General_IP, READ_ONLY } },
|
||||
{ { "General", "Port" }, { General_Port, READ_ONLY } },
|
||||
{ { "General", "MaxCars" }, { General_MaxCars, READ_WRITE } },
|
||||
{ { "General", "LogChat" }, { General_LogChat, READ_ONLY } },
|
||||
{ { "General", "ResourceFolder" }, { General_ResourceFolder, READ_ONLY } },
|
||||
{ { "General", "Debug" }, { General_Debug, READ_WRITE } },
|
||||
{ { "General", "AllowGuests" }, { General_AllowGuests, READ_WRITE } },
|
||||
{ { "General", "InformationPacket" }, { General_InformationPacket, READ_WRITE } },
|
||||
{ { "General", "Region" }, { General_Region, READ_WRITE } },
|
||||
{ { "Misc", "ImScaredOfUpdates" }, { Misc_ImScaredOfUpdates, READ_WRITE } },
|
||||
{ { "Misc", "UpdateReminderTime" }, { Misc_UpdateReminderTime, READ_WRITE } }
|
||||
};
|
||||
}
|
||||
|
||||
std::string Settings::getAsString(Key key) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined key accessed in Settings::getAsString" };
|
||||
}
|
||||
return std::get<std::string>(map->at(key));
|
||||
}
|
||||
int Settings::getAsInt(Key key) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined key accessed in Settings::getAsInt" };
|
||||
}
|
||||
return std::get<int>(map->at(key));
|
||||
}
|
||||
|
||||
bool Settings::getAsBool(Key key) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined key accessed in Settings::getAsBool" };
|
||||
}
|
||||
return std::get<bool>(map->at(key));
|
||||
}
|
||||
|
||||
Settings::SettingsTypeVariant Settings::get(Key key) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined setting key accessed in Settings::get" };
|
||||
}
|
||||
return map->at(key);
|
||||
}
|
||||
|
||||
void Settings::set(Key key, const std::string& value) {
|
||||
auto map = SettingsMap.synchronize();
|
||||
if (!map->contains(key)) {
|
||||
throw std::logic_error { "Undefined setting key accessed in Settings::set(std::string)" };
|
||||
}
|
||||
if (!std::holds_alternative<std::string>(map->at(key))) {
|
||||
throw std::logic_error { fmt::format("Wrong value type in Settings::set(std::string): index {}", map->at(key).index()) };
|
||||
}
|
||||
map->at(key) = value;
|
||||
}
|
||||
|
||||
const std::unordered_map<ComposedKey, Settings::SettingsAccessControl> Settings::getAccessControlMap() const {
|
||||
return *InputAccessMapping;
|
||||
}
|
||||
|
||||
Settings::SettingsAccessControl Settings::getConsoleInputAccessMapping(const ComposedKey& keyName) {
|
||||
auto acl_map = InputAccessMapping.synchronize();
|
||||
if (!acl_map->contains(keyName)) {
|
||||
throw std::logic_error { "Unknown key name accessed in Settings::getConsoleInputAccessMapping" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
||||
}
|
||||
return acl_map->at(keyName);
|
||||
}
|
||||
|
||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, const std::string& value) {
|
||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
||||
if (!acl_map->contains(keyName)) {
|
||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
||||
throw std::logic_error { "Setting '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
||||
}
|
||||
|
||||
Key key = acl_map->at(keyName).first;
|
||||
|
||||
if (!std::holds_alternative<std::string>(map->at(key))) {
|
||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected std::string" };
|
||||
}
|
||||
|
||||
map->at(key) = value;
|
||||
}
|
||||
|
||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, int value) {
|
||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
||||
if (!acl_map->contains(keyName)) {
|
||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
||||
}
|
||||
|
||||
Key key = acl_map->at(keyName).first;
|
||||
|
||||
if (!std::holds_alternative<int>(map->at(key))) {
|
||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected int" };
|
||||
}
|
||||
|
||||
map->at(key) = value;
|
||||
}
|
||||
|
||||
void Settings::setConsoleInputAccessMapping(const ComposedKey& keyName, bool value) {
|
||||
auto [map, acl_map] = boost::synchronize(SettingsMap, InputAccessMapping);
|
||||
if (!acl_map->contains(keyName)) {
|
||||
throw std::logic_error { "Unknown key name accessed in Settings::setConsoleInputAccessMapping" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::NO_ACCESS) {
|
||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not accessible from within the runtime!" };
|
||||
} else if (acl_map->at(keyName).second == SettingsAccessMask::READ_ONLY) {
|
||||
throw std::logic_error { "Key '" + keyName.Category + "::" + keyName.Key + "' is not writeable from within the runtime!" };
|
||||
}
|
||||
|
||||
Key key = acl_map->at(keyName).first;
|
||||
|
||||
if (!std::holds_alternative<bool>(map->at(key))) {
|
||||
throw std::logic_error { "Wrong value type in Settings::setConsoleInputAccessMapping: expected bool" };
|
||||
}
|
||||
|
||||
map->at(key) = value;
|
||||
}
|
||||
|
||||
TEST_CASE("settings get/set") {
|
||||
Settings settings;
|
||||
settings.set(Settings::General_Name, "hello, world");
|
||||
CHECK_EQ(settings.getAsString(Settings::General_Name), "hello, world");
|
||||
settings.set(Settings::General_Name, std::string("hello, world"));
|
||||
CHECK_EQ(settings.getAsString(Settings::General_Name), "hello, world");
|
||||
settings.set(Settings::General_MaxPlayers, 12);
|
||||
CHECK_EQ(settings.getAsInt(Settings::General_MaxPlayers), 12);
|
||||
}
|
||||
|
||||
TEST_CASE("settings check for exception on wrong input type") {
|
||||
Settings settings;
|
||||
CHECK_THROWS(settings.set(Settings::General_Debug, "hello, world"));
|
||||
CHECK_NOTHROW(settings.set(Settings::General_Debug, false));
|
||||
}
|
||||
+163
-147
@@ -18,18 +18,24 @@
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
#include "Env.h"
|
||||
#include "Settings.h"
|
||||
#include "TConfig.h"
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <sstream>
|
||||
#include <type_traits>
|
||||
|
||||
// General
|
||||
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 EnvStrPrivate = "BEAMMP_PRIVATE";
|
||||
static constexpr std::string_view StrIP = "IP";
|
||||
static constexpr std::string_view EnvStrIP = "BEAMMP_IP";
|
||||
static constexpr std::string_view StrPort = "Port";
|
||||
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
|
||||
static constexpr std::string_view StrMaxCars = "MaxCars";
|
||||
@@ -46,16 +52,23 @@ 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 EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
|
||||
static constexpr std::string_view StrRegion = "BackendRegion";
|
||||
static constexpr std::string_view EnvStrRegion = "BEAMMP_BACKEND_REGION";
|
||||
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 EnvStrLogChat = "BEAMMP_LOG_CHAT";
|
||||
static constexpr std::string_view StrAllowGuests = "AllowGuests";
|
||||
static constexpr std::string_view EnvStrAllowGuests = "BEAMMP_ALLOW_GUESTS";
|
||||
static constexpr std::string_view StrInformationPacket = "InformationPacket";
|
||||
static constexpr std::string_view EnvStrInformationPacket = "BEAMMP_INFORMATION_PACKET";
|
||||
static constexpr std::string_view StrPassword = "Password";
|
||||
|
||||
// Misc
|
||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||
static constexpr std::string_view EnvStrHideUpdateMessages = "BEAMMP_IM_SCARED_OF_UPDATES";
|
||||
static constexpr std::string_view StrUpdateReminderTime = "UpdateReminderTime";
|
||||
static constexpr std::string_view EnvStrUpdateReminderTime = "BEAMMP_UPDATE_REMINDER_TIME";
|
||||
|
||||
TEST_CASE("TConfig::TConfig") {
|
||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||
@@ -87,7 +100,9 @@ TEST_CASE("TConfig::TConfig") {
|
||||
TConfig::TConfig(const std::string& ConfigFileName)
|
||||
: mConfigFileName(ConfigFileName) {
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Starting);
|
||||
if (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName)) {
|
||||
auto DisableConfig = Env::Get(Env::Key::PROVIDER_DISABLE_CONFIG).value_or("false");
|
||||
mDisableConfig = DisableConfig == "true" || DisableConfig == "1";
|
||||
if (!mDisableConfig && (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName))) {
|
||||
beammp_info("No config file found! Generating one...");
|
||||
CreateConfigFile();
|
||||
}
|
||||
@@ -117,35 +132,42 @@ void SetComment(CommentsT& Comments, const std::string& Comment) {
|
||||
void TConfig::FlushToFile() {
|
||||
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||
auto data = toml::value {};
|
||||
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
||||
data["General"][StrAuthKey.data()] = Application::Settings.getAsString(Settings::Key::General_AuthKey);
|
||||
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
||||
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
|
||||
data["General"][StrLogChat.data()] = Application::Settings.getAsBool(Settings::Key::General_LogChat);
|
||||
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
|
||||
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
|
||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||
data["General"][StrDebug.data()] = Application::Settings.getAsBool(Settings::Key::General_Debug);
|
||||
data["General"][StrPrivate.data()] = Application::Settings.getAsBool(Settings::Key::General_Private);
|
||||
SetComment(data["General"][StrInformationPacket.data()].comments(), " Whether to allow unconnected clients to get the public server information without joining");
|
||||
data["General"][StrInformationPacket.data()] = Application::Settings.getAsBool(Settings::Key::General_InformationPacket);
|
||||
data["General"][StrAllowGuests.data()] = Application::Settings.getAsBool(Settings::Key::General_AllowGuests);
|
||||
SetComment(data["General"][StrAllowGuests.data()].comments(), " Whether to allow guests");
|
||||
data["General"][StrIP.data()] = Application::Settings.getAsString(Settings::Key::General_IP);
|
||||
SetComment(data["General"][StrIP.data()].comments(), " The IP address to bind the server to, this is NOT related to your public IP. Can be used if your machine has multiple network interfaces");
|
||||
data["General"][StrPort.data()] = Application::Settings.getAsInt(Settings::Key::General_Port);
|
||||
data["General"][StrName.data()] = Application::Settings.getAsString(Settings::Key::General_Name);
|
||||
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"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||
data["General"][StrTags.data()] = Application::Settings.getAsString(Settings::Key::General_Tags);
|
||||
data["General"][StrMaxCars.data()] = Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
||||
data["General"][StrMaxPlayers.data()] = Application::Settings.getAsInt(Settings::Key::General_MaxPlayers);
|
||||
data["General"][StrMap.data()] = Application::Settings.getAsString(Settings::Key::General_Map);
|
||||
data["General"][StrDescription.data()] = Application::Settings.getAsString(Settings::Key::General_Description);
|
||||
data["General"][StrResourceFolder.data()] = Application::Settings.getAsString(Settings::Key::General_ResourceFolder);
|
||||
if (Application::Settings.getAsString(Settings::Key::General_Region) != "") {
|
||||
data["General"][StrRegion.data()] = Application::Settings.getAsString(Settings::Key::General_Region);
|
||||
}
|
||||
// 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
|
||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.getAsBool(Settings::Key::Misc_ImScaredOfUpdates);
|
||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||
data["Misc"][StrUpdateReminderTime.data()] = Application::Settings.getAsString(Settings::Key::Misc_UpdateReminderTime);
|
||||
SetComment(data["Misc"][StrUpdateReminderTime.data()].comments(), " Specifies the time between update reminders. You can use any of \"s, min, h, d\" at the end to specify the units seconds, minutes, hours or days. So 30d or 0.5min will print the update message every 30 days or half a minute.");
|
||||
std::stringstream Ss;
|
||||
Ss << "# This is the BeamMP-Server config file.\n"
|
||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||
"# Help & Documentation: `https://docs.beammp.com/server/server-maintenance/`\n"
|
||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
|
||||
<< data;
|
||||
<< toml::format(data);
|
||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||
if (!File) {
|
||||
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
||||
@@ -161,172 +183,166 @@ void TConfig::FlushToFile() {
|
||||
|
||||
void TConfig::CreateConfigFile() {
|
||||
// build from old config Server.cfg
|
||||
|
||||
try {
|
||||
if (fs::exists("Server.cfg")) {
|
||||
// parse it (this is weird and bad and should be removed in some future version)
|
||||
ParseOldFormat();
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||
if (mDisableConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
FlushToFile();
|
||||
}
|
||||
|
||||
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()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||
}
|
||||
}
|
||||
// This arcane template magic is needed for using lambdas as overloaded visitors
|
||||
// See https://en.cppreference.com/w/cpp/utility/variant/visit for reference
|
||||
template <class... Ts>
|
||||
struct overloaded : Ts... {
|
||||
using Ts::operator()...;
|
||||
};
|
||||
template <class... Ts>
|
||||
overloaded(Ts...) -> overloaded<Ts...>;
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, Settings::Key key) {
|
||||
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()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||
}
|
||||
}
|
||||
if (const char* envp = std::getenv(Env.data());
|
||||
envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||
|
||||
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));
|
||||
std::visit(
|
||||
overloaded {
|
||||
[&envp, &key](std::string) {
|
||||
Application::Settings.set(key, std::string(envp));
|
||||
},
|
||||
[&envp, &key](int) {
|
||||
Application::Settings.set(key, int(std::strtol(envp, nullptr, 10)));
|
||||
},
|
||||
[&envp, &key](bool) {
|
||||
auto Str = std::string(envp);
|
||||
Application::Settings.set(key, bool(Str == "1" || Str == "true"));
|
||||
} },
|
||||
|
||||
Application::Settings.get(key));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
|
||||
}
|
||||
|
||||
std::visit([&Table, &Category, &Key, &key](auto&& arg) {
|
||||
using T = std::decay_t<decltype(arg)>;
|
||||
if constexpr (std::is_same_v<T, std::string>) {
|
||||
if (Table[Category.c_str()][Key.data()].is_string())
|
||||
Application::Settings.set(key, Table[Category.c_str()][Key.data()].as_string());
|
||||
else if (Table[Category.c_str()][Key.data()].is_empty())
|
||||
beammp_debugf("Value '{}.{}' is empty", Category, Key);
|
||||
else
|
||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'string'", Category, Key);
|
||||
} else if constexpr (std::is_same_v<T, int>) {
|
||||
if (Table[Category.c_str()][Key.data()].is_integer())
|
||||
Application::Settings.set(key, int(Table[Category.c_str()][Key.data()].as_integer()));
|
||||
else if (Table[Category.c_str()][Key.data()].is_empty())
|
||||
beammp_debugf("Value '{}.{}' is empty", Category, Key);
|
||||
else
|
||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'integer'", Category, Key);
|
||||
} else if constexpr (std::is_same_v<T, bool>) {
|
||||
if (Table[Category.c_str()][Key.data()].is_boolean())
|
||||
Application::Settings.set(key, Table[Category.c_str()][Key.data()].as_boolean());
|
||||
else if (Table[Category.c_str()][Key.data()].is_empty())
|
||||
beammp_debugf("Value '{}.{}' is empty", Category, Key);
|
||||
else
|
||||
beammp_warnf("Value '{}.{}' has unexpected type, expected type 'boolean'", Category, Key);
|
||||
} else {
|
||||
throw std::logic_error { "Invalid type for config value during read attempt" };
|
||||
}
|
||||
},
|
||||
Application::Settings.get(key));
|
||||
}
|
||||
|
||||
void TConfig::ParseFromFile(std::string_view name) {
|
||||
try {
|
||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||
toml::value data {};
|
||||
if (!mDisableConfig) {
|
||||
data = toml::parse(name.data());
|
||||
}
|
||||
|
||||
// GENERAL
|
||||
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
|
||||
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
|
||||
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
|
||||
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
|
||||
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
|
||||
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
|
||||
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
|
||||
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
|
||||
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
|
||||
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
|
||||
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
|
||||
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
|
||||
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
|
||||
|
||||
// Read into new Settings Singleton
|
||||
TryReadValue(data, "General", StrDebug, EnvStrDebug, Settings::Key::General_Debug);
|
||||
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Settings::Key::General_Private);
|
||||
TryReadValue(data, "General", StrInformationPacket, EnvStrInformationPacket, Settings::Key::General_InformationPacket);
|
||||
if (Env::Get(Env::Key::PROVIDER_PORT_ENV).has_value()) {
|
||||
TryReadValue(data, "General", StrPort, Env::Get(Env::Key::PROVIDER_PORT_ENV).value(), Settings::Key::General_Port);
|
||||
} else {
|
||||
TryReadValue(data, "General", StrPort, EnvStrPort, Settings::Key::General_Port);
|
||||
}
|
||||
if (Env::Get(Env::Key::PROVIDER_IP_ENV).has_value()) {
|
||||
TryReadValue(data, "General", StrIP, Env::Get(Env::Key::PROVIDER_IP_ENV).value(), Settings::Key::General_IP);
|
||||
} else {
|
||||
TryReadValue(data, "General", StrIP, EnvStrIP, Settings::Key::General_IP);
|
||||
}
|
||||
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Settings::Key::General_MaxCars);
|
||||
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Settings::Key::General_MaxPlayers);
|
||||
TryReadValue(data, "General", StrMap, EnvStrMap, Settings::Key::General_Map);
|
||||
TryReadValue(data, "General", StrName, EnvStrName, Settings::Key::General_Name);
|
||||
TryReadValue(data, "General", StrDescription, EnvStrDescription, Settings::Key::General_Description);
|
||||
TryReadValue(data, "General", StrTags, EnvStrTags, Settings::Key::General_Tags);
|
||||
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Settings::Key::General_ResourceFolder);
|
||||
TryReadValue(data, "General", StrRegion, EnvStrRegion, Settings::Key::General_Region);
|
||||
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Settings::Key::General_AuthKey);
|
||||
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Settings::Key::General_LogChat);
|
||||
TryReadValue(data, "General", StrAllowGuests, EnvStrAllowGuests, Settings::Key::General_AllowGuests);
|
||||
// Misc
|
||||
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
|
||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, EnvStrHideUpdateMessages, Settings::Key::Misc_ImScaredOfUpdates);
|
||||
TryReadValue(data, "Misc", StrUpdateReminderTime, EnvStrUpdateReminderTime, Settings::Key::Misc_UpdateReminderTime);
|
||||
|
||||
} catch (const std::exception& err) {
|
||||
beammp_error("Error parsing config file value: " + std::string(err.what()));
|
||||
mFailed = true;
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||
return;
|
||||
}
|
||||
PrintDebug();
|
||||
|
||||
// Update in any case
|
||||
FlushToFile();
|
||||
if (!mDisableConfig) {
|
||||
FlushToFile();
|
||||
}
|
||||
// all good so far, let's check if there's a key
|
||||
if (Application::Settings.Key.empty()) {
|
||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
||||
if (Application::Settings.getAsString(Settings::Key::General_AuthKey).empty()) {
|
||||
if (mDisableConfig) {
|
||||
beammp_error("No AuthKey specified in the environment.");
|
||||
} else {
|
||||
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
||||
}
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||
mFailed = true;
|
||||
return;
|
||||
}
|
||||
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
||||
if (Application::Settings.Key.size() != 36) {
|
||||
if (Application::Settings.getAsString(Settings::Key::General_AuthKey).size() != 36) {
|
||||
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::PrintDebug() {
|
||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||
if (mDisableConfig) {
|
||||
beammp_debug("Provider turned off the generation and parsing of the ServerConfig.toml");
|
||||
}
|
||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_Debug) ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false"));
|
||||
beammp_debug(std::string(StrInformationPacket) + ": " + std::string(Application::Settings.getAsBool(Settings::Key::General_InformationPacket) ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)));
|
||||
beammp_debug(std::string(StrIP) + ": \"" + Application::Settings.getAsString(Settings::Key::General_IP) + "\"");
|
||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxCars)));
|
||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)));
|
||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Map) + "\"");
|
||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Name) + "\"");
|
||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Description) + "\"");
|
||||
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
|
||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.getAsBool(Settings::Key::General_LogChat) ? "true" : "false") + "\"");
|
||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "\"");
|
||||
beammp_debug(std::string(StrRegion) + ": \"" + Application::Settings.getAsString(Settings::Key::General_Region) + "\"");
|
||||
beammp_debug(std::string(StrAllowGuests) + ": \"" + (Application::Settings.getAsBool(Settings::Key::General_AllowGuests) ? "true" : "false") + "\"");
|
||||
// special!
|
||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
|
||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.getAsString(Settings::Key::General_AuthKey).length()) + "");
|
||||
}
|
||||
|
||||
void TConfig::ParseOldFormat() {
|
||||
std::ifstream File("Server.cfg");
|
||||
// read all, strip comments
|
||||
std::string Content;
|
||||
for (;;) {
|
||||
std::string Line;
|
||||
std::getline(File, Line);
|
||||
if (!Line.empty() && Line.at(0) != '#') {
|
||||
Line = Line.substr(0, Line.find_first_of('#'));
|
||||
Content += Line + "\n";
|
||||
}
|
||||
if (!File.good()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::stringstream Str(Content);
|
||||
std::string Key, Ignore, Value;
|
||||
for (;;) {
|
||||
Str >> Key >> std::ws >> Ignore >> std::ws;
|
||||
std::getline(Str, Value);
|
||||
if (Str.eof()) {
|
||||
break;
|
||||
}
|
||||
std::stringstream ValueStream(Value);
|
||||
ValueStream >> std::ws; // strip leading whitespace if any
|
||||
Value = ValueStream.str();
|
||||
if (Key == "Debug") {
|
||||
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
|
||||
} else if (Key == "Private") {
|
||||
Application::Settings.Private = Value.find("true") != std::string::npos;
|
||||
} else if (Key == "Port") {
|
||||
ValueStream >> Application::Settings.Port;
|
||||
} else if (Key == "Cars") {
|
||||
ValueStream >> Application::Settings.MaxCars;
|
||||
} else if (Key == "MaxPlayers") {
|
||||
ValueStream >> Application::Settings.MaxPlayers;
|
||||
} else if (Key == "Map") {
|
||||
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "Name") {
|
||||
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "Desc") {
|
||||
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "use") {
|
||||
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
|
||||
} else if (Key == "AuthKey") {
|
||||
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||
} else {
|
||||
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||
}
|
||||
Str >> std::ws;
|
||||
}
|
||||
}
|
||||
std::string TConfig::TagsAsPrettyArray() const {
|
||||
std::vector<std::string> TagsArray = {};
|
||||
SplitString(Application::Settings.ServerTags, ',', TagsArray);
|
||||
SplitString(Application::Settings.getAsString(Settings::General_Tags), ',', TagsArray);
|
||||
std::string Pretty = {};
|
||||
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
|
||||
Pretty += '\"' + TagsArray[i] + "\", ";
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2026 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TConnectionLimiter.h"
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include "Common.h"
|
||||
|
||||
TConnectionLimiter::TConnectionLimiter(size_t maxPerIp, size_t maxGlobal)
|
||||
: mMaxPerIp(maxPerIp)
|
||||
, mMaxGlobal(maxGlobal) {
|
||||
if (maxPerIp == 0) {
|
||||
beammp_errorf("Max connections count per IP is set to zero; the server would reject ALL connections");
|
||||
throw std::runtime_error("Invalid maximum connections per IP setting");
|
||||
}
|
||||
if (maxGlobal == 0) {
|
||||
beammp_errorf("Max connection count is set to zero; the server would reject ALL connections");
|
||||
throw std::runtime_error("Invalid maximum connections setting");
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<TConnectionLimiter::TGuard> TConnectionLimiter::TryAcquire(const std::string& ip) {
|
||||
std::unique_lock Lock { mMutex };
|
||||
if (mGlobal >= mMaxGlobal) return std::nullopt;
|
||||
// `It` is the inserted element (so if insertion worked, its 0), or its the element that
|
||||
// was already there, in which case we must check the ip connection limit
|
||||
auto [It, _] = mPerIp.try_emplace(ip, 0);
|
||||
if (It->second >= mMaxPerIp) {
|
||||
return std::nullopt;
|
||||
}
|
||||
// now increment the counter finally
|
||||
++It->second;
|
||||
++mGlobal;
|
||||
// RAII guard will drop the count once destructed
|
||||
return TGuard(this, ip);
|
||||
}
|
||||
|
||||
TConnectionLimiter::TStats TConnectionLimiter::GetStats() {
|
||||
std::unique_lock Lock { mMutex };
|
||||
TStats Stats;
|
||||
Stats.CurrentGlobal = mGlobal;
|
||||
Stats.MaxGlobal = mMaxGlobal;
|
||||
Stats.ActiveIpBuckets = mPerIp.size();
|
||||
Stats.MaxPerIp = mMaxPerIp;
|
||||
for (const auto& [_, Count] : mPerIp) {
|
||||
if (Count > Stats.CurrentMaxPerIp) {
|
||||
Stats.CurrentMaxPerIp = Count;
|
||||
}
|
||||
if (Count >= mMaxPerIp) {
|
||||
++Stats.SaturatedIpBuckets;
|
||||
}
|
||||
}
|
||||
return Stats;
|
||||
}
|
||||
|
||||
TConnectionLimiter::TGuard::TGuard(TConnectionLimiter* owner, std::string ip)
|
||||
: mOwner(owner)
|
||||
, mIp(std::move(ip)) {
|
||||
beammp_debugf("Acquired connection guard for {}", mIp);
|
||||
}
|
||||
|
||||
TConnectionLimiter::TGuard& TConnectionLimiter::TGuard::operator=(TGuard&& other) noexcept {
|
||||
// identity check
|
||||
if (this != &other) {
|
||||
Release();
|
||||
mOwner = other.mOwner;
|
||||
mIp = std::move(other.mIp);
|
||||
other.mOwner = nullptr;
|
||||
// setting this so its obvious when this happens, instead of being UB or empty string
|
||||
other.mIp = "<moved-from>";
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void TConnectionLimiter::TGuard::Release() {
|
||||
if (mOwner) {
|
||||
mOwner->Release(mIp);
|
||||
mOwner = nullptr;
|
||||
beammp_debugf("Released connection guard for {}", mIp);
|
||||
}
|
||||
}
|
||||
+275
-78
@@ -22,12 +22,18 @@
|
||||
|
||||
#include "Client.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Http.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "TLuaEngine.h"
|
||||
#include "RegionHandler.h"
|
||||
|
||||
#include <ctime>
|
||||
#include <lua.hpp>
|
||||
#include <mutex>
|
||||
#include <openssl/opensslv.h>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
|
||||
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||
@@ -76,7 +82,7 @@ static std::string GetDate() {
|
||||
auto local_tm = std::localtime(&tt);
|
||||
char buf[30];
|
||||
std::string date;
|
||||
if (Application::Settings.DebugModeEnabled) {
|
||||
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
|
||||
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||
date += buf;
|
||||
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||
@@ -104,41 +110,6 @@ void TConsole::BackupOldLog() {
|
||||
} catch (const std::exception& e) {
|
||||
beammp_warn(e.what());
|
||||
}
|
||||
/*
|
||||
int err = 0;
|
||||
zip* z = zip_open("ServerLogs.zip", ZIP_CREATE, &err);
|
||||
if (!z) {
|
||||
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||
return;
|
||||
}
|
||||
FILE* File = std::fopen(Path.string().c_str(), "r");
|
||||
if (!File) {
|
||||
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> Buffer;
|
||||
Buffer.resize(fs::file_size(Path));
|
||||
std::fread(Buffer.data(), 1, Buffer.size(), File);
|
||||
std::fclose(File);
|
||||
|
||||
auto s = zip_source_buffer(z, Buffer.data(), Buffer.size(), 0);
|
||||
|
||||
auto TimePoint = fs::last_write_time(Path);
|
||||
auto Secs = TimePoint.time_since_epoch().count();
|
||||
auto MyTimeT = std::time(&Secs);
|
||||
|
||||
std::string NewName = Path.stem().string();
|
||||
NewName += "_";
|
||||
std::string Time;
|
||||
Time.resize(32);
|
||||
size_t n = strftime(Time.data(), Time.size(), "%F_%H.%M.%S", localtime(&MyTimeT));
|
||||
Time.resize(n);
|
||||
NewName += Time;
|
||||
NewName += ".log";
|
||||
|
||||
zip_file_add(z, NewName.c_str(), s, 0);
|
||||
zip_close(z);
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +161,7 @@ void TConsole::ChangeToRegularConsole() {
|
||||
}
|
||||
|
||||
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t n) {
|
||||
if (n == 0 && args.size() != 0) {
|
||||
if (n == 0 && !args.empty()) {
|
||||
Application::Console().WriteRaw("This command expects no arguments.");
|
||||
return false;
|
||||
} else if (args.size() != n) {
|
||||
@@ -228,7 +199,7 @@ void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& a
|
||||
} else {
|
||||
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
||||
}
|
||||
} else if (args.size() == 0) {
|
||||
} else if (args.empty()) {
|
||||
ChangeToLuaConsole(mDefaultStateId);
|
||||
}
|
||||
}
|
||||
@@ -239,15 +210,18 @@ void TConsole::Command_Help(const std::string&, const std::vector<std::string>&
|
||||
}
|
||||
static constexpr const char* sHelpString = R"(
|
||||
Commands:
|
||||
help displays this help
|
||||
exit shuts down the server
|
||||
kick <name> [reason] kicks specified player with an optional reason
|
||||
list lists all players and info about them
|
||||
say <message> sends the message to all players in chat
|
||||
lua [state id] switches to lua, optionally into a specific state id's lua
|
||||
settings [command] sets or gets settings for the server, run `settings help` for more info
|
||||
status how the server is doing and what it's up to
|
||||
clear clears the console window)";
|
||||
help displays this help
|
||||
exit shuts down the server
|
||||
kick <name> [reason] kicks specified player with an optional reason
|
||||
list lists all players and info about them
|
||||
say <message> sends the message to all players in chat
|
||||
lua [state id] switches to lua, optionally into a specific state id's lua
|
||||
settings [command] sets or gets settings for the server, run `settings help` for more info
|
||||
status how the server is doing and what it's up to
|
||||
clear clears the console window
|
||||
version displays the server version
|
||||
protectmod <name> <value> sets whether a mod is protected, value can be true or false
|
||||
reloadmods reloads all mods from the Resources Client folder)";
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
}
|
||||
|
||||
@@ -267,6 +241,85 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
|
||||
mCommandline->write("\x1b[;H\x1b[2J");
|
||||
}
|
||||
|
||||
void TConsole::Command_Version(const std::string& cmd, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::string platform;
|
||||
#if defined(BEAMMP_WINDOWS)
|
||||
platform = "Windows";
|
||||
#elif defined(BEAMMP_LINUX)
|
||||
platform = "Linux";
|
||||
#elif defined(BEAMMP_FREEBSD)
|
||||
platform = "FreeBSD";
|
||||
#elif defined(BEAMMP_APPLE)
|
||||
platform = "Apple";
|
||||
#else
|
||||
platform = "Unknown";
|
||||
#endif
|
||||
|
||||
Application::Console().WriteRaw("Platform: " + platform);
|
||||
Application::Console().WriteRaw("Server: v" + Application::ServerVersionString());
|
||||
std::string lua_version = fmt::format("Lua: v{}.{}.{}", LUA_VERSION_MAJOR, LUA_VERSION_MINOR, LUA_VERSION_RELEASE);
|
||||
Application::Console().WriteRaw(lua_version);
|
||||
std::string openssl_version = fmt::format("OpenSSL: v{}.{}.{}", OPENSSL_VERSION_MAJOR, OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH);
|
||||
Application::Console().WriteRaw(openssl_version);
|
||||
}
|
||||
void TConsole::Command_ProtectMod(const std::string& cmd, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 2)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& ModName = args.at(0);
|
||||
const auto& Protect = args.at(1);
|
||||
|
||||
for (auto mod : mLuaEngine->Network().ResourceManager().GetMods()) {
|
||||
if (mod["file_name"].get<std::string>() == ModName) {
|
||||
mLuaEngine->Network().ResourceManager().SetProtected(ModName, Protect == "true");
|
||||
Application::Console().WriteRaw("Mod " + ModName + " is now " + (Protect == "true" ? "protected" : "unprotected"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Application::Console().WriteRaw("Mod " + ModName + " not found.");
|
||||
}
|
||||
void TConsole::Command_ReloadMods(const std::string& cmd, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
mLuaEngine->Network().ResourceManager().RefreshFiles();
|
||||
Application::Console().WriteRaw("Mods reloaded.");
|
||||
}
|
||||
|
||||
void TConsole::Command_NetTest(const std::string& cmd, const std::vector<std::string>& args) {
|
||||
unsigned int status = 0;
|
||||
|
||||
std::string T = Http::GET(
|
||||
Application::GetServerCheckUrl() + "/api/v2/beammp/" + std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)), &status);
|
||||
if (T == Http::ErrorString || status != 200) {
|
||||
RegionHandler::TopLevelDomainFailed();
|
||||
T = Http::GET(Application::GetServerCheckUrl() + "/api/v2/beammp/" + std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)), &status);
|
||||
}
|
||||
|
||||
beammp_debugf("Status and response from Server Check API: {0}, {1}", status, T);
|
||||
|
||||
auto Doc = nlohmann::json::parse(T, nullptr, false);
|
||||
|
||||
if (Doc.is_discarded() || !Doc.is_object()) {
|
||||
beammp_warn("Failed to parse Server Check API response, however the server will most likely still work correctly.");
|
||||
} else {
|
||||
std::string status = Doc["status"];
|
||||
std::string details = "Response from Server Check API: " + std::string(Doc["details"]);
|
||||
if (status == "ok") {
|
||||
beammp_info(details);
|
||||
} else {
|
||||
beammp_warn(details);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||
return;
|
||||
@@ -285,10 +338,9 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
|
||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||
};
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
if (NameCompare(locked->GetName(), Name)) {
|
||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
||||
if (auto Locked = Client.lock()) {
|
||||
if (NameCompare(Locked->GetName(), Name)) {
|
||||
mLuaEngine->Network().ClientKick(*Locked, Reason);
|
||||
Kicked = true;
|
||||
return false;
|
||||
}
|
||||
@@ -307,7 +359,7 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
||||
// It correctly splits arguments, including respecting single and double quotes, as well as backticks
|
||||
auto End_i = CommandWithArgs.find_first_of(' ');
|
||||
std::string Command = CommandWithArgs.substr(0, End_i);
|
||||
std::string ArgsStr {};
|
||||
std::string ArgsStr { };
|
||||
if (End_i != std::string::npos) {
|
||||
ArgsStr = CommandWithArgs.substr(End_i);
|
||||
}
|
||||
@@ -357,8 +409,142 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
||||
return { Command, Args };
|
||||
}
|
||||
|
||||
template <class... Ts>
|
||||
struct overloaded : Ts... {
|
||||
using Ts::operator()...;
|
||||
};
|
||||
template <class... Ts>
|
||||
overloaded(Ts...) -> overloaded<Ts...>;
|
||||
|
||||
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||
if (!EnsureArgsCount(args, 1, 2)) {
|
||||
|
||||
static constexpr const char* sHelpString = R"(
|
||||
Settings:
|
||||
settings help displays this help
|
||||
settings list lists all settings
|
||||
settings get <category> <setting> prints current value of specified setting
|
||||
settings set <category> <setting> <value> sets specified setting to value
|
||||
)";
|
||||
|
||||
if (args.empty()) {
|
||||
beammp_errorf("No arguments specified for command 'settings'!");
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.front() == "help") {
|
||||
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
return;
|
||||
} else if (args.front() == "get") {
|
||||
if (args.size() < 3) {
|
||||
beammp_errorf("'settings get' needs at least two arguments!");
|
||||
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) });
|
||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
||||
|
||||
std::visit(
|
||||
overloaded {
|
||||
[&args](std::string keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
||||
},
|
||||
[&args](int keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
||||
},
|
||||
[&args](bool keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("'{}::{}' = {}", args.at(1), args.at(2), keyValue));
|
||||
}
|
||||
|
||||
},
|
||||
keyType);
|
||||
|
||||
} catch (std::logic_error& e) {
|
||||
beammp_errorf("Error when getting key: {}", e.what());
|
||||
return;
|
||||
}
|
||||
} else if (args.front() == "set") {
|
||||
if (args.size() <= 3) {
|
||||
beammp_errorf("'settings set' needs at least three arguments!");
|
||||
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) });
|
||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
||||
|
||||
std::visit(
|
||||
overloaded {
|
||||
[&args](std::string keyValue) {
|
||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, std::string(args.at(3)));
|
||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), std::string(args.at(3))));
|
||||
},
|
||||
[&args](int keyValue) {
|
||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, std::stoi(args.at(3)));
|
||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), std::stoi(args.at(3))));
|
||||
},
|
||||
[&args](bool keyValue) {
|
||||
if (args.at(3) == "true") {
|
||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, true);
|
||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), "true"));
|
||||
} else if (args.at(3) == "false") {
|
||||
Application::Settings.setConsoleInputAccessMapping(ComposedKey { args.at(1), args.at(2) }, false);
|
||||
Application::Console().WriteRaw(fmt::format("{}::{} := {}", args.at(1), args.at(2), "false"));
|
||||
} else {
|
||||
beammp_errorf("Error when setting key: {}::{} : Unknown literal, use either 'true', or 'false' to set boolean values.", args.at(1), args.at(2));
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
keyType);
|
||||
|
||||
} catch (std::logic_error& e) {
|
||||
beammp_errorf("Exception when setting settings key via console: {}", e.what());
|
||||
return;
|
||||
}
|
||||
|
||||
} else if (args.front() == "list") {
|
||||
for (const auto& [composedKey, keyACL] : Application::Settings.getAccessControlMap()) {
|
||||
// even though we have the value, we want to ignore it in order to make use of access
|
||||
// control checks
|
||||
|
||||
if (keyACL.second != Settings::SettingsAccessMask::NO_ACCESS) {
|
||||
|
||||
try {
|
||||
|
||||
Settings::SettingsAccessControl acl = Application::Settings.getConsoleInputAccessMapping(composedKey);
|
||||
Settings::SettingsTypeVariant keyType = Application::Settings.get(acl.first);
|
||||
|
||||
std::visit(
|
||||
overloaded {
|
||||
[&composedKey](std::string keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
||||
},
|
||||
[&composedKey](int keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
||||
},
|
||||
[&composedKey](bool keyValue) {
|
||||
Application::Console().WriteRaw(fmt::format("{} = {}", composedKey, keyValue));
|
||||
}
|
||||
|
||||
},
|
||||
keyType);
|
||||
} catch (std::logic_error& e) {
|
||||
beammp_errorf("Error when getting key: {}", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
beammp_errorf("Unknown argument for command 'settings': {}", args.front());
|
||||
|
||||
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -367,7 +553,7 @@ void TConsole::Command_Say(const std::string& FullCmd) {
|
||||
if (FullCmd.size() > 3) {
|
||||
auto Message = FullCmd.substr(4);
|
||||
LuaAPI::MP::SendChatMessage(-1, Message);
|
||||
if (!Application::Settings.LogChat) {
|
||||
if (!Application::Settings.getAsBool(Settings::Key::General_LogChat)) {
|
||||
Application::Console().WriteRaw("Chat message sent!");
|
||||
}
|
||||
}
|
||||
@@ -383,11 +569,10 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
|
||||
std::stringstream ss;
|
||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
ss << std::left << std::setw(25) << locked->GetName()
|
||||
<< std::setw(6) << locked->GetID()
|
||||
<< std::setw(6) << locked->GetCarCount() << "\n";
|
||||
if (auto Locked = Client.lock()) {
|
||||
ss << std::left << std::setw(25) << Locked->GetName()
|
||||
<< std::setw(6) << Locked->GetID()
|
||||
<< std::setw(6) << Locked->GetCarCount() << "\n";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
@@ -410,10 +595,9 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
size_t MissedPacketQueueSum = 0;
|
||||
int LargestSecondsSinceLastPing = 0;
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto Locked = Client.lock();
|
||||
if (auto Locked = Client.lock()) {
|
||||
CarCount += Locked->GetCarCount();
|
||||
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
||||
ConnectedCount += Locked->IsUDPConnected() ? 1 : 0;
|
||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
||||
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
||||
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
||||
@@ -430,11 +614,11 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
size_t SystemsBad = 0;
|
||||
size_t SystemsShuttingDown = 0;
|
||||
size_t SystemsShutdown = 0;
|
||||
std::string SystemsBadList {};
|
||||
std::string SystemsGoodList {};
|
||||
std::string SystemsStartingList {};
|
||||
std::string SystemsShuttingDownList {};
|
||||
std::string SystemsShutdownList {};
|
||||
std::string SystemsBadList { };
|
||||
std::string SystemsGoodList { };
|
||||
std::string SystemsStartingList { };
|
||||
std::string SystemsShuttingDownList { };
|
||||
std::string SystemsShutdownList { };
|
||||
auto Statuses = Application::GetSubsystemStatuses();
|
||||
for (const auto& NameStatusPair : Statuses) {
|
||||
switch (NameStatusPair.second) {
|
||||
@@ -470,6 +654,7 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||
|
||||
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
||||
auto ConnectionLimiterStats = mLuaEngine->Network().GetConnectionLimiterStats();
|
||||
|
||||
Status << "BeamMP-Server Status:\n"
|
||||
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
||||
@@ -484,6 +669,11 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||
<< "\t\tEvent timers: " << mLuaEngine->GetTimedEventsCount() << "\n"
|
||||
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
||||
<< "\tConnection limiter:\n"
|
||||
<< "\t\tActive/Max global: " << ConnectionLimiterStats.CurrentGlobal << "/" << ConnectionLimiterStats.MaxGlobal << "\n"
|
||||
<< "\t\tActive IP buckets: " << ConnectionLimiterStats.ActiveIpBuckets << "\n"
|
||||
<< "\t\tHighest single IP load: " << ConnectionLimiterStats.CurrentMaxPerIp << "/" << ConnectionLimiterStats.MaxPerIp << "\n"
|
||||
<< "\t\tSaturated IP buckets: " << ConnectionLimiterStats.SaturatedIpBuckets << "\n"
|
||||
<< "\tSubsystems:\n"
|
||||
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
||||
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
||||
@@ -500,9 +690,13 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
auto FutureIsNonNil =
|
||||
[](const std::shared_ptr<TLuaResult>& Future) {
|
||||
if (!Future->Error && Future->Result.valid()) {
|
||||
auto Type = Future->Result.get_type();
|
||||
return Type != sol::type::lua_nil && Type != sol::type::none;
|
||||
if (!Future->IsError()) {
|
||||
auto Snapshot = Future->GetDetachedSnapshot();
|
||||
if (Snapshot.Result.V.valueless_by_exception() || std::get_if<std::monostate>(&Snapshot.Result.V) != nullptr) {
|
||||
// no value contained
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -512,7 +706,7 @@ void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||
size_t Count = 0;
|
||||
for (auto& Future : Futures) {
|
||||
if (!Future->Error) {
|
||||
if (!Future->IsError()) {
|
||||
++Count;
|
||||
}
|
||||
}
|
||||
@@ -522,7 +716,7 @@ void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (NonNilFutures.size() == 0) {
|
||||
if (NonNilFutures.empty()) {
|
||||
if (!IgnoreNotACommand) {
|
||||
Application::Console().WriteRaw("Error: Unknown command: '" + cmd + "'. Type 'help' to see a list of valid commands.");
|
||||
}
|
||||
@@ -530,14 +724,16 @@ void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
std::stringstream Reply;
|
||||
if (NonNilFutures.size() > 1) {
|
||||
for (size_t i = 0; i < NonNilFutures.size(); ++i) {
|
||||
Reply << NonNilFutures[i]->StateId << ": \n"
|
||||
<< LuaAPI::LuaToString(NonNilFutures[i]->Result);
|
||||
auto Snapshot = NonNilFutures[i]->GetDetachedSnapshot();
|
||||
Reply << Snapshot.StateId << ": \n"
|
||||
<< Snapshot.Result;
|
||||
if (i < NonNilFutures.size() - 1) {
|
||||
Reply << "\n";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Reply << LuaAPI::LuaToString(NonNilFutures[0]->Result);
|
||||
auto Snapshot = NonNilFutures[0]->GetDetachedSnapshot();
|
||||
Reply << Snapshot.Result;
|
||||
}
|
||||
Application::Console().WriteRaw(Reply.str());
|
||||
}
|
||||
@@ -618,8 +814,9 @@ void TConsole::InitializeCommandline() {
|
||||
} else {
|
||||
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
||||
Future->WaitUntilReady();
|
||||
if (Future->Error) {
|
||||
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||
if (Future->IsError()) {
|
||||
auto Snapshot = Future->GetSnapshot();
|
||||
beammp_lua_error("error in " + mStateId + ": " + Snapshot.ErrorMessage);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -651,7 +848,7 @@ void TConsole::InitializeCommandline() {
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else {
|
||||
std::string prefix {}; // stores non-table part of input
|
||||
std::string prefix { }; // stores non-table part of input
|
||||
for (size_t i = stub.length(); i > 0; i--) { // separate table from input
|
||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
|
||||
prefix = stub.substr(0, i);
|
||||
|
||||
+59
-47
@@ -18,14 +18,13 @@
|
||||
|
||||
#include "THeartbeatThread.h"
|
||||
|
||||
#include "ChronoWrapper.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "Http.h"
|
||||
//#include "SocketIO.h"
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/rapidjson.h>
|
||||
#include <sstream>
|
||||
|
||||
namespace json = rapidjson;
|
||||
#include "RegionHandler.h"
|
||||
// #include "SocketIO.h"
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
void THeartbeatThread::operator()() {
|
||||
RegisterThread("Heartbeat");
|
||||
@@ -36,15 +35,17 @@ void THeartbeatThread::operator()() {
|
||||
static std::string Last;
|
||||
|
||||
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||
static std::chrono::high_resolution_clock::time_point LastUpdateReminderTime = std::chrono::high_resolution_clock::now();
|
||||
bool isAuth = false;
|
||||
size_t UpdateReminderCounter = 0;
|
||||
std::chrono::high_resolution_clock::duration UpdateReminderTimePassed;
|
||||
while (!Application::IsShuttingDown()) {
|
||||
++UpdateReminderCounter;
|
||||
auto UpdateReminderTimeout = ChronoWrapper::TimeFromStringWithLiteral(Application::Settings.getAsString(Settings::Key::Misc_UpdateReminderTime));
|
||||
Body = GenerateCall();
|
||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||
auto Now = std::chrono::high_resolution_clock::now();
|
||||
bool Unchanged = Last == Body;
|
||||
auto TimePassed = (Now - LastNormalUpdateTime);
|
||||
UpdateReminderTimePassed = (Now - LastUpdateReminderTime);
|
||||
auto Threshold = Unchanged ? 30 : 5;
|
||||
if (TimePassed < std::chrono::seconds(Threshold)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
@@ -54,22 +55,27 @@ void THeartbeatThread::operator()() {
|
||||
|
||||
Last = Body;
|
||||
LastNormalUpdateTime = Now;
|
||||
if (!Application::Settings.CustomIP.empty()) {
|
||||
Body += "&ip=" + Application::Settings.CustomIP;
|
||||
}
|
||||
|
||||
auto Target = "/heartbeat";
|
||||
unsigned int ResponseCode = 0;
|
||||
|
||||
json::Document Doc;
|
||||
nlohmann::json Doc;
|
||||
bool Ok = false;
|
||||
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||
Doc.Parse(T.data(), T.size());
|
||||
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||
if (!Application::Settings.Private) {
|
||||
T = Http::POST(Url + Target, Body, "application/json", &ResponseCode, { { "api-v", "2" } });
|
||||
if (T == Http::ErrorString || ResponseCode != 200) {
|
||||
RegionHandler::TopLevelDomainFailed();
|
||||
T = Http::POST(Url + Target, Body, "application/json", &ResponseCode, { { "api-v", "2" } });
|
||||
}
|
||||
|
||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
||||
beammp_debug("Backend response was: `" + T + "`");
|
||||
}
|
||||
|
||||
Doc = nlohmann::json::parse(T, nullptr, false);
|
||||
if (Doc.is_discarded() || !Doc.is_object()) {
|
||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
||||
beammp_trace("Backend response failed to parse as valid json");
|
||||
beammp_trace("Response was: `" + T + "`");
|
||||
}
|
||||
} else if (ResponseCode != 200) {
|
||||
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
|
||||
@@ -88,18 +94,18 @@ void THeartbeatThread::operator()() {
|
||||
const auto MessageKey = "msg";
|
||||
|
||||
if (Ok) {
|
||||
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
||||
Status = Doc[StatusKey].GetString();
|
||||
if (Doc.contains(StatusKey) && Doc[StatusKey].is_string()) {
|
||||
Status = Doc[StatusKey];
|
||||
} else {
|
||||
Ok = false;
|
||||
}
|
||||
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||
Code = Doc[CodeKey].GetString();
|
||||
if (Doc.contains(CodeKey) && Doc[CodeKey].is_string()) {
|
||||
Code = Doc[CodeKey];
|
||||
} else {
|
||||
Ok = false;
|
||||
}
|
||||
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||
Message = Doc[MessageKey].GetString();
|
||||
if (Doc.contains(MessageKey) && Doc[MessageKey].is_string()) {
|
||||
Message = Doc[MessageKey];
|
||||
} else {
|
||||
Ok = false;
|
||||
}
|
||||
@@ -107,12 +113,12 @@ void THeartbeatThread::operator()() {
|
||||
beammp_error("Missing/invalid json members in backend response");
|
||||
}
|
||||
} else {
|
||||
if (!Application::Settings.Private) {
|
||||
if (!Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
||||
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
||||
}
|
||||
}
|
||||
|
||||
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||
if (Ok && !isAuth && !Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
||||
if (Status == "2000") {
|
||||
beammp_info(("Authenticated! " + Message));
|
||||
isAuth = true;
|
||||
@@ -126,35 +132,41 @@ void THeartbeatThread::operator()() {
|
||||
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||
}
|
||||
}
|
||||
if (isAuth || Application::Settings.Private) {
|
||||
if (isAuth || Application::Settings.getAsBool(Settings::Key::General_Private)) {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||
}
|
||||
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||
if (!Application::Settings.getAsBool(Settings::Key::Misc_ImScaredOfUpdates) && UpdateReminderTimePassed.count() > UpdateReminderTimeout.count()) {
|
||||
LastUpdateReminderTime = std::chrono::high_resolution_clock::now();
|
||||
Application::CheckForUpdates();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string THeartbeatThread::GenerateCall() {
|
||||
std::stringstream Ret;
|
||||
nlohmann::json Ret = {
|
||||
{ "players", std::to_string(mServer.ClientCount()) },
|
||||
{ "maxplayers", std::to_string(Application::Settings.getAsInt(Settings::Key::General_MaxPlayers)) },
|
||||
{ "port", std::to_string(Application::Settings.getAsInt(Settings::Key::General_Port)) },
|
||||
{ "map", Application::Settings.getAsString(Settings::Key::General_Map) },
|
||||
{ "private", Application::Settings.getAsBool(Settings::Key::General_Private) ? "true" : "false" },
|
||||
{ "version", Application::ServerVersionString() },
|
||||
{ "clientversion", Application::ClientMinimumVersion().AsString() },
|
||||
{ "name", Application::Settings.getAsString(Settings::Key::General_Name) },
|
||||
{ "tags", Application::Settings.getAsString(Settings::Key::General_Tags) },
|
||||
{ "guests", Application::Settings.getAsBool(Settings::Key::General_AllowGuests) ? "true" : "false" },
|
||||
{ "modlist", mResourceManager.TrimmedList() },
|
||||
{ "modstotalsize", std::to_string(mResourceManager.MaxModSize()) },
|
||||
{ "modstotal", std::to_string(mResourceManager.ModsLoaded()) },
|
||||
{ "playerslist", GetPlayers() },
|
||||
{ "desc", Application::Settings.getAsString(Settings::Key::General_Description) }
|
||||
};
|
||||
|
||||
Ret << "uuid=" << Application::Settings.Key
|
||||
<< "&players=" << mServer.ClientCount()
|
||||
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||
<< "&port=" << Application::Settings.Port
|
||||
<< "&map=" << Application::Settings.MapName
|
||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||
<< "&version=" << Application::ServerVersionString()
|
||||
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||
<< "&name=" << Application::Settings.ServerName
|
||||
<< "&tags=" << Application::Settings.ServerTags
|
||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||
<< "&playerslist=" << GetPlayers()
|
||||
<< "&desc=" << Application::Settings.ServerDesc
|
||||
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||
return Ret.str();
|
||||
lastCall = Ret.dump();
|
||||
|
||||
// Add sensitive information here because value of lastCall is used for the information packet.
|
||||
Ret["uuid"] = Application::Settings.getAsString(Settings::Key::General_AuthKey);
|
||||
|
||||
return Ret.dump();
|
||||
}
|
||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||
: mResourceManager(ResourceManager)
|
||||
@@ -173,8 +185,8 @@ std::string THeartbeatThread::GetPlayers() {
|
||||
std::string Return;
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
Return += ClientPtr.lock()->GetName() + ";";
|
||||
if (auto Client = ClientPtr.lock()) {
|
||||
Return += Client->GetName() + ";";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TIoPollThread.h"
|
||||
|
||||
TIoPollThread::TIoPollThread()
|
||||
: mWorkGuard(boost::asio::make_work_guard(mIoCtx))
|
||||
, mThread([this](std::stop_token StopToken) {
|
||||
while (!StopToken.stop_requested()) {
|
||||
try {
|
||||
mIoCtx.run();
|
||||
break;
|
||||
} catch (...) {
|
||||
mIoCtx.restart();
|
||||
}
|
||||
}
|
||||
}) { }
|
||||
|
||||
TIoPollThread::~TIoPollThread() {
|
||||
mWorkGuard.reset();
|
||||
mIoCtx.stop();
|
||||
}
|
||||
+527
-194
File diff suppressed because it is too large
Load Diff
+4
-3
@@ -44,7 +44,7 @@ TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const
|
||||
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
|
||||
return firstStr < secondStr;
|
||||
});
|
||||
std::vector<std::pair<fs::path, std::shared_ptr<TLuaResult>>> ResultsToCheck;
|
||||
std::vector<std::pair<fs::path, std::shared_ptr<TLuaVoidResult>>> ResultsToCheck;
|
||||
for (const auto& Entry : Entries) {
|
||||
// read in entire file
|
||||
try {
|
||||
@@ -63,8 +63,9 @@ TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const
|
||||
}
|
||||
for (auto& Result : ResultsToCheck) {
|
||||
Result.second->WaitUntilReady();
|
||||
if (Result.second->Error) {
|
||||
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Result.second->ErrorMessage);
|
||||
auto Snapshot = Result.second->GetSnapshot();
|
||||
if (Snapshot.Error) {
|
||||
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Snapshot.ErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2026 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TLuaResult.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <sol/unsafe_function_result.hpp>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const TDetachedLuaValue& value) {
|
||||
std::visit([&os](auto&& arg) {
|
||||
using T = std::decay_t<decltype(arg)>;
|
||||
if constexpr (std::is_same_v<T, TDetachedLuaValue::Array>) {
|
||||
size_t i = 0;
|
||||
for (const auto& val : arg) {
|
||||
if (i > 0) {
|
||||
os << ", ";
|
||||
}
|
||||
os << val;
|
||||
++i;
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, TDetachedLuaValue::Object>) {
|
||||
size_t i = 0;
|
||||
for (const auto& [key, val] : arg) {
|
||||
if (i > 0) {
|
||||
os << ", ";
|
||||
}
|
||||
os << key << "=" << val;
|
||||
++i;
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, bool>)
|
||||
os << (arg ? "true" : "false");
|
||||
else if constexpr (std::is_same_v<T, double>)
|
||||
os << arg;
|
||||
else if constexpr (std::is_same_v<T, int>)
|
||||
os << arg;
|
||||
else if constexpr (std::is_same_v<T, std::string>)
|
||||
os << arg;
|
||||
else if constexpr (std::is_same_v<T, std::monostate>)
|
||||
// monostate means no result value
|
||||
os << "";
|
||||
else
|
||||
static_assert(AlwaysFalseV<T>, "non-exhaustive visitor!");
|
||||
},
|
||||
value.V);
|
||||
|
||||
return os;
|
||||
}
|
||||
|
||||
void TLuaVoidResult::MarkReadySuccess() {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = false;
|
||||
mErrorMessage.clear();
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
void TLuaVoidResult::MarkReadyError(sol::protected_function_result Res) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = true;
|
||||
SetErrorMessageFromResult(Res);
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
void TLuaVoidResult::MarkReadyError(std::string Res) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = true;
|
||||
mErrorMessage = std::move(Res);
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
bool TLuaVoidResult::IsReady() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
return mReady;
|
||||
}
|
||||
|
||||
bool TLuaVoidResult::IsError() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
return mError;
|
||||
}
|
||||
|
||||
TLuaVoidResult::Snapshot TLuaVoidResult::GetSnapshot() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
Snapshot snapshot {
|
||||
.Error = mError,
|
||||
.Ready = mReady,
|
||||
.ErrorMessage = mErrorMessage,
|
||||
.StateId = mStateId,
|
||||
};
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
void TLuaVoidResult::MarkAsReady() {
|
||||
mReady = true;
|
||||
mReadyCondition.notify_all();
|
||||
}
|
||||
|
||||
void TLuaVoidResult::WaitUntilReady() {
|
||||
std::unique_lock Lock(mMutex);
|
||||
while (!mReady)
|
||||
mReadyCondition.wait_for(Lock, std::chrono::milliseconds(50),
|
||||
[this] {
|
||||
return mReady;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void TLuaResult::MarkReadySuccess(sol::object Res) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = false;
|
||||
mDetachedResult = Freeze(Res);
|
||||
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
void TLuaResult::MarkReadySuccessNoResult() {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = false;
|
||||
mDetachedResult = { { std::monostate { } } };
|
||||
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
void TLuaResult::MarkReadyError(sol::protected_function_result Res) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = true;
|
||||
SetErrorMessageFromResult(Res);
|
||||
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
void TLuaResult::MarkReadyError(std::string Res) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mError = true;
|
||||
mErrorMessage = std::move(Res);
|
||||
|
||||
MarkAsReady();
|
||||
}
|
||||
|
||||
bool TLuaResult::IsReady() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
return mReady;
|
||||
}
|
||||
bool TLuaResult::IsError() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
return mError;
|
||||
}
|
||||
|
||||
TLuaStateId TLuaResult::OwnerState() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
// copy
|
||||
return mStateId;
|
||||
}
|
||||
void TLuaResult::SetOwnerState(TLuaStateId StateId) {
|
||||
std::unique_lock Lock(mMutex);
|
||||
mStateId = std::move(StateId);
|
||||
}
|
||||
|
||||
TLuaResult::DetachedSnapshot TLuaResult::GetDetachedSnapshot() const {
|
||||
std::unique_lock Lock(mMutex);
|
||||
DetachedSnapshot snapshot {
|
||||
.Error = mError,
|
||||
.Ready = mReady,
|
||||
.ErrorMessage = mErrorMessage,
|
||||
.Result = mDetachedResult,
|
||||
.StateId = mStateId,
|
||||
.Function = mFunction,
|
||||
};
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
TDetachedLuaValue TLuaResult::Freeze(const sol::object& o, int depth) {
|
||||
if (depth > 64)
|
||||
throw std::runtime_error("max depth (64) reached");
|
||||
switch (o.get_type()) {
|
||||
case sol::type::lua_nil:
|
||||
return { { std::monostate { } } };
|
||||
case sol::type::boolean:
|
||||
return { { o.as<bool>() } };
|
||||
case sol::type::number: {
|
||||
if (o.is<int>()) {
|
||||
return { { o.as<int>() } };
|
||||
} else {
|
||||
return { { o.as<double>() } };
|
||||
}
|
||||
}
|
||||
case sol::type::string:
|
||||
return { { o.as<std::string>() } };
|
||||
case sol::type::table: {
|
||||
TDetachedLuaValue::Object ObjectOut;
|
||||
// numeric stuff is for arrays
|
||||
std::vector<std::pair<size_t, TDetachedLuaValue>> NumericEntries;
|
||||
bool HasNonStringOrNumericKey = false;
|
||||
size_t MaxNumericIndex = 0;
|
||||
for (auto&& [k, v] : o.as<sol::table>()) {
|
||||
if (k.is<std::string>()) {
|
||||
ObjectOut.emplace(k.as<std::string>(), std::make_shared<TDetachedLuaValue>(std::move(Freeze(v, depth + 1))));
|
||||
continue;
|
||||
}
|
||||
// Thanks to lua handling arrays in a weird way, and because they can also be sparse, this weird code is needed.
|
||||
if (k.get_type() == sol::type::number) {
|
||||
const double NumericKey = k.as<double>();
|
||||
const size_t CandidateIndex = static_cast<size_t>(NumericKey);
|
||||
// unsure if we need to do this, or if we can do the same int check we do in other places, but this works well
|
||||
const bool IsPositiveInteger = std::isfinite(NumericKey)
|
||||
&& NumericKey >= 1.0
|
||||
&& std::fabs(NumericKey - static_cast<double>(CandidateIndex)) <= std::numeric_limits<double>::epsilon();
|
||||
if (IsPositiveInteger) {
|
||||
const auto Index = CandidateIndex;
|
||||
MaxNumericIndex = std::max(MaxNumericIndex, Index);
|
||||
NumericEntries.emplace_back(Index, Freeze(v, depth + 1));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
HasNonStringOrNumericKey = true;
|
||||
}
|
||||
// Pure numeric-keyed tables are reconstructed as Lua arrays (1-based indexes).
|
||||
// This preserves array semantics across this serialization boundary :^)
|
||||
if (!NumericEntries.empty() && ObjectOut.empty() && !HasNonStringOrNumericKey) {
|
||||
TDetachedLuaValue::Array ArrayOut(MaxNumericIndex);
|
||||
for (const auto& [Index, Value] : NumericEntries) {
|
||||
if (Index > 0 && Index <= ArrayOut.size()) {
|
||||
ArrayOut[Index - 1] = Value;
|
||||
}
|
||||
}
|
||||
return { { std::move(ArrayOut) } };
|
||||
}
|
||||
return { { std::move(ObjectOut) } };
|
||||
}
|
||||
default:
|
||||
throw std::runtime_error("unsupported Lua type for cross-thread snapshot");
|
||||
}
|
||||
}
|
||||
void TLuaResult::MarkAsReady() {
|
||||
mReady = true;
|
||||
mReadyCondition.notify_all();
|
||||
}
|
||||
|
||||
void TLuaResult::WaitUntilReady() {
|
||||
std::unique_lock Lock(mMutex);
|
||||
while (!mReady)
|
||||
mReadyCondition.wait_for(Lock, std::chrono::milliseconds(50),
|
||||
[this] {
|
||||
return mReady;
|
||||
});
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaInStateResult MarkReadyError(string) marks ready and wakes waiters") {
|
||||
TLuaVoidResult result("state_local");
|
||||
std::atomic<bool> waiterDone { false };
|
||||
|
||||
auto waiter = std::thread([&] {
|
||||
result.WaitUntilReady();
|
||||
waiterDone.store(true, std::memory_order_release);
|
||||
});
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
CHECK_FALSE(waiterDone.load(std::memory_order_acquire));
|
||||
|
||||
result.MarkReadyError(std::string("boom"));
|
||||
waiter.join();
|
||||
|
||||
CHECK(result.IsReady());
|
||||
const auto snapshot = result.GetSnapshot();
|
||||
CHECK(snapshot.Ready);
|
||||
CHECK(snapshot.Error);
|
||||
CHECK(snapshot.ErrorMessage == "boom");
|
||||
CHECK(snapshot.StateId == "state_local");
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaInStateResult MarkReadySuccess clears error state") {
|
||||
TLuaVoidResult result("state_local_success");
|
||||
result.MarkReadySuccess();
|
||||
|
||||
CHECK(result.IsReady());
|
||||
CHECK_FALSE(result.IsError());
|
||||
const auto snapshot = result.GetSnapshot();
|
||||
CHECK(snapshot.Ready);
|
||||
CHECK_FALSE(snapshot.Error);
|
||||
CHECK(snapshot.ErrorMessage.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaResult MarkReadyError(string) marks ready and wakes waiters") {
|
||||
TLuaResult result("state_a", "fn_a");
|
||||
std::atomic<bool> waiterDone { false };
|
||||
|
||||
auto waiter = std::thread([&] {
|
||||
result.WaitUntilReady();
|
||||
waiterDone.store(true, std::memory_order_release);
|
||||
});
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
CHECK_FALSE(waiterDone.load(std::memory_order_acquire));
|
||||
|
||||
result.MarkReadyError(std::string("boom"));
|
||||
waiter.join();
|
||||
|
||||
CHECK(result.IsReady());
|
||||
const auto snapshot = result.GetDetachedSnapshot();
|
||||
CHECK(snapshot.Ready);
|
||||
CHECK(snapshot.Error);
|
||||
CHECK(snapshot.ErrorMessage == "boom");
|
||||
CHECK(snapshot.StateId == "state_a");
|
||||
CHECK(snapshot.Function == "fn_a");
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaResult detached snapshot freezes nested string-keyed tables") {
|
||||
sol::state lua;
|
||||
TLuaResult result("state_table", "fn_table");
|
||||
lua.open_libraries(sol::lib::base);
|
||||
|
||||
auto outer = lua.create_table();
|
||||
auto inner = lua.create_table();
|
||||
inner["k"] = std::string("v");
|
||||
|
||||
outer["flag"] = true;
|
||||
outer["msg"] = std::string("hello");
|
||||
outer["inner"] = inner;
|
||||
outer[1] = std::string("ignored_numeric_key");
|
||||
|
||||
result.MarkReadySuccess(sol::make_object(lua.lua_state(), outer));
|
||||
const auto detached = result.GetDetachedSnapshot();
|
||||
|
||||
CHECK(detached.Ready);
|
||||
CHECK_FALSE(detached.Error);
|
||||
const auto* object = std::get_if<TDetachedLuaValue::Object>(&detached.Result.V);
|
||||
REQUIRE(object != nullptr);
|
||||
|
||||
CHECK(object->contains("flag"));
|
||||
CHECK(object->contains("msg"));
|
||||
CHECK(object->contains("inner"));
|
||||
CHECK_FALSE(object->contains("1"));
|
||||
|
||||
const auto* flag = std::get_if<bool>(&object->at("flag")->V);
|
||||
REQUIRE(flag != nullptr);
|
||||
CHECK(*flag);
|
||||
|
||||
const auto* msg = std::get_if<std::string>(&object->at("msg")->V);
|
||||
REQUIRE(msg != nullptr);
|
||||
CHECK(*msg == "hello");
|
||||
|
||||
const auto* innerObj = std::get_if<TDetachedLuaValue::Object>(&object->at("inner")->V);
|
||||
REQUIRE(innerObj != nullptr);
|
||||
REQUIRE(innerObj->contains("k"));
|
||||
const auto* innerValue = std::get_if<std::string>(&innerObj->at("k")->V);
|
||||
REQUIRE(innerValue != nullptr);
|
||||
CHECK(*innerValue == "v");
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaResult detached snapshot preserves numeric array tables") {
|
||||
sol::state lua;
|
||||
TLuaResult result("state_array", "fn_array");
|
||||
lua.open_libraries(sol::lib::base);
|
||||
|
||||
auto arr = lua.create_table();
|
||||
arr[1] = std::string("a");
|
||||
arr[2] = 42;
|
||||
arr[4] = true; // keep sparse indexes
|
||||
|
||||
result.MarkReadySuccess(sol::make_object(lua.lua_state(), arr));
|
||||
const auto detached = result.GetDetachedSnapshot();
|
||||
|
||||
CHECK(detached.Ready);
|
||||
CHECK_FALSE(detached.Error);
|
||||
|
||||
const auto* array = std::get_if<TDetachedLuaValue::Array>(&detached.Result.V);
|
||||
REQUIRE(array != nullptr);
|
||||
REQUIRE(array->size() == 4);
|
||||
|
||||
const auto* v1 = std::get_if<std::string>(&(*array)[0].V);
|
||||
REQUIRE(v1 != nullptr);
|
||||
CHECK(*v1 == "a");
|
||||
|
||||
const auto* v2 = std::get_if<int>(&(*array)[1].V);
|
||||
REQUIRE(v2 != nullptr);
|
||||
CHECK(*v2 == 42);
|
||||
|
||||
CHECK(std::holds_alternative<std::monostate>((*array)[2].V));
|
||||
|
||||
const auto* v4 = std::get_if<bool>(&(*array)[3].V);
|
||||
REQUIRE(v4 != nullptr);
|
||||
CHECK(*v4);
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaResult MarkReadySuccess throws on unsupported Lua function value") {
|
||||
sol::state lua;
|
||||
TLuaResult result("state_fn", "fn_fn");
|
||||
lua.open_libraries(sol::lib::base);
|
||||
lua["f"] = [] { return 1; };
|
||||
const sol::table globals = lua.globals();
|
||||
const sol::protected_function fn = globals.get<sol::protected_function>("f");
|
||||
const sol::object fnObj = sol::make_object(lua.lua_state(), fn);
|
||||
|
||||
CHECK_THROWS_AS(result.MarkReadySuccess(fnObj), std::runtime_error);
|
||||
CHECK_FALSE(result.IsReady());
|
||||
}
|
||||
|
||||
TEST_CASE("TLuaResult MarkReadySuccessNoResult stores monostate") {
|
||||
TLuaResult result("state_empty", "fn_empty");
|
||||
result.MarkReadySuccessNoResult();
|
||||
|
||||
CHECK(result.IsReady());
|
||||
const auto snapshot = result.GetDetachedSnapshot();
|
||||
CHECK_FALSE(snapshot.Error);
|
||||
CHECK(std::holds_alternative<std::monostate>(snapshot.Result.V));
|
||||
}
|
||||
+611
-272
File diff suppressed because it is too large
Load Diff
+7
-4
@@ -55,8 +55,8 @@ void TPPSMonitor::operator()() {
|
||||
std::shared_ptr<TClient> c;
|
||||
{
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
c = ClientPtr.lock();
|
||||
if (auto Locked = ClientPtr.lock()) {
|
||||
c = std::move(Locked);
|
||||
} else
|
||||
return true;
|
||||
}
|
||||
@@ -66,14 +66,17 @@ void TPPSMonitor::operator()() {
|
||||
}
|
||||
// kick on "no ping"
|
||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
||||
beammp_debugf("client {} ({}) timing out: {}", c->GetID(), c->GetName(), c->SecondsSinceLastPing());
|
||||
TimedOutClients.push_back(c);
|
||||
} else if (c->IsSynced() && c->SecondsSinceLastPing() > (1 * 60)) {
|
||||
beammp_debugf("client {} ({}) timing out: {}", c->GetName(), c->GetID(), c->SecondsSinceLastPing());
|
||||
TimedOutClients.push_back(c);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
for (auto& ClientToKick : TimedOutClients) {
|
||||
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
||||
Network().DisconnectClient(*ClientToKick, "Timeout");
|
||||
}
|
||||
TimedOutClients.clear();
|
||||
if (C == 0 || mInternalPPS == 0) {
|
||||
|
||||
+20
-14
@@ -57,21 +57,27 @@ void TPluginMonitor::operator()() {
|
||||
mFileTimes[Pair.first] = CurrentTime;
|
||||
// grandparent of the path should be Resources/Server
|
||||
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
|
||||
beammp_infof("File \"{}\" changed, reloading", Pair.first);
|
||||
// is in root folder, so reload
|
||||
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
||||
auto Size = std::filesystem::file_size(Pair.first);
|
||||
auto Contents = std::make_shared<std::string>();
|
||||
Contents->resize(Size);
|
||||
FileStream.read(Contents->data(), Contents->size());
|
||||
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
||||
auto StateID = mEngine->GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
||||
auto Res = mEngine->EnqueueScript(StateID, Chunk);
|
||||
Res->WaitUntilReady();
|
||||
if (Res->Error) {
|
||||
beammp_lua_errorf("Error while hot-reloading \"{}\": {}", Pair.first, Res->ErrorMessage);
|
||||
if (LowerString(fs::path(Pair.first).extension().string()) == ".lua") {
|
||||
beammp_infof("File \"{}\" changed, reloading", Pair.first);
|
||||
// is in root folder, so reload
|
||||
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
||||
auto Size = std::filesystem::file_size(Pair.first);
|
||||
auto Contents = std::make_shared<std::string>();
|
||||
Contents->resize(Size);
|
||||
FileStream.read(Contents->data(), Contents->size());
|
||||
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
||||
auto StateID = mEngine->GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
||||
auto Res = mEngine->EnqueueScript(StateID, Chunk);
|
||||
Res->WaitUntilReady();
|
||||
if (Res->IsError()) {
|
||||
auto Snapshot = Res->GetSnapshot();
|
||||
beammp_lua_errorf("Error while hot-reloading \"{}\": {}", Pair.first, Snapshot.ErrorMessage);
|
||||
} else {
|
||||
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
|
||||
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||
}
|
||||
} else {
|
||||
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
|
||||
beammp_debugf("File \"{}\" changed, not reloading because it's not a lua file. Triggering 'onFileChanged' event instead", Pair.first);
|
||||
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||
}
|
||||
} else {
|
||||
|
||||
+188
-1
@@ -17,15 +17,20 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TResourceManager.h"
|
||||
#include "Common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <fmt/core.h>
|
||||
#include <ios>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <openssl/evp.h>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
TResourceManager::TResourceManager() {
|
||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||
std::string Path = Application::Settings.Resource + "/Client";
|
||||
std::string Path = Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "/Client";
|
||||
if (!fs::exists(Path))
|
||||
fs::create_directories(Path);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
@@ -52,3 +57,185 @@ TResourceManager::TResourceManager() {
|
||||
|
||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
||||
}
|
||||
|
||||
void TResourceManager::RefreshFiles() {
|
||||
mMods.clear();
|
||||
std::unique_lock Lock(mModsMutex);
|
||||
|
||||
std::string Path = Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "/Client";
|
||||
|
||||
nlohmann::json modsDB;
|
||||
|
||||
if (std::filesystem::exists(Path + "/mods.json")) {
|
||||
try {
|
||||
std::ifstream stream(Path + "/mods.json");
|
||||
|
||||
stream >> modsDB;
|
||||
|
||||
stream.close();
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("Failed to load mods.json: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
std::string File(entry.path().string());
|
||||
|
||||
if (entry.path().filename().string() == "mods.json") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.path().extension() != ".zip" || std::filesystem::is_directory(entry.path())) {
|
||||
beammp_warnf("'{}' is not a ZIP file and will be ignored", File);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (modsDB.contains(entry.path().filename().string())) {
|
||||
auto& dbEntry = modsDB[entry.path().filename().string()];
|
||||
if (entry.last_write_time().time_since_epoch().count() > dbEntry["lastwrite"] || std::filesystem::file_size(File) != dbEntry["filesize"].get<size_t>()) {
|
||||
beammp_infof("File '{}' has been modified, rehashing", File);
|
||||
} else {
|
||||
dbEntry["exists"] = true;
|
||||
|
||||
mMods.push_back(nlohmann::json {
|
||||
{ "file_name", std::filesystem::path(File).filename() },
|
||||
{ "file_size", std::filesystem::file_size(File) },
|
||||
{ "hash_algorithm", "sha256" },
|
||||
{ "hash", dbEntry["hash"] },
|
||||
{ "protected", dbEntry["protected"] } });
|
||||
|
||||
beammp_debugf("Mod '{}' loaded from cache", File);
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
EVP_MD_CTX* mdctx;
|
||||
const EVP_MD* md;
|
||||
uint8_t sha256_value[EVP_MAX_MD_SIZE];
|
||||
md = EVP_sha256();
|
||||
if (md == nullptr) {
|
||||
throw std::runtime_error("EVP_sha256() failed");
|
||||
}
|
||||
|
||||
mdctx = EVP_MD_CTX_new();
|
||||
if (mdctx == nullptr) {
|
||||
throw std::runtime_error("EVP_MD_CTX_new() failed");
|
||||
}
|
||||
if (!EVP_DigestInit_ex2(mdctx, md, NULL)) {
|
||||
EVP_MD_CTX_free(mdctx);
|
||||
throw std::runtime_error("EVP_DigestInit_ex2() failed");
|
||||
}
|
||||
|
||||
std::ifstream stream(File, std::ios::binary);
|
||||
|
||||
const size_t FileSize = std::filesystem::file_size(File);
|
||||
size_t Read = 0;
|
||||
std::vector<char> Data;
|
||||
while (Read < FileSize) {
|
||||
Data.resize(size_t(std::min<size_t>(FileSize - Read, 4096)));
|
||||
size_t RealDataSize = Data.size();
|
||||
stream.read(Data.data(), std::streamsize(Data.size()));
|
||||
if (stream.eof() || stream.fail()) {
|
||||
RealDataSize = size_t(stream.gcount());
|
||||
}
|
||||
Data.resize(RealDataSize);
|
||||
if (RealDataSize == 0) {
|
||||
break;
|
||||
}
|
||||
if (RealDataSize > 0 && !EVP_DigestUpdate(mdctx, Data.data(), Data.size())) {
|
||||
EVP_MD_CTX_free(mdctx);
|
||||
throw std::runtime_error("EVP_DigestUpdate() failed");
|
||||
}
|
||||
Read += RealDataSize;
|
||||
}
|
||||
unsigned int sha256_len = 0;
|
||||
if (!EVP_DigestFinal_ex(mdctx, sha256_value, &sha256_len)) {
|
||||
EVP_MD_CTX_free(mdctx);
|
||||
throw std::runtime_error("EVP_DigestFinal_ex() failed");
|
||||
}
|
||||
EVP_MD_CTX_free(mdctx);
|
||||
|
||||
stream.close();
|
||||
|
||||
std::string result;
|
||||
for (size_t i = 0; i < sha256_len; i++) {
|
||||
result += fmt::format("{:02x}", sha256_value[i]);
|
||||
}
|
||||
beammp_debugf("sha256('{}'): {}", File, result);
|
||||
mMods.push_back(nlohmann::json {
|
||||
{ "file_name", std::filesystem::path(File).filename() },
|
||||
{ "file_size", std::filesystem::file_size(File) },
|
||||
{ "hash_algorithm", "sha256" },
|
||||
{ "hash", result },
|
||||
{ "protected", false } });
|
||||
|
||||
modsDB[std::filesystem::path(File).filename().string()] = {
|
||||
{ "lastwrite", entry.last_write_time().time_since_epoch().count() },
|
||||
{ "hash", result },
|
||||
{ "filesize", std::filesystem::file_size(File) },
|
||||
{ "protected", false },
|
||||
{ "exists", true }
|
||||
};
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("Sha256 hashing of '{}' failed: {}", File, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
for (auto it = modsDB.begin(); it != modsDB.end();) {
|
||||
if (!it.value().contains("exists")) {
|
||||
it = modsDB.erase(it);
|
||||
} else {
|
||||
it.value().erase("exists");
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
std::ofstream stream(Path + "/mods.json");
|
||||
|
||||
stream << modsDB.dump(4);
|
||||
|
||||
stream.close();
|
||||
} catch (std::exception& e) {
|
||||
beammp_error("Failed to update mod DB: " + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void TResourceManager::SetProtected(const std::string& ModName, bool Protected) {
|
||||
std::unique_lock Lock(mModsMutex);
|
||||
|
||||
for (auto& mod : mMods) {
|
||||
if (mod["file_name"].get<std::string>() == ModName) {
|
||||
mod["protected"] = Protected;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
auto modsDBPath = Application::Settings.getAsString(Settings::Key::General_ResourceFolder) + "/Client/mods.json";
|
||||
|
||||
if (std::filesystem::exists(modsDBPath)) {
|
||||
try {
|
||||
nlohmann::json modsDB;
|
||||
|
||||
std::fstream stream(modsDBPath);
|
||||
|
||||
stream >> modsDB;
|
||||
|
||||
if (modsDB.contains(ModName)) {
|
||||
modsDB[ModName]["protected"] = Protected;
|
||||
}
|
||||
|
||||
stream.clear();
|
||||
stream.seekp(0, std::ios::beg);
|
||||
|
||||
stream << modsDB.dump(4);
|
||||
|
||||
stream.close();
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("Failed to update mods.json: {}", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+193
-73
@@ -20,6 +20,7 @@
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "TLuaEngine.h"
|
||||
#include "TNetwork.h"
|
||||
#include "TPPSMonitor.h"
|
||||
#include <TLuaPlugin.h>
|
||||
@@ -27,6 +28,7 @@
|
||||
#include <any>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -52,7 +54,6 @@ static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
TEST_CASE("GetPidVid") {
|
||||
SUBCASE("Valid singledigit") {
|
||||
const auto MaybePidVid = GetPidVid("0-1");
|
||||
@@ -119,39 +120,22 @@ TEST_CASE("GetPidVid") {
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
}
|
||||
|
||||
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||
if (Arguments.size() > 1) {
|
||||
Application::Settings.CustomIP = Arguments[0];
|
||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
||||
Application::Settings.CustomIP.clear();
|
||||
beammp_warn("IP Specified is invalid! Ignoring");
|
||||
} else {
|
||||
beammp_info("server started with custom IP");
|
||||
}
|
||||
}
|
||||
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
||||
}
|
||||
|
||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
||||
try {
|
||||
LockedClientPtr = WeakClientPtr.lock();
|
||||
} catch (const std::exception&) {
|
||||
// silently fail, as there's nothing to do
|
||||
auto LockedClientPtr = WeakClientPtr.lock();
|
||||
if (!LockedClientPtr) {
|
||||
return;
|
||||
}
|
||||
beammp_assert(LockedClientPtr != nullptr);
|
||||
TClient& Client = *LockedClientPtr;
|
||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||
// TODO: Send delete packets for all cars
|
||||
Client.ClearCars();
|
||||
WriteLock Lock(mClientsMutex);
|
||||
mClients.erase(WeakClientPtr.lock());
|
||||
mClients.erase(LockedClientPtr);
|
||||
}
|
||||
|
||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||
@@ -172,20 +156,34 @@ size_t TServer::ClientCount() const {
|
||||
return mClients.size();
|
||||
}
|
||||
|
||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network, bool udp) {
|
||||
constexpr std::string_view ABG = "ABG:";
|
||||
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
||||
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
||||
Packet = DeComp(Packet);
|
||||
try {
|
||||
Packet = DeComp(Packet);
|
||||
} catch (const InvalidDataError& ) {
|
||||
if (auto LockedClient = Client.lock()) {
|
||||
beammp_errorf("Failed to decompress packet from client {}. The client sent invalid data and will now be disconnected.", LockedClient->GetID());
|
||||
Network.ClientKick(*LockedClient, "Sent invalid compressed packet (this is likely a bug on your end)");
|
||||
}
|
||||
return;
|
||||
} catch (const std::runtime_error& e) {
|
||||
if (auto LockedClient = Client.lock()) {
|
||||
beammp_errorf("Failed to decompress packet from client {}: {}. The server might be out of RAM! The client will now be disconnected.", LockedClient->GetID(), e.what());
|
||||
Network.ClientKick(*LockedClient, "Decompression failed (likely a server-side problem)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (Packet.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Client.expired()) {
|
||||
auto LockedClient = Client.lock();
|
||||
if (!LockedClient) {
|
||||
return;
|
||||
}
|
||||
auto LockedClient = Client.lock();
|
||||
|
||||
std::any Res;
|
||||
char Code = Packet.at(0);
|
||||
@@ -194,12 +192,29 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
||||
|
||||
// V to Y
|
||||
if (Code <= 89 && Code >= 86) {
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
|
||||
auto pidVidPart = StringPacket.substr(3);
|
||||
auto MaybePidVid = GetPidVid(pidVidPart.substr(0, pidVidPart.find(':')));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
|
||||
if (PID == -1 || VID == -1 || PID != LockedClient->GetID()) {
|
||||
return;
|
||||
}
|
||||
|
||||
PPSMonitor.IncrementInternalPPS();
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||
return;
|
||||
}
|
||||
switch (Code) {
|
||||
case 'H': // initial connection
|
||||
if (udp) {
|
||||
beammp_debugf("Received 'H' packet over UDP from client '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
if (!Network.SyncClient(Client)) {
|
||||
// TODO handle
|
||||
}
|
||||
@@ -207,18 +222,26 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
||||
case 'p':
|
||||
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
||||
// failed to send
|
||||
LockedClient->Disconnect("Failed to send ping");
|
||||
Network.DisconnectClient(*LockedClient, "Failed to send ping");
|
||||
} else {
|
||||
Network.UpdatePlayer(*LockedClient);
|
||||
}
|
||||
return;
|
||||
case 'O':
|
||||
if (udp) {
|
||||
beammp_debugf("Received 'O' packet over UDP from client '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
if (Packet.size() > 1000) {
|
||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
||||
}
|
||||
ParseVehicle(*LockedClient, StringPacket, Network);
|
||||
return;
|
||||
case 'C': {
|
||||
if (udp) {
|
||||
beammp_debugf("Received 'C' packet over UDP from client '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
||||
break;
|
||||
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||
@@ -231,33 +254,63 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
|
||||
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
if (Message.size() > 500) {
|
||||
beammp_debugf("Chat message too long from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
||||
if (std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||
return !Elem->Error
|
||||
&& Elem->Result.is<int>()
|
||||
&& bool(Elem->Result.as<int>());
|
||||
})) {
|
||||
break;
|
||||
bool Rejected = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||
auto Snapshot = Elem->GetDetachedSnapshot();
|
||||
if (Snapshot.Error) {
|
||||
return false;
|
||||
}
|
||||
const int* MaybeInt = std::get_if<int>(&Snapshot.Result.V);
|
||||
if (MaybeInt == nullptr) {
|
||||
return false;
|
||||
}
|
||||
return bool(*MaybeInt);
|
||||
});
|
||||
if (!Rejected) {
|
||||
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
||||
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
||||
}
|
||||
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
||||
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postChatMessage", "", !Rejected, LockedClient->GetID(), LockedClient->GetName(), Message);
|
||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
||||
return;
|
||||
}
|
||||
case 'E':
|
||||
if (udp) {
|
||||
beammp_debugf("Received 'E' packet over UDP from client '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
|
||||
return;
|
||||
}
|
||||
HandleEvent(*LockedClient, StringPacket);
|
||||
return;
|
||||
case 'N':
|
||||
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||
return;
|
||||
case 'Z': // position packet
|
||||
case 'Z': { // position packet
|
||||
PPSMonitor.IncrementInternalPPS();
|
||||
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
|
||||
auto pidVidPart = StringPacket.substr(3);
|
||||
auto MaybePidVid = GetPidVid(pidVidPart.substr(0, pidVidPart.find(':')));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
|
||||
if (PID == -1 || VID == -1 || PID != LockedClient->GetID()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||
HandlePosition(*LockedClient, StringPacket);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
@@ -276,6 +329,15 @@ void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||
}
|
||||
std::string Name = RawData.substr(2, NameDataSep - 2);
|
||||
std::string Data = RawData.substr(NameDataSep + 1);
|
||||
|
||||
std::vector<std::string> exclude = {"onInit", "onFileChanged","onVehicleDeleted","onConsoleInput","onPlayerAuth","postPlayerAuth", "onPlayerDisconnect",
|
||||
"onPlayerConnecting","onPlayerJoining","onPlayerJoin","onChatMessage","postChatMessage","onVehicleSpawn","postVehicleSpawn","onVehicleEdited", "postVehicleEdited",
|
||||
"onVehicleReset","onVehiclePaintChanged","onShutdown"};
|
||||
|
||||
if (std::ranges::find(exclude, Name) != exclude.end()) {
|
||||
beammp_debugf("Excluded event triggered by client '{}' ({}): '{}', ignoring.", c.GetName(), c.GetID(), Name);
|
||||
return;
|
||||
}
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
||||
}
|
||||
|
||||
@@ -297,7 +359,7 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
||||
c.SetUnicycleID(ID);
|
||||
return true;
|
||||
} else {
|
||||
return c.GetCarCount() < Application::Settings.MaxCars;
|
||||
return c.GetCarCount() < Application::Settings.getAsInt(Settings::Key::General_MaxCars);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,22 +384,38 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||
auto Snapshot = Result->GetDetachedSnapshot();
|
||||
if (Snapshot.Error) {
|
||||
return false;
|
||||
}
|
||||
const int* MaybeInt = std::get_if<int>(&Snapshot.Result.V);
|
||||
if (MaybeInt == nullptr) {
|
||||
return false;
|
||||
}
|
||||
return *MaybeInt != 0;
|
||||
});
|
||||
|
||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||
c.AddNewCar(CarID, Packet);
|
||||
bool SpawnConfirmed = false;
|
||||
auto CarJsonDoc = nlohmann::json::parse(CarJson, nullptr, false);
|
||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn && !CarJsonDoc.is_discarded()) {
|
||||
c.AddNewCar(CarID, CarJsonDoc);
|
||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
SpawnConfirmed = true;
|
||||
} else {
|
||||
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
||||
// TODO: handle
|
||||
}
|
||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), CarID));
|
||||
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
||||
// TODO: handle
|
||||
}
|
||||
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
||||
SpawnConfirmed = false;
|
||||
}
|
||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postVehicleSpawn", "", SpawnConfirmed, c.GetID(), CarID, Packet.substr(3));
|
||||
// the post event is not cancellable so we dont wait for it
|
||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
||||
}
|
||||
return;
|
||||
case 'c': {
|
||||
@@ -351,23 +429,39 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||
auto Snapshot = Result->GetDetachedSnapshot();
|
||||
if (Snapshot.Error) {
|
||||
return false;
|
||||
}
|
||||
const int* MaybeInt = std::get_if<int>(&Snapshot.Result.V);
|
||||
if (MaybeInt == nullptr) {
|
||||
return false;
|
||||
}
|
||||
return *MaybeInt != 0;
|
||||
});
|
||||
|
||||
auto FoundPos = Packet.find('{');
|
||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||
bool Allowed = false;
|
||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||
&& !ShouldntAllow) {
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
Apply(c, VID, Packet);
|
||||
Allowed = true;
|
||||
} else {
|
||||
if (c.GetUnicycleID() == VID) {
|
||||
c.SetUnicycleID(-1);
|
||||
}
|
||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||
c.DeleteCar(VID);
|
||||
Allowed = false;
|
||||
}
|
||||
|
||||
auto PostFutures = LuaAPI::MP::Engine->TriggerEvent("postVehicleEdited", "", Allowed, c.GetID(), VID, Packet.substr(3));
|
||||
// the post event is not cancellable so we dont wait for it
|
||||
LuaAPI::MP::Engine->ReportErrors(PostFutures);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -397,19 +491,65 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
}
|
||||
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
Data = Data.substr(Data.find('{'));
|
||||
auto BracketPos = Data.find('{');
|
||||
if (BracketPos == std::string::npos) {
|
||||
beammp_debugf("Invalid 'Or' packet body from client {}", c.GetID());
|
||||
return;
|
||||
}
|
||||
|
||||
Data = Data.substr(BracketPos);
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 't':
|
||||
case 't': {
|
||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'm': {
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
return;
|
||||
case 'm':
|
||||
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
||||
}
|
||||
case 'p': {
|
||||
beammp_trace(std::string(("got 'Op' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
auto BracketPos = Data.find('[');
|
||||
if (BracketPos == std::string::npos) {
|
||||
beammp_debugf("Invalid 'Op' packet body from client {}", c.GetID());
|
||||
return;
|
||||
}
|
||||
|
||||
Data = Data.substr(BracketPos);
|
||||
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehiclePaintChanged", "", c.GetID(), VID, Data));
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
|
||||
auto CarData = c.GetCarData(VID);
|
||||
if (CarData == nlohmann::detail::value_t::null)
|
||||
return;
|
||||
|
||||
if (CarData.contains("vcf") && CarData.at("vcf").is_object())
|
||||
if (CarData.at("vcf").contains("paints") && CarData.at("vcf").at("paints").is_array()) {
|
||||
CarData.at("vcf")["paints"] = nlohmann::json::parse(Data);
|
||||
c.SetCarData(VID, CarData);
|
||||
}
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
default:
|
||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||
return;
|
||||
@@ -422,42 +562,22 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
||||
beammp_error("Malformed packet received, no '{' found");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string Packet = pckt.substr(FoundPos);
|
||||
std::string VD = c.GetCarData(VID);
|
||||
if (VD.empty()) {
|
||||
nlohmann::json VD = c.GetCarData(VID);
|
||||
if (VD == nlohmann::detail::value_t::null) {
|
||||
beammp_error("Tried to apply change to vehicle that does not exist");
|
||||
return;
|
||||
}
|
||||
std::string Header = VD.substr(0, VD.find('{'));
|
||||
|
||||
FoundPos = VD.find('{');
|
||||
if (FoundPos == std::string::npos) {
|
||||
return;
|
||||
}
|
||||
VD = VD.substr(FoundPos);
|
||||
rapidjson::Document Veh, Pack;
|
||||
Veh.Parse(VD.c_str());
|
||||
if (Veh.HasParseError()) {
|
||||
beammp_error("Could not get vehicle config!");
|
||||
return;
|
||||
}
|
||||
Pack.Parse(Packet.c_str());
|
||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
||||
nlohmann::json Pack = nlohmann::json::parse(Packet, nullptr, false);
|
||||
|
||||
if (Pack.is_discarded()) {
|
||||
beammp_error("Could not get active vehicle config!");
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto& M : Pack.GetObject()) {
|
||||
if (Veh[M.name].IsNull()) {
|
||||
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
|
||||
} else {
|
||||
Veh[M.name] = Pack[M.name];
|
||||
}
|
||||
}
|
||||
rapidjson::StringBuffer Buffer;
|
||||
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
|
||||
Veh.Accept(writer);
|
||||
c.SetCarData(VID, Header + Buffer.GetString());
|
||||
c.SetCarData(VID, Pack);
|
||||
}
|
||||
|
||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
||||
|
||||
+5
-1
@@ -21,7 +21,7 @@
|
||||
#include "Common.h"
|
||||
#include <utility>
|
||||
|
||||
TVehicleData::TVehicleData(int ID, std::string Data)
|
||||
TVehicleData::TVehicleData(int ID, nlohmann::json Data)
|
||||
: mID(ID)
|
||||
, mData(std::move(Data)) {
|
||||
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
|
||||
@@ -30,3 +30,7 @@ TVehicleData::TVehicleData(int ID, std::string Data)
|
||||
TVehicleData::~TVehicleData() {
|
||||
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
|
||||
}
|
||||
|
||||
std::string TVehicleData::DataAsPacket(const std::string& Role, const std::string& Name, const int ID) const {
|
||||
return "Os:" + Role + ":" + Name + ":" + std::to_string(ID) + "-" + std::to_string(this->mID) + ":" + this->mData.dump();
|
||||
}
|
||||
+60
-20
@@ -17,9 +17,11 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "ArgsParser.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "Http.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "Settings.h"
|
||||
#include "SignalHandling.h"
|
||||
#include "TConfig.h"
|
||||
#include "THeartbeatThread.h"
|
||||
@@ -30,20 +32,24 @@
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
static const std::string sCommandlineArguments = R"(
|
||||
USAGE:
|
||||
USAGE:
|
||||
BeamMP-Server [arguments]
|
||||
|
||||
|
||||
ARGUMENTS:
|
||||
--help
|
||||
--help
|
||||
Displays this help and exits.
|
||||
--port=1234
|
||||
Sets the server's listening TCP and
|
||||
UDP port. Overrides ENV and ServerConfig.
|
||||
--config=/path/to/ServerConfig.toml
|
||||
Absolute or relative path to the
|
||||
Absolute or relative path to the
|
||||
Server Config file, including the
|
||||
filename. For paths and filenames with
|
||||
filename. For paths and filenames with
|
||||
spaces, put quotes around the path.
|
||||
--working-directory=/path/to/folder
|
||||
Sets the working directory of the Server.
|
||||
@@ -54,7 +60,7 @@ ARGUMENTS:
|
||||
|
||||
EXAMPLES:
|
||||
BeamMP-Server --config=../MyWestCoastServerConfig.toml
|
||||
Runs the BeamMP-Server and uses the server config file
|
||||
Runs the BeamMP-Server and uses the server config file
|
||||
which is one directory above it and is named
|
||||
'MyWestCoastServerConfig.toml'.
|
||||
)";
|
||||
@@ -91,6 +97,7 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
|
||||
Parser.RegisterArgument({ "port" }, ArgsParser::HAS_VALUE);
|
||||
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
|
||||
Parser.Parse(Arguments.List);
|
||||
if (!Parser.Verify()) {
|
||||
@@ -124,7 +131,7 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
TConfig Config(ConfigPath);
|
||||
|
||||
if (Config.Failed()) {
|
||||
@@ -135,6 +142,24 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// override port if provided via arguments
|
||||
if (Parser.FoundArgument({ "port" })) {
|
||||
auto Port = Parser.GetValueOfArgument({ "port" });
|
||||
if (Port.has_value()) {
|
||||
auto P = int(std::strtoul(Port.value().c_str(), nullptr, 10));
|
||||
if (P == 0 || P < 0 || P > UINT16_MAX) {
|
||||
beammp_errorf("Custom port requested via --port is invalid: '{}'", Port.value());
|
||||
return 1;
|
||||
} else {
|
||||
Application::Settings.set(Settings::Key::General_Port, P);
|
||||
beammp_info("Custom port requested via commandline arguments: " + Port.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Config.PrintDebug();
|
||||
|
||||
Application::InitializeConsole();
|
||||
Application::Console().StartLoggingToFile();
|
||||
|
||||
@@ -142,41 +167,50 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
|
||||
SetupSignalHandlers();
|
||||
|
||||
Settings settings {};
|
||||
beammp_infof("Server name set in new impl: {}", settings.getAsString(Settings::Key::General_Name));
|
||||
|
||||
bool Shutdown = false;
|
||||
Application::RegisterShutdownHandler([&Shutdown] {
|
||||
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
|
||||
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
|
||||
Shutdown = true;
|
||||
});
|
||||
Application::RegisterShutdownHandler([] {
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
|
||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||
});
|
||||
|
||||
TServer Server(Arguments.List);
|
||||
|
||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||
LuaEngine->SetServer(&Server);
|
||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||
|
||||
RegisterThread("Main");
|
||||
|
||||
beammp_trace("Running in debug mode on a debug build");
|
||||
TResourceManager ResourceManager;
|
||||
ResourceManager.RefreshFiles();
|
||||
TPPSMonitor PPSMonitor(Server);
|
||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
||||
|
||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||
LuaEngine->SetServer(&Server);
|
||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||
LuaEngine->SetNetwork(&Network);
|
||||
PPSMonitor.SetNetwork(Network);
|
||||
Application::CheckForUpdates();
|
||||
|
||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.getAsString(Settings::Key::General_ResourceFolder)) / "Server", LuaEngine);
|
||||
|
||||
if (Application::Settings.HTTPServerEnabled) {
|
||||
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||
}
|
||||
Application::RegisterShutdownHandler([] {
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
|
||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||
});
|
||||
Application::RegisterShutdownHandler([&Server, &Network] {
|
||||
beammp_debug("Kicking all players due to shutdown");
|
||||
Server.ForEachClient([&Network](std::weak_ptr<TClient> client) -> bool {
|
||||
if (!client.expired()) {
|
||||
Network.ClientKick(*client.lock(), "Server shutdown");
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||
RegisterThread("Main(Waiting)");
|
||||
|
||||
std::set<std::string> IgnoreSubsystems {
|
||||
@@ -191,6 +225,10 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
std::string SystemsBadList {};
|
||||
auto Statuses = Application::GetSubsystemStatuses();
|
||||
for (const auto& NameStatusPair : Statuses) {
|
||||
if (NameStatusPair.first == "Main") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IgnoreSubsystems.count(NameStatusPair.first) > 0) {
|
||||
continue; // ignore
|
||||
}
|
||||
@@ -204,6 +242,8 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
// remove ", "
|
||||
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
|
||||
if (FullyStarted) {
|
||||
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||
|
||||
if (!WithErrors) {
|
||||
beammp_info("ALL SYSTEMS STARTED SUCCESSFULLY, EVERYTHING IS OKAY");
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
local function assert_eq(x, y, explain)
|
||||
if x ~= y then
|
||||
print("assertion '"..explain.."' failed:\n\tgot:\t", x, "\n\texpected:", y)
|
||||
end
|
||||
end
|
||||
|
||||
---@param o1 any|table First object to compare
|
||||
---@param o2 any|table Second object to compare
|
||||
---@param ignore_mt boolean True to ignore metatables (a recursive function to tests tables inside tables)
|
||||
function equals(o1, o2, ignore_mt)
|
||||
if o1 == o2 then return true end
|
||||
local o1Type = type(o1)
|
||||
local o2Type = type(o2)
|
||||
if o1Type ~= o2Type then return false end
|
||||
if o1Type ~= 'table' then return false end
|
||||
|
||||
if not ignore_mt then
|
||||
local mt1 = getmetatable(o1)
|
||||
if mt1 and mt1.__eq then
|
||||
--compare using built in method
|
||||
return o1 == o2
|
||||
end
|
||||
end
|
||||
|
||||
local keySet = {}
|
||||
|
||||
for key1, value1 in pairs(o1) do
|
||||
local value2 = o2[key1]
|
||||
if value2 == nil or equals(value1, value2, ignore_mt) == false then
|
||||
return false
|
||||
end
|
||||
keySet[key1] = true
|
||||
end
|
||||
|
||||
for key2, _ in pairs(o2) do
|
||||
if not keySet[key2] then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
|
||||
local function assert_table_eq(x, y, explain)
|
||||
if not equals(x, y, true) then
|
||||
print("assertion '"..explain.."' failed:\n\tgot:\t", x, "\n\texpected:", y)
|
||||
end
|
||||
end
|
||||
|
||||
assert_eq(Util.JsonEncode({1, 2, 3, 4, 5}), "[1,2,3,4,5]", "table to array")
|
||||
assert_eq(Util.JsonEncode({"a", 1, 2, 3, 4, 5}), '["a",1,2,3,4,5]', "table to array")
|
||||
assert_eq(Util.JsonEncode({"a", 1, 2.0, 3, 4, 5}), '["a",1,2.0,3,4,5]', "table to array")
|
||||
assert_eq(Util.JsonEncode({hello="world", john={doe = 1, jane = 2.5, mike = {2, 3, 4}}, dave={}}), '{"dave":{},"hello":"world","john":{"doe":1,"jane":2.5,"mike":[2,3,4]}}', "table to obj")
|
||||
assert_eq(Util.JsonEncode({a = nil}), "{}", "null obj member")
|
||||
assert_eq(Util.JsonEncode({1, nil, 3}), "[1,3]", "null array member")
|
||||
assert_eq(Util.JsonEncode({}), "{}", "empty array/table")
|
||||
assert_eq(Util.JsonEncode({1234}), "[1234]", "int")
|
||||
assert_eq(Util.JsonEncode({1234.0}), "[1234.0]", "double")
|
||||
|
||||
assert_table_eq(Util.JsonDecode("[1,2,3,4,5]"), {1, 2, 3, 4, 5}, "decode table to array")
|
||||
assert_table_eq(Util.JsonDecode('["a",1,2,3,4,5]'), {"a", 1, 2, 3, 4, 5}, "decode table to array")
|
||||
assert_table_eq(Util.JsonDecode('["a",1,2.0,3,4,5]'), {"a", 1, 2.0, 3, 4, 5}, "decode table to array")
|
||||
assert_table_eq(Util.JsonDecode('{"dave":{},"hello":"world","john":{"doe":1,"jane":2.5,"mike":[2,3,4]}}'), {hello="world", john={doe = 1, jane = 2.5, mike = {2, 3, 4}}, dave={}}, "decode table to obj")
|
||||
assert_table_eq(Util.JsonDecode("{}"), {a = nil}, "decode null obj member")
|
||||
assert_table_eq(Util.JsonDecode("[1,3]"), {1, 3}, "decode null array member")
|
||||
assert_table_eq(Util.JsonDecode("{}"), {}, "decode empty array/table")
|
||||
assert_table_eq(Util.JsonDecode("[1234]"), {1234}, "decode int")
|
||||
assert_table_eq(Util.JsonDecode("[1234.0]"), {1234.0}, "decode double")
|
||||
+1
-1
Submodule vcpkg updated: 8397227251...5bf0c55239
+14
-2
@@ -14,6 +14,18 @@
|
||||
"openssl",
|
||||
"rapidjson",
|
||||
"sol2",
|
||||
"toml11"
|
||||
]
|
||||
"curl",
|
||||
"lua"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"name": "sol2",
|
||||
"version": "3.3.1"
|
||||
},
|
||||
{
|
||||
"name": "lua",
|
||||
"version": "5.3.5#6"
|
||||
}
|
||||
],
|
||||
"builtin-baseline": "5bf0c55239da398b8c6f450818c9e28d36bf9966"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user