mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 18:24:16 +00:00
Compare commits
446 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b209e70d62 | |||
| 5394122d77 | |||
| f48b8ff1a1 | |||
| de2a3795cc | |||
| 054016a099 | |||
| 8b57f6e35a | |||
| f21d3d0389 | |||
| 2ed92c4aa1 | |||
| fd7b11f436 | |||
| 6a94060970 | |||
| 51ccf31373 | |||
| a2cc629153 | |||
| ad414ec5c9 | |||
| 0a8e7d8e50 | |||
| bbd026e399 | |||
| 04bbdff6b7 | |||
| 2d8ce09b2c | |||
| 05251efc06 | |||
| f8d622352f | |||
| 6c1d02a425 | |||
| 38eeec39b4 | |||
| 696e080e1c | |||
| 98681254e6 | |||
| 420e6c3533 | |||
| 06f8ba5a0e | |||
| 9420d8a7a0 | |||
| dfa90da8af | |||
| 6e46d5aca9 | |||
| 817bd4b588 | |||
| 25391fa0c7 | |||
| 28270072d4 | |||
| 758d5b2c96 | |||
| 1970d97ea4 | |||
| d8526f0649 | |||
| 0621c0bf82 | |||
| 36547d1e9e | |||
| f06f31c2a0 | |||
| 46b92b4992 | |||
| 70e53c2a70 | |||
| cc35d83834 | |||
| b4f97a6da0 | |||
| 3d7db6d0bc | |||
| 1c3b1ecc76 | |||
| 303da19f48 | |||
| c455d4855c | |||
| 8df61fe44c | |||
| 7224e90c68 | |||
| fde5bc7fb6 | |||
| 22b63220c7 | |||
| 811ace1999 | |||
| 2cf083a7e4 | |||
| 28c43a51ee | |||
| 00f156cb86 | |||
| 67b8565a4d | |||
| ed8d8a6419 | |||
| 895058f85f | |||
| a0876ed58c | |||
| 4f69ca1ad0 | |||
| bc1628afeb | |||
| 019c5202ea | |||
| 2dd181d492 | |||
| a5153e4bc1 | |||
| 8d7505956d | |||
| 3b2016d09f | |||
| ed03096cf5 | |||
| 88f1976668 | |||
| ca52d233c0 | |||
| 34b39aad4d | |||
| f4eb492d91 | |||
| 7f41a2a574 | |||
| 11c53e0b3a | |||
| 974dda9f8b | |||
| 0979c8b1e4 | |||
| 0761036c8c | |||
| 5ded713b4b | |||
| 668cc496b6 | |||
| 056d20292a | |||
| 58e2383b2e | |||
| d8c33c03ee | |||
| 1bab3276e9 | |||
| 4ff69528bd | |||
| 5e4c7eac51 | |||
| 952631bb80 | |||
| 23af76dba1 | |||
| 5755ead9be | |||
| 450f0a6875 | |||
| 104737571c | |||
| d01d79a49a | |||
| d4b30a2583 | |||
| 81dbf747d5 | |||
| b97397132d | |||
| d86efabb1a | |||
| de82caef33 | |||
| f8c58f363a | |||
| 71c2d4b859 | |||
| b2f27c21be | |||
| b780a08f73 | |||
| cd4332b790 | |||
| 7a814ed35e | |||
| 9e0d02c6db | |||
| d0bb32ec63 | |||
| 5180c96e2b | |||
| dbfe4a4d11 | |||
| 4cb299061e | |||
| ef902a03f3 | |||
| c1e216957b | |||
| 39db1a5e42 | |||
| be498be661 | |||
| 0466ae55a4 | |||
| 6a43694c0f | |||
| fe06726d75 | |||
| 3c08e54471 | |||
| a97763a94f | |||
| daa674f448 | |||
| 710b15535e | |||
| a85fef15c2 | |||
| 359faee696 | |||
| 299004b14e | |||
| b09f5a401d | |||
| 2caa74d913 | |||
| e3d9d11bbd | |||
| 09c9b24cbf | |||
| a450531b8a | |||
| ace7aaada7 | |||
| ca3314b416 | |||
| 7d97c3b560 | |||
| dd5cf1a4af | |||
| 9a0cdc6517 | |||
| 965935a0e6 | |||
| 96a0e4b6fb | |||
| b52677e585 | |||
| 95b417bb36 | |||
| 8ce3be03a3 | |||
| 687b4e4235 | |||
| 86ad28abdc | |||
| a982d54202 | |||
| 588c68ebe1 | |||
| 548b2512cc | |||
| 8ff94a57d7 | |||
| a44684f6e7 | |||
| 944b68c6d5 | |||
| 01268821dc | |||
| 5553aca0bb | |||
| beaea4f624 | |||
| a4f07c9a4d | |||
| dada8fe6bf | |||
| 36853ca683 | |||
| d969c4a2c2 | |||
| f26ca6b40d | |||
| 17c571811a | |||
| b72de4bd0a | |||
| fdb7c9ce71 | |||
| c391abcc93 | |||
| 144ccf14ec | |||
| 40b23cbbe6 | |||
| 7b458e3e27 | |||
| 69656f95db | |||
| 0f5c476d09 | |||
| 86b6aed350 | |||
| 81780294f8 | |||
| 7c1fb12625 | |||
| 9f892af997 | |||
| 9494bc70fb | |||
| 5c44a307bc | |||
| 754053e73f | |||
| 29f8d29e33 | |||
| e043361abb | |||
| fd12ee672d | |||
| fca5bbcec9 | |||
| 2a588954be | |||
| cd4129e05d | |||
| c42c748b37 | |||
| 179b33a7ab | |||
| 1b14206a3c | |||
| 0cf81cf3f4 | |||
| 801780bcb1 | |||
| 84d52578e0 | |||
| 3555cec5fe | |||
| 71efe30345 | |||
| 5df8aedf08 | |||
| c3ab4b729a | |||
| 464aa3b59f | |||
| cfe63198c7 | |||
| 435d73f0c1 | |||
| a5c23f8dde | |||
| 6c5b2cbeb5 | |||
| ca5b3956a1 | |||
| 924e18c163 | |||
| bbe92dfa0f | |||
| a19943c96d | |||
| cd19ae0836 | |||
| 3ee83904a1 | |||
| fe652cbf42 | |||
| 2c115a2b2c | |||
| 1172420b77 | |||
| 92d9857902 | |||
| 816d3d5df8 | |||
| 817a146699 | |||
| 3cce875fbb | |||
| a1335e8c7d | |||
| 0f74eca2ee | |||
| 279c93179c | |||
| 62cc1e9ce4 | |||
| bd41382233 | |||
| 9d283738aa | |||
| b33d50361c | |||
| 479bb9f931 | |||
| 672c7d02d1 | |||
| a289d0e872 | |||
| 86169ad0fa | |||
| f477570a1c | |||
| 7b99ccb08e | |||
| 265dd710cf | |||
| eb67f483b2 | |||
| 98c7fea139 | |||
| ccdc5dae17 | |||
| 1bc9a5293e | |||
| c3151093e2 | |||
| 8f77f1c8c0 | |||
| 19d67dee95 | |||
| fc440bea2a | |||
| c91f3ee33c | |||
| 297b646d33 | |||
| 768d0466f4 | |||
| 1e0ab6bbb3 | |||
| 472ec3390c | |||
| a4123d7d7c | |||
| 6fd54f7907 | |||
| fd7bea0f36 | |||
| 9d2d4bb221 | |||
| e1756298af | |||
| eae27633db | |||
| 938774618c | |||
| 1a2a123d87 | |||
| 6247061d09 | |||
| 08a62261e7 | |||
| a7db41ebaa | |||
| 66d4e34a75 | |||
| 7169e65305 | |||
| 097e52674b | |||
| 1ec47252f2 | |||
| 2ddac7f138 | |||
| cf08dee84f | |||
| f1148ed1c4 | |||
| b6fa3574fd | |||
| 7079e80b71 | |||
| 48b9aa72dc | |||
| c36ea52f60 | |||
| 87f23427a1 | |||
| 7197c23632 | |||
| b5ea084c9b | |||
| f8af134dc9 | |||
| 3e7aa763ed | |||
| 5fdd7beac8 | |||
| 701a7feee3 | |||
| 1e305c3c90 | |||
| 9f5fa8fb9b | |||
| fdc205f521 | |||
| a18abd6c8b | |||
| 1b2ea88a71 | |||
| 50589fbe3d | |||
| 7287fce341 | |||
| 6de625682d | |||
| 6189aed6e7 | |||
| c4d6aab08b | |||
| 577d4c429d | |||
| d027f7f29f | |||
| af14188ec0 | |||
| 1ee45c9d1a | |||
| d1f890752a | |||
| 9eabd19e17 | |||
| ae7a63669f | |||
| 243e96d503 | |||
| 932fbe2b2f | |||
| 26ec50b199 | |||
| 87ecc3f9f6 | |||
| 7f1d37a0e6 | |||
| 255feb4f8e | |||
| 013ca14ab8 | |||
| e7f29ce04f | |||
| e948edca8d | |||
| d0431c0b9d | |||
| 0961f86662 | |||
| 7f2ca025f8 | |||
| 33ebfa82f0 | |||
| 9d0caf2c7d | |||
| fe3ccafc1d | |||
| 23ffa25d78 | |||
| 908f67a799 | |||
| 27b5c6d850 | |||
| 32756ccc4a | |||
| 3626f4108e | |||
| d7a4322313 | |||
| d84051bdd3 | |||
| 238577a4f7 | |||
| 041db23a69 | |||
| a3a18a3b56 | |||
| 9efe352e7a | |||
| 3edb9322d4 | |||
| 4bf89706b4 | |||
| a97791d4ee | |||
| 323184911d | |||
| 6f9f790c5b | |||
| 4de80e0c7a | |||
| 366a7dc9a6 | |||
| 785b858651 | |||
| a4ff9488c5 | |||
| 60b86e2be6 | |||
| 701e613990 | |||
| 7dbf859529 | |||
| 8419ca2234 | |||
| 7f63dd8d7d | |||
| da78d77e6c | |||
| 1ff5107707 | |||
| dd70e88e4c | |||
| 38dffc5462 | |||
| f98ef7d41c | |||
| 29a858e74a | |||
| e53f2d9877 | |||
| be3ac45abb | |||
| 246f8289b6 | |||
| 3c7109b23f | |||
| 82a5fc3999 | |||
| 11d4d9ff91 | |||
| 48caae25fd | |||
| 9dfe9f659a | |||
| a07b5062de | |||
| fcbb188ee0 | |||
| 883d69ba27 | |||
| 7459779363 | |||
| a0c47d9947 | |||
| 7db345cfbc | |||
| 1d3958817f | |||
| fd3088c78f | |||
| c2b73d93b5 | |||
| 9a37ed4341 | |||
| e64114e4fa | |||
| 79531334dd | |||
| ed6f5282d9 | |||
| 62fd369625 | |||
| 1880536276 | |||
| bac476ec34 | |||
| e75e65815c | |||
| b0c467f971 | |||
| 6b17990d4d | |||
| c73d56c143 | |||
| a44050f0f1 | |||
| cb1eb40def | |||
| 4c03a90157 | |||
| be61511bdf | |||
| 968d9ff999 | |||
| 1c80a4deb7 | |||
| e602decb96 | |||
| dca573b15c | |||
| 26231c6272 | |||
| ebe3630ec8 | |||
| d7f7a81cb0 | |||
| 9ef6c32864 | |||
| 9b9c18a4c1 | |||
| 5978665ad6 | |||
| 2cf368c2b0 | |||
| ba0678dade | |||
| c309fa28c6 | |||
| f5b2be0a03 | |||
| dd4e4c4467 | |||
| d082620525 | |||
| be90a8a2c0 | |||
| 8b69127cdd | |||
| bb34378b8e | |||
| 588242822c | |||
| 58da200901 | |||
| f4ccf6c177 | |||
| 27103a73a9 | |||
| 2727f90430 | |||
| 2a96546c8c | |||
| 6462636b29 | |||
| 5742ab0dad | |||
| 0087205d55 | |||
| d16843e45d | |||
| 24516dbfd7 | |||
| a311d58e11 | |||
| 1444d91e7e | |||
| 1e2f060107 | |||
| fdb5da2ed6 | |||
| de57613326 | |||
| b49782e8a3 | |||
| ff80b4cf63 | |||
| 4c23b78f84 | |||
| aca3c52c20 | |||
| 51d6c4fb0a | |||
| 2af9491fd6 | |||
| 95c036836e | |||
| a7f2f85e45 | |||
| 42c5aaad5a | |||
| 88684bd9af | |||
| c6457f7df4 | |||
| ba3fd0e144 | |||
| e3b6fd7998 | |||
| 943159cd40 | |||
| 9423831937 | |||
| 95188042c5 | |||
| a0a7b8ecce | |||
| 53617abae4 | |||
| 853b078124 | |||
| 549517c518 | |||
| 2be4b8fd91 | |||
| 2cfb27820a | |||
| 1ff12cb2bf | |||
| 518cb0664e | |||
| 80432eb718 | |||
| b1caf5c29a | |||
| 950cee9fd0 | |||
| 046097579e | |||
| 35a3dab1ce | |||
| 131ade02cd | |||
| 2c2f76b340 | |||
| 106d8e5863 | |||
| 1fb7cb6bc1 | |||
| 9666fff622 | |||
| 5d5f155f0c | |||
| cfe348770c | |||
| 206120dcef | |||
| 2a3bb1bef8 | |||
| 0faa46d48c | |||
| dae52a71fd | |||
| c46c36bf09 | |||
| ed3d0834e6 | |||
| 9d4c6e880b | |||
| d39b5d7c77 | |||
| b071906db5 | |||
| 8420cdb5bf | |||
| e11211f201 | |||
| 9595ef164e | |||
| d18afdf84b | |||
| 0acbb70d10 | |||
| 7a3848e640 | |||
| 261aa8f320 | |||
| e994cdd8a2 | |||
| 44e0f3aa21 | |||
| 8853cef809 | |||
| fb76b8309a | |||
| a23946dddf | |||
| 55ee1d3747 | |||
| 4cd0093687 | |||
| cc88734279 | |||
| a865c95e2a |
@@ -7,40 +7,72 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
linux-build:
|
linux-build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
with:
|
with:
|
||||||
submodules: 'recursive'
|
submodules: "recursive"
|
||||||
|
|
||||||
- name: Install Dependencies
|
- name: Install Dependencies
|
||||||
env:
|
env:
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||||
run: |
|
run: |
|
||||||
echo ${#beammp_sentry_url}
|
echo ${#beammp_sentry_url}
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
|
||||||
sudo add-apt-repository ppa:mhier/libboost-latest
|
|
||||||
sudo apt-get install -y libboost1.70-dev libboost1.70
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
|
|
||||||
- name: Configure CMake
|
- name: Configure CMake
|
||||||
shell: bash
|
shell: bash
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
working-directory: ${{github.workspace}}/build-linux
|
||||||
env:
|
env:
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||||
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||||
|
|
||||||
- name: Build
|
- name: Build Server
|
||||||
working-directory: ${{github.workspace}}/build-linux
|
working-directory: ${{github.workspace}}/build-linux
|
||||||
shell: bash
|
shell: bash
|
||||||
run: cmake --build . --config $BUILD_TYPE
|
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
|
||||||
|
|
||||||
- name: Archive artifacts
|
- name: Build Tests
|
||||||
uses: actions/upload-artifact@v2
|
working-directory: ${{github.workspace}}/build-linux
|
||||||
with:
|
shell: bash
|
||||||
name: BeamMP-Server-linux
|
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server-tests --parallel
|
||||||
path: ${{github.workspace}}/build-linux/BeamMP-Server
|
|
||||||
|
- name: Archive server artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-linux
|
||||||
|
path: ${{github.workspace}}/build-linux/BeamMP-Server
|
||||||
|
|
||||||
|
- name: Archive test artifact
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-linux-tests
|
||||||
|
path: ${{github.workspace}}/build-linux/BeamMP-Server-tests
|
||||||
|
|
||||||
|
run-tests:
|
||||||
|
needs: linux-build
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@master
|
||||||
|
with:
|
||||||
|
name: BeamMP-Server-linux-tests
|
||||||
|
path: ${{github.workspace}}
|
||||||
|
|
||||||
|
- name: Install Runtime Dependencies
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y liblua5.3 openssl
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
working-directory: ${{github.workspace}}
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
chmod +x ./BeamMP-Server-tests
|
||||||
|
./BeamMP-Server-tests
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ name: CMake Windows Build
|
|||||||
on: [push]
|
on: [push]
|
||||||
|
|
||||||
env:
|
env:
|
||||||
BUILD_TYPE: RelWithDebInfo
|
BUILD_TYPE: Release
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
windows-build:
|
windows-build:
|
||||||
@@ -15,12 +15,12 @@ jobs:
|
|||||||
submodules: 'recursive'
|
submodules: 'recursive'
|
||||||
|
|
||||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||||
uses: lukka/run-vcpkg@main
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp curl'
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
|
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
@@ -31,7 +31,7 @@ jobs:
|
|||||||
working-directory: ${{github.workspace}}/build-windows
|
working-directory: ${{github.workspace}}/build-windows
|
||||||
env:
|
env:
|
||||||
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
|
||||||
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
working-directory: ${{github.workspace}}/build-windows
|
working-directory: ${{github.workspace}}/build-windows
|
||||||
@@ -42,12 +42,17 @@ jobs:
|
|||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server.exe
|
name: BeamMP-Server.exe
|
||||||
path: ${{github.workspace}}/build-windows/RelWithDebInfo/BeamMP-Server.exe
|
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
|
||||||
|
|
||||||
- name: Archive artifacts
|
- name: Build debug
|
||||||
|
working-directory: ${{github.workspace}}/build-windows
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
cmake --build . --config Debug
|
||||||
|
|
||||||
|
- name: Archive debug artifacts
|
||||||
uses: actions/upload-artifact@v2
|
uses: actions/upload-artifact@v2
|
||||||
with:
|
with:
|
||||||
name: BeamMP-Server.pdb
|
name: BeamMP-Server-debug.exe
|
||||||
path: ${{github.workspace}}/build-windows/RelWithDebInfo/BeamMP-Server.pdb
|
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -43,8 +43,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
|
||||||
sudo add-apt-repository ppa:mhier/libboost-latest
|
|
||||||
sudo apt-get install -y libboost1.70-dev libboost1.70
|
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
run: cmake -E make_directory ${{github.workspace}}/build-linux
|
||||||
@@ -82,12 +80,12 @@ jobs:
|
|||||||
submodules: 'recursive'
|
submodules: 'recursive'
|
||||||
|
|
||||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||||
uses: lukka/run-vcpkg@main
|
uses: lukka/run-vcpkg@v7
|
||||||
id: runvcpkg
|
id: runvcpkg
|
||||||
with:
|
with:
|
||||||
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp curl'
|
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||||
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
|
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||||
vcpkgTriplet: 'x64-windows-static'
|
vcpkgTriplet: 'x64-windows-static'
|
||||||
|
|
||||||
- name: Create Build Environment
|
- name: Create Build Environment
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
.idea/
|
.idea/
|
||||||
|
.sentry-native/
|
||||||
*.orig
|
*.orig
|
||||||
*.toml
|
*.toml
|
||||||
boost_*
|
boost_*
|
||||||
|
|||||||
+33
-15
@@ -1,18 +1,36 @@
|
|||||||
[submodule "include/commandline"]
|
[submodule "deps/commandline"]
|
||||||
path = include/commandline
|
path = deps/commandline
|
||||||
url = https://github.com/lionkor/commandline
|
url = https://github.com/lionkor/commandline
|
||||||
[submodule "socket.io-client-cpp"]
|
[submodule "deps/asio"]
|
||||||
path = socket.io-client-cpp
|
path = deps/asio
|
||||||
url = https://github.com/socketio/socket.io-client-cpp
|
|
||||||
[submodule "asio"]
|
|
||||||
path = asio
|
|
||||||
url = https://github.com/chriskohlhoff/asio
|
url = https://github.com/chriskohlhoff/asio
|
||||||
[submodule "rapidjson"]
|
[submodule "deps/rapidjson"]
|
||||||
path = rapidjson
|
path = deps/rapidjson
|
||||||
url = https://github.com/Tencent/rapidjson
|
url = https://github.com/Tencent/rapidjson
|
||||||
[submodule "include/tomlplusplus"]
|
[submodule "deps/toml11"]
|
||||||
path = include/tomlplusplus
|
path = deps/toml11
|
||||||
url = https://github.com/marzer/tomlplusplus
|
url = https://github.com/ToruNiina/toml11
|
||||||
[submodule "include/sentry-native"]
|
[submodule "deps/sentry-native"]
|
||||||
path = include/sentry-native
|
path = deps/sentry-native
|
||||||
url = https://github.com/getsentry/sentry-native
|
url = https://github.com/getsentry/sentry-native
|
||||||
|
[submodule "deps/sol2"]
|
||||||
|
path = deps/sol2
|
||||||
|
url = https://github.com/ThePhD/sol2
|
||||||
|
[submodule "deps/libzip"]
|
||||||
|
path = deps/libzip
|
||||||
|
url = https://github.com/nih-at/libzip
|
||||||
|
[submodule "deps/cpp-httplib"]
|
||||||
|
path = deps/cpp-httplib
|
||||||
|
url = https://github.com/yhirose/cpp-httplib
|
||||||
|
[submodule "deps/json"]
|
||||||
|
path = deps/json
|
||||||
|
url = https://github.com/nlohmann/json
|
||||||
|
[submodule "deps/fmt"]
|
||||||
|
path = deps/fmt
|
||||||
|
url = https://github.com/fmtlib/fmt
|
||||||
|
[submodule "deps/doctest"]
|
||||||
|
path = deps/doctest
|
||||||
|
url = https://github.com/doctest/doctest
|
||||||
|
[submodule "deps/dlhttp"]
|
||||||
|
path = deps/dlhttp
|
||||||
|
url = https://github.com/lionkor/dlhttp
|
||||||
|
|||||||
+160
-102
@@ -1,4 +1,5 @@
|
|||||||
cmake_minimum_required(VERSION 3.0)
|
# 3.4 is required for imported targets.
|
||||||
|
cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
|
||||||
|
|
||||||
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
message(STATUS "You can find build instructions and a list of dependencies in the README at \
|
||||||
https://github.com/BeamMP/BeamMP-Server")
|
https://github.com/BeamMP/BeamMP-Server")
|
||||||
@@ -8,39 +9,66 @@ project(BeamMP-Server
|
|||||||
HOMEPAGE_URL https://beammp.com
|
HOMEPAGE_URL https://beammp.com
|
||||||
LANGUAGES CXX C)
|
LANGUAGES CXX C)
|
||||||
|
|
||||||
if (WIN32)
|
option(BEAMMP_RUN_GIT "Run git to make sure submodules are updated (leave this on unless you know what you're doing)" ON)
|
||||||
|
|
||||||
|
if (BEAMMP_RUN_GIT)
|
||||||
|
find_package(Git REQUIRED)
|
||||||
|
# Update submodules as needed
|
||||||
|
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||||
|
if(GIT_SUBMODULE)
|
||||||
|
message(STATUS "Submodule update")
|
||||||
|
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||||
|
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||||
|
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||||
|
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||||
|
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|
||||||
|
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
||||||
|
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
||||||
|
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/websocketpp")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include")
|
||||||
|
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps")
|
||||||
|
|
||||||
|
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
||||||
|
|
||||||
|
# ------------------------ APPLE ---------------------------------
|
||||||
|
if(APPLE)
|
||||||
|
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||||
|
set(LUA_LIBRARIES lua)
|
||||||
|
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||||
|
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||||
|
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||||
|
# ------------------------ WINDOWS ---------------------------------
|
||||||
|
elseif (WIN32)
|
||||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||||
endif()
|
# ------------------------ LINUX ---------------------------------
|
||||||
|
|
||||||
include_directories("include/sentry-native/include")
|
|
||||||
|
|
||||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
|
||||||
if (MSVC)
|
|
||||||
set(SENTRY_BUILD_RUNTIMESTATIC ON)
|
|
||||||
endif()
|
|
||||||
set(SENTRY_BACKEND breakpad)
|
|
||||||
add_subdirectory("include/sentry-native")
|
|
||||||
|
|
||||||
message(STATUS "Setting compiler flags")
|
|
||||||
if (WIN32)
|
|
||||||
add_subdirectory("include/watchdog")
|
|
||||||
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
|
||||||
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
|
|
||||||
include_directories(${VcpkgRoot}/include)
|
|
||||||
link_directories(${VcpkgRoot}/lib)
|
|
||||||
elseif (UNIX)
|
elseif (UNIX)
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic")
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
||||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -gz -fno-builtin")
|
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
||||||
|
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
||||||
if (SANITIZE)
|
if (SANITIZE)
|
||||||
message(STATUS "sanitize is ON")
|
message(STATUS "sanitize is ON")
|
||||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
||||||
endif (SANITIZE)
|
endif (SANITIZE)
|
||||||
endif ()
|
endif ()
|
||||||
|
|
||||||
|
include_directories("include/sentry-native/include")
|
||||||
|
set(BUILD_SHARED_LIBS OFF)
|
||||||
|
# ------------------------ SENTRY ---------------------------------
|
||||||
message(STATUS "Checking for Sentry URL")
|
message(STATUS "Checking for Sentry URL")
|
||||||
# this is set by the build system.
|
# this is set by the build system.
|
||||||
# IMPORTANT: if you're building from source, just leave this empty
|
# IMPORTANT: if you're building from source, just leave this empty
|
||||||
@@ -48,98 +76,128 @@ if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
|
|||||||
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
|
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
|
||||||
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
|
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
|
||||||
set(BEAMMP_SECRET_SENTRY_URL "")
|
set(BEAMMP_SECRET_SENTRY_URL "")
|
||||||
|
set(SENTRY_BACKEND none)
|
||||||
else()
|
else()
|
||||||
string(LENGTH ${BEAMMP_SECRET_SENTRY_URL} URL_LEN)
|
set(SENTRY_BACKEND breakpad)
|
||||||
message(STATUS "Sentry URL is length ${URL_LEN}")
|
|
||||||
endif()
|
endif()
|
||||||
|
add_subdirectory("deps/sentry-native")
|
||||||
|
|
||||||
|
# ------------------------ C++ SETUP ---------------------------------
|
||||||
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
if (MSVC)
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
|
||||||
|
endif ()
|
||||||
|
|
||||||
|
# ------------------------ DEPENDENCIES ------------------------------
|
||||||
message(STATUS "Adding local source dependencies")
|
message(STATUS "Adding local source dependencies")
|
||||||
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
|
||||||
include_directories("asio/asio/include")
|
add_subdirectory(deps)
|
||||||
include_directories("rapidjson/include")
|
|
||||||
include_directories("websocketpp")
|
|
||||||
add_subdirectory("socket.io-client-cpp")
|
|
||||||
add_subdirectory("include/commandline")
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
# ------------------------ VARIABLES ---------------------------------
|
||||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
|
||||||
|
|
||||||
message(STATUS "Looking for Boost")
|
include(FindLua)
|
||||||
find_package(Boost REQUIRED COMPONENTS system thread)
|
include(FindOpenSSL)
|
||||||
|
include(FindThreads)
|
||||||
|
include(FindZLIB)
|
||||||
|
|
||||||
file(GLOB source_files src/main.cpp
|
set(BeamMP_Sources
|
||||||
include/TConsole.h src/TConsole.cpp
|
include/TConsole.h src/TConsole.cpp
|
||||||
include/TServer.h src/TServer.cpp
|
include/TServer.h src/TServer.cpp
|
||||||
include/Compat.h src/Compat.cpp
|
include/Compat.h src/Compat.cpp
|
||||||
include/Common.h src/Common.cpp
|
include/Common.h src/Common.cpp
|
||||||
include/Client.h src/Client.cpp
|
include/Client.h src/Client.cpp
|
||||||
include/VehicleData.h src/VehicleData.cpp
|
include/VehicleData.h src/VehicleData.cpp
|
||||||
include/TConfig.h src/TConfig.cpp
|
include/TConfig.h src/TConfig.cpp
|
||||||
include/TLuaEngine.h src/TLuaEngine.cpp
|
include/TLuaEngine.h src/TLuaEngine.cpp
|
||||||
include/TLuaFile.h src/TLuaFile.cpp
|
include/TLuaPlugin.h src/TLuaPlugin.cpp
|
||||||
include/TResourceManager.h src/TResourceManager.cpp
|
include/TResourceManager.h src/TResourceManager.cpp
|
||||||
include/THeartbeatThread.h src/THeartbeatThread.cpp
|
include/THeartbeatThread.h src/THeartbeatThread.cpp
|
||||||
include/Http.h src/Http.cpp
|
include/Http.h src/Http.cpp
|
||||||
include/TSentry.h src/TSentry.cpp
|
include/TSentry.h src/TSentry.cpp
|
||||||
include/TPPSMonitor.h src/TPPSMonitor.cpp
|
include/TPPSMonitor.h src/TPPSMonitor.cpp
|
||||||
include/TNetwork.h src/TNetwork.cpp
|
include/TNetwork.h src/TNetwork.cpp
|
||||||
include/SignalHandling.h src/SignalHandling.cpp)
|
include/LuaAPI.h src/LuaAPI.cpp
|
||||||
|
include/TScopedTimer.h src/TScopedTimer.cpp
|
||||||
|
include/SignalHandling.h src/SignalHandling.cpp
|
||||||
|
include/ArgsParser.h src/ArgsParser.cpp
|
||||||
|
include/TPluginMonitor.h src/TPluginMonitor.cpp
|
||||||
|
include/Environment.h
|
||||||
|
)
|
||||||
|
|
||||||
add_executable(BeamMP-Server ${source_files})
|
set(BeamMP_Includes
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||||
target_compile_definitions(BeamMP-Server PRIVATE SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}")
|
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
|
||||||
|
${LUA_INCLUDE_DIR}
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline")
|
|
||||||
|
|
||||||
message(STATUS "Looking for Lua")
|
|
||||||
find_package(Lua REQUIRED)
|
|
||||||
target_include_directories(BeamMP-Server PUBLIC
|
|
||||||
${Boost_INCLUDE_DIRS}
|
|
||||||
${LUA_INCLUDE_DIR}
|
|
||||||
${CURL_INCLUDE_DIRS}
|
${CURL_INCLUDE_DIRS}
|
||||||
"socket.io-client-cpp/src"
|
"include/tomlplusplus"
|
||||||
"include/tomlplusplus"
|
|
||||||
"include/sentry-native/include"
|
"include/sentry-native/include"
|
||||||
"include/curl/include")
|
"include/curl/include"
|
||||||
|
)
|
||||||
|
|
||||||
message(STATUS "Looking for SSL")
|
set(BeamMP_Definitions
|
||||||
find_package(OpenSSL REQUIRED)
|
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
||||||
|
)
|
||||||
|
|
||||||
message(STATUS "CURL IS ${CURL_LIBRARIES}")
|
set(BeamMP_Libraries
|
||||||
|
doctest::doctest
|
||||||
|
OpenSSL::SSL
|
||||||
|
OpenSSL::Crypto
|
||||||
|
sol2::sol2
|
||||||
|
fmt::fmt
|
||||||
|
Threads::Threads
|
||||||
|
ZLIB::ZLIB
|
||||||
|
${LUA_LIBRARIES}
|
||||||
|
commandline
|
||||||
|
sentry
|
||||||
|
dlhttp
|
||||||
|
)
|
||||||
|
|
||||||
if (UNIX)
|
if (WIN32)
|
||||||
target_link_libraries(BeamMP-Server
|
set(BeamMP_PlatformLibs wsock32 ws2_32)
|
||||||
z
|
|
||||||
pthread
|
|
||||||
stdc++fs
|
|
||||||
${LUA_LIBRARIES}
|
|
||||||
crypto
|
|
||||||
${OPENSSL_LIBRARIES}
|
|
||||||
commandline
|
|
||||||
sioclient_tls
|
|
||||||
sentry)
|
|
||||||
elseif (WIN32)
|
|
||||||
set_source_files_properties(${source_files} PROPERTIES COMPILE_FLAGS "/Gh /GH")
|
|
||||||
add_compile_options("$<$<NOT:$<CONFIG:Debug>>:/Zi>")
|
|
||||||
add_link_options("$<$<NOT:$<CONFIG:Debug>>:/DEBUG>")
|
|
||||||
add_link_options("$<$<NOT:$<CONFIG:Debug>>:/OPT:REF>")
|
|
||||||
add_link_options("$<$<NOT:$<CONFIG:Debug>>:/OPT:ICF>")
|
|
||||||
include(FindLua)
|
|
||||||
message(STATUS "Looking for libz")
|
|
||||||
find_package(ZLIB REQUIRED)
|
|
||||||
message(STATUS "Looking for RapidJSON")
|
|
||||||
find_package(RapidJSON CONFIG REQUIRED)
|
|
||||||
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
|
|
||||||
target_link_libraries(BeamMP-Server PRIVATE
|
|
||||||
ws2_32
|
|
||||||
ZLIB::ZLIB
|
|
||||||
${LUA_LIBRARIES}
|
|
||||||
${OPENSSL_LIBRARIES}
|
|
||||||
commandline
|
|
||||||
sioclient_tls
|
|
||||||
sentry
|
|
||||||
watchdog
|
|
||||||
Dbghelp)
|
|
||||||
endif ()
|
endif ()
|
||||||
|
|
||||||
|
# ------------------------ BEAMMP SERVER -----------------------------
|
||||||
|
|
||||||
|
add_executable(BeamMP-Server
|
||||||
|
src/main.cpp
|
||||||
|
${BeamMP_Sources}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_definitions(BeamMP-Server PRIVATE
|
||||||
|
${BeamMP_Definitions}
|
||||||
|
DOCTEST_CONFIG_DISABLE
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(BeamMP-Server PUBLIC
|
||||||
|
${BeamMP_Includes}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(BeamMP-Server
|
||||||
|
${BeamMP_Libraries}
|
||||||
|
${BeamMP_PlatformLibs}
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------ BEAMMP SERVER TESTS -----------------------
|
||||||
|
|
||||||
|
option(BUILD_TESTS "Build BeamMP-Server tests" ON)
|
||||||
|
|
||||||
|
if(BUILD_TESTS)
|
||||||
|
add_executable(BeamMP-Server-tests
|
||||||
|
test/test_main.cpp
|
||||||
|
${BeamMP_Sources}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
||||||
|
${BeamMP_Definitions}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(BeamMP-Server-tests PUBLIC
|
||||||
|
${BeamMP_Includes}
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(BeamMP-Server-tests
|
||||||
|
${BeamMP_Libraries}
|
||||||
|
${BeamMP_PlatformLibs}
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,60 @@
|
|||||||
|
|
||||||
|
# v3.1.0
|
||||||
|
|
||||||
|
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
|
||||||
|
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
|
||||||
|
- ADDED MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa
|
||||||
|
- ADDED FS.ListFiles and FS.ListDirectories
|
||||||
|
- ADDED onFileChanged event, triggered when a server plugin file changes
|
||||||
|
- FIXED `ip` in MP.GetIdentifiers
|
||||||
|
- FIXED issue with client->server events which contain ':'
|
||||||
|
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||||
|
- FIXED onInit not being called on hot-reload
|
||||||
|
- FIXED incorrect timing calculation of Lua EventTimer loop
|
||||||
|
- FIXED bug which caused hot-reload not to report syntax errors
|
||||||
|
- FIXED missing error messages on some event handler calls
|
||||||
|
|
||||||
|
# v3.0.2
|
||||||
|
|
||||||
|
- ADDED Periodic update message if a new server is released
|
||||||
|
- ADDED Config setting for the IP the http server listens on
|
||||||
|
- CHANGED Default MaxPlayers to 8
|
||||||
|
- CHANGED Default http server listen IP to localhost
|
||||||
|
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
|
||||||
|
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
|
||||||
|
- FIXED Lua result queue handling not checking all results
|
||||||
|
- FIXED bug which caused ServerConfig.toml to generate incorrectly
|
||||||
|
|
||||||
|
# v3.0.1
|
||||||
|
|
||||||
|
- ADDED Backup URLs to UpdateCheck (will fail less often now)
|
||||||
|
- ADDED console cursor left and right movement (with arrow keys) and working HOME and END key (via github.com/lionkor/commandline)
|
||||||
|
- FIXED infinite snowmen / infinite unicycle spawning bug
|
||||||
|
- FIXED a bug where, when run with --working-directory, the Server.log would still be in the original directory
|
||||||
|
- FIXED a bug which could cause the plugin reload thread to spin at 100% if the reloaded plugin's didn't terminate
|
||||||
|
- FIXED an issue which would cause servers to crash on mod download via SIGPIPE on POSIX
|
||||||
|
- FIXED an issue which would cause servers to crash when checking if a vehicle is a unicycle
|
||||||
|
|
||||||
|
# v3.0.0
|
||||||
|
|
||||||
|
- CHANGED entire plugin Lua implementation (rewrite)
|
||||||
|
- CHANGED moved *almost all* Lua functions into MP.\*
|
||||||
|
- CHANGED console to use a custom language (type `help`, `list`, or `status`!)
|
||||||
|
- CHANGED all files of a Lua plugin to share a Lua state (no more state-per-file)
|
||||||
|
- ADDED many new Lua API functions, which can be found at <https://wiki.beammp.com/en/Scripting/functions>
|
||||||
|
- ADDED Commandline options. Run with `--help` to see all options.
|
||||||
|
- ADDED HTTP(S) Server (OpenAPI spec coming soon!)
|
||||||
|
- ADDED plugin directories to `package.path` and `package.cpath` before `onInit`
|
||||||
|
- ADDED ability to add `PluginConfig.toml` to your plugin folder to change some settings
|
||||||
|
- ADDED ability to share a lua state with other plugins via `StateId` setting in `PluginConfig.toml`
|
||||||
|
- ADDED ability to see name-to-thread-ID association in debug mode
|
||||||
|
- ADDED dumping tables with `print()` (try it with `print(MP)`)
|
||||||
|
- ADDED `MP.GetOSName()`, `MP.CreateTimer()`, `MP.GetLuaMemoryUsage()` and many more (see <https://wiki.beammp.com/en/Scripting/functions>)
|
||||||
|
- ADDED `MP.Settings` table to make usage of `MP.Set()` easier
|
||||||
|
- ADDED `FS.*` table with common filesystem operations (do `print(FS)` to see them!)
|
||||||
|
- FIXED i/o thread spin when stdout is /dev/null on linux
|
||||||
|
- FIXED removed extra whitespace infront of onChatMessage message
|
||||||
|
|
||||||
# v2.3.3
|
# v2.3.3
|
||||||
|
|
||||||
- CHANGED servers to be private by default
|
- CHANGED servers to be private by default
|
||||||
|
|||||||
@@ -6,6 +6,15 @@
|
|||||||
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
||||||
The server is the point throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
The server is the point throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
||||||
|
|
||||||
|
**For Linux, you __need__ the runtime dependencies, listed below under "prerequisites".**
|
||||||
|
|
||||||
|
## Support + Contact
|
||||||
|
|
||||||
|
Feel free to ask any questions via the following channels:
|
||||||
|
|
||||||
|
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
|
||||||
|
- **Discord**: [click for invite](https://discord.gg/beammp)
|
||||||
|
|
||||||
## Minimum Requirements
|
## Minimum Requirements
|
||||||
|
|
||||||
These values are guesstimated and are subject to change with each release.
|
These values are guesstimated and are subject to change with each release.
|
||||||
@@ -41,7 +50,7 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
|||||||
|
|
||||||
## Build Instructions
|
## Build Instructions
|
||||||
|
|
||||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.0`!__**
|
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
||||||
|
|
||||||
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||||
|
|
||||||
@@ -51,39 +60,57 @@ Currently only linux and windows are supported (generally). See [Releases](https
|
|||||||
|
|
||||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||||
|
|
||||||
Dependencies for windows can be installed with `vcpkg`, in which case the current dependencies are the `x64-windows-static` versions of `lua`, `zlib`, `rapidjson`, `boost-beast`, `boost-asio` and `openssl`.
|
Dependencies for **windows** can be installed with `vcpkg`.
|
||||||
|
These are:
|
||||||
|
```
|
||||||
|
lua
|
||||||
|
zlib
|
||||||
|
rapidjson
|
||||||
|
openssl
|
||||||
|
websocketpp
|
||||||
|
curl
|
||||||
|
```
|
||||||
|
|
||||||
#### Linux / \*nix
|
#### Linux
|
||||||
|
|
||||||
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
||||||
|
|
||||||
- `git`
|
Runtime dependencies for **linux** are (debian/ubuntu):
|
||||||
- `make`
|
```
|
||||||
- `cmake`
|
libz-dev
|
||||||
- `g++`
|
rapidjson-dev
|
||||||
- `libcurl4-openssl-dev` or similar (search for `libcurl` and look for one with `-dev`)
|
liblua5.3
|
||||||
|
libssl-dev
|
||||||
Must support ISO C++17. If your distro's `g++` doesn't support C++17, chances are that it has a `g++-8` or `g++-10` package that does. If this is the case. you just need to run CMake with `-DCMAKE_CXX_COMPILER=g++-10` (replace `g++-10` with your compiler's name).
|
libwebsocketpp-dev
|
||||||
- `liblua5.3-dev`
|
libcurl4-openssl-dev
|
||||||
|
```
|
||||||
Any 5.x version should work, but 5.3 is what we officially use. Any other version might break in the future.
|
|
||||||
You can also use any version of `libluajit`, but the same applies regarding the version.
|
|
||||||
- `libz-dev`
|
|
||||||
- `rapidjson-dev`
|
|
||||||
- `libopenssl-dev` or `libssl-dev`
|
|
||||||
|
|
||||||
**If** you're building it from source, you'll need `libboost1.70-all-dev` or `libboost1.71-all-dev` or higher as well.
|
Build-time dependencies for **linux** are:
|
||||||
If you can't find this version of boost (only 1.6x, for example), you can either update to a newer version of your distro, build boost yourself, or use an unstable rolling release (like Debian `sid` aka `unstable`).
|
```
|
||||||
|
git
|
||||||
|
make
|
||||||
|
cmake
|
||||||
|
g++
|
||||||
|
```
|
||||||
|
|
||||||
|
For other distributions (e.g. Arch) you want to find packages for:
|
||||||
|
- libz
|
||||||
|
- rapidjson
|
||||||
|
- lua5.3
|
||||||
|
- ssl / openssl
|
||||||
|
- websocketpp
|
||||||
|
- curl (with ssl support)
|
||||||
|
- \+ the build time dependencies from above
|
||||||
|
|
||||||
### How to build
|
### How to build
|
||||||
|
|
||||||
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||||
|
|
||||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
1. Make sure you have all [prerequisites](#prerequisites) installed
|
||||||
2. Clone the repository in a location of your choice with **`git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`**. Now change into the cloned directory by running `cd BeamMP-Server`.
|
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
||||||
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
||||||
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v1.20` for version 1.20. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v3.0.1` for version 3.0.1. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||||
5. Run `cmake .` (with `.`)
|
5. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||||
6. Run `make`
|
6. Run `make`
|
||||||
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||||
|
|
||||||
|
|||||||
-1
Submodule asio deleted from 230c0d2ae0
Vendored
+14
@@ -0,0 +1,14 @@
|
|||||||
|
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
||||||
|
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||||
|
|
||||||
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||||
|
if (NOT TARGET fmt)
|
||||||
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
||||||
|
endif()
|
||||||
|
if (NOT TARGET sol2)
|
||||||
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
||||||
|
endif()
|
||||||
|
if (NOT TARGET doctest)
|
||||||
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
|
||||||
|
endif()
|
||||||
|
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/dlhttp")
|
||||||
+1
Submodule deps/asio added at d038fb3c2f
+1
Submodule deps/commandline added at d6b1c32c8a
+1
Submodule deps/cpp-httplib added at 47044c05a8
+1
Submodule deps/dlhttp added at f507c6c4e6
+1
Submodule deps/doctest added at 7b98851331
+1
Submodule deps/fmt added at ce246aaf74
+1
Submodule deps/json added at ede6667858
+1
Submodule deps/libzip added at 76df02f86b
+1
Submodule deps/rapidjson added at 00dbcf2c6e
+1
Submodule deps/sentry-native added at 90966cc102
+1
Submodule deps/sol2 added at c068aefbed
+1
Submodule deps/toml11 added at 1400dd223f
@@ -0,0 +1,49 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Allows syntax:
|
||||||
|
* --help : long flags
|
||||||
|
* --path=/home/lion : long assignments
|
||||||
|
*/
|
||||||
|
class ArgsParser {
|
||||||
|
public:
|
||||||
|
enum Flags : int {
|
||||||
|
NONE = 0,
|
||||||
|
REQUIRED = 1, // argument is required
|
||||||
|
HAS_VALUE = 2, // argument must have a value
|
||||||
|
};
|
||||||
|
|
||||||
|
ArgsParser() = default;
|
||||||
|
|
||||||
|
void Parse(const std::vector<std::string_view>& ArgList);
|
||||||
|
// prints errors if any errors occurred, in that case also returns false
|
||||||
|
bool Verify();
|
||||||
|
void RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags);
|
||||||
|
// pass all possible names for this argument (short, long, etc)
|
||||||
|
bool FoundArgument(const std::vector<std::string>& Names);
|
||||||
|
std::optional<std::string> GetValueOfArgument(const std::vector<std::string>& Names);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void ConsumeLongAssignment(const std::string& Arg);
|
||||||
|
void ConsumeLongFlag(const std::string& Arg);
|
||||||
|
bool IsRegistered(const std::string& Name);
|
||||||
|
|
||||||
|
struct Argument {
|
||||||
|
std::string Name;
|
||||||
|
std::optional<std::string> Value;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RegisteredArgument {
|
||||||
|
std::vector<std::string> Names;
|
||||||
|
int Flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<RegisteredArgument> mRegisteredArguments;
|
||||||
|
std::vector<Argument> mFoundArgs;
|
||||||
|
};
|
||||||
+18
-4
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_set>
|
#include <unordered_set>
|
||||||
@@ -12,6 +13,17 @@
|
|||||||
|
|
||||||
class TServer;
|
class TServer;
|
||||||
|
|
||||||
|
#ifdef BEAMMP_WINDOWS
|
||||||
|
// for socklen_t
|
||||||
|
#include <WS2tcpip.h>
|
||||||
|
#endif // WINDOWS
|
||||||
|
|
||||||
|
struct TConnection final {
|
||||||
|
SOCKET Socket;
|
||||||
|
struct sockaddr SockAddr;
|
||||||
|
socklen_t SockAddrLen;
|
||||||
|
};
|
||||||
|
|
||||||
class TClient final {
|
class TClient final {
|
||||||
public:
|
public:
|
||||||
using TSetOfVehicleData = std::vector<TVehicleData>;
|
using TSetOfVehicleData = std::vector<TVehicleData>;
|
||||||
@@ -30,7 +42,7 @@ public:
|
|||||||
TVehicleDataLockPair GetAllCars();
|
TVehicleDataLockPair GetAllCars();
|
||||||
void SetName(const std::string& Name) { mName = Name; }
|
void SetName(const std::string& Name) { mName = Name; }
|
||||||
void SetRoles(const std::string& Role) { mRole = Role; }
|
void SetRoles(const std::string& Role) { mRole = Role; }
|
||||||
void AddIdentifier(const std::string& ID) { mIdentifiers.insert(ID); };
|
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||||
std::string GetCarData(int Ident);
|
std::string GetCarData(int Ident);
|
||||||
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
|
||||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
||||||
@@ -38,7 +50,7 @@ public:
|
|||||||
void SetStatus(int Status) { mStatus = Status; }
|
void SetStatus(int Status) { mStatus = Status; }
|
||||||
// locks
|
// locks
|
||||||
void DeleteCar(int Ident);
|
void DeleteCar(int Ident);
|
||||||
[[nodiscard]] std::set<std::string> GetIdentifiers() const { return mIdentifiers; }
|
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||||
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
|
||||||
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
|
||||||
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
|
||||||
@@ -78,9 +90,9 @@ private:
|
|||||||
bool mIsSyncing = false;
|
bool mIsSyncing = false;
|
||||||
mutable std::mutex mMissedPacketsMutex;
|
mutable std::mutex mMissedPacketsMutex;
|
||||||
std::queue<std::string> mPacketsSync;
|
std::queue<std::string> mPacketsSync;
|
||||||
std::set<std::string> mIdentifiers;
|
std::unordered_map<std::string, std::string> mIdentifiers;
|
||||||
bool mIsGuest = false;
|
bool mIsGuest = false;
|
||||||
std::mutex mVehicleDataMutex;
|
mutable std::mutex mVehicleDataMutex;
|
||||||
TSetOfVehicleData mVehicleData;
|
TSetOfVehicleData mVehicleData;
|
||||||
std::string mName = "Unknown Client";
|
std::string mName = "Unknown Client";
|
||||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
||||||
@@ -92,3 +104,5 @@ private:
|
|||||||
int mID = -1;
|
int mID = -1;
|
||||||
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
|
||||||
|
|||||||
+254
-87
@@ -5,13 +5,34 @@ extern TSentry Sentry;
|
|||||||
|
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <cstring>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fmt/format.h>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <shared_mutex>
|
||||||
|
#include <sstream>
|
||||||
|
#include <zlib.h>
|
||||||
|
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
#include <filesystem>
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
#include "Compat.h"
|
||||||
|
|
||||||
#include "TConsole.h"
|
#include "TConsole.h"
|
||||||
|
|
||||||
|
struct Version {
|
||||||
|
uint8_t major;
|
||||||
|
uint8_t minor;
|
||||||
|
uint8_t patch;
|
||||||
|
Version(uint8_t major, uint8_t minor, uint8_t patch);
|
||||||
|
Version(const std::array<uint8_t, 3>& v);
|
||||||
|
std::string AsString();
|
||||||
|
};
|
||||||
|
|
||||||
// static class handling application start, shutdown, etc.
|
// static class handling application start, shutdown, etc.
|
||||||
// yes, static classes, singletons, globals are all pretty
|
// yes, static classes, singletons, globals are all pretty
|
||||||
// bad idioms. In this case we need a central way to access
|
// bad idioms. In this case we need a central way to access
|
||||||
@@ -21,33 +42,31 @@ class Application final {
|
|||||||
public:
|
public:
|
||||||
// types
|
// types
|
||||||
struct TSettings {
|
struct TSettings {
|
||||||
TSettings() noexcept
|
std::string ServerName { "BeamMP Server" };
|
||||||
: ServerName("BeamMP Server")
|
std::string ServerDesc { "BeamMP Default Description" };
|
||||||
, ServerDesc("BeamMP Default Description")
|
std::string Resource { "Resources" };
|
||||||
, Resource("Resources")
|
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||||
, MapName("/levels/gridmap_v2/info.json")
|
std::string Key {};
|
||||||
, MaxPlayers(10)
|
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||||
, Private(true)
|
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||||
, MaxCars(1)
|
bool HTTPServerEnabled { false };
|
||||||
, DebugModeEnabled(false)
|
int MaxPlayers { 8 };
|
||||||
, Port(30814)
|
bool Private { true };
|
||||||
, SendErrors(true)
|
int MaxCars { 1 };
|
||||||
, SendErrorsMessageEnabled(true) { }
|
bool DebugModeEnabled { false };
|
||||||
std::string ServerName;
|
int Port { 30814 };
|
||||||
std::string ServerDesc;
|
int DownloadThreads { 4 };
|
||||||
std::string Resource;
|
std::string CustomIP {};
|
||||||
std::string MapName;
|
bool LogChat { true };
|
||||||
std::string Key;
|
bool SendErrors { true };
|
||||||
int MaxPlayers;
|
bool SendErrorsMessageEnabled { true };
|
||||||
bool Private;
|
int HTTPServerPort { 8080 };
|
||||||
int MaxCars;
|
std::string HTTPServerIP { "127.0.0.1" };
|
||||||
bool DebugModeEnabled;
|
bool HTTPServerUseSSL { false };
|
||||||
int Port;
|
bool HideUpdateMessages { false };
|
||||||
std::string CustomIP;
|
|
||||||
bool SendErrors;
|
|
||||||
bool SendErrorsMessageEnabled;
|
|
||||||
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
|
||||||
};
|
};
|
||||||
|
|
||||||
using TShutdownHandler = std::function<void()>;
|
using TShutdownHandler = std::function<void()>;
|
||||||
|
|
||||||
// methods
|
// methods
|
||||||
@@ -58,100 +77,248 @@ public:
|
|||||||
// Causes all threads to finish up and exit gracefull gracefully
|
// Causes all threads to finish up and exit gracefull gracefully
|
||||||
static void GracefullyShutdown();
|
static void GracefullyShutdown();
|
||||||
static TConsole& Console() { return *mConsole; }
|
static TConsole& Console() { return *mConsole; }
|
||||||
static std::string ServerVersion() { return "2.3.2"; }
|
static std::string ServerVersionString();
|
||||||
static std::string ClientVersion() { return "2.0"; }
|
static const Version& ServerVersion() { return mVersion; }
|
||||||
|
static std::string ClientVersionString() { return "2.0"; }
|
||||||
static std::string PPS() { return mPPS; }
|
static std::string PPS() { return mPPS; }
|
||||||
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
|
||||||
|
|
||||||
static inline TSettings Settings {};
|
static TSettings Settings;
|
||||||
|
|
||||||
|
static std::vector<std::string> GetBackendUrlsInOrder() {
|
||||||
|
return {
|
||||||
|
"backend.beammp.com",
|
||||||
|
"backup1.beammp.com",
|
||||||
|
"backup2.beammp.com"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
|
||||||
static std::string GetBackendHostname() { return "backend.beammp.com"; }
|
|
||||||
static std::string GetBackup1Hostname() { return "backup1.beammp.com"; }
|
|
||||||
static std::string GetBackup2Hostname() { return "backup2.beammp.com"; }
|
|
||||||
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
|
||||||
static void CheckForUpdates();
|
static void CheckForUpdates();
|
||||||
static std::array<int, 3> VersionStrToInts(const std::string& str);
|
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
|
||||||
static bool IsOutdated(const std::array<int, 3>& Current, const std::array<int, 3>& Newest);
|
static bool IsOutdated(const Version& Current, const Version& Newest);
|
||||||
|
static bool IsShuttingDown();
|
||||||
|
static void SleepSafeSeconds(size_t Seconds);
|
||||||
|
|
||||||
|
static void InitializeConsole() {
|
||||||
|
if (!mConsole) {
|
||||||
|
mConsole = std::make_unique<TConsole>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class Status {
|
||||||
|
Starting,
|
||||||
|
Good,
|
||||||
|
Bad,
|
||||||
|
ShuttingDown,
|
||||||
|
Shutdown,
|
||||||
|
};
|
||||||
|
|
||||||
|
using SystemStatusMap = std::unordered_map<std::string /* system name */, Status /* status */>;
|
||||||
|
|
||||||
|
static const SystemStatusMap& GetSubsystemStatuses() {
|
||||||
|
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||||
|
return mSystemStatusMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
static void SetShutdown(bool Val);
|
||||||
|
|
||||||
|
static inline SystemStatusMap mSystemStatusMap {};
|
||||||
|
static inline std::mutex mSystemStatusMapMutex {};
|
||||||
static inline std::string mPPS;
|
static inline std::string mPPS;
|
||||||
static std::unique_ptr<TConsole> mConsole;
|
static inline std::unique_ptr<TConsole> mConsole;
|
||||||
|
static inline std::shared_mutex mShutdownMtx {};
|
||||||
|
static inline bool mShutdown { false };
|
||||||
static inline std::mutex mShutdownHandlersMutex {};
|
static inline std::mutex mShutdownHandlersMutex {};
|
||||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||||
|
|
||||||
|
static inline Version mVersion { 3, 1, 0 };
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string ThreadName(bool DebugModeOverride = false);
|
std::string ThreadName(bool DebugModeOverride = false);
|
||||||
void RegisterThread(const std::string& str);
|
void RegisterThread(const std::string& str);
|
||||||
#define RegisterThreadAuto() RegisterThread(__func__)
|
#define RegisterThreadAuto() RegisterThread(__func__)
|
||||||
|
|
||||||
#define KB 1024
|
#define KB 1024llu
|
||||||
#define MB (KB * 1024)
|
#define MB (KB * 1024llu)
|
||||||
|
#define GB (MB * 1024llu)
|
||||||
#define SSU_UNRAW SECRET_SENTRY_URL
|
#define SSU_UNRAW SECRET_SENTRY_URL
|
||||||
|
|
||||||
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
#define _file_basename std::filesystem::path(__FILE__).filename().string()
|
||||||
#define _line std::to_string(__LINE__)
|
#define _line std::to_string(__LINE__)
|
||||||
#define _in_lambda (std::string(__func__) == "operator()")
|
#define _in_lambda (std::string(__func__) == "operator()")
|
||||||
|
|
||||||
// we would like the full function signature 'void a::foo() const'
|
// for those times when you just need to ignore something :^)
|
||||||
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
|
// explicity disables a [[nodiscard]] warning
|
||||||
// feel free to add more
|
#define beammp_ignore(x) (void)x
|
||||||
#if defined(WIN32)
|
|
||||||
#define _function_name std::string(__FUNCSIG__)
|
// clang-format off
|
||||||
#elif defined(__unix) || defined(__unix__)
|
#ifdef DOCTEST_CONFIG_DISABLE
|
||||||
#define _function_name std::string(__PRETTY_FUNCTION__)
|
|
||||||
#else
|
// we would like the full function signature 'void a::foo() const'
|
||||||
#define _function_name std::string(__func__)
|
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
|
||||||
#endif
|
// feel free to add more
|
||||||
|
#if defined(WIN32)
|
||||||
|
#define _function_name std::string(__FUNCSIG__)
|
||||||
|
#elif defined(__unix) || defined(__unix__)
|
||||||
|
#define _function_name std::string(__PRETTY_FUNCTION__)
|
||||||
|
#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)
|
||||||
|
#define _this_location (ThreadName() + _function_name + " ")
|
||||||
|
#else
|
||||||
|
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
|
||||||
|
#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) \
|
||||||
|
do { \
|
||||||
|
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
||||||
|
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
||||||
|
} while (false)
|
||||||
|
#define beammp_lua_error(x) \
|
||||||
|
do { \
|
||||||
|
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
|
||||||
|
} while (false)
|
||||||
|
#define beammp_lua_warn(x) \
|
||||||
|
do { \
|
||||||
|
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||||
|
} while (false)
|
||||||
|
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||||
|
#define beammp_debug(x) \
|
||||||
|
do { \
|
||||||
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
|
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
||||||
|
} \
|
||||||
|
} while (false)
|
||||||
|
#define beammp_event(x) \
|
||||||
|
do { \
|
||||||
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
|
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
|
||||||
|
} \
|
||||||
|
} while (false)
|
||||||
|
// trace() is a debug-build debug()
|
||||||
|
#if defined(DEBUG)
|
||||||
|
#define beammp_trace(x) \
|
||||||
|
do { \
|
||||||
|
if (Application::Settings.DebugModeEnabled) { \
|
||||||
|
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__))
|
||||||
|
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||||
|
#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__))
|
||||||
|
|
||||||
|
#else // DOCTEST_CONFIG_DISABLE
|
||||||
|
|
||||||
|
#define beammp_error(x) /* x */
|
||||||
|
#define beammp_lua_error(x) /* x */
|
||||||
|
#define beammp_warn(x) /* x */
|
||||||
|
#define beammp_lua_warn(x) /* x */
|
||||||
|
#define beammp_info(x) /* x */
|
||||||
|
#define beammp_event(x) /* x */
|
||||||
|
#define beammp_debug(x) /* x */
|
||||||
|
#define beammp_trace(x) /* x */
|
||||||
|
#define luaprint(x) /* x */
|
||||||
|
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||||
|
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||||
|
#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__))
|
||||||
|
|
||||||
|
#endif // DOCTEST_CONFIG_DISABLE
|
||||||
|
|
||||||
#if defined(DEBUG)
|
#if defined(DEBUG)
|
||||||
|
#define SU_RAW SSU_UNRAW
|
||||||
// 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)
|
|
||||||
#define _this_location (ThreadName() + _function_name + " ")
|
|
||||||
#else
|
#else
|
||||||
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
|
#define SU_RAW RAWIFY(SSU_UNRAW)
|
||||||
|
#define _this_location (ThreadName())
|
||||||
#endif
|
#endif
|
||||||
#define SU_RAW SSU_UNRAW
|
|
||||||
|
|
||||||
#else // !defined(DEBUG)
|
// clang-format on
|
||||||
|
|
||||||
#define SU_RAW RAWIFY(SSU_UNRAW)
|
|
||||||
#define _this_location (ThreadName())
|
|
||||||
|
|
||||||
#endif // defined(DEBUG)
|
|
||||||
|
|
||||||
#define warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
|
|
||||||
#define info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
|
|
||||||
#define error(x) \
|
|
||||||
do { \
|
|
||||||
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
|
|
||||||
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
|
|
||||||
} while (false)
|
|
||||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
|
||||||
#define debug(x) \
|
|
||||||
do { \
|
|
||||||
if (Application::Settings.DebugModeEnabled) { \
|
|
||||||
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
|
|
||||||
} \
|
|
||||||
} while (false)
|
|
||||||
// trace() is a debug-build debug()
|
|
||||||
#if defined(DEBUG)
|
|
||||||
#define trace(x) \
|
|
||||||
do { \
|
|
||||||
if (Application::Settings.DebugModeEnabled) { \
|
|
||||||
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
|
|
||||||
} \
|
|
||||||
} while (false)
|
|
||||||
#else
|
|
||||||
#define trace(x)
|
|
||||||
#endif // defined(DEBUG)
|
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|
||||||
#define Biggest 30000
|
#define Biggest 30000
|
||||||
std::string Comp(std::string Data);
|
|
||||||
std::string DeComp(std::string Compressed);
|
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
inline T Comp(const T& Data) {
|
||||||
|
std::array<char, Biggest> C {};
|
||||||
|
// obsolete
|
||||||
|
C.fill(0);
|
||||||
|
z_stream defstream;
|
||||||
|
defstream.zalloc = Z_NULL;
|
||||||
|
defstream.zfree = Z_NULL;
|
||||||
|
defstream.opaque = Z_NULL;
|
||||||
|
defstream.avail_in = (uInt)Data.size();
|
||||||
|
defstream.next_in = (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 = Z_NULL;
|
||||||
|
infstream.zfree = Z_NULL;
|
||||||
|
infstream.opaque = Z_NULL;
|
||||||
|
infstream.avail_in = Biggest;
|
||||||
|
infstream.next_in = (Bytef*)(&Compressed[0]);
|
||||||
|
infstream.avail_out = Biggest;
|
||||||
|
infstream.next_out = (Bytef*)(C.data());
|
||||||
|
inflateInit(&infstream);
|
||||||
|
inflate(&infstream, Z_SYNC_FLUSH);
|
||||||
|
inflate(&infstream, Z_FINISH);
|
||||||
|
inflateEnd(&infstream);
|
||||||
|
size_t TotalOut = infstream.total_out;
|
||||||
|
T Ret;
|
||||||
|
Ret.resize(TotalOut);
|
||||||
|
std::fill(Ret.begin(), Ret.end(), 0);
|
||||||
|
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||||
|
return Ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string GetPlatformAgnosticErrorString();
|
||||||
#define S_DSN SU_RAW
|
#define S_DSN SU_RAW
|
||||||
|
|
||||||
|
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||||
|
|||||||
+29
-7
@@ -1,9 +1,12 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include "Environment.h"
|
||||||
|
|
||||||
// ======================= UNIX ========================
|
// ======================= UNIX ========================
|
||||||
|
|
||||||
#ifdef __unix
|
#ifdef BEAMMP_LINUX
|
||||||
#include <arpa/inet.h>
|
#include <arpa/inet.h>
|
||||||
|
#include <errno.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include <termios.h>
|
#include <termios.h>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
@@ -18,9 +21,28 @@ inline void CloseSocketProper(int TheSocket) {
|
|||||||
}
|
}
|
||||||
#endif // unix
|
#endif // unix
|
||||||
|
|
||||||
// ======================= WIN32 =======================
|
// ======================= APPLE ========================
|
||||||
|
|
||||||
#ifdef WIN32
|
#ifdef BEAMMP_APPLE
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <errno.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <termios.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
using SOCKET = int;
|
||||||
|
using DWORD = unsigned long;
|
||||||
|
using PDWORD = unsigned long*;
|
||||||
|
using LPDWORD = unsigned long*;
|
||||||
|
char _getch();
|
||||||
|
inline void CloseSocketProper(int TheSocket) {
|
||||||
|
shutdown(TheSocket, SHUT_RDWR);
|
||||||
|
close(TheSocket);
|
||||||
|
}
|
||||||
|
#endif // unix
|
||||||
|
|
||||||
|
// ======================= WINDOWS =======================
|
||||||
|
|
||||||
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <conio.h>
|
#include <conio.h>
|
||||||
#include <winsock2.h>
|
#include <winsock2.h>
|
||||||
inline void CloseSocketProper(SOCKET TheSocket) {
|
inline void CloseSocketProper(SOCKET TheSocket) {
|
||||||
@@ -29,8 +51,8 @@ inline void CloseSocketProper(SOCKET TheSocket) {
|
|||||||
}
|
}
|
||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
// ======================= OTHER =======================
|
#ifdef INVALID_SOCKET
|
||||||
|
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
|
||||||
#if !defined(WIN32) && !defined(__unix)
|
#else
|
||||||
#error "OS not supported"
|
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -91,14 +91,14 @@ static auto w_printf_s = [](const char* fmt, ...) {
|
|||||||
va_end(args);
|
va_end(args);
|
||||||
};
|
};
|
||||||
|
|
||||||
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
static auto w_sprintf_s = [](char* buf, size_t, const char* fmt, ...) {
|
||||||
va_list args;
|
va_list args;
|
||||||
va_start(args, fmt);
|
va_start(args, fmt);
|
||||||
vsprintf(buf, fmt, args);
|
vsprintf(buf, fmt, args);
|
||||||
va_end(args);
|
va_end(args);
|
||||||
};
|
};
|
||||||
|
|
||||||
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
static auto w_sprintf_s_ret = [](char* buf, size_t, const char* fmt, ...) {
|
||||||
int ret;
|
int ret;
|
||||||
va_list args;
|
va_list args;
|
||||||
va_start(args, fmt);
|
va_start(args, fmt);
|
||||||
|
|||||||
@@ -55,18 +55,18 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#define Assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||||
#define AssertNotReachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||||
#else
|
#else
|
||||||
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
||||||
#define Assert(cond) \
|
#define beammp_assert(cond) \
|
||||||
do { \
|
do { \
|
||||||
bool result = (cond); \
|
bool result = (cond); \
|
||||||
if (!result) { \
|
if (!result) { \
|
||||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
||||||
} \
|
} \
|
||||||
} while (false)
|
} while (false)
|
||||||
#define AssertNotReachable() \
|
#define beammp_assert_not_reachable() \
|
||||||
do { \
|
do { \
|
||||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
||||||
} while (false)
|
} while (false)
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
|
||||||
|
|
||||||
|
// clang-format off
|
||||||
|
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE)
|
||||||
|
#if defined(_WIN32) || defined(__CYGWIN__)
|
||||||
|
#define BEAMMP_WINDOWS
|
||||||
|
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__unix__) || defined(__unix) || defined(unix)
|
||||||
|
#define BEAMMP_LINUX
|
||||||
|
#elif defined(__APPLE__) || defined(__MACH__)
|
||||||
|
#define BEAMMP_APPLE
|
||||||
|
#else
|
||||||
|
#error "This platform is not known. Please define one of the above for your OS."
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
// clang-format on
|
||||||
+29
-1
@@ -1,12 +1,40 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <Common.h>
|
||||||
|
#include <IThreaded.h>
|
||||||
|
#include <filesystem>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
|
#if defined(BEAMMP_LINUX)
|
||||||
|
#pragma GCC diagnostic push
|
||||||
|
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||||
|
#endif
|
||||||
|
#include <httplib.h>
|
||||||
|
#if defined(BEAMMP_LINUX)
|
||||||
|
#pragma GCC diagnostic pop
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
namespace Http {
|
namespace Http {
|
||||||
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
|
||||||
std::string POST(const std::string& host, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, bool json, 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 = {});
|
||||||
namespace Status {
|
namespace Status {
|
||||||
std::string ToString(int code);
|
std::string ToString(int code);
|
||||||
}
|
}
|
||||||
|
const std::string ErrorString = "-1";
|
||||||
|
|
||||||
|
namespace Server {
|
||||||
|
class THttpServerInstance {
|
||||||
|
public:
|
||||||
|
THttpServerInstance();
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void operator()();
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::thread mThread;
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ public:
|
|||||||
IThreaded()
|
IThreaded()
|
||||||
// invokes operator() on this object
|
// invokes operator() on this object
|
||||||
: mThread() { }
|
: mThread() { }
|
||||||
|
~IThreaded() noexcept {
|
||||||
|
if (mThread.joinable()) {
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
virtual void Start() final {
|
virtual void Start() final {
|
||||||
mThread = std::thread([this] { (*this)(); });
|
mThread = std::thread([this] { (*this)(); });
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
#include <tuple>
|
||||||
|
|
||||||
|
namespace LuaAPI {
|
||||||
|
int PanicHandler(lua_State* State);
|
||||||
|
std::string LuaToString(const sol::object Value, size_t Indent = 1, bool QuoteStrings = false);
|
||||||
|
void Print(sol::variadic_args);
|
||||||
|
namespace MP {
|
||||||
|
extern TLuaEngine* Engine;
|
||||||
|
|
||||||
|
std::string GetOSName();
|
||||||
|
std::tuple<int, int, int> GetServerVersion();
|
||||||
|
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||||
|
bool TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||||
|
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||||
|
void DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||||
|
void SendChatMessage(int ID, const std::string& Message);
|
||||||
|
void RemoveVehicle(int PlayerID, int VehicleID);
|
||||||
|
void Set(int ConfigID, sol::object NewValue);
|
||||||
|
bool IsPlayerGuest(int ID);
|
||||||
|
bool IsPlayerConnected(int ID);
|
||||||
|
void Sleep(size_t Ms);
|
||||||
|
void PrintRaw(sol::variadic_args);
|
||||||
|
std::string JsonEncode(const sol::table& object);
|
||||||
|
std::string JsonDiff(const std::string& a, const std::string& b);
|
||||||
|
std::string JsonDiffApply(const std::string& data, const std::string& patch);
|
||||||
|
std::string JsonPrettify(const std::string& json);
|
||||||
|
std::string JsonMinify(const std::string& json);
|
||||||
|
std::string JsonFlatten(const std::string& json);
|
||||||
|
std::string JsonUnflatten(const std::string& json);
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace FS {
|
||||||
|
std::pair<bool, std::string> CreateDirectory(const std::string& Path);
|
||||||
|
std::pair<bool, std::string> Remove(const std::string& Path);
|
||||||
|
std::pair<bool, std::string> Rename(const std::string& Path, const std::string& NewPath);
|
||||||
|
std::pair<bool, std::string> Copy(const std::string& Path, const std::string& NewPath);
|
||||||
|
std::string GetFilename(const std::string& Path);
|
||||||
|
std::string GetExtension(const std::string& Path);
|
||||||
|
std::string GetParentFolder(const std::string& Path);
|
||||||
|
bool Exists(const std::string& Path);
|
||||||
|
bool IsDirectory(const std::string& Path);
|
||||||
|
bool IsFile(const std::string& Path);
|
||||||
|
std::string ConcatPaths(sol::variadic_args Args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <deque>
|
|
||||||
#include <mutex>
|
|
||||||
#include <sio_client.h>
|
|
||||||
#include <thread>
|
|
||||||
#include <memory>
|
|
||||||
|
|
||||||
/*
|
|
||||||
* We send relevant server events over socket.io to the backend.
|
|
||||||
*
|
|
||||||
* We send all events to `backend.beammp.com`, to the room `/key`
|
|
||||||
* where `key` is the currently active auth-key.
|
|
||||||
*/
|
|
||||||
|
|
||||||
enum class SocketIOEvent {
|
|
||||||
ConsoleOut,
|
|
||||||
CPUUsage,
|
|
||||||
MemoryUsage,
|
|
||||||
NetworkUsage,
|
|
||||||
PlayerList,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class SocketIORoom {
|
|
||||||
None,
|
|
||||||
Stats,
|
|
||||||
Player,
|
|
||||||
Info,
|
|
||||||
Console,
|
|
||||||
};
|
|
||||||
|
|
||||||
class SocketIO final {
|
|
||||||
private:
|
|
||||||
struct Event;
|
|
||||||
|
|
||||||
public:
|
|
||||||
enum class EventType {
|
|
||||||
};
|
|
||||||
|
|
||||||
// Singleton pattern
|
|
||||||
static SocketIO& Get();
|
|
||||||
|
|
||||||
void Emit(SocketIOEvent Event, const std::string& Data);
|
|
||||||
|
|
||||||
~SocketIO();
|
|
||||||
|
|
||||||
void SetAuthenticated(bool auth) { mAuthenticated = auth; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
SocketIO() noexcept;
|
|
||||||
|
|
||||||
void ThreadMain();
|
|
||||||
|
|
||||||
struct Event {
|
|
||||||
std::string Name;
|
|
||||||
std::string Data;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool mAuthenticated { false };
|
|
||||||
sio::client mClient;
|
|
||||||
std::thread mThread;
|
|
||||||
std::atomic_bool mCloseThread { false };
|
|
||||||
std::mutex mQueueMutex;
|
|
||||||
std::deque<Event> mQueue;
|
|
||||||
|
|
||||||
friend std::unique_ptr<SocketIO> std::make_unique<SocketIO>();
|
|
||||||
};
|
|
||||||
|
|
||||||
+15
-3
@@ -3,19 +3,31 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
|
||||||
|
#include <toml11/toml.hpp> // header-only version of TOML++
|
||||||
|
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
class TConfig {
|
class TConfig {
|
||||||
public:
|
public:
|
||||||
explicit TConfig();
|
explicit TConfig(const std::string& ConfigFileName);
|
||||||
|
|
||||||
[[nodiscard]] bool Failed() const { return mFailed; }
|
[[nodiscard]] bool Failed() const { return mFailed; }
|
||||||
|
|
||||||
|
void FlushToFile();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void CreateConfigFile(std::string_view name);
|
void CreateConfigFile();
|
||||||
void ParseFromFile(std::string_view name);
|
void ParseFromFile(std::string_view name);
|
||||||
void PrintDebug();
|
void PrintDebug();
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
||||||
|
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
||||||
|
|
||||||
void ParseOldFormat();
|
void ParseOldFormat();
|
||||||
|
bool IsDefault();
|
||||||
bool mFailed { false };
|
bool mFailed { false };
|
||||||
|
std::string mConfigFileName;
|
||||||
};
|
};
|
||||||
|
|||||||
+51
-3
@@ -1,10 +1,16 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "commandline/commandline.h"
|
|
||||||
#include "TLuaFile.h"
|
|
||||||
#include "Cryptography.h"
|
#include "Cryptography.h"
|
||||||
|
#include "commandline.h"
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
|
#include <tuple>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
class TLuaEngine;
|
||||||
|
|
||||||
class TConsole {
|
class TConsole {
|
||||||
public:
|
public:
|
||||||
@@ -13,8 +19,50 @@ public:
|
|||||||
void Write(const std::string& str);
|
void Write(const std::string& str);
|
||||||
void WriteRaw(const std::string& str);
|
void WriteRaw(const std::string& str);
|
||||||
void InitializeLuaConsole(TLuaEngine& Engine);
|
void InitializeLuaConsole(TLuaEngine& Engine);
|
||||||
|
void BackupOldLog();
|
||||||
|
void StartLoggingToFile();
|
||||||
|
Commandline& Internal() { return mCommandline; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::unique_ptr<TLuaFile> mLuaConsole { nullptr };
|
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
||||||
|
void ChangeToLuaConsole(const std::string& LuaStateId);
|
||||||
|
void ChangeToRegularConsole();
|
||||||
|
void HandleLuaInternalCommand(const std::string& cmd);
|
||||||
|
|
||||||
|
void Command_Lua(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_Help(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_Kick(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_List(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
|
||||||
|
void Command_Clear(const std::string&, const std::vector<std::string>& args);
|
||||||
|
|
||||||
|
void Command_Say(const std::string& FullCommand);
|
||||||
|
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
|
||||||
|
bool EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max);
|
||||||
|
|
||||||
|
static std::tuple<std::string, std::vector<std::string>> ParseCommand(const std::string& cmd);
|
||||||
|
static std::string ConcatArgs(const std::vector<std::string>& args, char space = ' ');
|
||||||
|
|
||||||
|
std::unordered_map<std::string, std::function<void(const std::string&, const std::vector<std::string>&)>> mCommandMap = {
|
||||||
|
{ "lua", [this](const auto& a, const auto& b) { Command_Lua(a, b); } },
|
||||||
|
{ "help", [this](const auto& a, const auto& b) { Command_Help(a, b); } },
|
||||||
|
{ "kick", [this](const auto& a, const auto& b) { Command_Kick(a, b); } },
|
||||||
|
{ "list", [this](const auto& a, const auto& b) { Command_List(a, b); } },
|
||||||
|
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
|
||||||
|
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
|
||||||
|
{ "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
|
||||||
|
};
|
||||||
|
|
||||||
Commandline mCommandline;
|
Commandline mCommandline;
|
||||||
|
std::vector<std::string> mCachedLuaHistory;
|
||||||
|
std::vector<std::string> mCachedRegularHistory;
|
||||||
|
TLuaEngine* mLuaEngine { nullptr };
|
||||||
|
bool mIsLuaConsole { false };
|
||||||
|
bool mFirstTime { true };
|
||||||
|
std::string mStateId;
|
||||||
|
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
||||||
|
std::ofstream mLogFileStream;
|
||||||
|
std::mutex mLogFileStreamMtx;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ private:
|
|||||||
std::string GenerateCall();
|
std::string GenerateCall();
|
||||||
std::string GetPlayers();
|
std::string GetPlayers();
|
||||||
|
|
||||||
bool mShutdown = false;
|
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
};
|
};
|
||||||
|
|||||||
+245
-22
@@ -1,39 +1,262 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Common.h"
|
#include "TNetwork.h"
|
||||||
#include "IThreaded.h"
|
|
||||||
#include "TLuaFile.h"
|
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
#include <any>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <list>
|
||||||
#include <lua.hpp>
|
#include <lua.hpp>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <mutex>
|
||||||
|
#include <queue>
|
||||||
|
#include <random>
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <toml11/toml.hpp>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
class TLuaEngine : public IThreaded {
|
#define SOL_ALL_SAFETIES_ON 1
|
||||||
|
#include <sol/sol.hpp>
|
||||||
|
|
||||||
|
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>;
|
||||||
|
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;
|
||||||
|
|
||||||
|
class TLuaPlugin;
|
||||||
|
|
||||||
|
struct TLuaResult {
|
||||||
|
bool Ready;
|
||||||
|
bool Error;
|
||||||
|
std::string ErrorMessage;
|
||||||
|
sol::object Result { sol::lua_nil };
|
||||||
|
TLuaStateId StateId;
|
||||||
|
std::string Function;
|
||||||
|
// TODO: Add condition_variable
|
||||||
|
void WaitUntilReady();
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TLuaPluginConfig {
|
||||||
|
static inline const std::string FileName = "PluginConfig.toml";
|
||||||
|
TLuaStateId StateId;
|
||||||
|
// TODO: Add execute list
|
||||||
|
// TODO: Build a better toml serializer, or some way to do this in an easier way
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TLuaChunk {
|
||||||
|
TLuaChunk(std::shared_ptr<std::string> Content,
|
||||||
|
std::string FileName,
|
||||||
|
std::string PluginPath);
|
||||||
|
std::shared_ptr<std::string> Content;
|
||||||
|
std::string FileName;
|
||||||
|
std::string PluginPath;
|
||||||
|
};
|
||||||
|
|
||||||
|
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
|
||||||
public:
|
public:
|
||||||
explicit TLuaEngine(TServer& Server, TNetwork& Network);
|
enum CallStrategy : int {
|
||||||
|
BestEffort,
|
||||||
|
Precise,
|
||||||
|
};
|
||||||
|
|
||||||
using TSetOfLuaFile = std::set<std::unique_ptr<TLuaFile>>;
|
struct QueuedFunction {
|
||||||
|
std::string FunctionName;
|
||||||
|
std::shared_ptr<TLuaResult> Result;
|
||||||
|
std::vector<TLuaArgTypes> Args;
|
||||||
|
std::string EventName; // optional, may be empty
|
||||||
|
};
|
||||||
|
|
||||||
|
TLuaEngine();
|
||||||
|
~TLuaEngine() noexcept {
|
||||||
|
beammp_debug("Lua Engine terminated");
|
||||||
|
}
|
||||||
|
|
||||||
void operator()() override;
|
void operator()() override;
|
||||||
|
|
||||||
[[nodiscard]] const TSetOfLuaFile& LuaFiles() const { return mLuaFiles; }
|
TNetwork& Network() { return *mNetwork; }
|
||||||
[[nodiscard]] TServer& Server() { return mServer; }
|
TServer& Server() { return *mServer; }
|
||||||
[[nodiscard]] const TServer& Server() const { return mServer; }
|
|
||||||
[[nodiscard]] TNetwork& Network() { return mNetwork; }
|
|
||||||
[[nodiscard]] const TNetwork& Network() const { return mNetwork; }
|
|
||||||
|
|
||||||
std::optional<std::reference_wrapper<TLuaFile>> GetScript(lua_State* L);
|
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
|
||||||
|
void SetServer(TServer* Server) { mServer = Server; }
|
||||||
|
|
||||||
|
size_t GetResultsToCheckSize() {
|
||||||
|
std::unique_lock Lock(mResultsToCheckMutex);
|
||||||
|
return mResultsToCheck.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t GetLuaStateCount() {
|
||||||
|
std::unique_lock Lock(mLuaStatesMutex);
|
||||||
|
return mLuaStates.size();
|
||||||
|
}
|
||||||
|
size_t GetTimedEventsCount() {
|
||||||
|
std::unique_lock Lock(mTimedEventsMutex);
|
||||||
|
return mTimedEvents.size();
|
||||||
|
}
|
||||||
|
size_t GetRegisteredEventHandlerCount() {
|
||||||
|
std::unique_lock Lock(mLuaEventsMutex);
|
||||||
|
size_t LuaEventsCount = 0;
|
||||||
|
for (const auto& State : mLuaEvents) {
|
||||||
|
for (const auto& Events : State.second) {
|
||||||
|
LuaEventsCount += Events.second.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return LuaEventsCount - GetLuaStateCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
|
||||||
|
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);
|
||||||
|
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||||
|
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @tparam ArgsT Template Arguments for the event (Metadata) todo: figure out what this means
|
||||||
|
* @param EventName Name of the event
|
||||||
|
* @param IgnoreId
|
||||||
|
* @param Args
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
template <typename... ArgsT>
|
||||||
|
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerEvent(const std::string& EventName, TLuaStateId IgnoreId, ArgsT&&... Args) {
|
||||||
|
std::unique_lock Lock(mLuaEventsMutex);
|
||||||
|
beammp_event(EventName);
|
||||||
|
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Results; //
|
||||||
|
}
|
||||||
|
template <typename... ArgsT>
|
||||||
|
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerLocalEvent(const TLuaStateId& StateId, const std::string& EventName, ArgsT&&... Args) {
|
||||||
|
std::unique_lock Lock(mLuaEventsMutex);
|
||||||
|
beammp_event(EventName + " in '" + StateId + "'");
|
||||||
|
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||||
|
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||||
|
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||||
|
for (const auto& Handler : Handlers) {
|
||||||
|
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||||
|
}
|
||||||
|
return Results;
|
||||||
|
}
|
||||||
|
std::set<std::string> GetEventHandlersForState(const std::string& EventName, TLuaStateId StateId);
|
||||||
|
void CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy);
|
||||||
|
void CancelEventTimers(const std::string& EventName, TLuaStateId StateId);
|
||||||
|
sol::state_view GetStateForPlugin(const fs::path& PluginPath);
|
||||||
|
TLuaStateId GetStateIDForPlugin(const fs::path& PluginPath);
|
||||||
|
void AddResultToCheck(const std::shared_ptr<TLuaResult>& Result);
|
||||||
|
|
||||||
|
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
||||||
|
|
||||||
|
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
||||||
|
|
||||||
|
// 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::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
|
||||||
|
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void FolderList(const std::string& Path, bool HotSwap);
|
void CollectAndInitPlugins();
|
||||||
void RegisterFiles(const fs::path& Path, bool HotSwap);
|
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
||||||
bool IsNewFile(const std::string& Path);
|
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||||
|
size_t CalculateMemoryUsage();
|
||||||
|
|
||||||
TNetwork& mNetwork;
|
class StateThreadData : IThreaded {
|
||||||
TServer& mServer;
|
public:
|
||||||
std::string mPath;
|
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||||
bool mShutdown { false };
|
StateThreadData(const StateThreadData&) = delete;
|
||||||
TSetOfLuaFile mLuaFiles;
|
~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||||
std::mutex mListMutex;
|
[[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);
|
||||||
|
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;
|
||||||
|
sol::state_view State() { return sol::state_view(mState); }
|
||||||
|
|
||||||
|
std::vector<std::string> GetStateGlobalKeys();
|
||||||
|
|
||||||
|
// Debug functions, slow
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> 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);
|
||||||
|
sol::table Lua_GetPlayers();
|
||||||
|
std::string Lua_GetPlayerName(int ID);
|
||||||
|
sol::table Lua_GetPlayerVehicles(int ID);
|
||||||
|
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
|
||||||
|
sol::table Lua_JsonDecode(const std::string& str);
|
||||||
|
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||||
|
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||||
|
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||||
|
|
||||||
|
std::string mName;
|
||||||
|
TLuaStateId mStateId;
|
||||||
|
lua_State* mState;
|
||||||
|
std::thread mThread;
|
||||||
|
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||||
|
std::recursive_mutex mStateExecuteQueueMutex;
|
||||||
|
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||||
|
std::mutex mStateFunctionQueueMutex;
|
||||||
|
std::condition_variable mStateFunctionQueueCond;
|
||||||
|
TLuaEngine* mEngine;
|
||||||
|
sol::state_view mStateView { mState };
|
||||||
|
std::queue<fs::path> mPaths;
|
||||||
|
std::recursive_mutex mPathsMutex;
|
||||||
|
std::mt19937 mMersenneTwister;
|
||||||
|
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TimedEvent {
|
||||||
|
std::chrono::high_resolution_clock::duration Duration {};
|
||||||
|
std::chrono::high_resolution_clock::time_point LastCompletion {};
|
||||||
|
std::string EventName;
|
||||||
|
TLuaStateId StateId;
|
||||||
|
CallStrategy Strategy;
|
||||||
|
bool Expired();
|
||||||
|
void Reset();
|
||||||
|
};
|
||||||
|
|
||||||
|
TNetwork* mNetwork;
|
||||||
|
TServer* mServer;
|
||||||
|
const fs::path mResourceServerPath;
|
||||||
|
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
||||||
|
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
||||||
|
std::recursive_mutex mLuaStatesMutex;
|
||||||
|
std::unordered_map<std::string /* event name */, std::unordered_map<TLuaStateId, std::set<std::string>>> mLuaEvents;
|
||||||
|
std::recursive_mutex mLuaEventsMutex;
|
||||||
|
std::vector<TimedEvent> mTimedEvents;
|
||||||
|
std::recursive_mutex mTimedEventsMutex;
|
||||||
|
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
||||||
|
std::mutex mResultsToCheckMutex;
|
||||||
|
std::condition_variable mResultsToCheckCond;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
#ifndef TLUAFILE_H
|
|
||||||
#define TLUAFILE_H
|
|
||||||
|
|
||||||
#include <any>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <lua.hpp>
|
|
||||||
#include <mutex>
|
|
||||||
#include <set>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
|
||||||
|
|
||||||
struct TLuaArg {
|
|
||||||
std::vector<std::any> args;
|
|
||||||
void PushArgs(lua_State* State);
|
|
||||||
};
|
|
||||||
|
|
||||||
class TLuaEngine;
|
|
||||||
|
|
||||||
class TLuaFile {
|
|
||||||
public:
|
|
||||||
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
|
|
||||||
void UnRegisterEvent(const std::string& Event);
|
|
||||||
void SetLastWrite(fs::file_time_type time);
|
|
||||||
bool IsRegistered(const std::string& Event);
|
|
||||||
void SetPluginName(const std::string& Name);
|
|
||||||
void Execute(const std::string& Command);
|
|
||||||
void SetFileName(const std::string& Name);
|
|
||||||
fs::file_time_type GetLastWrite();
|
|
||||||
lua_State* GetState();
|
|
||||||
std::string GetOrigin();
|
|
||||||
std::mutex Lock;
|
|
||||||
void Reload();
|
|
||||||
void Init(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote);
|
|
||||||
explicit TLuaFile(TLuaEngine& Engine, bool Console = false);
|
|
||||||
~TLuaFile();
|
|
||||||
void SetStopThread(bool StopThread) { mStopThread = StopThread; }
|
|
||||||
TLuaEngine& Engine() { return mEngine; }
|
|
||||||
[[nodiscard]] std::string GetPluginName() const;
|
|
||||||
[[nodiscard]] std::string GetFileName() const;
|
|
||||||
[[nodiscard]] const lua_State* GetState() const;
|
|
||||||
[[nodiscard]] bool GetStopThread() const { return mStopThread; }
|
|
||||||
[[nodiscard]] const TLuaEngine& Engine() const { return mEngine; }
|
|
||||||
[[nodiscard]] std::string GetRegistered(const std::string& Event) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
TLuaEngine& mEngine;
|
|
||||||
std::set<std::pair<std::string, std::string>> mRegisteredEvents;
|
|
||||||
lua_State* mLuaState { nullptr };
|
|
||||||
fs::file_time_type mLastWrote;
|
|
||||||
std::string mPluginName {};
|
|
||||||
std::string mFileName {};
|
|
||||||
bool mStopThread = false;
|
|
||||||
bool mConsole = false;
|
|
||||||
void Load();
|
|
||||||
std::mutex mInitMutex;
|
|
||||||
};
|
|
||||||
|
|
||||||
std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
|
||||||
|
|
||||||
#endif // TLUAFILE_H
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
|
class TLuaPlugin {
|
||||||
|
public:
|
||||||
|
TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder);
|
||||||
|
TLuaPlugin(const TLuaPlugin&) = delete;
|
||||||
|
TLuaPlugin& operator=(const TLuaPlugin&) = delete;
|
||||||
|
~TLuaPlugin() noexcept = default;
|
||||||
|
|
||||||
|
const TLuaPluginConfig& GetConfig() const { return mConfig; }
|
||||||
|
fs::path GetFolder() const { return mFolder; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
TLuaPluginConfig mConfig;
|
||||||
|
TLuaEngine& mEngine;
|
||||||
|
fs::path mFolder;
|
||||||
|
std::string mPluginName;
|
||||||
|
std::unordered_map<std::string, std::shared_ptr<std::string>> mFileContents;
|
||||||
|
};
|
||||||
+5
-3
@@ -4,6 +4,8 @@
|
|||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
|
|
||||||
|
struct TConnection;
|
||||||
|
|
||||||
class TNetwork {
|
class TNetwork {
|
||||||
public:
|
public:
|
||||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||||
@@ -15,8 +17,8 @@ public:
|
|||||||
std::string TCPRcv(TClient& c);
|
std::string TCPRcv(TClient& c);
|
||||||
void ClientKick(TClient& c, const std::string& R);
|
void ClientKick(TClient& c, const std::string& R);
|
||||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||||
void Identify(SOCKET TCPSock);
|
void Identify(const TConnection& client);
|
||||||
void Authentication(SOCKET TCPSock);
|
void Authentication(const TConnection& ClientConnection);
|
||||||
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
|
||||||
void SyncResources(TClient& c);
|
void SyncResources(TClient& c);
|
||||||
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
|
||||||
@@ -30,7 +32,6 @@ private:
|
|||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
TPPSMonitor& mPPSMonitor;
|
TPPSMonitor& mPPSMonitor;
|
||||||
SOCKET mUDPSock {};
|
SOCKET mUDPSock {};
|
||||||
bool mShutdown { false };
|
|
||||||
TResourceManager& mResourceManager;
|
TResourceManager& mResourceManager;
|
||||||
std::thread mUDPThread;
|
std::thread mUDPThread;
|
||||||
std::thread mTCPThread;
|
std::thread mTCPThread;
|
||||||
@@ -46,4 +47,5 @@ private:
|
|||||||
void SendFile(TClient& c, const std::string& Name);
|
void SendFile(TClient& c, const std::string& Name);
|
||||||
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
|
||||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||||
|
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -22,6 +22,5 @@ private:
|
|||||||
|
|
||||||
TServer& mServer;
|
TServer& mServer;
|
||||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
||||||
bool mShutdown { false };
|
|
||||||
int mInternalPPS { 0 };
|
int mInternalPPS { 0 };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Common.h"
|
||||||
|
#include "IThreaded.h"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <memory>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
class TLuaEngine;
|
||||||
|
|
||||||
|
class TPluginMonitor : IThreaded, public std::enable_shared_from_this<TPluginMonitor> {
|
||||||
|
public:
|
||||||
|
TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine);
|
||||||
|
|
||||||
|
void operator()();
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::shared_ptr<TLuaEngine> mEngine;
|
||||||
|
fs::path mPath;
|
||||||
|
std::unordered_map<std::string, fs::file_time_type> mFileTimes;
|
||||||
|
};
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class TScopedTimer {
|
||||||
|
public:
|
||||||
|
TScopedTimer();
|
||||||
|
TScopedTimer(const std::string& Name);
|
||||||
|
TScopedTimer(std::function<void(size_t)> OnDestroy);
|
||||||
|
~TScopedTimer();
|
||||||
|
auto GetElapsedTime() const {
|
||||||
|
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||||
|
auto Delta = EndTime - mStartTime;
|
||||||
|
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||||
|
return TimeDelta;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::chrono::high_resolution_clock::time_point mStartTime;
|
||||||
|
std::string Name;
|
||||||
|
};
|
||||||
+5
-1
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include "IThreaded.h"
|
#include "IThreaded.h"
|
||||||
#include "RWMutex.h"
|
#include "RWMutex.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
@@ -15,7 +16,7 @@ class TServer final {
|
|||||||
public:
|
public:
|
||||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
||||||
|
|
||||||
TServer(int argc, char** argv);
|
TServer(const std::vector<std::string_view>& Arguments);
|
||||||
|
|
||||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||||
std::weak_ptr<TClient> InsertNewClient();
|
std::weak_ptr<TClient> InsertNewClient();
|
||||||
@@ -27,6 +28,9 @@ public:
|
|||||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||||
static void HandleEvent(TClient& c, const std::string& Data);
|
static void HandleEvent(TClient& c, const std::string& Data);
|
||||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||||
|
|
||||||
|
|
||||||
|
const TScopedTimer UptimeTimer;
|
||||||
private:
|
private:
|
||||||
TClientSet mClients;
|
TClientSet mClients;
|
||||||
mutable RWMutex mClientsMutex;
|
mutable RWMutex mClientsMutex;
|
||||||
|
|||||||
Submodule include/commandline deleted from 4931aa89c1
Submodule include/sentry-native deleted from 521860373d
Submodule include/tomlplusplus deleted from bc6891e1fb
@@ -1,8 +0,0 @@
|
|||||||
cmake_minimum_required(VERSION 3.0)
|
|
||||||
project(watchdog CXX ASM_MASM)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
|
||||||
add_library(watchdog STATIC watchdog.cpp watchdog.h x64Def.asm)
|
|
||||||
set_source_files_properties(watchdog.cpp PROPERTIES COMPILE_FLAGS "/O2 /Ob2 /DNDEBUG")
|
|
||||||
STRING(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
|
||||||
target_link_libraries(watchdog Dbghelp)
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
//
|
|
||||||
// Created by Anonymous275 on 9/5/2021.
|
|
||||||
//
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include <cstring>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
namespace fst {
|
|
||||||
template<size_t Cap>
|
|
||||||
class stack_string {
|
|
||||||
public:
|
|
||||||
stack_string() noexcept {
|
|
||||||
memset(Data, 0, Cap);
|
|
||||||
}
|
|
||||||
explicit stack_string(const char* Ptr) {
|
|
||||||
size_t len = strlen(Ptr);
|
|
||||||
Copy(Ptr, len);
|
|
||||||
memset(Data + len, 0, Cap - len);
|
|
||||||
}
|
|
||||||
stack_string(const char* Ptr, size_t PSize) {
|
|
||||||
Copy(Ptr, PSize);
|
|
||||||
memset(Data + PSize, 0, Cap - PSize);
|
|
||||||
}
|
|
||||||
inline size_t capacity() noexcept {
|
|
||||||
return Cap;
|
|
||||||
}
|
|
||||||
inline size_t size() noexcept {
|
|
||||||
return Size;
|
|
||||||
}
|
|
||||||
inline size_t length() noexcept {
|
|
||||||
return Size;
|
|
||||||
}
|
|
||||||
inline char* get() {
|
|
||||||
return Data;
|
|
||||||
}
|
|
||||||
[[nodiscard]] inline const char* c_str() const noexcept {
|
|
||||||
return Data;
|
|
||||||
}
|
|
||||||
char& operator[](size_t idx) {
|
|
||||||
if (idx >= Size) {
|
|
||||||
throw std::exception("stack_string out of boundaries operator[]");
|
|
||||||
}
|
|
||||||
return Data[idx];
|
|
||||||
}
|
|
||||||
inline void resize(size_t newSize) noexcept {
|
|
||||||
Size = newSize;
|
|
||||||
}
|
|
||||||
inline void push_back(const char* Ptr) {
|
|
||||||
Copy(Ptr, strlen(Ptr));
|
|
||||||
}
|
|
||||||
inline void push_back(const char* Ptr, size_t Count) {
|
|
||||||
Copy(Ptr, Count);
|
|
||||||
}
|
|
||||||
inline void push_back(char Ptr) {
|
|
||||||
Copy(&Ptr, 1);
|
|
||||||
}
|
|
||||||
friend std::ostream& operator<<(std::ostream& os, const stack_string& obj) {
|
|
||||||
os << obj.Data;
|
|
||||||
return os;
|
|
||||||
}
|
|
||||||
inline stack_string& operator+=(const char* Ptr) {
|
|
||||||
push_back(Ptr);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
inline stack_string& operator+=(char Ptr) {
|
|
||||||
push_back(Ptr);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
inline void Copy(const char* Ptr, size_t PSize) {
|
|
||||||
if((PSize + Size) <= Cap) {
|
|
||||||
memcpy(&Data[Size], Ptr, PSize);
|
|
||||||
Size += PSize;
|
|
||||||
} else throw std::exception("stack_string out of boundaries copy");
|
|
||||||
}
|
|
||||||
char Data[Cap]{};
|
|
||||||
size_t Size{0};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
//
|
|
||||||
// Created by Anonymous275 on 9/9/2021.
|
|
||||||
//
|
|
||||||
|
|
||||||
#include <windows.h>
|
|
||||||
#include <imagehlp.h>
|
|
||||||
#include <strsafe.h>
|
|
||||||
#include <cstdint>
|
|
||||||
#include "stack_string.h"
|
|
||||||
|
|
||||||
struct function_info {
|
|
||||||
void* func_address;
|
|
||||||
uint32_t thread_id;
|
|
||||||
bool enter;
|
|
||||||
};
|
|
||||||
|
|
||||||
fst::stack_string<1024> crash_file;
|
|
||||||
|
|
||||||
template <typename I>
|
|
||||||
fst::stack_string<(sizeof(I)<<1)+1> HexString(I w) {
|
|
||||||
static const char* digits = "0123456789ABCDEF";
|
|
||||||
const size_t hex_len = sizeof(I)<<1;
|
|
||||||
fst::stack_string<hex_len+1> rc;
|
|
||||||
rc.resize(hex_len+1);
|
|
||||||
memset(rc.get(), '0', hex_len);
|
|
||||||
memset(rc.get() + hex_len, 0, 1);
|
|
||||||
for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
|
|
||||||
rc[i] = digits[(w>>j) & 0x0f];
|
|
||||||
return rc;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<class T_>
|
|
||||||
class heap_array {
|
|
||||||
public:
|
|
||||||
heap_array() noexcept {
|
|
||||||
Data = (T_*)(GlobalAlloc(GPTR, Cap * sizeof(T_)));
|
|
||||||
init = true;
|
|
||||||
}
|
|
||||||
explicit heap_array(size_t Cap_) noexcept {
|
|
||||||
Cap = Cap_;
|
|
||||||
Data = (T_*)(GlobalAlloc(GPTR, Cap * sizeof(T_)));
|
|
||||||
init = true;
|
|
||||||
}
|
|
||||||
~heap_array() {
|
|
||||||
free(Data);
|
|
||||||
}
|
|
||||||
inline T_* get() noexcept {
|
|
||||||
return Data;
|
|
||||||
}
|
|
||||||
inline const T_* cget() noexcept {
|
|
||||||
return Data;
|
|
||||||
}
|
|
||||||
inline void insert(const T_& T) {
|
|
||||||
if(!init)return;
|
|
||||||
if(Size >= Cap) {
|
|
||||||
Grow();
|
|
||||||
}
|
|
||||||
Data[Size++] = T;
|
|
||||||
}
|
|
||||||
inline void string_insert(const T_* T, size_t len = 0) {
|
|
||||||
if(len == 0)len = strlen(T);
|
|
||||||
if(Size+len >= Cap) {
|
|
||||||
Grow(len);
|
|
||||||
}
|
|
||||||
memcpy(&Data[Size], T, len);
|
|
||||||
Size += len;
|
|
||||||
}
|
|
||||||
inline T_ at(size_t idx) {
|
|
||||||
return Data[idx];
|
|
||||||
}
|
|
||||||
inline size_t size() const noexcept {
|
|
||||||
return Size;
|
|
||||||
}
|
|
||||||
const T_& operator[](size_t idx) {
|
|
||||||
if (idx >= Size) {
|
|
||||||
throw std::exception("out of boundaries operator[]");
|
|
||||||
}
|
|
||||||
return Data[idx];
|
|
||||||
}
|
|
||||||
private:
|
|
||||||
inline void Grow(size_t add = 0) {
|
|
||||||
Cap = (Cap*2) + add;
|
|
||||||
auto* NewData = (T_*)(GlobalAlloc(GPTR, Cap * sizeof(T_)));
|
|
||||||
for(size_t C = 0; C < Size; C++) {
|
|
||||||
NewData[C] = Data[C];
|
|
||||||
}
|
|
||||||
GlobalFree(Data);
|
|
||||||
Data = NewData;
|
|
||||||
}
|
|
||||||
size_t Size{0}, Cap{5};
|
|
||||||
bool init{false};
|
|
||||||
T_* Data;
|
|
||||||
};
|
|
||||||
|
|
||||||
heap_array<function_info>* watch_data;
|
|
||||||
|
|
||||||
struct watchdog_mutex {
|
|
||||||
static void Create() noexcept {
|
|
||||||
hMutex = CreateMutex(nullptr, FALSE, nullptr);
|
|
||||||
}
|
|
||||||
static void Lock() {
|
|
||||||
WaitForSingleObject(hMutex, INFINITE);
|
|
||||||
}
|
|
||||||
static void Unlock() {
|
|
||||||
ReleaseMutex(hMutex);
|
|
||||||
}
|
|
||||||
struct [[nodiscard]] ScopedLock {
|
|
||||||
ScopedLock() {
|
|
||||||
if(hMutex)
|
|
||||||
watchdog_mutex::Lock();
|
|
||||||
}
|
|
||||||
~ScopedLock() {
|
|
||||||
if(hMutex)
|
|
||||||
watchdog_mutex::Unlock();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
private:
|
|
||||||
static HANDLE hMutex;
|
|
||||||
};
|
|
||||||
HANDLE watchdog_mutex::hMutex{nullptr};
|
|
||||||
std::atomic<bool> Init{false}, Sym;
|
|
||||||
std::atomic<int64_t> Offset{0};
|
|
||||||
|
|
||||||
void watchdog_setOffset(int64_t Off) {
|
|
||||||
Offset.store(Off);
|
|
||||||
}
|
|
||||||
|
|
||||||
void notify(const char* msg) {
|
|
||||||
HANDLE stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
|
|
||||||
if (stdOut != nullptr && stdOut != INVALID_HANDLE_VALUE) {
|
|
||||||
DWORD written = 0;
|
|
||||||
WriteConsoleA(stdOut, "[WATCHDOG] ", 11, &written, nullptr);
|
|
||||||
WriteConsoleA(stdOut, msg, DWORD(strlen(msg)), &written, nullptr);
|
|
||||||
WriteConsoleA(stdOut, "\n", 1, &written, nullptr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fst::stack_string<MAX_SYM_NAME> FindFunction(void* Address) {
|
|
||||||
if(!Sym.load()) {
|
|
||||||
fst::stack_string<MAX_SYM_NAME> undName;
|
|
||||||
return undName;
|
|
||||||
}
|
|
||||||
static HANDLE process = GetCurrentProcess();
|
|
||||||
DWORD64 symDisplacement = 0;
|
|
||||||
fst::stack_string<MAX_SYM_NAME> undName;
|
|
||||||
TCHAR buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
|
|
||||||
memset(&buffer,0, sizeof(buffer));
|
|
||||||
auto pSymbolInfo = (PSYMBOL_INFO)buffer;
|
|
||||||
pSymbolInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
|
|
||||||
pSymbolInfo->MaxNameLen = MAX_SYM_NAME;
|
|
||||||
if (SymFromAddr(process, DWORD64(Address) + Offset, &symDisplacement, pSymbolInfo)) {
|
|
||||||
undName.push_back(pSymbolInfo->Name);
|
|
||||||
}
|
|
||||||
return undName;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fst::stack_string<512> getCrashInfo(void* Address){
|
|
||||||
if(!Sym.load()){
|
|
||||||
fst::stack_string<512> Value;
|
|
||||||
Value.push_back("unknown", 7);
|
|
||||||
return Value;
|
|
||||||
}
|
|
||||||
DWORD pdwDisplacement = 0;
|
|
||||||
IMAGEHLP_LINE64 line{sizeof(IMAGEHLP_LINE64)};
|
|
||||||
SymGetLineFromAddr64(GetCurrentProcess(), DWORD64(Address) + Offset, &pdwDisplacement, &line);
|
|
||||||
char* Name = nullptr;
|
|
||||||
if(line.FileName) {
|
|
||||||
Name = strrchr(line.FileName, '\\');
|
|
||||||
}
|
|
||||||
fst::stack_string<512> Value;
|
|
||||||
if(Name)Value.push_back(Name+1);
|
|
||||||
else Value.push_back("unknown", 7);
|
|
||||||
char buffer[20];
|
|
||||||
auto n = sprintf(buffer, ":%lu", line.LineNumber);
|
|
||||||
Value.push_back(buffer, n);
|
|
||||||
return Value;
|
|
||||||
}
|
|
||||||
const char* getFunctionDetails(void* Address) {
|
|
||||||
return FindFunction(Address).c_str();
|
|
||||||
}
|
|
||||||
const char* getCrashLocation(void* Address) {
|
|
||||||
return getCrashInfo(Address).c_str();
|
|
||||||
}
|
|
||||||
|
|
||||||
void InitSym(const char* PDBLocation) {
|
|
||||||
SymInitialize(GetCurrentProcess(), PDBLocation, TRUE);
|
|
||||||
Sym.store(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
void write_report(const char* report, size_t size) {
|
|
||||||
HANDLE hFile = CreateFile(crash_file.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
||||||
if (hFile == INVALID_HANDLE_VALUE) {
|
|
||||||
notify("Failed to open crash file for writing!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
DWORD dwBytesWritten = 0;
|
|
||||||
auto Flag = WriteFile(hFile, report, DWORD(size), &dwBytesWritten, nullptr);
|
|
||||||
if (Flag == FALSE) {
|
|
||||||
notify("Failed to write to crash file!");
|
|
||||||
}
|
|
||||||
CloseHandle(hFile);
|
|
||||||
}
|
|
||||||
|
|
||||||
void generate_crash_report(uint32_t Code, void* Address) {
|
|
||||||
watchdog_mutex::ScopedLock guard;
|
|
||||||
notify("generating crash report, please wait");
|
|
||||||
Init.store(false);
|
|
||||||
heap_array<char> Report(watch_data->size() * sizeof(function_info));
|
|
||||||
Report.string_insert("crash code ");
|
|
||||||
Report.string_insert(HexString(Code).c_str());
|
|
||||||
Report.string_insert(" at ");
|
|
||||||
Report.string_insert(HexString(size_t(Address) + Offset).c_str());
|
|
||||||
Report.string_insert("\n");
|
|
||||||
if(Address) {
|
|
||||||
Report.string_insert("origin and line number -> ");
|
|
||||||
Report.string_insert(getCrashInfo(Address).c_str());
|
|
||||||
Report.string_insert("\n");
|
|
||||||
}
|
|
||||||
Report.string_insert("Call history: \n");
|
|
||||||
char buff[20];
|
|
||||||
for(size_t C = 0; C < watch_data->size(); C++){
|
|
||||||
auto entry = watch_data->at(C);
|
|
||||||
auto Name = FindFunction(entry.func_address);
|
|
||||||
if(entry.enter){
|
|
||||||
Report.string_insert("[Entry] ");
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
Report.string_insert("[Exit ] ");
|
|
||||||
}
|
|
||||||
auto n = sprintf(buff, "(%d) ", entry.thread_id);
|
|
||||||
Report.string_insert(buff, n);
|
|
||||||
if(Name.size() > 0){
|
|
||||||
Report.string_insert(Name.c_str(), Name.size());
|
|
||||||
Report.string_insert(" | ");
|
|
||||||
auto location = getCrashInfo(entry.func_address);
|
|
||||||
Report.string_insert(location.c_str(), location.size());
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
Report.string_insert(HexString(size_t(entry.func_address) + Offset).c_str());
|
|
||||||
}
|
|
||||||
Report.string_insert("\n");
|
|
||||||
}
|
|
||||||
write_report(Report.cget(), Report.size());
|
|
||||||
notify("crash report generated");
|
|
||||||
Init.store(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
LONG WINAPI CrashHandler(EXCEPTION_POINTERS* p) {
|
|
||||||
Init.store(false);
|
|
||||||
notify("CAUGHT EXCEPTION!");
|
|
||||||
generate_crash_report(p->ExceptionRecord->ExceptionCode, p->ExceptionRecord->ExceptionAddress);
|
|
||||||
return EXCEPTION_EXECUTE_HANDLER;
|
|
||||||
}
|
|
||||||
|
|
||||||
void watchdog_init(const char* crashFile, const char* SpecificPDBLocation, bool Symbols) {
|
|
||||||
if(Symbols)SymInitialize(GetCurrentProcess(), SpecificPDBLocation, TRUE);
|
|
||||||
Sym.store(Symbols);
|
|
||||||
SetUnhandledExceptionFilter(CrashHandler);
|
|
||||||
watch_data = new heap_array<function_info>();
|
|
||||||
watchdog_mutex::Create();
|
|
||||||
crash_file.push_back(crashFile);
|
|
||||||
notify("initialized!");
|
|
||||||
Init.store(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void AddEntry(void* func_address, uint32_t thread_id, bool entry) {
|
|
||||||
watchdog_mutex::ScopedLock guard;
|
|
||||||
if(Init.load()) {
|
|
||||||
watch_data->insert({func_address, thread_id, entry});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
void FuncEntry(void* func) {
|
|
||||||
AddEntry(func, GetCurrentThreadId(), true);
|
|
||||||
}
|
|
||||||
void FuncExit(void* func) {
|
|
||||||
AddEntry(func, GetCurrentThreadId(), false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
//
|
|
||||||
// Created by Anonymous275 on 9/9/2021.
|
|
||||||
//
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include <cstdint>
|
|
||||||
extern void watchdog_init(const char* crashFile, const char* SpecificPDBLocation, bool Symbols = true);
|
|
||||||
extern void generate_crash_report(uint32_t Code, void* Address);
|
|
||||||
const char* getFunctionDetails(void* Address);
|
|
||||||
extern void watchdog_setOffset(int64_t Off);
|
|
||||||
const char* getCrashLocation(void* Address);
|
|
||||||
void InitSym(const char* PDBLocation);
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
;//
|
|
||||||
;// Created by Anonymous275 on 9/9/2021.
|
|
||||||
;//
|
|
||||||
;External C functions used by _penter and _pexit
|
|
||||||
extern FuncEntry:Proc
|
|
||||||
extern FuncExit:Proc
|
|
||||||
|
|
||||||
.code
|
|
||||||
|
|
||||||
_penter proc
|
|
||||||
|
|
||||||
; Store the volatile registers
|
|
||||||
push r11
|
|
||||||
push r10
|
|
||||||
push r9
|
|
||||||
push r8
|
|
||||||
push rax
|
|
||||||
push rdx
|
|
||||||
push rcx
|
|
||||||
|
|
||||||
; reserve space for 4 registers [ rcx,rdx,r8 and r9 ] 32 bytes
|
|
||||||
sub rsp,20h
|
|
||||||
|
|
||||||
; Get the return address of the function
|
|
||||||
mov rcx,rsp
|
|
||||||
mov rcx,qword ptr[rcx+58h]
|
|
||||||
sub rcx,5
|
|
||||||
|
|
||||||
;call the function to get the name of the callee and caller
|
|
||||||
call FuncEntry
|
|
||||||
|
|
||||||
;Release the space reserved for the registersk by adding 32 bytes
|
|
||||||
add rsp,20h
|
|
||||||
|
|
||||||
;Restore the registers back by poping out
|
|
||||||
pop rcx
|
|
||||||
pop rdx
|
|
||||||
pop rax
|
|
||||||
pop r8
|
|
||||||
pop r9
|
|
||||||
pop r10
|
|
||||||
pop r11
|
|
||||||
|
|
||||||
;return
|
|
||||||
ret
|
|
||||||
|
|
||||||
_penter endp
|
|
||||||
|
|
||||||
_pexit proc
|
|
||||||
|
|
||||||
; Store the volatile registers
|
|
||||||
push r11
|
|
||||||
push r10
|
|
||||||
push r9
|
|
||||||
push r8
|
|
||||||
push rax
|
|
||||||
push rdx
|
|
||||||
push rcx
|
|
||||||
|
|
||||||
; reserve space for 4 registers [ rcx,rdx,r8 and r9 ] 32 bytes
|
|
||||||
sub rsp,20h
|
|
||||||
|
|
||||||
; Get the return address of the function
|
|
||||||
mov rcx,rsp
|
|
||||||
mov rcx,qword ptr[rcx+58h]
|
|
||||||
|
|
||||||
call FuncExit
|
|
||||||
|
|
||||||
;Release the space reserved for the registersk by adding 32 bytes
|
|
||||||
add rsp,20h
|
|
||||||
|
|
||||||
;Restore the registers back by poping out
|
|
||||||
pop rcx
|
|
||||||
pop rdx
|
|
||||||
pop rax
|
|
||||||
pop r8
|
|
||||||
pop r9
|
|
||||||
pop r10
|
|
||||||
pop r11
|
|
||||||
|
|
||||||
;return
|
|
||||||
ret
|
|
||||||
|
|
||||||
_pexit endp
|
|
||||||
end
|
|
||||||
-1
Submodule rapidjson deleted from 13dfc96c9c
Submodule socket.io-client-cpp deleted from b196fa7537
@@ -0,0 +1,170 @@
|
|||||||
|
#include "ArgsParser.h"
|
||||||
|
#include "Common.h"
|
||||||
|
#include <algorithm>
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
|
void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
|
||||||
|
for (const auto& Arg : ArgList) {
|
||||||
|
if (Arg.size() > 2 && Arg.substr(0, 2) == "--") {
|
||||||
|
// long arg
|
||||||
|
if (Arg.find("=") != Arg.npos) {
|
||||||
|
ConsumeLongAssignment(std::string(Arg));
|
||||||
|
} else {
|
||||||
|
ConsumeLongFlag(std::string(Arg));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ArgsParser::Verify() {
|
||||||
|
bool Ok = true;
|
||||||
|
for (const auto& RegisteredArg : mRegisteredArguments) {
|
||||||
|
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
|
||||||
|
beammp_errorf("Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
|
||||||
|
Ok = false;
|
||||||
|
continue;
|
||||||
|
} else if (FoundArgument(RegisteredArg.Names)) {
|
||||||
|
if (RegisteredArg.Flags & Flags::HAS_VALUE) {
|
||||||
|
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||||
|
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' expects a value, but no value was given.");
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
|
||||||
|
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' does not expect a value, but one was given.");
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ArgsParser::RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags) {
|
||||||
|
mRegisteredArguments.push_back({ ArgumentNames, Flags });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ArgsParser::FoundArgument(const std::vector<std::string>& Names) {
|
||||||
|
// if any of the found args match any of the names
|
||||||
|
return std::any_of(mFoundArgs.begin(), mFoundArgs.end(),
|
||||||
|
[&Names](const Argument& Arg) -> bool {
|
||||||
|
// if any of the names match this arg's name
|
||||||
|
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string& Name) -> bool {
|
||||||
|
return Arg.Name == Name;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::string> ArgsParser::GetValueOfArgument(const std::vector<std::string>& Names) {
|
||||||
|
// finds an entry which has a name that is any of the names in 'Names'
|
||||||
|
auto Found = std::find_if(mFoundArgs.begin(), mFoundArgs.end(), [&Names](const Argument& Arg) -> bool {
|
||||||
|
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string_view& Name) -> bool {
|
||||||
|
return Arg.Name == Name;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (Found != mFoundArgs.end()) {
|
||||||
|
// found
|
||||||
|
return Found->Value;
|
||||||
|
} else {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ArgsParser::IsRegistered(const std::string& Name) {
|
||||||
|
return std::any_of(mRegisteredArguments.begin(), mRegisteredArguments.end(), [&Name](const RegisteredArgument& Arg) {
|
||||||
|
auto Iter = std::find(Arg.Names.begin(), Arg.Names.end(), Name);
|
||||||
|
return Iter != Arg.Names.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void ArgsParser::ConsumeLongAssignment(const std::string& Arg) {
|
||||||
|
auto Value = Arg.substr(Arg.rfind("=") + 1);
|
||||||
|
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||||
|
if (!IsRegistered(Name)) {
|
||||||
|
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||||
|
}
|
||||||
|
mFoundArgs.push_back({ Name, Value });
|
||||||
|
}
|
||||||
|
|
||||||
|
void ArgsParser::ConsumeLongFlag(const std::string& Arg) {
|
||||||
|
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
|
||||||
|
mFoundArgs.push_back({ Name, std::nullopt });
|
||||||
|
if (!IsRegistered(Name)) {
|
||||||
|
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("ArgsParser") {
|
||||||
|
ArgsParser parser;
|
||||||
|
|
||||||
|
SUBCASE("Simple args") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||||
|
parser.Parse({ "--a", "--hello" });
|
||||||
|
CHECK(parser.Verify());
|
||||||
|
CHECK(parser.FoundArgument({ "a" }));
|
||||||
|
CHECK(parser.FoundArgument({ "hello" }));
|
||||||
|
CHECK(parser.FoundArgument({ "a", "hello" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "b" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "goodbye" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
SUBCASE("No args") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||||
|
parser.Parse({});
|
||||||
|
CHECK(parser.Verify());
|
||||||
|
CHECK(!parser.FoundArgument({ "a" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "hello" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "a", "hello" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "b" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "goodbye" }));
|
||||||
|
CHECK(!parser.FoundArgument({ "" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
SUBCASE("Value args") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::HAS_VALUE);
|
||||||
|
parser.Parse({ "--a=5", "--hello=world" });
|
||||||
|
CHECK(parser.Verify());
|
||||||
|
REQUIRE(parser.FoundArgument({ "a" }));
|
||||||
|
REQUIRE(parser.FoundArgument({ "hello" }));
|
||||||
|
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
|
||||||
|
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
|
||||||
|
CHECK(parser.GetValueOfArgument({ "hello" }).has_value());
|
||||||
|
CHECK(parser.GetValueOfArgument({ "hello" }).value() == "world");
|
||||||
|
}
|
||||||
|
|
||||||
|
SUBCASE("Mixed value & no-value args") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
|
||||||
|
parser.Parse({ "--a=5", "--hello" });
|
||||||
|
CHECK(parser.Verify());
|
||||||
|
REQUIRE(parser.FoundArgument({ "a" }));
|
||||||
|
REQUIRE(parser.FoundArgument({ "hello" }));
|
||||||
|
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
|
||||||
|
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
|
||||||
|
CHECK(!parser.GetValueOfArgument({ "hello" }).has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
SUBCASE("Required args") {
|
||||||
|
SUBCASE("Two required, two present") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.Parse({ "--a", "--hello" });
|
||||||
|
CHECK(parser.Verify());
|
||||||
|
}
|
||||||
|
SUBCASE("Two required, one present") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.Parse({ "--a" });
|
||||||
|
CHECK(!parser.Verify());
|
||||||
|
}
|
||||||
|
SUBCASE("Two required, none present") {
|
||||||
|
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
|
||||||
|
parser.Parse({ "--b" });
|
||||||
|
CHECK(!parser.Verify());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
-3
@@ -1,9 +1,9 @@
|
|||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
|
#include "TServer.h"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <optional>
|
||||||
// FIXME: add debug prints
|
|
||||||
|
|
||||||
void TClient::DeleteCar(int Ident) {
|
void TClient::DeleteCar(int Ident) {
|
||||||
std::unique_lock lock(mVehicleDataMutex);
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
@@ -13,7 +13,7 @@ void TClient::DeleteCar(int Ident) {
|
|||||||
if (iter != mVehicleData.end()) {
|
if (iter != mVehicleData.end()) {
|
||||||
mVehicleData.erase(iter);
|
mVehicleData.erase(iter);
|
||||||
} else {
|
} else {
|
||||||
debug("tried to erase a vehicle that doesn't exist (not an error)");
|
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,6 +25,7 @@ void TClient::ClearCars() {
|
|||||||
int TClient::GetOpenCarID() const {
|
int TClient::GetOpenCarID() const {
|
||||||
int OpenID = 0;
|
int OpenID = 0;
|
||||||
bool found;
|
bool found;
|
||||||
|
std::unique_lock lock(mVehicleDataMutex);
|
||||||
do {
|
do {
|
||||||
found = true;
|
found = true;
|
||||||
for (auto& v : mVehicleData) {
|
for (auto& v : mVehicleData) {
|
||||||
@@ -99,3 +100,19 @@ int TClient::SecondsSinceLastPing() {
|
|||||||
.count();
|
.count();
|
||||||
return int(seconds);
|
return int(seconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
||||||
|
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
||||||
|
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
||||||
|
ReadLock Lock(Server.GetClientMutex());
|
||||||
|
if (!CPtr.expired()) {
|
||||||
|
auto C = CPtr.lock();
|
||||||
|
if (C->GetID() == ID) {
|
||||||
|
MaybeClient = CPtr;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return MaybeClient;
|
||||||
|
}
|
||||||
|
|||||||
+262
-86
@@ -8,12 +8,14 @@
|
|||||||
#include <regex>
|
#include <regex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <zlib.h>
|
|
||||||
|
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
std::unique_ptr<TConsole> Application::mConsole = std::make_unique<TConsole>();
|
// global, yes, this is ugly, no, it cant be done another way
|
||||||
|
TSentry Sentry {};
|
||||||
|
|
||||||
|
Application::TSettings Application::Settings = {};
|
||||||
|
|
||||||
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
@@ -23,33 +25,39 @@ void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Application::GracefullyShutdown() {
|
void Application::GracefullyShutdown() {
|
||||||
|
SetShutdown(true);
|
||||||
static bool AlreadyShuttingDown = false;
|
static bool AlreadyShuttingDown = false;
|
||||||
static uint8_t ShutdownAttempts = 0;
|
static uint8_t ShutdownAttempts = 0;
|
||||||
if (AlreadyShuttingDown) {
|
if (AlreadyShuttingDown) {
|
||||||
++ShutdownAttempts;
|
++ShutdownAttempts;
|
||||||
// hard shutdown at 2 additional tries
|
// hard shutdown at 2 additional tries
|
||||||
if (ShutdownAttempts == 2) {
|
if (ShutdownAttempts == 2) {
|
||||||
info("hard shutdown forced by multiple shutdown requests");
|
beammp_info("hard shutdown forced by multiple shutdown requests");
|
||||||
std::exit(0);
|
std::exit(0);
|
||||||
}
|
}
|
||||||
info("already shutting down!");
|
beammp_info("already shutting down!");
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
AlreadyShuttingDown = true;
|
AlreadyShuttingDown = true;
|
||||||
}
|
}
|
||||||
trace("waiting for lock release");
|
beammp_trace("waiting for lock release");
|
||||||
std::unique_lock Lock(mShutdownHandlersMutex);
|
std::unique_lock Lock(mShutdownHandlersMutex);
|
||||||
info("please wait while all subsystems are shutting down...");
|
beammp_info("please wait while all subsystems are shutting down...");
|
||||||
for (size_t i = 0; i < mShutdownHandlers.size(); ++i) {
|
for (size_t i = 0; i < mShutdownHandlers.size(); ++i) {
|
||||||
info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
|
beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
|
||||||
mShutdownHandlers[i]();
|
mShutdownHandlers[i]();
|
||||||
}
|
}
|
||||||
|
// std::exit(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::array<int, 3> Application::VersionStrToInts(const std::string& str) {
|
std::string Application::ServerVersionString() {
|
||||||
std::array<int, 3> Version;
|
return mVersion.AsString();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
|
||||||
|
std::array<uint8_t, 3> Version;
|
||||||
std::stringstream ss(str);
|
std::stringstream ss(str);
|
||||||
for (int& i : Version) {
|
for (uint8_t& i : Version) {
|
||||||
std::string Part;
|
std::string Part;
|
||||||
std::getline(ss, Part, '.');
|
std::getline(ss, Part, '.');
|
||||||
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), i);
|
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), i);
|
||||||
@@ -57,87 +65,168 @@ std::array<int, 3> Application::VersionStrToInts(const std::string& str) {
|
|||||||
return Version;
|
return Version;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Application::IsOutdated(const std::array<int, 3>& Current, const std::array<int, 3>& Newest) {
|
TEST_CASE("Application::VersionStrToInts") {
|
||||||
if (Newest[0] > Current[0]) {
|
auto v = Application::VersionStrToInts("1.2.3");
|
||||||
|
CHECK(v[0] == 1);
|
||||||
|
CHECK(v[1] == 2);
|
||||||
|
CHECK(v[2] == 3);
|
||||||
|
|
||||||
|
v = Application::VersionStrToInts("10.20.30");
|
||||||
|
CHECK(v[0] == 10);
|
||||||
|
CHECK(v[1] == 20);
|
||||||
|
CHECK(v[2] == 30);
|
||||||
|
|
||||||
|
v = Application::VersionStrToInts("100.200.255");
|
||||||
|
CHECK(v[0] == 100);
|
||||||
|
CHECK(v[1] == 200);
|
||||||
|
CHECK(v[2] == 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
|
||||||
|
if (Newest.major > Current.major) {
|
||||||
return true;
|
return true;
|
||||||
} else if (Newest[0] == Current[0] && Newest[1] > Current[1]) {
|
} else if (Newest.major == Current.major && Newest.minor > Current.minor) {
|
||||||
return true;
|
return true;
|
||||||
} else if (Newest[0] == Current[0] && Newest[1] == Current[1] && Newest[2] > Current[2]) {
|
} else if (Newest.major == Current.major && Newest.minor == Current.minor && Newest.patch > Current.patch) {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Application::CheckForUpdates() {
|
bool Application::IsShuttingDown() {
|
||||||
// checks current version against latest version
|
std::shared_lock Lock(mShutdownMtx);
|
||||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
return mShutdown;
|
||||||
auto Response = Http::GET(GetBackendHostname(), 443, "/v/s");
|
}
|
||||||
bool Matches = std::regex_match(Response, VersionRegex);
|
|
||||||
if (Matches) {
|
void Application::SleepSafeSeconds(size_t Seconds) {
|
||||||
auto MyVersion = VersionStrToInts(ServerVersion());
|
// Sleeps for 500 ms, checks if a shutdown occurred, and so forth
|
||||||
auto RemoteVersion = VersionStrToInts(Response);
|
for (size_t i = 0; i < Seconds * 2; ++i) {
|
||||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
if (Application::IsShuttingDown()) {
|
||||||
std::string RealVersionString = std::to_string(RemoteVersion[0]) + ".";
|
return;
|
||||||
RealVersionString += std::to_string(RemoteVersion[1]) + ".";
|
|
||||||
RealVersionString += std::to_string(RemoteVersion[2]);
|
|
||||||
warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION OUT! There's a new version (v" + RealVersionString + ") of the BeamMP-Server available! For more info visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server." + std::string(ANSI_RESET));
|
|
||||||
} else {
|
} else {
|
||||||
info("Server up-to-date!");
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
char* crasher = nullptr;
|
|
||||||
crasher[4555] = 'c';
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
warn("Unable to fetch version from backend.");
|
|
||||||
trace("got " + Response);
|
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
|
||||||
Sentry.SetContext("get-response", { { "response", Response } });
|
|
||||||
Sentry.LogError("failed to get server version", _file_basename, _line);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Comp(std::string Data) {
|
TEST_CASE("Application::IsOutdated (version check)") {
|
||||||
std::array<char, Biggest> C {};
|
SUBCASE("Same version") {
|
||||||
// obsolete
|
CHECK(!Application::IsOutdated({ 1, 2, 3 }, { 1, 2, 3 }));
|
||||||
C.fill(0);
|
}
|
||||||
z_stream defstream;
|
// we need to use over 1-2 digits to test against lexical comparisons
|
||||||
defstream.zalloc = Z_NULL;
|
SUBCASE("Patch outdated") {
|
||||||
defstream.zfree = Z_NULL;
|
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||||
defstream.opaque = Z_NULL;
|
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||||
defstream.avail_in = (uInt)Data.length();
|
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||||
defstream.next_in = (Bytef*)&Data[0];
|
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor), uint8_t(Patch + 1) }));
|
||||||
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);
|
SUBCASE("Minor outdated") {
|
||||||
deflateEnd(&defstream);
|
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||||
size_t TO = defstream.total_out;
|
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||||
std::string Ret(TO, 0);
|
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||||
std::copy_n(C.begin(), TO, Ret.begin());
|
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor + 1), uint8_t(Patch) }));
|
||||||
return Ret;
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SUBCASE("Major outdated") {
|
||||||
|
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||||
|
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||||
|
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||||
|
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor), uint8_t(Patch) }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SUBCASE("All outdated") {
|
||||||
|
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
|
||||||
|
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
|
||||||
|
for (uint8_t Major = 0; Major < 10; ++Major) {
|
||||||
|
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor + 1), uint8_t(Patch + 1) }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string DeComp(std::string Compressed) {
|
void Application::SetSubsystemStatus(const std::string& Subsystem, Status status) {
|
||||||
std::array<char, Biggest> C {};
|
switch (status) {
|
||||||
// not needed
|
case Status::Good:
|
||||||
C.fill(0);
|
beammp_trace("Subsystem '" + Subsystem + "': Good");
|
||||||
z_stream infstream;
|
break;
|
||||||
infstream.zalloc = Z_NULL;
|
case Status::Bad:
|
||||||
infstream.zfree = Z_NULL;
|
beammp_trace("Subsystem '" + Subsystem + "': Bad");
|
||||||
infstream.opaque = Z_NULL;
|
break;
|
||||||
infstream.avail_in = Biggest;
|
case Status::Starting:
|
||||||
infstream.next_in = (Bytef*)(&Compressed[0]);
|
beammp_trace("Subsystem '" + Subsystem + "': Starting");
|
||||||
infstream.avail_out = Biggest;
|
break;
|
||||||
infstream.next_out = (Bytef*)(C.data());
|
case Status::ShuttingDown:
|
||||||
inflateInit(&infstream);
|
beammp_trace("Subsystem '" + Subsystem + "': Shutting down");
|
||||||
inflate(&infstream, Z_SYNC_FLUSH);
|
break;
|
||||||
inflate(&infstream, Z_FINISH);
|
case Status::Shutdown:
|
||||||
inflateEnd(&infstream);
|
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
||||||
size_t TO = infstream.total_out;
|
break;
|
||||||
std::string Ret(TO, 0);
|
}
|
||||||
std::copy_n(C.begin(), TO, Ret.begin());
|
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||||
return Ret;
|
mSystemStatusMap[Subsystem] = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Application::SetShutdown(bool Val) {
|
||||||
|
std::unique_lock Lock(mShutdownMtx);
|
||||||
|
mShutdown = Val;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("Application::SetSubsystemStatus") {
|
||||||
|
Application::SetSubsystemStatus("Test", Application::Status::Good);
|
||||||
|
auto Map = Application::GetSubsystemStatuses();
|
||||||
|
CHECK(Map.at("Test") == Application::Status::Good);
|
||||||
|
Application::SetSubsystemStatus("Test", Application::Status::Bad);
|
||||||
|
Map = Application::GetSubsystemStatuses();
|
||||||
|
CHECK(Map.at("Test") == Application::Status::Bad);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Application::CheckForUpdates() {
|
||||||
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Starting);
|
||||||
|
static bool FirstTime = true;
|
||||||
|
// checks current version against latest version
|
||||||
|
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||||
|
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||||
|
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/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 = RemoteVersion.AsString();
|
||||||
|
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET));
|
||||||
|
} else {
|
||||||
|
if (FirstTime) {
|
||||||
|
beammp_info("Server up-to-date!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Good);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
if (FirstTime) {
|
||||||
|
beammp_debug("Failed to fetch version from: " + url);
|
||||||
|
beammp_trace("got " + Response);
|
||||||
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
|
Sentry.SetContext("get-response", { { "response", Response } });
|
||||||
|
Sentry.LogError("failed to get server version", _file_basename, _line);
|
||||||
|
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Application::GetSubsystemStatuses().at("UpdateCheck") == Application::Status::Bad) {
|
||||||
|
if (FirstTime) {
|
||||||
|
beammp_warn("Unable to fetch version info from backend.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FirstTime = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// thread name stuff
|
// thread name stuff
|
||||||
@@ -157,19 +246,106 @@ std::string ThreadName(bool DebugModeOverride) {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE("ThreadName") {
|
||||||
|
RegisterThread("MyThread");
|
||||||
|
auto OrigDebug = Application::Settings.DebugModeEnabled;
|
||||||
|
|
||||||
|
// ThreadName adds a space at the end, legacy but we need it still
|
||||||
|
SUBCASE("Debug mode enabled") {
|
||||||
|
Application::Settings.DebugModeEnabled = true;
|
||||||
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
|
CHECK(ThreadName(false) == "MyThread ");
|
||||||
|
}
|
||||||
|
SUBCASE("Debug mode disabled") {
|
||||||
|
Application::Settings.DebugModeEnabled = false;
|
||||||
|
CHECK(ThreadName(true) == "MyThread ");
|
||||||
|
CHECK(ThreadName(false) == "");
|
||||||
|
}
|
||||||
|
// cleanup
|
||||||
|
Application::Settings.DebugModeEnabled = OrigDebug;
|
||||||
|
}
|
||||||
|
|
||||||
void RegisterThread(const std::string& str) {
|
void RegisterThread(const std::string& str) {
|
||||||
|
std::string ThreadId;
|
||||||
|
#ifdef BEAMMP_WINDOWS
|
||||||
|
ThreadId = std::to_string(GetCurrentThreadId());
|
||||||
|
#elif defined(BEAMMP_APPLE)
|
||||||
|
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
|
||||||
|
#elif defined(BEAMMP_LINUX)
|
||||||
|
ThreadId = std::to_string(gettid());
|
||||||
|
#endif
|
||||||
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
|
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
||||||
|
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
|
||||||
|
}
|
||||||
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
auto Lock = std::unique_lock(ThreadNameMapMutex);
|
||||||
threadNameMap[std::this_thread::get_id()] = str;
|
threadNameMap[std::this_thread::get_id()] = str;
|
||||||
}
|
}
|
||||||
|
|
||||||
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
TEST_CASE("RegisterThread") {
|
||||||
std::stringstream ss;
|
RegisterThread("MyThread");
|
||||||
ss << "[CHAT] ";
|
CHECK(threadNameMap.at(std::this_thread::get_id()) == "MyThread");
|
||||||
if (id != -1) {
|
}
|
||||||
ss << "(" << id << ") <" << name << ">";
|
|
||||||
} else {
|
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
|
||||||
ss << name << "";
|
: major(major)
|
||||||
}
|
, minor(minor)
|
||||||
ss << msg;
|
, patch(patch) { }
|
||||||
Application::Console().Write(ss.str());
|
|
||||||
|
Version::Version(const std::array<uint8_t, 3>& v)
|
||||||
|
: Version(v[0], v[1], v[2]) {
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Version::AsString() {
|
||||||
|
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("Version::AsString") {
|
||||||
|
CHECK(Version { 0, 0, 0 }.AsString() == "0.0.0");
|
||||||
|
CHECK(Version { 1, 2, 3 }.AsString() == "1.2.3");
|
||||||
|
CHECK(Version { 255, 255, 255 }.AsString() == "255.255.255");
|
||||||
|
}
|
||||||
|
|
||||||
|
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
|
||||||
|
if (Application::Settings.LogChat) {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << ThreadName();
|
||||||
|
ss << "[CHAT] ";
|
||||||
|
if (id != -1) {
|
||||||
|
ss << "(" << id << ") <" << name << "> ";
|
||||||
|
} else {
|
||||||
|
ss << name << "";
|
||||||
|
}
|
||||||
|
ss << msg;
|
||||||
|
#ifdef DOCTEST_CONFIG_DISABLE
|
||||||
|
Application::Console().Write(ss.str());
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string GetPlatformAgnosticErrorString() {
|
||||||
|
#ifdef BEAMMP_WINDOWS
|
||||||
|
// This will provide us with the error code and an error message, all in one.
|
||||||
|
int err;
|
||||||
|
char msgbuf[256];
|
||||||
|
msgbuf[0] = '\0';
|
||||||
|
|
||||||
|
err = GetLastError();
|
||||||
|
|
||||||
|
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||||
|
nullptr,
|
||||||
|
err,
|
||||||
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||||
|
msgbuf,
|
||||||
|
sizeof(msgbuf),
|
||||||
|
nullptr);
|
||||||
|
|
||||||
|
if (*msgbuf) {
|
||||||
|
return std::to_string(GetLastError()) + " - " + std::string(msgbuf);
|
||||||
|
} else {
|
||||||
|
return std::to_string(GetLastError());
|
||||||
|
}
|
||||||
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
|
return std::strerror(errno);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
|
|
||||||
static struct termios old, current;
|
static struct termios old, current;
|
||||||
@@ -20,6 +23,23 @@ void resetTermios(void) {
|
|||||||
tcsetattr(0, TCSANOW, &old);
|
tcsetattr(0, TCSANOW, &old);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE("init and reset termios") {
|
||||||
|
if (isatty(STDIN_FILENO)) {
|
||||||
|
struct termios original;
|
||||||
|
tcgetattr(0, &original);
|
||||||
|
SUBCASE("no echo") {
|
||||||
|
initTermios(false);
|
||||||
|
}
|
||||||
|
SUBCASE("yes echo") {
|
||||||
|
initTermios(true);
|
||||||
|
}
|
||||||
|
resetTermios();
|
||||||
|
struct termios current;
|
||||||
|
tcgetattr(0, ¤t);
|
||||||
|
CHECK(std::memcmp(&original, ¤t, sizeof(struct termios)) == 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
char getch_(int echo) {
|
char getch_(int echo) {
|
||||||
char ch;
|
char ch;
|
||||||
initTermios(echo);
|
initTermios(echo);
|
||||||
|
|||||||
+107
-197
@@ -1,216 +1,56 @@
|
|||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
|
||||||
|
#include "Client.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#undef error
|
#include "CustomAssert.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "httplib.h"
|
||||||
|
|
||||||
#include <boost/asio/connect.hpp>
|
|
||||||
#include <boost/asio/ip/tcp.hpp>
|
|
||||||
#include <boost/beast.hpp>
|
|
||||||
#include <boost/beast/ssl.hpp>
|
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
#include <random>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
namespace beast = boost::beast; // from <boost/beast.hpp>
|
// TODO: Add sentry error handling back
|
||||||
namespace http = beast::http; // from <boost/beast/http.hpp>
|
|
||||||
namespace net = boost::asio; // from <boost/asio.hpp>
|
using json = nlohmann::json;
|
||||||
namespace ssl = net::ssl; // from <boost/asio/ssl.hpp>
|
|
||||||
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
|
|
||||||
|
|
||||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||||
try {
|
httplib::SSLClient client(host, port);
|
||||||
// Check command line arguments.
|
client.enable_server_certificate_verification(false);
|
||||||
int version = 11;
|
client.set_address_family(AF_INET);
|
||||||
|
auto res = client.Get(target.c_str());
|
||||||
// The io_context is required for all I/O
|
if (res) {
|
||||||
net::io_context ioc;
|
|
||||||
|
|
||||||
// The SSL context is required, and holds certificates
|
|
||||||
ssl::context ctx(ssl::context::tlsv12_client);
|
|
||||||
|
|
||||||
// This holds the root certificate used for verification
|
|
||||||
// we don't do / have this
|
|
||||||
// load_root_certificates(ctx);
|
|
||||||
|
|
||||||
// Verify the remote server's certificate
|
|
||||||
ctx.set_verify_mode(ssl::verify_none);
|
|
||||||
|
|
||||||
// These objects perform our I/O
|
|
||||||
tcp::resolver resolver(ioc);
|
|
||||||
beast::ssl_stream<beast::tcp_stream> stream(ioc, ctx);
|
|
||||||
|
|
||||||
// Set SNI Hostname (many hosts need this to handshake successfully)
|
|
||||||
if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) {
|
|
||||||
beast::error_code ec { static_cast<int>(::ERR_get_error()), net::error::get_ssl_category() };
|
|
||||||
throw beast::system_error { ec };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Look up the domain name
|
|
||||||
auto const results = resolver.resolve(host.c_str(), std::to_string(port));
|
|
||||||
|
|
||||||
// Make the connection on the IP address we get from a lookup
|
|
||||||
beast::get_lowest_layer(stream).connect(results);
|
|
||||||
|
|
||||||
// Perform the SSL handshake
|
|
||||||
stream.handshake(ssl::stream_base::client);
|
|
||||||
|
|
||||||
// Set up an HTTP GET request message
|
|
||||||
http::request<http::string_body> req { http::verb::get, target, version };
|
|
||||||
req.set(http::field::host, host);
|
|
||||||
|
|
||||||
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
|
|
||||||
|
|
||||||
// Send the HTTP request to the remote host
|
|
||||||
http::write(stream, req);
|
|
||||||
|
|
||||||
// This buffer is used for reading and must be persisted
|
|
||||||
beast::flat_buffer buffer;
|
|
||||||
|
|
||||||
// Declare a container to hold the response
|
|
||||||
http::response<http::string_body> res;
|
|
||||||
|
|
||||||
// Receive the HTTP response
|
|
||||||
http::read(stream, buffer, res);
|
|
||||||
|
|
||||||
// Gracefully close the stream
|
|
||||||
beast::error_code ec;
|
|
||||||
stream.shutdown(ec);
|
|
||||||
if (ec == net::error::eof) {
|
|
||||||
// Rationale:
|
|
||||||
// http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
|
|
||||||
ec = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status) {
|
if (status) {
|
||||||
*status = res.base().result_int();
|
*status = res->status;
|
||||||
}
|
}
|
||||||
|
return res->body;
|
||||||
// ignore ec
|
} else {
|
||||||
|
return Http::ErrorString;
|
||||||
// If we get here then the connection is closed gracefully
|
|
||||||
return std::string(res.body());
|
|
||||||
} catch (std::exception const& e) {
|
|
||||||
Application::Console().Write(__func__ + std::string(": ") + e.what());
|
|
||||||
return "-1";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Http::POST(const std::string& host, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, bool json, int* status) {
|
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) {
|
||||||
try {
|
httplib::SSLClient client(host, port);
|
||||||
net::io_context io;
|
client.set_read_timeout(std::chrono::seconds(10));
|
||||||
|
beammp_assert(client.is_valid());
|
||||||
// The SSL context is required, and holds certificates
|
client.enable_server_certificate_verification(false);
|
||||||
ssl::context ctx(ssl::context::tlsv13);
|
client.set_address_family(AF_INET);
|
||||||
|
auto res = client.Post(target.c_str(), headers, body.c_str(), body.size(), ContentType.c_str());
|
||||||
ctx.set_verify_mode(ssl::verify_none);
|
if (res) {
|
||||||
|
|
||||||
tcp::resolver resolver(io);
|
|
||||||
beast::ssl_stream<beast::tcp_stream> stream(io, ctx);
|
|
||||||
decltype(resolver)::results_type results;
|
|
||||||
auto try_connect_with_protocol = [&](tcp protocol) {
|
|
||||||
try {
|
|
||||||
results = resolver.resolve(protocol, host, std::to_string(443));
|
|
||||||
if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) {
|
|
||||||
boost::system::error_code ec { static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
|
|
||||||
// FIXME: we could throw and crash, if we like
|
|
||||||
// throw boost::system::system_error { ec };
|
|
||||||
//debug("POST " + host + target + " failed.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
beast::get_lowest_layer(stream).connect(results);
|
|
||||||
} catch (const boost::system::system_error&) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
//bool ok = try_connect_with_protocol(tcp::v6());
|
|
||||||
//if (!ok) {
|
|
||||||
//debug("IPv6 connect failed, trying IPv4");
|
|
||||||
bool ok = try_connect_with_protocol(tcp::v4());
|
|
||||||
if (!ok) {
|
|
||||||
Application::Console().Write("[ERROR] failed to resolve or connect in POST " + host + target);
|
|
||||||
Sentry.AddErrorBreadcrumb("failed to resolve or connect to " + host + target, __FILE__, std::to_string(__LINE__)); // FIXME: this is ugly.
|
|
||||||
return "-1";
|
|
||||||
}
|
|
||||||
//}
|
|
||||||
stream.handshake(ssl::stream_base::client);
|
|
||||||
http::request<http::string_body> req { http::verb::post, target, 11 /* http 1.1 */ };
|
|
||||||
|
|
||||||
req.set(http::field::host, host);
|
|
||||||
if (!body.empty()) {
|
|
||||||
if (json) {
|
|
||||||
req.set(http::field::content_type, "application/json");
|
|
||||||
} else {
|
|
||||||
req.set(http::field::content_type, "application/x-www-form-urlencoded");
|
|
||||||
}
|
|
||||||
req.set(http::field::content_length, std::to_string(body.size()));
|
|
||||||
req.body() = body;
|
|
||||||
// info("body is " + body + " (" + req.body() + ")");
|
|
||||||
// info("content size is " + std::to_string(body.size()) + " (" + boost::lexical_cast<std::string>(body.size()) + ")");
|
|
||||||
}
|
|
||||||
for (const auto& pair : fields) {
|
|
||||||
// info("setting " + pair.first + " to " + pair.second);
|
|
||||||
req.set(pair.first, pair.second);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::unordered_map<std::string, std::string> request_data;
|
|
||||||
for (const auto& header : req.base()) {
|
|
||||||
// need to do explicit casts to convert string_view to string
|
|
||||||
// since string_view may not be null-terminated (and in fact isn't, here)
|
|
||||||
std::string KeyString(header.name_string());
|
|
||||||
std::string ValueString(header.value());
|
|
||||||
request_data[KeyString] = ValueString;
|
|
||||||
}
|
|
||||||
Sentry.SetContext("https-post-request-data", request_data);
|
|
||||||
|
|
||||||
std::stringstream oss;
|
|
||||||
oss << req;
|
|
||||||
|
|
||||||
beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(5));
|
|
||||||
|
|
||||||
http::write(stream, req);
|
|
||||||
|
|
||||||
// used for reading
|
|
||||||
beast::flat_buffer buffer;
|
|
||||||
http::response<http::string_body> response;
|
|
||||||
|
|
||||||
http::read(stream, buffer, response);
|
|
||||||
|
|
||||||
std::unordered_map<std::string, std::string> response_data;
|
|
||||||
response_data["reponse-code"] = std::to_string(response.result_int());
|
|
||||||
if (status) {
|
if (status) {
|
||||||
*status = response.result_int();
|
*status = res->status;
|
||||||
}
|
}
|
||||||
for (const auto& header : response.base()) {
|
return res->body;
|
||||||
// need to do explicit casts to convert string_view to string
|
} else {
|
||||||
// since string_view may not be null-terminated (and in fact isn't, here)
|
beammp_debug("POST failed: " + httplib::to_string(res.error()));
|
||||||
std::string KeyString(header.name_string());
|
return Http::ErrorString;
|
||||||
std::string ValueString(header.value());
|
|
||||||
response_data[KeyString] = ValueString;
|
|
||||||
}
|
|
||||||
Sentry.SetContext("https-post-response-data", response_data);
|
|
||||||
|
|
||||||
std::stringstream result;
|
|
||||||
result << response;
|
|
||||||
|
|
||||||
beast::error_code ec;
|
|
||||||
stream.shutdown(ec);
|
|
||||||
// IGNORING ec
|
|
||||||
|
|
||||||
// info(result.str());
|
|
||||||
std::string debug_response_str;
|
|
||||||
std::getline(result, debug_response_str);
|
|
||||||
//debug("POST " + host + target + ": " + debug_response_str);
|
|
||||||
return std::string(response.body());
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
Application::Console().Write(e.what());
|
|
||||||
Sentry.AddErrorBreadcrumb(e.what(), __FILE__, std::to_string(__LINE__)); // FIXME: this is ugly.
|
|
||||||
return "-1";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// RFC 2616, RFC 7231
|
// RFC 2616, RFC 7231
|
||||||
static std::map<size_t, const char*> Map = {
|
static std::map<size_t, const char*> Map = {
|
||||||
{ -1, "Invalid Response Code"},
|
{ -1, "Invalid Response Code" },
|
||||||
{ 100, "Continue" },
|
{ 100, "Continue" },
|
||||||
{ 101, "Switching Protocols" },
|
{ 101, "Switching Protocols" },
|
||||||
{ 102, "Processing" },
|
{ 102, "Processing" },
|
||||||
@@ -285,10 +125,80 @@ static std::map<size_t, const char*> Map = {
|
|||||||
{ 530, "(CDN) 1XXX Internal Error" },
|
{ 530, "(CDN) 1XXX Internal Error" },
|
||||||
};
|
};
|
||||||
|
|
||||||
std::string Http::Status::ToString(int code) {
|
static const char Magic[] = {
|
||||||
if (Map.find(code) != Map.end()) {
|
0x20, 0x2f, 0x5c, 0x5f,
|
||||||
return Map.at(code);
|
0x2f, 0x5c, 0x0a, 0x28,
|
||||||
|
0x20, 0x6f, 0x2e, 0x6f,
|
||||||
|
0x20, 0x29, 0x0a, 0x20,
|
||||||
|
0x3e, 0x20, 0x5e, 0x20,
|
||||||
|
0x3c, 0x0a, 0x00
|
||||||
|
};
|
||||||
|
|
||||||
|
std::string Http::Status::ToString(int Code) {
|
||||||
|
if (Map.find(Code) != Map.end()) {
|
||||||
|
return Map.at(Code);
|
||||||
} else {
|
} else {
|
||||||
return std::to_string(code);
|
return std::to_string(Code);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE("Http::Status::ToString") {
|
||||||
|
CHECK(Http::Status::ToString(200) == "OK");
|
||||||
|
CHECK(Http::Status::ToString(696969) == "696969");
|
||||||
|
CHECK(Http::Status::ToString(-1) == "Invalid Response Code");
|
||||||
|
}
|
||||||
|
|
||||||
|
Http::Server::THttpServerInstance::THttpServerInstance() {
|
||||||
|
Application::SetSubsystemStatus("HTTPServer", Application::Status::Starting);
|
||||||
|
mThread = std::thread(&Http::Server::THttpServerInstance::operator(), this);
|
||||||
|
mThread.detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
HttpLibServerInstance->Get("/", [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
res.set_content("<!DOCTYPE html><article><h1>Hello World!</h1><section><p>BeamMP Server can now serve HTTP requests!</p></section></article></html>", "text/html");
|
||||||
|
});
|
||||||
|
HttpLibServerInstance->Get("/health", [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
size_t SystemsGood = 0;
|
||||||
|
size_t SystemsBad = 0;
|
||||||
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
|
switch (NameStatusPair.second) {
|
||||||
|
case Application::Status::Starting:
|
||||||
|
case Application::Status::ShuttingDown:
|
||||||
|
case Application::Status::Shutdown:
|
||||||
|
case Application::Status::Good:
|
||||||
|
SystemsGood++;
|
||||||
|
break;
|
||||||
|
case Application::Status::Bad:
|
||||||
|
SystemsBad++;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.set_content(
|
||||||
|
json {
|
||||||
|
{ "ok", SystemsBad == 0 },
|
||||||
|
}
|
||||||
|
.dump(),
|
||||||
|
"application/json");
|
||||||
|
res.status = 200;
|
||||||
|
});
|
||||||
|
// magic endpoint
|
||||||
|
HttpLibServerInstance->Get({ 0x2f, 0x6b, 0x69, 0x74, 0x74, 0x79 }, [](const httplib::Request&, httplib::Response& res) {
|
||||||
|
res.set_content(std::string(Magic), "text/plain");
|
||||||
|
});
|
||||||
|
HttpLibServerInstance->set_logger([](const httplib::Request& Req, const httplib::Response& Res) {
|
||||||
|
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()));
|
||||||
|
}
|
||||||
|
|||||||
+650
@@ -0,0 +1,650 @@
|
|||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "Client.h"
|
||||||
|
#include "Common.h"
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
|
#define SOL_ALL_SAFETIES_ON 1
|
||||||
|
#include <sol/sol.hpp>
|
||||||
|
|
||||||
|
std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool QuoteStrings) {
|
||||||
|
if (Indent > 80) {
|
||||||
|
return "[[possible recursion, refusing to keep printing]]";
|
||||||
|
}
|
||||||
|
switch (Value.get_type()) {
|
||||||
|
case sol::type::userdata: {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << "[[userdata: " << Value.as<sol::userdata>().pointer() << "]]";
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
case sol::type::thread: {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << "[[thread: " << Value.as<sol::thread>().pointer() << "]] {"
|
||||||
|
<< "\n";
|
||||||
|
for (size_t i = 0; i < Indent; ++i) {
|
||||||
|
ss << "\t";
|
||||||
|
}
|
||||||
|
ss << "status: " << std::to_string(int(Value.as<sol::thread>().status())) << "\n}";
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
case sol::type::lightuserdata: {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << "[[lightuserdata: " << Value.as<sol::lightuserdata>().pointer() << "]]";
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
case sol::type::string:
|
||||||
|
if (QuoteStrings) {
|
||||||
|
return "\"" + Value.as<std::string>() + "\"";
|
||||||
|
} else {
|
||||||
|
return Value.as<std::string>();
|
||||||
|
}
|
||||||
|
case sol::type::number: {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << Value.as<float>();
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
case sol::type::lua_nil:
|
||||||
|
case sol::type::none:
|
||||||
|
return "<nil>";
|
||||||
|
case sol::type::boolean:
|
||||||
|
return Value.as<bool>() ? "true" : "false";
|
||||||
|
case sol::type::table: {
|
||||||
|
std::stringstream Result;
|
||||||
|
auto Table = Value.as<sol::table>();
|
||||||
|
Result << "[[table: " << Table.pointer() << "]]: {";
|
||||||
|
if (!Table.empty()) {
|
||||||
|
for (const auto& Entry : Table) {
|
||||||
|
Result << "\n";
|
||||||
|
for (size_t i = 0; i < Indent; ++i) {
|
||||||
|
Result << "\t";
|
||||||
|
}
|
||||||
|
Result << LuaToString(Entry.first, Indent + 1) << ": " << LuaToString(Entry.second, Indent + 1, true) << ",";
|
||||||
|
}
|
||||||
|
Result << "\n";
|
||||||
|
}
|
||||||
|
for (size_t i = 0; i < Indent - 1; ++i) {
|
||||||
|
Result << "\t";
|
||||||
|
}
|
||||||
|
Result << "}";
|
||||||
|
return Result.str();
|
||||||
|
}
|
||||||
|
case sol::type::function: {
|
||||||
|
std::stringstream ss;
|
||||||
|
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return "((unprintable type))";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::GetOSName() {
|
||||||
|
#if WIN32
|
||||||
|
return "Windows";
|
||||||
|
#elif __linux
|
||||||
|
return "Linux";
|
||||||
|
#else
|
||||||
|
return "Other";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
std::tuple<int, int, int> LuaAPI::MP::GetServerVersion() {
|
||||||
|
return { Application::ServerVersion().major, Application::ServerVersion().minor, Application::ServerVersion().patch };
|
||||||
|
}
|
||||||
|
|
||||||
|
void LuaAPI::Print(sol::variadic_args Args) {
|
||||||
|
std::string ToPrint = "";
|
||||||
|
for (const auto& Arg : Args) {
|
||||||
|
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||||
|
ToPrint += "\t";
|
||||||
|
}
|
||||||
|
luaprint(ToPrint);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
||||||
|
const auto [ma, mi, pa] = LuaAPI::MP::GetServerVersion();
|
||||||
|
const auto real = Application::ServerVersion();
|
||||||
|
CHECK(ma == real.major);
|
||||||
|
CHECK(mi == real.minor);
|
||||||
|
CHECK(pa == real.patch);
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline bool InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||||
|
std::string Packet = "E:" + EventName + ":" + Data;
|
||||||
|
if (PlayerID == -1)
|
||||||
|
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||||
|
else {
|
||||||
|
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||||
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
|
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
auto c = MaybeClient.value().lock();
|
||||||
|
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
||||||
|
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
||||||
|
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||||
|
std::string Data = DataObj.as<std::string>();
|
||||||
|
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||||
|
}
|
||||||
|
|
||||||
|
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||||
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
|
beammp_lua_error("Tried to drop client with id " + std::to_string(ID) + ", who doesn't exist");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto c = MaybeClient.value().lock();
|
||||||
|
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||||
|
}
|
||||||
|
|
||||||
|
void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||||
|
std::string Packet = "C:Server: " + Message;
|
||||||
|
if (ID == -1) {
|
||||||
|
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||||
|
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||||
|
} else {
|
||||||
|
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||||
|
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||||
|
auto c = MaybeClient.value().lock();
|
||||||
|
if (!c->IsSynced())
|
||||||
|
return;
|
||||||
|
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||||
|
Engine->Network().Respond(*c, Packet, true);
|
||||||
|
} else {
|
||||||
|
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||||
|
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||||
|
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||||
|
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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, Destroy, true, true);
|
||||||
|
c->DeleteCar(VID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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"));
|
||||||
|
} 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"));
|
||||||
|
} 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));
|
||||||
|
} 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));
|
||||||
|
} 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);
|
||||||
|
} 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);
|
||||||
|
} 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);
|
||||||
|
} else {
|
||||||
|
beammp_lua_error("set invalid argument [2] expected string");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||||
|
std::string ToPrint = "";
|
||||||
|
for (const auto& Arg : Args) {
|
||||||
|
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||||
|
ToPrint += "\t";
|
||||||
|
}
|
||||||
|
#ifdef DOCTEST_CONFIG_DISABLE
|
||||||
|
Application::Console().WriteRaw(ToPrint);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
int LuaAPI::PanicHandler(lua_State* State) {
|
||||||
|
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename FnT, typename... ArgsT>
|
||||||
|
static std::pair<bool, std::string> FSWrapper(FnT Fn, ArgsT&&... Args) {
|
||||||
|
std::error_code errc;
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
|
Fn(std::forward<ArgsT>(Args)..., errc);
|
||||||
|
Result.first = errc == std::error_code {};
|
||||||
|
if (!Result.first) {
|
||||||
|
Result.second = errc.message();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::pair<bool, std::string> LuaAPI::FS::CreateDirectory(const std::string& Path) {
|
||||||
|
std::error_code errc;
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
|
fs::create_directories(Path, errc);
|
||||||
|
Result.first = errc == std::error_code {};
|
||||||
|
if (!Result.first) {
|
||||||
|
Result.second = errc.message();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::CreateDirectory") {
|
||||||
|
std::string TestDir = "beammp_test_dir";
|
||||||
|
fs::remove_all(TestDir);
|
||||||
|
SUBCASE("Single level dir") {
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK(Err == "");
|
||||||
|
CHECK(fs::exists(TestDir));
|
||||||
|
}
|
||||||
|
SUBCASE("Multi level dir") {
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir + "/a/b/c");
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK(Err == "");
|
||||||
|
CHECK(fs::exists(TestDir + "/a/b/c"));
|
||||||
|
}
|
||||||
|
SUBCASE("Already exists") {
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK(Err == "");
|
||||||
|
CHECK(fs::exists(TestDir));
|
||||||
|
const auto [Ok2, Err2] = LuaAPI::FS::CreateDirectory(TestDir);
|
||||||
|
CHECK(Ok2);
|
||||||
|
CHECK(Err2 == "");
|
||||||
|
}
|
||||||
|
fs::remove_all(TestDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::pair<bool, std::string> LuaAPI::FS::Remove(const std::string& Path) {
|
||||||
|
std::error_code errc;
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
|
fs::remove(fs::relative(Path), errc);
|
||||||
|
Result.first = errc == std::error_code {};
|
||||||
|
if (!Result.first) {
|
||||||
|
Result.second = errc.message();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::Remove") {
|
||||||
|
const std::string TestFileOrDir = "beammp_test_thing";
|
||||||
|
SUBCASE("Remove existing directory") {
|
||||||
|
fs::create_directory(TestFileOrDir);
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK_EQ(Err, "");
|
||||||
|
CHECK(!fs::exists(TestFileOrDir));
|
||||||
|
}
|
||||||
|
SUBCASE("Remove non-existing directory") {
|
||||||
|
fs::remove_all(TestFileOrDir);
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK_EQ(Err, "");
|
||||||
|
CHECK(!fs::exists(TestFileOrDir));
|
||||||
|
}
|
||||||
|
// TODO: add tests for files
|
||||||
|
// TODO: add tests for files and folders without access permissions (failure)
|
||||||
|
}
|
||||||
|
|
||||||
|
std::pair<bool, std::string> LuaAPI::FS::Rename(const std::string& Path, const std::string& NewPath) {
|
||||||
|
std::error_code errc;
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
|
fs::rename(Path, NewPath, errc);
|
||||||
|
Result.first = errc == std::error_code {};
|
||||||
|
if (!Result.first) {
|
||||||
|
Result.second = errc.message();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::Rename") {
|
||||||
|
const auto TestDir = "beammp_test_dir";
|
||||||
|
const auto OtherTestDir = "beammp_test_dir_2";
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::create_directory(TestDir);
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::Rename(TestDir, OtherTestDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK_EQ(Err, "");
|
||||||
|
CHECK(!fs::exists(TestDir));
|
||||||
|
CHECK(fs::exists(OtherTestDir));
|
||||||
|
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::remove_all(TestDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::pair<bool, std::string> LuaAPI::FS::Copy(const std::string& Path, const std::string& NewPath) {
|
||||||
|
std::error_code errc;
|
||||||
|
std::pair<bool, std::string> Result;
|
||||||
|
fs::copy(Path, NewPath, fs::copy_options::recursive, errc);
|
||||||
|
Result.first = errc == std::error_code {};
|
||||||
|
if (!Result.first) {
|
||||||
|
Result.second = errc.message();
|
||||||
|
}
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::Copy") {
|
||||||
|
const auto TestDir = "beammp_test_dir";
|
||||||
|
const auto OtherTestDir = "beammp_test_dir_2";
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::create_directory(TestDir);
|
||||||
|
const auto [Ok, Err] = LuaAPI::FS::Copy(TestDir, OtherTestDir);
|
||||||
|
CHECK(Ok);
|
||||||
|
CHECK_EQ(Err, "");
|
||||||
|
CHECK(fs::exists(TestDir));
|
||||||
|
CHECK(fs::exists(OtherTestDir));
|
||||||
|
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::remove_all(TestDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LuaAPI::FS::Exists(const std::string& Path) {
|
||||||
|
return fs::exists(Path);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::Exists") {
|
||||||
|
const auto TestDir = "beammp_test_dir";
|
||||||
|
const auto OtherTestDir = "beammp_test_dir_2";
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::create_directory(TestDir);
|
||||||
|
|
||||||
|
CHECK(LuaAPI::FS::Exists(TestDir));
|
||||||
|
CHECK(!LuaAPI::FS::Exists(OtherTestDir));
|
||||||
|
|
||||||
|
fs::remove_all(OtherTestDir);
|
||||||
|
fs::remove_all(TestDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::FS::GetFilename(const std::string& Path) {
|
||||||
|
return fs::path(Path).filename().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::GetFilename") {
|
||||||
|
CHECK(LuaAPI::FS::GetFilename("test.txt") == "test.txt");
|
||||||
|
CHECK(LuaAPI::FS::GetFilename("/test.txt") == "test.txt");
|
||||||
|
CHECK(LuaAPI::FS::GetFilename("place/test.txt") == "test.txt");
|
||||||
|
CHECK(LuaAPI::FS::GetFilename("/some/../place/test.txt") == "test.txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::FS::GetExtension(const std::string& Path) {
|
||||||
|
return fs::path(Path).extension().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::GetExtension") {
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("test.txt") == ".txt");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/test.txt") == ".txt");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("place/test.txt") == ".txt");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.txt") == ".txt");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/some/../place/test") == "");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.c") == ".c");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.") == ".");
|
||||||
|
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.") == ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::FS::GetParentFolder(const std::string& Path) {
|
||||||
|
return fs::path(Path).parent_path().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("LuaAPI::FS::GetParentFolder") {
|
||||||
|
CHECK(LuaAPI::FS::GetParentFolder("test.txt") == "");
|
||||||
|
CHECK(LuaAPI::FS::GetParentFolder("/test.txt") == "/");
|
||||||
|
CHECK(LuaAPI::FS::GetParentFolder("place/test.txt") == "place");
|
||||||
|
CHECK(LuaAPI::FS::GetParentFolder("/some/../place/test.txt") == "/some/../place");
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: add tests
|
||||||
|
bool LuaAPI::FS::IsDirectory(const std::string& Path) {
|
||||||
|
return fs::is_directory(Path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: add tests
|
||||||
|
bool LuaAPI::FS::IsFile(const std::string& Path) {
|
||||||
|
return fs::is_regular_file(Path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: add tests
|
||||||
|
std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
|
||||||
|
fs::path Path;
|
||||||
|
for (size_t i = 0; i < Args.size(); ++i) {
|
||||||
|
auto Obj = Args[i];
|
||||||
|
if (!Obj.is<std::string>()) {
|
||||||
|
beammp_lua_error("FS.Concat called with non-string argument");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
Path += Obj.as<std::string>();
|
||||||
|
if (i < Args.size() - 1 && !Path.empty()) {
|
||||||
|
Path += fs::path::preferred_separator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto Result = Path.lexically_normal().string();
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, const sol::object& right, bool is_array, size_t depth = 0) {
|
||||||
|
if (depth > 100) {
|
||||||
|
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::string key;
|
||||||
|
switch (left.get_type()) {
|
||||||
|
case sol::type::lua_nil:
|
||||||
|
case sol::type::none:
|
||||||
|
case sol::type::poly:
|
||||||
|
case sol::type::boolean:
|
||||||
|
case sol::type::lightuserdata:
|
||||||
|
case sol::type::userdata:
|
||||||
|
case sol::type::thread:
|
||||||
|
case sol::type::function:
|
||||||
|
case sol::type::table:
|
||||||
|
beammp_lua_error("JsonEncode: left side of table field is unexpected type");
|
||||||
|
return;
|
||||||
|
case sol::type::string:
|
||||||
|
key = left.as<std::string>();
|
||||||
|
break;
|
||||||
|
case sol::type::number:
|
||||||
|
key = std::to_string(left.as<double>());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
nlohmann::json value;
|
||||||
|
switch (right.get_type()) {
|
||||||
|
case sol::type::lua_nil:
|
||||||
|
case sol::type::none:
|
||||||
|
return;
|
||||||
|
case sol::type::poly:
|
||||||
|
beammp_lua_warn("unsure what to do with poly type in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::boolean:
|
||||||
|
value = right.as<bool>();
|
||||||
|
break;
|
||||||
|
case sol::type::lightuserdata:
|
||||||
|
beammp_lua_warn("unsure what to do with lightuserdata in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::userdata:
|
||||||
|
beammp_lua_warn("unsure what to do with userdata in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::thread:
|
||||||
|
beammp_lua_warn("unsure what to do with thread in JsonEncode, ignoring");
|
||||||
|
return;
|
||||||
|
case sol::type::string:
|
||||||
|
value = right.as<std::string>();
|
||||||
|
break;
|
||||||
|
case sol::type::number:
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& pair : right.as<sol::table>()) {
|
||||||
|
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (is_array) {
|
||||||
|
json.push_back(value);
|
||||||
|
} else {
|
||||||
|
json[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& entry : object) {
|
||||||
|
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||||
|
}
|
||||||
|
return json.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonDiff(const std::string& a, const std::string& b) {
|
||||||
|
if (!nlohmann::json::accept(a)) {
|
||||||
|
beammp_lua_error("JsonDiff first argument is not valid json: `" + a + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (!nlohmann::json::accept(b)) {
|
||||||
|
beammp_lua_error("JsonDiff second argument is not valid json: `" + b + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
auto a_json = nlohmann::json::parse(a);
|
||||||
|
auto b_json = nlohmann::json::parse(b);
|
||||||
|
return nlohmann::json::diff(a_json, b_json).dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonDiffApply(const std::string& data, const std::string& patch) {
|
||||||
|
if (!nlohmann::json::accept(data)) {
|
||||||
|
beammp_lua_error("JsonDiffApply first argument is not valid json: `" + data + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (!nlohmann::json::accept(patch)) {
|
||||||
|
beammp_lua_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
auto a_json = nlohmann::json::parse(data);
|
||||||
|
auto b_json = nlohmann::json::parse(patch);
|
||||||
|
a_json.patch(b_json);
|
||||||
|
return a_json.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonPrettify(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonPrettify argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).dump(4);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonMinify(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonMinify argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonFlatten(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonFlatten argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).flatten().dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
||||||
|
if (!nlohmann::json::accept(json)) {
|
||||||
|
beammp_lua_error("JsonUnflatten argument is not valid json: `" + json + "`");
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||||
|
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||||
|
}
|
||||||
+16
-19
@@ -1,65 +1,62 @@
|
|||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
|
|
||||||
#ifdef __unix
|
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
#include <csignal>
|
#include <csignal>
|
||||||
static void UnixSignalHandler(int sig) {
|
static void UnixSignalHandler(int sig) {
|
||||||
switch (sig) {
|
switch (sig) {
|
||||||
case SIGPIPE:
|
case SIGPIPE:
|
||||||
warn("ignoring SIGPIPE");
|
beammp_warn("ignoring SIGPIPE");
|
||||||
break;
|
break;
|
||||||
case SIGTERM:
|
case SIGTERM:
|
||||||
info("gracefully shutting down via SIGTERM");
|
beammp_info("gracefully shutting down via SIGTERM");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
break;
|
break;
|
||||||
case SIGINT:
|
case SIGINT:
|
||||||
info("gracefully shutting down via SIGINT");
|
beammp_info("gracefully shutting down via SIGINT");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
debug("unhandled signal: " + std::to_string(sig));
|
beammp_debug("unhandled signal: " + std::to_string(sig));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // __unix
|
#endif // UNIX
|
||||||
|
|
||||||
#ifdef WIN32
|
#ifdef BEAMMP_WINDOWS
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
// return TRUE if handled, FALSE if not
|
// return TRUE if handled, FALSE if not
|
||||||
BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
|
BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
|
||||||
switch (CtrlType) {
|
switch (CtrlType) {
|
||||||
case CTRL_C_EVENT:
|
case CTRL_C_EVENT:
|
||||||
info("gracefully shutting down via CTRL+C");
|
beammp_info("gracefully shutting down via CTRL+C");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
return TRUE;
|
return TRUE;
|
||||||
case CTRL_BREAK_EVENT:
|
case CTRL_BREAK_EVENT:
|
||||||
info("gracefully shutting down via CTRL+BREAK");
|
beammp_info("gracefully shutting down via CTRL+BREAK");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
return TRUE;
|
return TRUE;
|
||||||
case CTRL_CLOSE_EVENT:
|
case CTRL_CLOSE_EVENT:
|
||||||
info("gracefully shutting down via close");
|
beammp_info("gracefully shutting down via close");
|
||||||
Application::GracefullyShutdown();
|
Application::GracefullyShutdown();
|
||||||
return TRUE;
|
return TRUE;
|
||||||
}
|
}
|
||||||
// we dont care for any others like CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT
|
// we dont care for any others like CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT
|
||||||
return FALSE;
|
return FALSE;
|
||||||
}
|
}
|
||||||
#endif // WIN32
|
#endif // WINDOWS
|
||||||
|
|
||||||
void SetupSignalHandlers() {
|
void SetupSignalHandlers() {
|
||||||
// signal handlers for unix#include <windows.h>
|
// signal handlers for unix#include <windows.h>
|
||||||
#ifdef __unix
|
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
trace("registering handlers for SIGINT, SIGTERM, SIGPIPE");
|
beammp_trace("registering handlers for signals");
|
||||||
signal(SIGPIPE, UnixSignalHandler);
|
signal(SIGPIPE, UnixSignalHandler);
|
||||||
signal(SIGTERM, UnixSignalHandler);
|
signal(SIGTERM, UnixSignalHandler);
|
||||||
#ifndef DEBUG
|
#ifndef DEBUG
|
||||||
signal(SIGINT, UnixSignalHandler);
|
signal(SIGINT, UnixSignalHandler);
|
||||||
#endif // DEBUG
|
#endif // DEBUG
|
||||||
#endif // __unix
|
#elif defined(BEAMMP_WINDOWS)
|
||||||
|
beammp_trace("registering handlers for CTRL_*_EVENTs");
|
||||||
// signal handlers for win32
|
|
||||||
#ifdef WIN32
|
|
||||||
trace("registering handlers for CTRL_*_EVENTs");
|
|
||||||
SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE);
|
SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE);
|
||||||
#endif // WIN32
|
#endif
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
#include "SocketIO.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
|
|
||||||
//TODO Default disabled with config option
|
|
||||||
static std::unique_ptr<SocketIO> SocketIOInstance = std::make_unique<SocketIO>();
|
|
||||||
|
|
||||||
SocketIO& SocketIO::Get() {
|
|
||||||
return *SocketIOInstance;
|
|
||||||
}
|
|
||||||
|
|
||||||
SocketIO::SocketIO() noexcept
|
|
||||||
: mThread([this] { ThreadMain(); }) {
|
|
||||||
|
|
||||||
mClient.socket()->on("network", [&](sio::event&e) {
|
|
||||||
if(e.get_message()->get_string() == "Welcome"){
|
|
||||||
info("SocketIO Authenticated!");
|
|
||||||
mAuthenticated = true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
mClient.socket()->on("welcome", [&](sio::event&) {
|
|
||||||
info("Got welcome from backend! Authenticating SocketIO...");
|
|
||||||
mClient.socket()->emit("onInitConnection", Application::Settings.Key);
|
|
||||||
});
|
|
||||||
|
|
||||||
mClient.set_logs_quiet();
|
|
||||||
mClient.set_reconnect_delay(10000);
|
|
||||||
mClient.connect(Application::GetBackendUrlForSocketIO());
|
|
||||||
}
|
|
||||||
|
|
||||||
SocketIO::~SocketIO() {
|
|
||||||
mCloseThread.store(true);
|
|
||||||
mThread.join();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static constexpr auto EventNameFromEnum(SocketIOEvent Event) {
|
|
||||||
switch (Event) {
|
|
||||||
case SocketIOEvent::CPUUsage:
|
|
||||||
return "cpu usage";
|
|
||||||
case SocketIOEvent::MemoryUsage:
|
|
||||||
return "memory usage";
|
|
||||||
case SocketIOEvent::ConsoleOut:
|
|
||||||
return "console out";
|
|
||||||
case SocketIOEvent::NetworkUsage:
|
|
||||||
return "network usage";
|
|
||||||
case SocketIOEvent::PlayerList:
|
|
||||||
return "player list";
|
|
||||||
default:
|
|
||||||
error("unreachable code reached (developer error)");
|
|
||||||
abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void SocketIO::Emit(SocketIOEvent Event, const std::string& Data) {
|
|
||||||
if (!mAuthenticated) {
|
|
||||||
debug("trying to emit a socket.io event when not yet authenticated");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::string EventName = EventNameFromEnum(Event);
|
|
||||||
debug("emitting event \"" + EventName + "\" with data: \"" + Data);
|
|
||||||
std::unique_lock Lock(mQueueMutex);
|
|
||||||
mQueue.push_back({EventName, Data });
|
|
||||||
debug("queue now has " + std::to_string(mQueue.size()) + " events");
|
|
||||||
}
|
|
||||||
|
|
||||||
void SocketIO::ThreadMain() {
|
|
||||||
while (!mCloseThread.load()) {
|
|
||||||
bool empty;
|
|
||||||
{ // queue lock scope
|
|
||||||
std::unique_lock Lock(mQueueMutex);
|
|
||||||
empty = mQueue.empty();
|
|
||||||
} // end queue lock scope
|
|
||||||
if (empty || !mClient.opened()) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
Event TheEvent;
|
|
||||||
{ // queue lock scope
|
|
||||||
std::unique_lock Lock(mQueueMutex);
|
|
||||||
TheEvent = mQueue.front();
|
|
||||||
mQueue.pop_front();
|
|
||||||
} // end queue lock scope
|
|
||||||
debug("sending \"" + TheEvent.Name + "\" event");
|
|
||||||
mClient.socket()->emit(TheEvent.Name, TheEvent.Data);
|
|
||||||
debug("sent \"" + TheEvent.Name + "\" event");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// using std::cout as this happens during static destruction and the logger might be dead already
|
|
||||||
std::cout << "closing " + std::string(__func__) << std::endl;
|
|
||||||
|
|
||||||
mClient.sync_close();
|
|
||||||
mClient.clear_con_listeners();
|
|
||||||
|
|
||||||
std::cout << "closed" << std::endl;
|
|
||||||
}
|
|
||||||
+188
-127
@@ -1,4 +1,4 @@
|
|||||||
#include <toml.hpp> // header-only version of TOML++
|
#include "Common.h"
|
||||||
|
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
@@ -6,8 +6,7 @@
|
|||||||
#include <istream>
|
#include <istream>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
static const char* ConfigFileName = static_cast<const char*>("ServerConfig.toml");
|
// General
|
||||||
|
|
||||||
static constexpr std::string_view StrDebug = "Debug";
|
static constexpr std::string_view StrDebug = "Debug";
|
||||||
static constexpr std::string_view StrPrivate = "Private";
|
static constexpr std::string_view StrPrivate = "Private";
|
||||||
static constexpr std::string_view StrPort = "Port";
|
static constexpr std::string_view StrPort = "Port";
|
||||||
@@ -18,32 +17,131 @@ static constexpr std::string_view StrName = "Name";
|
|||||||
static constexpr std::string_view StrDescription = "Description";
|
static constexpr std::string_view StrDescription = "Description";
|
||||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||||
|
static constexpr std::string_view StrLogChat = "LogChat";
|
||||||
|
static constexpr std::string_view StrDownloadThreads = "DownloadThreads";
|
||||||
|
|
||||||
|
// Misc
|
||||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||||
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||||
|
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||||
|
|
||||||
TConfig::TConfig() {
|
// HTTP
|
||||||
if (!fs::exists(ConfigFileName) || !fs::is_regular_file(ConfigFileName)) {
|
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||||
info("No config file found! Generating one...");
|
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
||||||
CreateConfigFile(ConfigFileName);
|
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
||||||
|
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
||||||
|
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
||||||
|
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||||
|
|
||||||
|
TEST_CASE("TConfig::TConfig") {
|
||||||
|
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||||
|
fs::remove(CfgFile);
|
||||||
|
|
||||||
|
TConfig Cfg(CfgFile);
|
||||||
|
|
||||||
|
CHECK(fs::file_size(CfgFile) != 0);
|
||||||
|
|
||||||
|
std::string buf;
|
||||||
|
{
|
||||||
|
buf.resize(fs::file_size(CfgFile));
|
||||||
|
auto fp = std::fopen(CfgFile.c_str(), "r");
|
||||||
|
std::fread(buf.data(), 1, buf.size(), fp);
|
||||||
|
std::fclose(fp);
|
||||||
|
}
|
||||||
|
INFO("file contents are:", buf);
|
||||||
|
|
||||||
|
const auto table = toml::parse(CfgFile);
|
||||||
|
CHECK(table.at("General").is_table());
|
||||||
|
CHECK(table.at("Misc").is_table());
|
||||||
|
CHECK(table.at("HTTP").is_table());
|
||||||
|
|
||||||
|
fs::remove(CfgFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
TConfig::TConfig(const std::string& ConfigFileName)
|
||||||
|
: mConfigFileName(ConfigFileName) {
|
||||||
|
Application::SetSubsystemStatus("Config", Application::Status::Starting);
|
||||||
|
if (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName)) {
|
||||||
|
beammp_info("No config file found! Generating one...");
|
||||||
|
CreateConfigFile();
|
||||||
}
|
}
|
||||||
if (!mFailed) {
|
if (!mFailed) {
|
||||||
if (fs::exists("Server.cfg")) {
|
if (fs::exists("Server.cfg")) {
|
||||||
warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(ConfigFileName) + "\" is used. You can safely delete the \"Server.cfg\".");
|
beammp_warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(mConfigFileName) + "\" is used. You can safely delete the \"Server.cfg\".");
|
||||||
}
|
}
|
||||||
ParseFromFile(ConfigFileName);
|
ParseFromFile(mConfigFileName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void WriteSendErrors(const std::string& name) {
|
template <typename CommentsT>
|
||||||
std::ofstream CfgFile { name, std::ios::out | std::ios::app };
|
void SetComment(CommentsT& Comments, const std::string& Comment) {
|
||||||
CfgFile << "# You can turn on/off the SendErrors message you get on startup here" << std::endl
|
Comments.clear();
|
||||||
<< StrSendErrorsMessageEnabled << " = true" << std::endl
|
Comments.push_back(Comment);
|
||||||
<< "# 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`."
|
|
||||||
<< std::endl
|
|
||||||
<< StrSendErrors << " = true" << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::CreateConfigFile(std::string_view name) {
|
/**
|
||||||
|
* @brief Writes out the loaded application state into ServerConfig.toml
|
||||||
|
*
|
||||||
|
* This writes out the current state of application settings that are
|
||||||
|
* applied to the server instance (i.e. the current application settings loaded in the server).
|
||||||
|
* If the state of the application settings changes during runtime,
|
||||||
|
* call this function whenever something about the config changes
|
||||||
|
* whether it is in TConfig.cpp or the configuration file.
|
||||||
|
*/
|
||||||
|
void TConfig::FlushToFile() {
|
||||||
|
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
|
||||||
|
auto data = toml::value {};
|
||||||
|
data["General"][StrAuthKey.data()] = Application::Settings.Key;
|
||||||
|
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
|
||||||
|
data["General"][StrLogChat.data()] = Application::Settings.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"][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"][StrDownloadThreads.data()] = Application::Settings.DownloadThreads;
|
||||||
|
SetComment(data["General"][StrDownloadThreads.data()].comments(), " How many simultaneous downloads may run at the same time");
|
||||||
|
// Misc
|
||||||
|
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||||
|
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||||
|
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||||
|
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||||
|
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||||
|
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||||
|
// HTTP
|
||||||
|
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
||||||
|
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
||||||
|
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
||||||
|
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
||||||
|
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
||||||
|
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
|
||||||
|
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
||||||
|
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
||||||
|
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
||||||
|
std::stringstream Ss;
|
||||||
|
Ss << "# This is the BeamMP-Server config file.\n"
|
||||||
|
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||||
|
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
||||||
|
<< data;
|
||||||
|
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||||
|
if (!File) {
|
||||||
|
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
|
||||||
|
throw std::runtime_error("Failed to create/write to config file");
|
||||||
|
}
|
||||||
|
auto Str = Ss.str();
|
||||||
|
auto N = std::fwrite(Str.data(), sizeof(char), Str.size(), File);
|
||||||
|
if (N != Str.size()) {
|
||||||
|
beammp_error("Failed to write to config file properly, config file might be misshapen");
|
||||||
|
}
|
||||||
|
std::fclose(File);
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConfig::CreateConfigFile() {
|
||||||
// build from old config Server.cfg
|
// build from old config Server.cfg
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -52,138 +150,101 @@ void TConfig::CreateConfigFile(std::string_view name) {
|
|||||||
ParseOldFormat();
|
ParseOldFormat();
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
|
|
||||||
toml::table tbl { {
|
FlushToFile();
|
||||||
|
}
|
||||||
|
|
||||||
{ "General",
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
||||||
toml::table { {
|
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||||
|
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
{ StrDebug, Application::Settings.DebugModeEnabled },
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
|
||||||
{ StrPrivate, Application::Settings.Private },
|
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||||
{ StrPort, Application::Settings.Port },
|
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||||
{ StrMaxCars, Application::Settings.MaxCars },
|
}
|
||||||
{ StrMaxPlayers, Application::Settings.MaxPlayers },
|
}
|
||||||
{ StrMap, Application::Settings.MapName },
|
|
||||||
{ StrName, Application::Settings.ServerName },
|
|
||||||
{ StrDescription, Application::Settings.ServerDesc },
|
|
||||||
{ StrResourceFolder, Application::Settings.Resource },
|
|
||||||
{ StrAuthKey, Application::Settings.Key },
|
|
||||||
//{ StrSendErrors, Application::Settings.SendErrors },
|
|
||||||
|
|
||||||
} } },
|
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
|
||||||
|
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||||
} };
|
OutValue = Table[Category.c_str()][Key.data()].as_integer();
|
||||||
std::ofstream ofs { std::string(name) };
|
|
||||||
if (ofs.good()) {
|
|
||||||
ofs << "# This is the BeamMP-Server config file.\n"
|
|
||||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
|
||||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
|
||||||
<< '\n';
|
|
||||||
ofs << tbl << '\n';
|
|
||||||
error("There was no \"" + std::string(ConfigFileName) + "\" file (this is normal for the first time running the server), so one was generated for you. It was automatically filled with the settings from your Server.cfg, if you have one. Please open ServerConfig.toml and ensure your AuthKey and other settings are filled in and correct, then restart the server. The old Server.cfg file will no longer be used and causes a warning if it exists from now on.");
|
|
||||||
mFailed = true;
|
|
||||||
ofs.close();
|
|
||||||
WriteSendErrors(std::string(name));
|
|
||||||
} else {
|
|
||||||
error("Couldn't create " + std::string(name) + ". Check permissions, try again, and contact support if it continues not to work.");
|
|
||||||
mFailed = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseFromFile(std::string_view name) {
|
void TConfig::ParseFromFile(std::string_view name) {
|
||||||
try {
|
try {
|
||||||
toml::table FullTable = toml::parse_file(name);
|
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||||
toml::table GeneralTable = *FullTable["General"].as_table();
|
// GENERAL
|
||||||
if (auto val = GeneralTable[StrDebug].value<bool>(); val.has_value()) {
|
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
||||||
Application::Settings.DebugModeEnabled = val.value();
|
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
||||||
} else {
|
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
||||||
throw std::runtime_error(std::string(StrDebug));
|
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
||||||
}
|
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
if (auto val = GeneralTable[StrPrivate].value<bool>(); val.has_value()) {
|
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
||||||
Application::Settings.Private = val.value();
|
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
||||||
} else {
|
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
||||||
throw std::runtime_error(std::string(StrPrivate));
|
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||||
}
|
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||||
if (auto val = GeneralTable[StrPort].value<int>(); val.has_value()) {
|
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||||
Application::Settings.Port = val.value();
|
TryReadValue(data, "General", StrDownloadThreads, Application::Settings.DownloadThreads);
|
||||||
} else {
|
// Misc
|
||||||
throw std::runtime_error(std::string(StrPort));
|
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||||
}
|
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||||
if (auto val = GeneralTable[StrMaxCars].value<int>(); val.has_value()) {
|
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
||||||
Application::Settings.MaxCars = val.value();
|
// HTTP
|
||||||
} else {
|
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||||
throw std::runtime_error(std::string(StrMaxCars));
|
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||||
}
|
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||||
if (auto val = GeneralTable[StrMaxPlayers].value<int>(); val.has_value()) {
|
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||||
Application::Settings.MaxPlayers = val.value();
|
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
||||||
} else {
|
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
|
||||||
throw std::runtime_error(std::string(StrMaxPlayers));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrMap].value<std::string>(); val.has_value()) {
|
|
||||||
Application::Settings.MapName = val.value();
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error(std::string(StrMap));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrName].value<std::string>(); val.has_value()) {
|
|
||||||
Application::Settings.ServerName = val.value();
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error(std::string(StrName));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrDescription].value<std::string>(); val.has_value()) {
|
|
||||||
Application::Settings.ServerDesc = val.value();
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error(std::string(StrDescription));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrResourceFolder].value<std::string>(); val.has_value()) {
|
|
||||||
Application::Settings.Resource = val.value();
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error(std::string(StrResourceFolder));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrAuthKey].value<std::string>(); val.has_value()) {
|
|
||||||
Application::Settings.Key = val.value();
|
|
||||||
} else {
|
|
||||||
throw std::runtime_error(std::string(StrAuthKey));
|
|
||||||
}
|
|
||||||
// added later, so behaves differently
|
|
||||||
if (auto val = GeneralTable[StrSendErrors].value<bool>(); val.has_value()) {
|
|
||||||
Application::Settings.SendErrors = val.value();
|
|
||||||
} else {
|
|
||||||
// dont throw, instead write it into the file and use default
|
|
||||||
WriteSendErrors(std::string(name));
|
|
||||||
}
|
|
||||||
if (auto val = GeneralTable[StrSendErrorsMessageEnabled].value<bool>(); val.has_value()) {
|
|
||||||
Application::Settings.SendErrorsMessageEnabled = val.value();
|
|
||||||
} else {
|
|
||||||
// no idea what to do here, ignore...?
|
|
||||||
// this entire toml parser sucks and is replaced in the upcoming lua.
|
|
||||||
}
|
|
||||||
} catch (const std::exception& err) {
|
} catch (const std::exception& err) {
|
||||||
error("Error parsing config file value: " + std::string(err.what()));
|
beammp_error("Error parsing config file value: " + std::string(err.what()));
|
||||||
mFailed = true;
|
mFailed = true;
|
||||||
|
Application::SetSubsystemStatus("Config", Application::Status::Bad);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
PrintDebug();
|
PrintDebug();
|
||||||
|
|
||||||
|
// Update in any case
|
||||||
|
FlushToFile();
|
||||||
// all good so far, let's check if there's a key
|
// all good so far, let's check if there's a key
|
||||||
if (Application::Settings.Key.empty()) {
|
if (Application::Settings.Key.empty()) {
|
||||||
error("No AuthKey specified in the \"" + std::string(ConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
|
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;
|
mFailed = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("Config", Application::Status::Good);
|
||||||
|
if (Application::Settings.Key.size() != 36) {
|
||||||
|
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::PrintDebug() {
|
void TConfig::PrintDebug() {
|
||||||
debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
beammp_debugf("{}: {}", StrDebug, Application::Settings.DebugModeEnabled ? "true" : "false");
|
||||||
debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
beammp_debugf("{}: {}", StrPrivate, Application::Settings.Private ? "true" : "false");
|
||||||
debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
beammp_debugf("{}: {}", StrPort, Application::Settings.Port);
|
||||||
debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
beammp_debugf("{}: {}", StrMaxCars, Application::Settings.MaxCars);
|
||||||
debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
beammp_debugf("{}: {}", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||||
debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
beammp_debugf("{}: '{}'", StrMap, Application::Settings.MapName);
|
||||||
debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
beammp_debugf("{}: '{}'", StrName, Application::Settings.ServerName);
|
||||||
debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
beammp_debugf("{}: '{}'", StrDescription, Application::Settings.ServerDesc);
|
||||||
debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
beammp_debugf("{}: {}", StrLogChat, Application::Settings.LogChat ? "true" : "false");
|
||||||
|
beammp_debugf("{}: '{}'", StrResourceFolder, Application::Settings.Resource);
|
||||||
|
beammp_debugf("{}: '{}'", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||||
|
beammp_debugf("{}: '{}'", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||||
|
beammp_debugf("{}: {}", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||||
|
beammp_debugf("{}: '{}'", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||||
|
beammp_debugf("{}: {}", StrDownloadThreads, Application::Settings.DownloadThreads);
|
||||||
|
if (Application::Settings.DownloadThreads < 1) {
|
||||||
|
beammp_warnf("'{}' of <1 is not allowed, will use 1", StrDownloadThreads);
|
||||||
|
}
|
||||||
// special!
|
// special!
|
||||||
debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
beammp_debugf("Key Length: {}", Application::Settings.Key.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConfig::ParseOldFormat() {
|
void TConfig::ParseOldFormat() {
|
||||||
@@ -233,7 +294,7 @@ void TConfig::ParseOldFormat() {
|
|||||||
} else if (Key == "AuthKey") {
|
} else if (Key == "AuthKey") {
|
||||||
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
Application::Settings.Key = Value.substr(1, Value.size() - 3);
|
||||||
} else {
|
} else {
|
||||||
warn("unknown key in old auth file (ignored): " + Key);
|
beammp_warn("unknown key in old auth file (ignored): " + Key);
|
||||||
}
|
}
|
||||||
Str >> std::ws;
|
Str >> std::ws;
|
||||||
}
|
}
|
||||||
|
|||||||
+643
-46
@@ -2,77 +2,674 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "Compat.h"
|
#include "Compat.h"
|
||||||
|
|
||||||
|
#include "Client.h"
|
||||||
|
#include "CustomAssert.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
#include <ctime>
|
#include <ctime>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
|
||||||
|
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("StringStartsWith") {
|
||||||
|
CHECK(StringStartsWith("Hello, World", "Hello"));
|
||||||
|
CHECK(StringStartsWith("Hello, World", "H"));
|
||||||
|
CHECK(StringStartsWith("Hello, World", ""));
|
||||||
|
CHECK(!StringStartsWith("Hello, World", "ello"));
|
||||||
|
CHECK(!StringStartsWith("Hello, World", "World"));
|
||||||
|
CHECK(StringStartsWith("", ""));
|
||||||
|
CHECK(!StringStartsWith("", "hello"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trims leading and trailing spaces, newlines, tabs, etc.
|
||||||
|
static inline std::string TrimString(std::string S) {
|
||||||
|
S.erase(S.begin(), std::find_if(S.begin(), S.end(), [](unsigned char ch) {
|
||||||
|
return !std::isspace(ch);
|
||||||
|
}));
|
||||||
|
S.erase(std::find_if(S.rbegin(), S.rend(), [](unsigned char ch) {
|
||||||
|
return !std::isspace(ch);
|
||||||
|
}).base(),
|
||||||
|
S.end());
|
||||||
|
return S;
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("TrimString") {
|
||||||
|
CHECK(TrimString("hel lo") == "hel lo");
|
||||||
|
CHECK(TrimString(" hel lo") == "hel lo");
|
||||||
|
CHECK(TrimString(" hel lo ") == "hel lo");
|
||||||
|
CHECK(TrimString("hel lo ") == "hel lo");
|
||||||
|
CHECK(TrimString(" hel lo") == "hel lo");
|
||||||
|
CHECK(TrimString("hel lo ") == "hel lo");
|
||||||
|
CHECK(TrimString(" hel lo ") == "hel lo");
|
||||||
|
CHECK(TrimString("\t\thel\nlo\n\n") == "hel\nlo");
|
||||||
|
CHECK(TrimString("\n\thel\tlo\n\t") == "hel\tlo");
|
||||||
|
CHECK(TrimString(" ") == "");
|
||||||
|
CHECK(TrimString(" \t\n\r ") == "");
|
||||||
|
CHECK(TrimString("") == "");
|
||||||
|
}
|
||||||
|
|
||||||
std::string GetDate() {
|
std::string GetDate() {
|
||||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||||
time_t tt = std::chrono::system_clock::to_time_t(now);
|
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||||
tm local_tm {};
|
auto local_tm = std::localtime(&tt);
|
||||||
#ifdef WIN32
|
char buf[30];
|
||||||
localtime_s(&local_tm, &tt);
|
std::string date;
|
||||||
#else // unix
|
if (Application::Settings.DebugModeEnabled) {
|
||||||
localtime_r(&tt, &local_tm);
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
|
||||||
#endif // WIN32
|
date += buf;
|
||||||
std::stringstream date;
|
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
|
||||||
int S = local_tm.tm_sec;
|
auto fraction = now - seconds;
|
||||||
int M = local_tm.tm_min;
|
size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(fraction).count();
|
||||||
int H = local_tm.tm_hour;
|
char fracstr[5];
|
||||||
std::string Secs = (S > 9 ? std::to_string(S) : "0" + std::to_string(S));
|
std::sprintf(fracstr, "%03lu", ms);
|
||||||
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
|
date += fracstr;
|
||||||
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
|
date += "] ";
|
||||||
date
|
} else {
|
||||||
<< "["
|
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
|
||||||
<< local_tm.tm_mday << "/"
|
date += buf;
|
||||||
<< local_tm.tm_mon + 1 << "/"
|
|
||||||
<< local_tm.tm_year + 1900 << " "
|
|
||||||
<< Hour << ":"
|
|
||||||
<< Min << ":"
|
|
||||||
<< Secs
|
|
||||||
<< "] ";
|
|
||||||
/* TODO
|
|
||||||
if (Debug) {
|
|
||||||
date << ThreadName()
|
|
||||||
<< " ";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::BackupOldLog() {
|
||||||
|
fs::path Path = "Server.log";
|
||||||
|
if (fs::exists(Path)) {
|
||||||
|
auto OldLog = Path.filename().stem().string() + ".old.log";
|
||||||
|
try {
|
||||||
|
fs::rename(Path, OldLog);
|
||||||
|
beammp_debug("renamed old log file to '" + OldLog + "'");
|
||||||
|
} 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);
|
||||||
*/
|
*/
|
||||||
return date.str();
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::StartLoggingToFile() {
|
||||||
|
mLogFileStream.open("Server.log");
|
||||||
|
Application::Console().Internal().on_write = [this](const std::string& ToWrite) {
|
||||||
|
// TODO: Sanitize by removing all ansi escape codes (vt100)
|
||||||
|
std::unique_lock Lock(mLogFileStreamMtx);
|
||||||
|
mLogFileStream.write(ToWrite.c_str(), ToWrite.size());
|
||||||
|
mLogFileStream.write("\n", 1);
|
||||||
|
mLogFileStream.flush();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
||||||
|
if (!mIsLuaConsole) {
|
||||||
|
if (!mLuaEngine) {
|
||||||
|
beammp_error("Lua engine not initialized yet, please wait and try again");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mLuaEngine->EnsureStateExists(mDefaultStateId, "Console");
|
||||||
|
mStateId = LuaStateId;
|
||||||
|
mIsLuaConsole = true;
|
||||||
|
if (mStateId != mDefaultStateId) {
|
||||||
|
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:detach`");
|
||||||
|
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:detach`");
|
||||||
|
mCommandline.set_prompt("lua> ");
|
||||||
|
}
|
||||||
|
mCachedRegularHistory = mCommandline.history();
|
||||||
|
mCommandline.set_history(mCachedLuaHistory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::ChangeToRegularConsole() {
|
||||||
|
if (mIsLuaConsole) {
|
||||||
|
mIsLuaConsole = false;
|
||||||
|
if (mStateId != mDefaultStateId) {
|
||||||
|
Application::Console().WriteRaw("Detached from Lua state '" + mStateId + "'.");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw("Detached from Lua.");
|
||||||
|
}
|
||||||
|
mCachedLuaHistory = mCommandline.history();
|
||||||
|
mCommandline.set_history(mCachedRegularHistory);
|
||||||
|
mCommandline.set_prompt("> ");
|
||||||
|
mStateId = mDefaultStateId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t n) {
|
||||||
|
if (n == 0 && args.size() != 0) {
|
||||||
|
Application::Console().WriteRaw("This command expects no arguments.");
|
||||||
|
return false;
|
||||||
|
} else if (args.size() != n) {
|
||||||
|
Application::Console().WriteRaw("Expected " + std::to_string(n) + " argument(s), instead got " + std::to_string(args.size()));
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max) {
|
||||||
|
if (min == max) {
|
||||||
|
return EnsureArgsCount(args, min);
|
||||||
|
} else {
|
||||||
|
if (args.size() > max) {
|
||||||
|
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
|
return false;
|
||||||
|
} else if (args.size() < min) {
|
||||||
|
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0, 1)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (args.size() == 1) {
|
||||||
|
auto NewStateId = args.at(0);
|
||||||
|
beammp_assert(!NewStateId.empty());
|
||||||
|
if (mLuaEngine->HasState(NewStateId)) {
|
||||||
|
ChangeToLuaConsole(NewStateId);
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
||||||
|
}
|
||||||
|
} else if (args.size() == 0) {
|
||||||
|
ChangeToLuaConsole(mDefaultStateId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Help(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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)";
|
||||||
|
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string TConsole::ConcatArgs(const std::vector<std::string>& args, char space) {
|
||||||
|
std::string Result;
|
||||||
|
for (const auto& arg : args) {
|
||||||
|
Result += arg + space;
|
||||||
|
}
|
||||||
|
Result = Result.substr(0, Result.size() - 1); // strip trailing space
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Clear(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0, size_t(-1))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mCommandline.write("\x1b[;H\x1b[2J");
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 1, size_t(-1))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto Name = args.at(0);
|
||||||
|
std::string Reason = "Kicked by server console";
|
||||||
|
if (args.size() > 1) {
|
||||||
|
Reason = ConcatArgs({ args.begin() + 1, args.end() });
|
||||||
|
}
|
||||||
|
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||||
|
bool Kicked = false;
|
||||||
|
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||||
|
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
||||||
|
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
||||||
|
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);
|
||||||
|
Kicked = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (!Kicked) {
|
||||||
|
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw("Kicked player '" + Name + "' for reason: '" + Reason + "'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const std::string& CommandWithArgs) {
|
||||||
|
// Algorithm designed and implemented by Lion Kortlepel (c) 2022
|
||||||
|
// 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 {};
|
||||||
|
if (End_i != std::string::npos) {
|
||||||
|
ArgsStr = CommandWithArgs.substr(End_i);
|
||||||
|
}
|
||||||
|
std::vector<std::string> Args;
|
||||||
|
char* PrevPtr = ArgsStr.data();
|
||||||
|
char* Ptr = ArgsStr.data();
|
||||||
|
const char* End = ArgsStr.data() + ArgsStr.size();
|
||||||
|
while (Ptr != End) {
|
||||||
|
std::string Arg = "";
|
||||||
|
// advance while space
|
||||||
|
while (Ptr != End && std::isspace(*Ptr))
|
||||||
|
++Ptr;
|
||||||
|
PrevPtr = Ptr;
|
||||||
|
// advance while NOT space, also handle quotes
|
||||||
|
while (Ptr != End && !std::isspace(*Ptr)) {
|
||||||
|
// TODO: backslash escaping quotes
|
||||||
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
|
if (*Ptr == Quote) {
|
||||||
|
// seek if there's a closing quote
|
||||||
|
// if there is, go there and continue, otherwise ignore
|
||||||
|
char* Seeker = Ptr + 1;
|
||||||
|
while (Seeker != End && *Seeker != Quote)
|
||||||
|
++Seeker;
|
||||||
|
if (Seeker != End) {
|
||||||
|
// found closing quote
|
||||||
|
Ptr = Seeker;
|
||||||
|
}
|
||||||
|
break; // exit for loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
++Ptr;
|
||||||
|
}
|
||||||
|
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
||||||
|
// remove quotes if enclosed in quotes
|
||||||
|
for (char Quote : { '"', '\'', '`' }) {
|
||||||
|
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||||
|
Arg = Arg.substr(1, Arg.size() - 2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Arg.empty()) {
|
||||||
|
Args.push_back(Arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { Command, Args };
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
Application::Console().WriteRaw("Chat message sent!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_List(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||||
|
Application::Console().WriteRaw("No players online.");
|
||||||
|
} else {
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
auto Str = ss.str();
|
||||||
|
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||||
|
if (!EnsureArgsCount(args, 0)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::stringstream Status;
|
||||||
|
|
||||||
|
size_t CarCount = 0;
|
||||||
|
size_t ConnectedCount = 0;
|
||||||
|
size_t GuestCount = 0;
|
||||||
|
size_t SyncedCount = 0;
|
||||||
|
size_t SyncingCount = 0;
|
||||||
|
size_t MissedPacketQueueSum = 0;
|
||||||
|
int LargestSecondsSinceLastPing = 0;
|
||||||
|
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||||
|
if (!Client.expired()) {
|
||||||
|
auto Locked = Client.lock();
|
||||||
|
CarCount += Locked->GetCarCount();
|
||||||
|
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
||||||
|
GuestCount += Locked->IsGuest() ? 1 : 0;
|
||||||
|
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
||||||
|
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
||||||
|
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
||||||
|
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
||||||
|
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
size_t SystemsStarting = 0;
|
||||||
|
size_t SystemsGood = 0;
|
||||||
|
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 {};
|
||||||
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
|
switch (NameStatusPair.second) {
|
||||||
|
case Application::Status::Good:
|
||||||
|
SystemsGood++;
|
||||||
|
SystemsGoodList += NameStatusPair.first + ", ";
|
||||||
|
break;
|
||||||
|
case Application::Status::Bad:
|
||||||
|
SystemsBad++;
|
||||||
|
SystemsBadList += NameStatusPair.first + ", ";
|
||||||
|
break;
|
||||||
|
case Application::Status::Starting:
|
||||||
|
SystemsStarting++;
|
||||||
|
SystemsStartingList += NameStatusPair.first + ", ";
|
||||||
|
break;
|
||||||
|
case Application::Status::ShuttingDown:
|
||||||
|
SystemsShuttingDown++;
|
||||||
|
SystemsShuttingDownList += NameStatusPair.first + ", ";
|
||||||
|
break;
|
||||||
|
case Application::Status::Shutdown:
|
||||||
|
SystemsShutdown++;
|
||||||
|
SystemsShutdownList += NameStatusPair.first + ", ";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// remove ", " at the end
|
||||||
|
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
|
||||||
|
SystemsGoodList = SystemsGoodList.substr(0, SystemsGoodList.size() - 2);
|
||||||
|
SystemsStartingList = SystemsStartingList.substr(0, SystemsStartingList.size() - 2);
|
||||||
|
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
||||||
|
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||||
|
|
||||||
|
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
||||||
|
|
||||||
|
Status << "BeamMP-Server Status:\n"
|
||||||
|
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
||||||
|
<< "\tSyncing Players: " << SyncingCount << "\n"
|
||||||
|
<< "\tSynced Players: " << SyncedCount << "\n"
|
||||||
|
<< "\tConnected Players: " << ConnectedCount << "\n"
|
||||||
|
<< "\tGuests: " << GuestCount << "\n"
|
||||||
|
<< "\tCars: " << CarCount << "\n"
|
||||||
|
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||||
|
<< "\tLua:\n"
|
||||||
|
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||||
|
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||||
|
<< "\t\tEvent timers: " << mLuaEngine->GetTimedEventsCount() << "\n"
|
||||||
|
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
|
||||||
|
<< "\tSubsystems:\n"
|
||||||
|
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
|
||||||
|
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
|
||||||
|
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
|
||||||
|
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
|
||||||
|
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
||||||
|
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
||||||
|
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||||
|
<< "";
|
||||||
|
|
||||||
|
Application::Console().WriteRaw(Status.str());
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
std::vector<std::shared_ptr<TLuaResult>> NonNilFutures;
|
||||||
|
{ // Futures scope
|
||||||
|
auto Futures = mLuaEngine->TriggerEvent("onConsoleInput", "", cmd);
|
||||||
|
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||||
|
size_t Count = 0;
|
||||||
|
for (auto& Future : Futures) {
|
||||||
|
if (!Future->Error) {
|
||||||
|
++Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& Future : Futures) {
|
||||||
|
if (FutureIsNonNil(Future)) {
|
||||||
|
NonNilFutures.push_back(Future);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (NonNilFutures.size() == 0) {
|
||||||
|
if (!IgnoreNotACommand) {
|
||||||
|
Application::Console().WriteRaw("Error: Unknown command: '" + cmd + "'. Type 'help' to see a list of valid commands.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
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);
|
||||||
|
if (i < NonNilFutures.size() - 1) {
|
||||||
|
Reply << "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Reply << LuaAPI::LuaToString(NonNilFutures[0]->Result);
|
||||||
|
}
|
||||||
|
Application::Console().WriteRaw(Reply.str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TConsole::HandleLuaInternalCommand(const std::string& cmd) {
|
||||||
|
if (cmd == "exit") {
|
||||||
|
ChangeToRegularConsole();
|
||||||
|
} else if (cmd == "queued") {
|
||||||
|
auto QueuedFunctions = LuaAPI::MP::Engine->Debug_GetStateFunctionQueueForState(mStateId);
|
||||||
|
Application::Console().WriteRaw("Pending functions in State '" + mStateId + "'");
|
||||||
|
std::unordered_map<std::string, size_t> FunctionsCount;
|
||||||
|
std::vector<std::string> FunctionsInOrder;
|
||||||
|
while (!QueuedFunctions.empty()) {
|
||||||
|
auto Tuple = QueuedFunctions.front();
|
||||||
|
QueuedFunctions.erase(QueuedFunctions.begin());
|
||||||
|
FunctionsInOrder.push_back(Tuple.FunctionName);
|
||||||
|
FunctionsCount[Tuple.FunctionName] += 1;
|
||||||
|
}
|
||||||
|
std::set<std::string> Uniques;
|
||||||
|
for (const auto& Function : FunctionsInOrder) {
|
||||||
|
if (Uniques.count(Function) == 0) {
|
||||||
|
Uniques.insert(Function);
|
||||||
|
if (FunctionsCount.at(Function) > 1) {
|
||||||
|
Application::Console().WriteRaw(" " + Function + " (" + std::to_string(FunctionsCount.at(Function)) + "x)");
|
||||||
|
} else {
|
||||||
|
Application::Console().WriteRaw(" " + Function);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::Console().WriteRaw("Executed functions waiting to be checked in State '" + mStateId + "'");
|
||||||
|
for (const auto& Function : LuaAPI::MP::Engine->Debug_GetResultsToCheckForState(mStateId)) {
|
||||||
|
Application::Console().WriteRaw(" '" + Function.Function + "' (Ready? " + (Function.Ready ? "Yes" : "No") + ", Error? " + (Function.Error ? "Yes: '" + Function.ErrorMessage + "'" : "No") + ")");
|
||||||
|
}
|
||||||
|
} else if (cmd == "events") {
|
||||||
|
auto Events = LuaAPI::MP::Engine->Debug_GetEventsForState(mStateId);
|
||||||
|
Application::Console().WriteRaw("Registered Events + Handlers for State '" + mStateId + "'");
|
||||||
|
for (const auto& EventHandlerPair : Events) {
|
||||||
|
Application::Console().WriteRaw(" Event '" + EventHandlerPair.first + "'");
|
||||||
|
for (const auto& Handler : EventHandlerPair.second) {
|
||||||
|
Application::Console().WriteRaw(" " + Handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (cmd == "help") {
|
||||||
|
Application::Console().WriteRaw(R"(BeamMP Lua Debugger
|
||||||
|
All commands must be prefixed with a `:`. Non-prefixed commands are interpreted as Lua.
|
||||||
|
|
||||||
|
Commands
|
||||||
|
:exit detaches (exits) from this Lua console
|
||||||
|
:help displays this help
|
||||||
|
:events shows a list of currently registered events
|
||||||
|
:queued shows a list of all pending and queued functions)");
|
||||||
|
} else {
|
||||||
|
beammp_error("internal command '" + cmd + "' is not known");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
TConsole::TConsole() {
|
TConsole::TConsole() {
|
||||||
mCommandline.enable_history();
|
mCommandline.enable_history();
|
||||||
mCommandline.set_history_limit(20);
|
mCommandline.set_history_limit(20);
|
||||||
mCommandline.set_prompt("> ");
|
mCommandline.set_prompt("> ");
|
||||||
bool success = mCommandline.enable_write_to_file("Server.log");
|
BackupOldLog();
|
||||||
if (!success) {
|
|
||||||
error("unable to open file for writing: \"Server.log\"");
|
|
||||||
}
|
|
||||||
mCommandline.on_command = [this](Commandline& c) {
|
mCommandline.on_command = [this](Commandline& c) {
|
||||||
auto cmd = c.get_command();
|
try {
|
||||||
mCommandline.write("> " + cmd);
|
auto TrimmedCmd = c.get_command();
|
||||||
if (cmd == "exit") {
|
TrimmedCmd = TrimString(TrimmedCmd);
|
||||||
info("gracefully shutting down");
|
auto [cmd, args] = ParseCommand(TrimmedCmd);
|
||||||
Application::GracefullyShutdown();
|
mCommandline.write(mCommandline.prompt() + TrimmedCmd);
|
||||||
} else if (cmd == "clear" || cmd == "cls") {
|
if (mIsLuaConsole) {
|
||||||
// TODO: clear screen
|
if (!mLuaEngine) {
|
||||||
} else {
|
beammp_info("Lua not started yet, please try again in a second");
|
||||||
if (mLuaConsole) {
|
} else if (!cmd.empty() && cmd.at(0) == ':') {
|
||||||
mLuaConsole->Execute(cmd);
|
HandleLuaInternalCommand(cmd.substr(1));
|
||||||
|
} else {
|
||||||
|
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
|
||||||
|
while (!Future->Ready) {
|
||||||
|
std::this_thread::yield(); // TODO: Add a timeout
|
||||||
|
}
|
||||||
|
if (Future->Error) {
|
||||||
|
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
error("Lua subsystem not yet initialized, please wait a few seconds and try again");
|
if (!mLuaEngine) {
|
||||||
|
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
|
||||||
|
} else if (cmd == "exit") {
|
||||||
|
beammp_info("gracefully shutting down");
|
||||||
|
Application::GracefullyShutdown();
|
||||||
|
} else if (cmd == "say") {
|
||||||
|
RunAsCommand(TrimmedCmd, true);
|
||||||
|
Command_Say(TrimmedCmd);
|
||||||
|
} else {
|
||||||
|
if (mCommandMap.find(cmd) != mCommandMap.end()) {
|
||||||
|
mCommandMap.at(cmd)(cmd, args);
|
||||||
|
RunAsCommand(TrimmedCmd, true);
|
||||||
|
} else {
|
||||||
|
RunAsCommand(TrimmedCmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||||
|
std::vector<std::string> suggestions;
|
||||||
|
try {
|
||||||
|
auto cmd = TrimString(stub);
|
||||||
|
// beammp_error("yes 1");
|
||||||
|
// beammp_error(stub);
|
||||||
|
if (mIsLuaConsole) { // if lua
|
||||||
|
if (!mLuaEngine) {
|
||||||
|
beammp_info("Lua not started yet, please try again in a second");
|
||||||
|
} else {
|
||||||
|
std::string prefix {};
|
||||||
|
for (size_t i = stub.length(); i > 0; i--) {
|
||||||
|
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') {
|
||||||
|
prefix = stub.substr(0, i);
|
||||||
|
stub = stub.substr(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
|
||||||
|
for (const auto& key : keys) {
|
||||||
|
std::string::size_type n = key.find(stub);
|
||||||
|
if (n == 0) {
|
||||||
|
suggestions.push_back(prefix + key);
|
||||||
|
// beammp_warn(cmd_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else { // if not lua
|
||||||
|
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||||
|
std::string::size_type n = cmd_name.find(stub);
|
||||||
|
if (n == 0) {
|
||||||
|
suggestions.push_back(cmd_name);
|
||||||
|
// beammp_warn(cmd_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||||
|
}
|
||||||
|
return suggestions;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::Write(const std::string& str) {
|
void TConsole::Write(const std::string& str) {
|
||||||
auto ToWrite = GetDate() + str;
|
auto ToWrite = GetDate() + str;
|
||||||
mCommandline.write(ToWrite);
|
mCommandline.write(ToWrite);
|
||||||
// TODO write to logfile, too
|
|
||||||
}
|
|
||||||
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
|
||||||
mLuaConsole = std::make_unique<TLuaFile>(Engine, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TConsole::WriteRaw(const std::string& str) {
|
void TConsole::WriteRaw(const std::string& str) {
|
||||||
mCommandline.write(str);
|
mCommandline.write(str);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
||||||
|
mLuaEngine = &Engine;
|
||||||
|
}
|
||||||
|
|||||||
+89
-29
@@ -3,8 +3,12 @@
|
|||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
//#include "SocketIO.h"
|
//#include "SocketIO.h"
|
||||||
|
#include <rapidjson/document.h>
|
||||||
|
#include <rapidjson/rapidjson.h>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
namespace json = rapidjson;
|
||||||
|
|
||||||
void THeartbeatThread::operator()() {
|
void THeartbeatThread::operator()() {
|
||||||
RegisterThread("Heartbeat");
|
RegisterThread("Heartbeat");
|
||||||
std::string Body;
|
std::string Body;
|
||||||
@@ -15,7 +19,9 @@ void THeartbeatThread::operator()() {
|
|||||||
|
|
||||||
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
|
||||||
bool isAuth = false;
|
bool isAuth = false;
|
||||||
while (!mShutdown) {
|
size_t UpdateReminderCounter = 0;
|
||||||
|
while (!Application::IsShuttingDown()) {
|
||||||
|
++UpdateReminderCounter;
|
||||||
Body = GenerateCall();
|
Body = GenerateCall();
|
||||||
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
// a hot-change occurs when a setting has changed, to update the backend of that change.
|
||||||
auto Now = std::chrono::high_resolution_clock::now();
|
auto Now = std::chrono::high_resolution_clock::now();
|
||||||
@@ -26,57 +32,109 @@ void THeartbeatThread::operator()() {
|
|||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
|
beammp_debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
|
||||||
|
|
||||||
Last = Body;
|
Last = Body;
|
||||||
LastNormalUpdateTime = Now;
|
LastNormalUpdateTime = Now;
|
||||||
if (!Application::Settings.CustomIP.empty())
|
if (!Application::Settings.CustomIP.empty()) {
|
||||||
Body += "&ip=" + Application::Settings.CustomIP;
|
Body += "&ip=" + Application::Settings.CustomIP;
|
||||||
|
}
|
||||||
|
|
||||||
Body += "&pps=" + Application::PPS();
|
Body += "&pps=" + Application::PPS();
|
||||||
|
|
||||||
|
beammp_trace("heartbeat body: '" + Body + "'");
|
||||||
|
|
||||||
auto SentryReportError = [&](const std::string& transaction, int status) {
|
auto SentryReportError = [&](const std::string& transaction, int status) {
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
Sentry.SetContext("heartbeat",
|
Sentry.SetContext("heartbeat",
|
||||||
{ { "response-body", T },
|
{ { "response-body", T },
|
||||||
{ "request-body", Body } });
|
{ "request-body", Body } });
|
||||||
Sentry.SetTransaction(transaction);
|
Sentry.SetTransaction(transaction);
|
||||||
trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
|
beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
|
||||||
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
|
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
|
||||||
};
|
};
|
||||||
|
|
||||||
auto Target = "/heartbeat";
|
auto Target = "/heartbeat";
|
||||||
int ResponseCode = -1;
|
unsigned int ResponseCode = 0;
|
||||||
T = Http::POST(Application::GetBackendHostname(), Target, {}, Body, false, &ResponseCode);
|
|
||||||
|
|
||||||
if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) {
|
json::Document Doc;
|
||||||
trace("got " + T + " from backend");
|
bool Ok = false;
|
||||||
SentryReportError(Application::GetBackendHostname() + Target, ResponseCode);
|
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
|
||||||
T = Http::POST(Application::GetBackup1Hostname(), Target, {}, Body, false, &ResponseCode);
|
beammp_trace(T);
|
||||||
if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) {
|
Doc.Parse(T.data(), T.size());
|
||||||
SentryReportError(Application::GetBackup1Hostname() + Target, ResponseCode);
|
if (Doc.HasParseError() || !Doc.IsObject()) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
if (!Application::Settings.Private) {
|
||||||
T = Http::POST(Application::GetBackup2Hostname(), Target, {}, Body, false, &ResponseCode);
|
beammp_error("Backend response failed to parse as valid json");
|
||||||
if ((T.substr(0, 2) != "20" && ResponseCode != 200) || ResponseCode != 200) {
|
beammp_trace("Response was: `" + T + "`");
|
||||||
warn("Backend system refused server! Server will not show in the public server list.");
|
|
||||||
isAuth = false;
|
|
||||||
SentryReportError(Application::GetBackup2Hostname() + Target, ResponseCode);
|
|
||||||
}
|
}
|
||||||
|
Sentry.SetContext("JSON Response", { { "reponse", T } });
|
||||||
|
SentryReportError(Url + Target, ResponseCode);
|
||||||
|
} else if (ResponseCode != 200) {
|
||||||
|
SentryReportError(Url + Target, ResponseCode);
|
||||||
|
} else {
|
||||||
|
// all ok
|
||||||
|
Ok = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
|
}
|
||||||
|
std::string Status {};
|
||||||
|
std::string Code {};
|
||||||
|
std::string Message {};
|
||||||
|
const auto StatusKey = "status";
|
||||||
|
const auto CodeKey = "code";
|
||||||
|
const auto MessageKey = "msg";
|
||||||
|
|
||||||
|
if (Ok) {
|
||||||
|
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
|
||||||
|
Status = Doc[StatusKey].GetString();
|
||||||
|
} else {
|
||||||
|
Sentry.SetContext("JSON Response", { { StatusKey, "invalid string / missing" } });
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
|
||||||
|
Code = Doc[CodeKey].GetString();
|
||||||
|
} else {
|
||||||
|
Sentry.SetContext("JSON Response", { { CodeKey, "invalid string / missing" } });
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
|
||||||
|
Message = Doc[MessageKey].GetString();
|
||||||
|
} else {
|
||||||
|
Sentry.SetContext("JSON Response", { { MessageKey, "invalid string / missing" } });
|
||||||
|
Ok = false;
|
||||||
|
}
|
||||||
|
if (!Ok) {
|
||||||
|
beammp_error("Missing/invalid json members in backend response");
|
||||||
|
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!Application::Settings.Private) {
|
||||||
|
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isAuth) {
|
if (Ok && !isAuth && !Application::Settings.Private) {
|
||||||
if (T == "2000") {
|
if (Status == "2000") {
|
||||||
info(("Authenticated!"));
|
beammp_info(("Authenticated! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
} else if (T == "200") {
|
} else if (Status == "200") {
|
||||||
info(("Resumed authenticated session!"));
|
beammp_info(("Resumed authenticated session! " + Message));
|
||||||
isAuth = true;
|
isAuth = true;
|
||||||
|
} else {
|
||||||
|
if (Message.empty()) {
|
||||||
|
Message = "Backend didn't provide a reason.";
|
||||||
|
}
|
||||||
|
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (isAuth || Application::Settings.Private) {
|
||||||
//SocketIO::Get().SetAuthenticated(isAuth);
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
|
||||||
|
}
|
||||||
|
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
|
||||||
|
Application::CheckForUpdates();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,8 +147,8 @@ std::string THeartbeatThread::GenerateCall() {
|
|||||||
<< "&port=" << Application::Settings.Port
|
<< "&port=" << Application::Settings.Port
|
||||||
<< "&map=" << Application::Settings.MapName
|
<< "&map=" << Application::Settings.MapName
|
||||||
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
<< "&private=" << (Application::Settings.Private ? "true" : "false")
|
||||||
<< "&version=" << Application::ServerVersion()
|
<< "&version=" << Application::ServerVersionString()
|
||||||
<< "&clientversion=" << Application::ClientVersion()
|
<< "&clientversion=" << Application::ClientVersionString()
|
||||||
<< "&name=" << Application::Settings.ServerName
|
<< "&name=" << Application::Settings.ServerName
|
||||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||||
@@ -102,11 +160,13 @@ std::string THeartbeatThread::GenerateCall() {
|
|||||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||||
: mResourceManager(ResourceManager)
|
: mResourceManager(ResourceManager)
|
||||||
, mServer(Server) {
|
, mServer(Server) {
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||||
if (mThread.joinable()) {
|
if (mThread.joinable()) {
|
||||||
mShutdown = true;
|
|
||||||
mThread.join();
|
mThread.join();
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("Heartbeat", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
|
|||||||
+959
-78
File diff suppressed because it is too large
Load Diff
@@ -1,847 +0,0 @@
|
|||||||
#include "TLuaFile.h"
|
|
||||||
#include "Client.h"
|
|
||||||
#include "Common.h"
|
|
||||||
#include "CustomAssert.h"
|
|
||||||
#include "Defer.h"
|
|
||||||
#include "TLuaEngine.h"
|
|
||||||
#include "TNetwork.h"
|
|
||||||
#include "TServer.h"
|
|
||||||
|
|
||||||
#include <future>
|
|
||||||
#include <thread>
|
|
||||||
|
|
||||||
// TODO: REWRITE
|
|
||||||
|
|
||||||
void SendError(TLuaEngine& Engine, lua_State* L, const std::string& msg);
|
|
||||||
std::any CallFunction(TLuaFile* lua, const std::string& FuncName, std::shared_ptr<TLuaArg> Arg);
|
|
||||||
std::any TriggerLuaEvent(TLuaEngine& Engine, const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
|
||||||
|
|
||||||
extern TLuaEngine* TheEngine;
|
|
||||||
|
|
||||||
static TLuaEngine& Engine() {
|
|
||||||
Assert(TheEngine);
|
|
||||||
return *TheEngine;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::shared_ptr<TLuaArg> CreateArg(lua_State* L, int T, int S) {
|
|
||||||
if (S > T)
|
|
||||||
return nullptr;
|
|
||||||
std::shared_ptr<TLuaArg> temp(new TLuaArg);
|
|
||||||
for (int C = S; C <= T; C++) {
|
|
||||||
if (lua_isstring(L, C)) {
|
|
||||||
temp->args.emplace_back(std::string(lua_tostring(L, C)));
|
|
||||||
} else if (lua_isinteger(L, C)) {
|
|
||||||
temp->args.emplace_back(int(lua_tointeger(L, C)));
|
|
||||||
} else if (lua_isboolean(L, C)) {
|
|
||||||
temp->args.emplace_back(bool(lua_toboolean(L, C)));
|
|
||||||
} else if (lua_isnumber(L, C)) {
|
|
||||||
temp->args.emplace_back(float(lua_tonumber(L, C)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return temp;
|
|
||||||
}
|
|
||||||
void ClearStack(lua_State* L) {
|
|
||||||
lua_settop(L, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::any Trigger(TLuaFile* lua, const std::string& R, std::shared_ptr<TLuaArg> arg) {
|
|
||||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
|
||||||
std::packaged_task<std::any(std::shared_ptr<TLuaArg>)> task([lua, R](std::shared_ptr<TLuaArg> arg) { return CallFunction(lua, R, arg); });
|
|
||||||
std::future<std::any> f1 = task.get_future();
|
|
||||||
std::thread t(std::move(task), arg);
|
|
||||||
t.detach();
|
|
||||||
auto status = f1.wait_for(std::chrono::seconds(5));
|
|
||||||
if (status != std::future_status::timeout)
|
|
||||||
return f1.get();
|
|
||||||
SendError(lua->Engine(), lua->GetState(), R + " took too long to respond");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::any FutureWait(TLuaFile* lua, const std::string& R, std::shared_ptr<TLuaArg> arg, bool Wait) {
|
|
||||||
Assert(lua);
|
|
||||||
std::packaged_task<std::any(std::shared_ptr<TLuaArg>)> task([lua, R](std::shared_ptr<TLuaArg> arg) { return Trigger(lua, R, arg); });
|
|
||||||
std::future<std::any> f1 = task.get_future();
|
|
||||||
std::thread t(std::move(task), arg);
|
|
||||||
t.detach();
|
|
||||||
int T = 0;
|
|
||||||
if (Wait)
|
|
||||||
T = 6;
|
|
||||||
auto status = f1.wait_for(std::chrono::seconds(T));
|
|
||||||
if (status != std::future_status::timeout)
|
|
||||||
return f1.get();
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait) {
|
|
||||||
std::any R;
|
|
||||||
int Ret = 0;
|
|
||||||
for (auto& Script : Engine().LuaFiles()) {
|
|
||||||
if (Script->IsRegistered(Event)) {
|
|
||||||
if (local) {
|
|
||||||
if (Script->GetPluginName() == Caller->GetPluginName()) {
|
|
||||||
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
|
||||||
if (R.type() == typeid(int)) {
|
|
||||||
if (std::any_cast<int>(R))
|
|
||||||
Ret++;
|
|
||||||
} else if (Event == "onPlayerAuth")
|
|
||||||
return R;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
|
||||||
if (R.type() == typeid(int)) {
|
|
||||||
if (std::any_cast<int>(R))
|
|
||||||
Ret++;
|
|
||||||
} else if (Event == "onPlayerAuth")
|
|
||||||
return R;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ConsoleCheck(lua_State* L, int r) {
|
|
||||||
if (r != LUA_OK) {
|
|
||||||
std::string msg = lua_tostring(L, -1);
|
|
||||||
warn(("_Console | ") + msg);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool CheckLua(lua_State* L, int r) {
|
|
||||||
if (r != LUA_OK) {
|
|
||||||
std::string msg = "Unknown";
|
|
||||||
if (lua_isstring(L, -1)) {
|
|
||||||
auto MsgMaybe = lua_tostring(L, -1);
|
|
||||||
if (MsgMaybe) {
|
|
||||||
msg = MsgMaybe;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
auto MaybeS = Engine().GetScript(L);
|
|
||||||
if (MaybeS.has_value()) {
|
|
||||||
TLuaFile& S = MaybeS.value();
|
|
||||||
std::string a = fs::path(S.GetFileName()).filename().string();
|
|
||||||
warn(a + " | " + msg);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// This should never happen since it's not directly called from "userspace" Lua.
|
|
||||||
AssertNotReachable();
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_RegisterEvent(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
auto MaybeScript = Engine().GetScript(L);
|
|
||||||
if (!MaybeScript.has_value()) {
|
|
||||||
error("RegisterEvent: There is no script associated with this lua_State.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
TLuaFile& Script = MaybeScript.value();
|
|
||||||
if (Args == 2 && lua_isstring(L, 1) && lua_isstring(L, 2)) {
|
|
||||||
Script.RegisterEvent(lua_tostring(L, 1), lua_tostring(L, 2));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, "RegisterEvent invalid argument count expected 2 got " + std::to_string(Args));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_TriggerEventL(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
auto MaybeScript = Engine().GetScript(L);
|
|
||||||
if (!MaybeScript.has_value()) {
|
|
||||||
error("TriggerEvent: There is no script associated with this lua_State.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
TLuaFile& Script = MaybeScript.value();
|
|
||||||
if (Args > 0) {
|
|
||||||
if (lua_isstring(L, 1)) {
|
|
||||||
TriggerLuaEvent(lua_tostring(L, 1), true, &Script, CreateArg(L, Args, 2), false);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("TriggerLocalEvent wrong argument [1] need string"));
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, ("TriggerLocalEvent not enough arguments expected 1 got 0"));
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_TriggerEventG(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
auto MaybeScript = Engine().GetScript(L);
|
|
||||||
if (!MaybeScript.has_value()) {
|
|
||||||
error("TriggerGlobalEvent: There is no script associated with this lua_State.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
TLuaFile& Script = MaybeScript.value();
|
|
||||||
if (Args > 0) {
|
|
||||||
if (lua_isstring(L, 1)) {
|
|
||||||
TriggerLuaEvent(lua_tostring(L, 1), false, &Script, CreateArg(L, Args, 2), false);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("TriggerGlobalEvent wrong argument [1] need string"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("TriggerGlobalEvent not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void SafeExecution(TLuaFile* lua, const std::string& FuncName) {
|
|
||||||
lua_State* luaState = lua->GetState();
|
|
||||||
lua_getglobal(luaState, FuncName.c_str());
|
|
||||||
if (lua_isfunction(luaState, -1)) {
|
|
||||||
int R = lua_pcall(luaState, 0, 0, 0);
|
|
||||||
CheckLua(luaState, R);
|
|
||||||
}
|
|
||||||
ClearStack(luaState);
|
|
||||||
}
|
|
||||||
|
|
||||||
void ExecuteAsync(TLuaFile* lua, const std::string& FuncName) {
|
|
||||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
|
||||||
SafeExecution(lua, FuncName);
|
|
||||||
}
|
|
||||||
|
|
||||||
void CallAsync(TLuaFile* lua, const std::string& Func, int U) {
|
|
||||||
lua->SetStopThread(false);
|
|
||||||
int D = 1000 / U;
|
|
||||||
while (!lua->GetStopThread()) {
|
|
||||||
ExecuteAsync(lua, Func);
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(D));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_StopThread(lua_State* L) {
|
|
||||||
auto MaybeScript = Engine().GetScript(L);
|
|
||||||
if (!MaybeScript.has_value()) {
|
|
||||||
error("StopThread: There is no script associated with this lua_State.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
// ugly, but whatever, this is very safe
|
|
||||||
MaybeScript.value().get().SetStopThread(true);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_CreateThread(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
if (Args > 1) {
|
|
||||||
if (lua_isstring(L, 1)) {
|
|
||||||
std::string STR = lua_tostring(L, 1);
|
|
||||||
if (lua_isinteger(L, 2) || lua_isnumber(L, 2)) {
|
|
||||||
int U = int(lua_tointeger(L, 2));
|
|
||||||
if (U > 0 && U < 501) {
|
|
||||||
auto MaybeScript = Engine().GetScript(L);
|
|
||||||
if (!MaybeScript.has_value()) {
|
|
||||||
error("CreateThread: There is no script associated with this lua_State.");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
TLuaFile& Script = MaybeScript.value();
|
|
||||||
std::thread t1(CallAsync, &Script, STR, U);
|
|
||||||
t1.detach();
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("CreateThread wrong argument [2] number must be between 1 and 500"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("CreateThread wrong argument [2] need number"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("CreateThread wrong argument [1] need string"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("CreateThread not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_Sleep(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int t = int(lua_tonumber(L, 1));
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(t));
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, ("Sleep not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
|
||||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
|
||||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
|
||||||
ReadLock Lock(Server.GetClientMutex());
|
|
||||||
if (!CPtr.expired()) {
|
|
||||||
auto C = CPtr.lock();
|
|
||||||
if (C->GetID() == ID) {
|
|
||||||
MaybeClient = CPtr;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return MaybeClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_isConnected(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired())
|
|
||||||
lua_pushboolean(L, MaybeClient.value().lock()->IsConnected());
|
|
||||||
else
|
|
||||||
return 0;
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, ("isConnected not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetPlayerName(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired())
|
|
||||||
lua_pushstring(L, MaybeClient.value().lock()->GetName().c_str());
|
|
||||||
else
|
|
||||||
return 0;
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, ("GetPlayerName not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetPlayerCount(lua_State* L) {
|
|
||||||
lua_pushinteger(L, Engine().Server().ClientCount());
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetGuest(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired())
|
|
||||||
lua_pushboolean(L, MaybeClient.value().lock()->IsGuest());
|
|
||||||
else
|
|
||||||
return 0;
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, "GetGuest not enough arguments");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetAllPlayers(lua_State* L) {
|
|
||||||
lua_newtable(L);
|
|
||||||
Engine().Server().ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
|
||||||
std::shared_ptr<TClient> Client;
|
|
||||||
{
|
|
||||||
ReadLock Lock(Engine().Server().GetClientMutex());
|
|
||||||
if (ClientPtr.expired())
|
|
||||||
return true;
|
|
||||||
Client = ClientPtr.lock();
|
|
||||||
}
|
|
||||||
lua_pushinteger(L, Client->GetID());
|
|
||||||
lua_pushstring(L, Client->GetName().c_str());
|
|
||||||
lua_settable(L, -3);
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
if (Engine().Server().ClientCount() == 0)
|
|
||||||
return 0;
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetIdentifiers(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), int(lua_tonumber(L, 1)));
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
|
||||||
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
|
|
||||||
if (IDs.empty())
|
|
||||||
return 0;
|
|
||||||
lua_newtable(L);
|
|
||||||
for (const std::string& ID : IDs) {
|
|
||||||
lua_pushstring(L, ID.substr(0, ID.find(':')).c_str());
|
|
||||||
lua_pushstring(L, ID.c_str());
|
|
||||||
lua_settable(L, -3);
|
|
||||||
}
|
|
||||||
} else
|
|
||||||
return 0;
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, "lua_GetIdentifiers wrong arguments");
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_GetCars(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
|
||||||
auto Client = MaybeClient.value().lock();
|
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
|
||||||
{ // Vehicle Data Lock Scope
|
|
||||||
auto LockedData = Client->GetAllCars();
|
|
||||||
VehicleData = *LockedData.VehicleData;
|
|
||||||
} // End Vehicle Data Lock Scope
|
|
||||||
if (VehicleData.empty())
|
|
||||||
return 0;
|
|
||||||
lua_newtable(L);
|
|
||||||
for (const auto& v : VehicleData) {
|
|
||||||
lua_pushinteger(L, v.ID());
|
|
||||||
lua_pushstring(L, v.Data().substr(3).c_str());
|
|
||||||
lua_settable(L, -3);
|
|
||||||
}
|
|
||||||
} else
|
|
||||||
return 0;
|
|
||||||
} else {
|
|
||||||
SendError(Engine(), L, ("GetPlayerVehicles wrong arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_dropPlayer(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (!MaybeClient || MaybeClient.value().expired())
|
|
||||||
return 0;
|
|
||||||
std::string Reason;
|
|
||||||
if (Args > 1 && lua_isstring(L, 2)) {
|
|
||||||
Reason = std::string((" Reason : ")) + lua_tostring(L, 2);
|
|
||||||
}
|
|
||||||
auto c = MaybeClient.value().lock();
|
|
||||||
Engine().Network().Respond(*c, "C:Server:You have been Kicked from the server! " + Reason, true);
|
|
||||||
c->SetStatus(-2);
|
|
||||||
info(("Closing socket due to kick"));
|
|
||||||
CloseSocketProper(c->GetTCPSock());
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("DropPlayer not enough arguments"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_sendChat(lua_State* L) {
|
|
||||||
if (lua_isinteger(L, 1) || lua_isnumber(L, 1)) {
|
|
||||||
if (lua_isstring(L, 2)) {
|
|
||||||
int ID = int(lua_tointeger(L, 1));
|
|
||||||
if (ID == -1) {
|
|
||||||
auto msg = std::string(lua_tostring(L, 2));
|
|
||||||
LogChatMessage("<Server> (to everyone) ", -1, msg);
|
|
||||||
std::string Packet = "C:Server: " + msg;
|
|
||||||
Engine().Network().SendToAll(nullptr, Packet, true, true);
|
|
||||||
} else {
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
|
||||||
auto c = MaybeClient.value().lock();
|
|
||||||
if (!c->IsSynced())
|
|
||||||
return 0;
|
|
||||||
auto msg = std::string(lua_tostring(L, 2));
|
|
||||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, msg);
|
|
||||||
std::string Packet = "C:Server: " + msg;
|
|
||||||
Engine().Network().Respond(*c, Packet, true);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("SendChatMessage invalid argument [1] invalid ID"));
|
|
||||||
}
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("SendChatMessage invalid argument [2] expected string"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("SendChatMessage invalid argument [1] expected number"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_RemoveVehicle(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
if (Args != 2) {
|
|
||||||
SendError(Engine(), L, ("RemoveVehicle invalid argument count expected 2 got ") + std::to_string(Args));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if ((lua_isinteger(L, 1) || lua_isnumber(L, 1)) && (lua_isinteger(L, 2) || lua_isnumber(L, 2))) {
|
|
||||||
int PID = int(lua_tointeger(L, 1));
|
|
||||||
int VID = int(lua_tointeger(L, 2));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), PID);
|
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
|
||||||
SendError(Engine(), L, ("RemoveVehicle invalid Player ID"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
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, Destroy, true, true);
|
|
||||||
c->DeleteCar(VID);
|
|
||||||
}
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("RemoveVehicle invalid argument expected number"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_HWID(lua_State* L) {
|
|
||||||
lua_pushinteger(L, -1);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_RemoteEvent(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
if (Args != 3) {
|
|
||||||
SendError(Engine(), L, ("TriggerClientEvent invalid argument count expected 3 got ") + std::to_string(Args));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!lua_isnumber(L, 1)) {
|
|
||||||
SendError(Engine(), L, ("TriggerClientEvent invalid argument [1] expected number"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!lua_isstring(L, 2)) {
|
|
||||||
SendError(Engine(), L, ("TriggerClientEvent invalid argument [2] expected string"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!lua_isstring(L, 3)) {
|
|
||||||
SendError(Engine(), L, ("TriggerClientEvent invalid argument [3] expected string"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
int ID = int(lua_tointeger(L, 1));
|
|
||||||
std::string Packet = "E:" + std::string(lua_tostring(L, 2)) + ":" + std::string(lua_tostring(L, 3));
|
|
||||||
if (ID == -1)
|
|
||||||
Engine().Network().SendToAll(nullptr, Packet, true, true);
|
|
||||||
else {
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
|
||||||
SendError(Engine(), L, ("TriggerClientEvent invalid Player ID"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
auto c = MaybeClient.value().lock();
|
|
||||||
Engine().Network().Respond(*c, Packet, true);
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_ServerExit(lua_State*) {
|
|
||||||
Application::GracefullyShutdown();
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_Set(lua_State* L) {
|
|
||||||
int Args = lua_gettop(L);
|
|
||||||
if (Args != 2) {
|
|
||||||
SendError(Engine(), L, ("set invalid argument count expected 2 got ") + std::to_string(Args));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
if (!lua_isnumber(L, 1)) {
|
|
||||||
SendError(Engine(), L, ("set invalid argument [1] expected number"));
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
auto MaybeSrc = Engine().GetScript(L);
|
|
||||||
std::string Name;
|
|
||||||
if (!MaybeSrc.has_value()) {
|
|
||||||
Name = ("_Console");
|
|
||||||
} else {
|
|
||||||
Name = MaybeSrc.value().get().GetPluginName();
|
|
||||||
}
|
|
||||||
int C = int(lua_tointeger(L, 1));
|
|
||||||
switch (C) {
|
|
||||||
case 0: //debug
|
|
||||||
if (lua_isboolean(L, 2)) {
|
|
||||||
Application::Settings.DebugModeEnabled = lua_toboolean(L, 2);
|
|
||||||
info(Name + (" | Debug -> ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected boolean for ID : 0"));
|
|
||||||
break;
|
|
||||||
case 1: //private
|
|
||||||
if (lua_isboolean(L, 2)) {
|
|
||||||
Application::Settings.Private = lua_toboolean(L, 2);
|
|
||||||
info(Name + (" | Private -> ") + (Application::Settings.Private ? "true" : "false"));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected boolean for ID : 1"));
|
|
||||||
break;
|
|
||||||
case 2: //max cars
|
|
||||||
if (lua_isnumber(L, 2)) {
|
|
||||||
Application::Settings.MaxCars = int(lua_tointeger(L, 2));
|
|
||||||
info(Name + (" | MaxCars -> ") + std::to_string(Application::Settings.MaxCars));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected number for ID : 2"));
|
|
||||||
break;
|
|
||||||
case 3: //max players
|
|
||||||
if (lua_isnumber(L, 2)) {
|
|
||||||
Application::Settings.MaxPlayers = int(lua_tointeger(L, 2));
|
|
||||||
info(Name + (" | MaxPlayers -> ") + std::to_string(Application::Settings.MaxPlayers));
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected number for ID : 3"));
|
|
||||||
break;
|
|
||||||
case 4: //Map
|
|
||||||
if (lua_isstring(L, 2)) {
|
|
||||||
Application::Settings.MapName = lua_tostring(L, 2);
|
|
||||||
info(Name + (" | MapName -> ") + Application::Settings.MapName);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 4"));
|
|
||||||
break;
|
|
||||||
case 5: //Name
|
|
||||||
if (lua_isstring(L, 2)) {
|
|
||||||
Application::Settings.ServerName = lua_tostring(L, 2);
|
|
||||||
info(Name + (" | ServerName -> ") + Application::Settings.ServerName);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 5"));
|
|
||||||
break;
|
|
||||||
case 6: //Desc
|
|
||||||
if (lua_isstring(L, 2)) {
|
|
||||||
Application::Settings.ServerDesc = lua_tostring(L, 2);
|
|
||||||
info(Name + (" | ServerDesc -> ") + Application::Settings.ServerDesc);
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 6"));
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
warn(("Invalid config ID : ") + std::to_string(C));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
int lua_Print(lua_State* L) {
|
|
||||||
int Arg = lua_gettop(L);
|
|
||||||
std::string to_print;
|
|
||||||
for (int i = 1; i <= Arg; i++) {
|
|
||||||
if (lua_isstring(L, i)) {
|
|
||||||
to_print += lua_tostring(L, i);
|
|
||||||
} else if (lua_isinteger(L, i)) {
|
|
||||||
to_print += std::to_string(lua_tointeger(L, 1));
|
|
||||||
} else if (lua_isnumber(L, i)) {
|
|
||||||
to_print += std::to_string(lua_tonumber(L, 1));
|
|
||||||
} else if (lua_isboolean(L, i)) {
|
|
||||||
to_print += lua_toboolean(L, i) ? "true" : "false";
|
|
||||||
} else if (lua_isfunction(L, i)) {
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << std::hex << reinterpret_cast<const void*>(lua_tocfunction(L, i));
|
|
||||||
to_print += "function: " + ss.str();
|
|
||||||
} else if (lua_istable(L, i)) {
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << std::hex << reinterpret_cast<const void*>(lua_topointer(L, i));
|
|
||||||
to_print += "table: " + ss.str();
|
|
||||||
} else if (lua_isnoneornil(L, i)) {
|
|
||||||
to_print += "nil";
|
|
||||||
} else if (lua_isthread(L, i)) {
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << std::hex << reinterpret_cast<const void*>(lua_tothread(L, i));
|
|
||||||
to_print += "thread: " + ss.str();
|
|
||||||
} else {
|
|
||||||
to_print += "(unknown)";
|
|
||||||
}
|
|
||||||
if (i + 1 <= Arg) {
|
|
||||||
to_print += "\t";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
luaprint(to_print);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_TempFix(lua_State* L);
|
|
||||||
|
|
||||||
void TLuaFile::Init(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote) {
|
|
||||||
auto Lock = std::unique_lock(mInitMutex);
|
|
||||||
// set global engine for lua_* functions
|
|
||||||
if (!TheEngine) {
|
|
||||||
TheEngine = &mEngine;
|
|
||||||
}
|
|
||||||
Assert(mLuaState);
|
|
||||||
if (!PluginName.empty()) {
|
|
||||||
SetPluginName(PluginName);
|
|
||||||
}
|
|
||||||
if (!FileName.empty()) {
|
|
||||||
SetFileName(FileName);
|
|
||||||
}
|
|
||||||
SetLastWrite(LastWrote);
|
|
||||||
Load();
|
|
||||||
}
|
|
||||||
|
|
||||||
TLuaFile::TLuaFile(TLuaEngine& Engine, bool Console)
|
|
||||||
: mEngine(Engine)
|
|
||||||
, mLuaState(luaL_newstate()) {
|
|
||||||
if (Console) {
|
|
||||||
mConsole = Console;
|
|
||||||
Load();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::Execute(const std::string& Command) {
|
|
||||||
if (ConsoleCheck(mLuaState, luaL_dostring(mLuaState, Command.c_str()))) {
|
|
||||||
lua_settop(mLuaState, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::Reload() {
|
|
||||||
if (CheckLua(mLuaState, luaL_dofile(mLuaState, mFileName.c_str()))) {
|
|
||||||
CallFunction(this, ("onInit"), nullptr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TLuaFile::GetOrigin() {
|
|
||||||
return fs::path(GetFileName()).filename().string();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::any CallFunction(TLuaFile* lua, const std::string& FuncName, std::shared_ptr<TLuaArg> Arg) {
|
|
||||||
lua_State* luaState = lua->GetState();
|
|
||||||
lua_getglobal(luaState, FuncName.c_str());
|
|
||||||
if (lua_isfunction(luaState, -1)) {
|
|
||||||
int Size = 0;
|
|
||||||
if (Arg != nullptr) {
|
|
||||||
Size = int(Arg->args.size());
|
|
||||||
Arg->PushArgs(luaState);
|
|
||||||
}
|
|
||||||
int R = lua_pcall(luaState, Size, 1, 0);
|
|
||||||
if (CheckLua(luaState, R)) {
|
|
||||||
if (lua_isnumber(luaState, -1)) {
|
|
||||||
auto ret = int(lua_tointeger(luaState, -1));
|
|
||||||
ClearStack(luaState);
|
|
||||||
return ret;
|
|
||||||
} else if (lua_isstring(luaState, -1)) {
|
|
||||||
auto ret = std::string(lua_tostring(luaState, -1));
|
|
||||||
ClearStack(luaState);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ClearStack(luaState);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::SetPluginName(const std::string& Name) {
|
|
||||||
mPluginName = Name;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::SetFileName(const std::string& Name) {
|
|
||||||
mFileName = Name;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::Load() {
|
|
||||||
Assert(mLuaState);
|
|
||||||
luaL_openlibs(mLuaState);
|
|
||||||
lua_register(mLuaState, "GetPlayerIdentifiers", lua_GetIdentifiers);
|
|
||||||
lua_register(mLuaState, "TriggerGlobalEvent", lua_TriggerEventG);
|
|
||||||
lua_register(mLuaState, "TriggerLocalEvent", lua_TriggerEventL);
|
|
||||||
lua_register(mLuaState, "TriggerClientEvent", lua_RemoteEvent);
|
|
||||||
lua_register(mLuaState, "GetPlayerCount", lua_GetPlayerCount);
|
|
||||||
lua_register(mLuaState, "isPlayerConnected", lua_isConnected);
|
|
||||||
lua_register(mLuaState, "RegisterEvent", lua_RegisterEvent);
|
|
||||||
lua_register(mLuaState, "GetPlayerName", lua_GetPlayerName);
|
|
||||||
lua_register(mLuaState, "RemoveVehicle", lua_RemoveVehicle);
|
|
||||||
lua_register(mLuaState, "GetPlayerDiscordID", lua_TempFix);
|
|
||||||
lua_register(mLuaState, "CreateThread", lua_CreateThread);
|
|
||||||
lua_register(mLuaState, "GetPlayerVehicles", lua_GetCars);
|
|
||||||
lua_register(mLuaState, "SendChatMessage", lua_sendChat);
|
|
||||||
lua_register(mLuaState, "GetPlayers", lua_GetAllPlayers);
|
|
||||||
lua_register(mLuaState, "GetPlayerGuest", lua_GetGuest);
|
|
||||||
lua_register(mLuaState, "StopThread", lua_StopThread);
|
|
||||||
lua_register(mLuaState, "DropPlayer", lua_dropPlayer);
|
|
||||||
lua_register(mLuaState, "GetPlayerHWID", lua_HWID);
|
|
||||||
lua_register(mLuaState, "exit", lua_ServerExit);
|
|
||||||
lua_register(mLuaState, "Sleep", lua_Sleep);
|
|
||||||
lua_register(mLuaState, "print", lua_Print);
|
|
||||||
lua_register(mLuaState, "Set", lua_Set);
|
|
||||||
if (!mConsole)
|
|
||||||
Reload();
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::RegisterEvent(const std::string& Event, const std::string& FunctionName) {
|
|
||||||
mRegisteredEvents.insert(std::make_pair(Event, FunctionName));
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::UnRegisterEvent(const std::string& Event) {
|
|
||||||
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
|
|
||||||
if (a.first == Event) {
|
|
||||||
mRegisteredEvents.erase(a);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TLuaFile::IsRegistered(const std::string& Event) {
|
|
||||||
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
|
|
||||||
if (a.first == Event)
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TLuaFile::GetRegistered(const std::string& Event) const {
|
|
||||||
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
|
|
||||||
if (a.first == Event)
|
|
||||||
return a.second;
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TLuaFile::GetFileName() const {
|
|
||||||
return mFileName;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string TLuaFile::GetPluginName() const {
|
|
||||||
return mPluginName;
|
|
||||||
}
|
|
||||||
|
|
||||||
lua_State* TLuaFile::GetState() {
|
|
||||||
return mLuaState;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lua_State* TLuaFile::GetState() const {
|
|
||||||
return mLuaState;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaFile::SetLastWrite(fs::file_time_type time) {
|
|
||||||
mLastWrote = time;
|
|
||||||
}
|
|
||||||
fs::file_time_type TLuaFile::GetLastWrite() {
|
|
||||||
return mLastWrote;
|
|
||||||
}
|
|
||||||
|
|
||||||
TLuaFile::~TLuaFile() {
|
|
||||||
info("closing lua state");
|
|
||||||
lua_close(mLuaState);
|
|
||||||
}
|
|
||||||
|
|
||||||
void SendError(TLuaEngine& Engine, lua_State* L, const std::string& msg) {
|
|
||||||
Assert(L);
|
|
||||||
auto MaybeS = Engine.GetScript(L);
|
|
||||||
std::string a;
|
|
||||||
if (!MaybeS.has_value()) {
|
|
||||||
a = ("_Console");
|
|
||||||
} else {
|
|
||||||
TLuaFile& S = MaybeS.value();
|
|
||||||
a = fs::path(S.GetFileName()).filename().string();
|
|
||||||
}
|
|
||||||
warn(a + (" | Incorrect Call of ") + msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
int lua_TempFix(lua_State* L) {
|
|
||||||
if (lua_isnumber(L, 1)) {
|
|
||||||
int ID = int(lua_tonumber(L, 1));
|
|
||||||
auto MaybeClient = GetClient(Engine().Server(), ID);
|
|
||||||
if (!MaybeClient || MaybeClient.value().expired())
|
|
||||||
return 0;
|
|
||||||
std::string Ret;
|
|
||||||
auto c = MaybeClient.value().lock();
|
|
||||||
if (c->IsGuest()) {
|
|
||||||
Ret = "Guest-" + c->GetName();
|
|
||||||
} else
|
|
||||||
Ret = c->GetName();
|
|
||||||
lua_pushstring(L, Ret.c_str());
|
|
||||||
} else
|
|
||||||
SendError(Engine(), L, "GetDID not enough arguments");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TLuaArg::PushArgs(lua_State* State) {
|
|
||||||
for (std::any arg : args) {
|
|
||||||
if (!arg.has_value()) {
|
|
||||||
error("arg didn't have a value, this is not expected, bad");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const auto& Type = arg.type();
|
|
||||||
if (Type == typeid(bool)) {
|
|
||||||
lua_pushboolean(State, std::any_cast<bool>(arg));
|
|
||||||
} else if (Type == typeid(std::string)) {
|
|
||||||
lua_pushstring(State, std::any_cast<std::string>(arg).c_str());
|
|
||||||
} else if (Type == typeid(const char*)) {
|
|
||||||
lua_pushstring(State, std::any_cast<const char*>(arg));
|
|
||||||
} else if (Type == typeid(int)) {
|
|
||||||
lua_pushinteger(State, std::any_cast<int>(arg));
|
|
||||||
} else if (Type == typeid(float)) {
|
|
||||||
lua_pushnumber(State, std::any_cast<float>(arg));
|
|
||||||
} else if (Type == typeid(double)) {
|
|
||||||
lua_pushnumber(State, std::any_cast<double>(arg));
|
|
||||||
} else {
|
|
||||||
// if this happens, implement a sane behavior for that value
|
|
||||||
error("what in the hell is " + std::string(arg.type().name()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#include "TLuaPlugin.h"
|
||||||
|
#include <chrono>
|
||||||
|
#include <functional>
|
||||||
|
#include <random>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder)
|
||||||
|
: mConfig(Config)
|
||||||
|
, mEngine(Engine)
|
||||||
|
, mFolder(MainFolder)
|
||||||
|
, mPluginName(MainFolder.stem().string())
|
||||||
|
, mFileContents(0) {
|
||||||
|
beammp_debug("Lua plugin \"" + mPluginName + "\" starting in \"" + mFolder.string() + "\"");
|
||||||
|
std::vector<fs::path> Entries;
|
||||||
|
for (const auto& Entry : fs::directory_iterator(mFolder)) {
|
||||||
|
if (Entry.is_regular_file() && Entry.path().extension() == ".lua") {
|
||||||
|
Entries.push_back(Entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// sort alphabetically (not needed if config is used to determine call order)
|
||||||
|
// TODO: Use config to figure out what to run in which order
|
||||||
|
std::sort(Entries.begin(), Entries.end(), [](const fs::path& first, const fs::path& second) {
|
||||||
|
auto firstStr = first.string();
|
||||||
|
auto secondStr = second.string();
|
||||||
|
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
|
||||||
|
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
|
||||||
|
return firstStr < secondStr;
|
||||||
|
});
|
||||||
|
std::vector<std::pair<fs::path, std::shared_ptr<TLuaResult>>> ResultsToCheck;
|
||||||
|
for (const auto& Entry : Entries) {
|
||||||
|
// read in entire file
|
||||||
|
try {
|
||||||
|
std::ifstream FileStream(Entry.string(), std::ios::in | std::ios::binary);
|
||||||
|
auto Size = std::filesystem::file_size(Entry);
|
||||||
|
auto Contents = std::make_shared<std::string>();
|
||||||
|
Contents->resize(Size);
|
||||||
|
FileStream.read(Contents->data(), Contents->size());
|
||||||
|
mFileContents[fs::relative(Entry).string()] = Contents;
|
||||||
|
// Execute first time
|
||||||
|
auto Result = mEngine.EnqueueScript(mConfig.StateId, TLuaChunk(Contents, Entry.string(), MainFolder.string()));
|
||||||
|
ResultsToCheck.emplace_back(Entry.string(), std::move(Result));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("Error loading file \"" + Entry.string() + "\": " + e.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (auto& Result : ResultsToCheck) {
|
||||||
|
Result.second->WaitUntilReady();
|
||||||
|
if (Result.second->Error) {
|
||||||
|
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Result.second->ErrorMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+277
-202
@@ -1,16 +1,21 @@
|
|||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "Client.h"
|
#include "Client.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
#include "TLuaEngine.h"
|
||||||
#include <CustomAssert.h>
|
#include <CustomAssert.h>
|
||||||
#include <Http.h>
|
#include <Http.h>
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
#include <dlhttp/dlhttp.h>
|
||||||
|
|
||||||
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
|
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
|
||||||
: mServer(Server)
|
: mServer(Server)
|
||||||
, mPPSMonitor(PPSMonitor)
|
, mPPSMonitor(PPSMonitor)
|
||||||
, mResourceManager(ResourceManager) {
|
, mResourceManager(ResourceManager) {
|
||||||
|
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting);
|
||||||
|
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
debug("Kicking all players due to shutdown");
|
beammp_debug("Kicking all players due to shutdown");
|
||||||
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
|
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
|
||||||
if (!client.expired()) {
|
if (!client.expired()) {
|
||||||
ClientKick(*client.lock(), "Server shutdown");
|
ClientKick(*client.lock(), "Server shutdown");
|
||||||
@@ -19,16 +24,18 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown);
|
||||||
if (mUDPThread.joinable()) {
|
if (mUDPThread.joinable()) {
|
||||||
mShutdown = true;
|
|
||||||
mUDPThread.detach();
|
mUDPThread.detach();
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("TCPNetwork", Application::Status::ShuttingDown);
|
||||||
if (mTCPThread.joinable()) {
|
if (mTCPThread.joinable()) {
|
||||||
mShutdown = true;
|
|
||||||
mTCPThread.detach();
|
mTCPThread.detach();
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
|
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
|
||||||
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
|
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
|
||||||
@@ -36,50 +43,34 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
|
|||||||
|
|
||||||
void TNetwork::UDPServerMain() {
|
void TNetwork::UDPServerMain() {
|
||||||
RegisterThread("UDPServer");
|
RegisterThread("UDPServer");
|
||||||
#ifdef WIN32
|
#if defined(BEAMMP_WINDOWS)
|
||||||
WSADATA data;
|
WSADATA data;
|
||||||
if (WSAStartup(514, &data)) {
|
if (WSAStartup(514, &data)) {
|
||||||
error(("Can't start Winsock!"));
|
beammp_error(("Can't start Winsock!"));
|
||||||
//return;
|
// return;
|
||||||
}
|
}
|
||||||
|
#endif // WINDOWS
|
||||||
mUDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
mUDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
// Create a server hint structure for the server
|
// Create a server hint structure for the server
|
||||||
sockaddr_in serverAddr {};
|
sockaddr_in serverAddr {};
|
||||||
serverAddr.sin_addr.S_un.S_addr = ADDR_ANY; //Any Local
|
serverAddr.sin_addr.s_addr = INADDR_ANY; // Any Local
|
||||||
serverAddr.sin_family = AF_INET; // Address format is IPv4
|
|
||||||
serverAddr.sin_port = htons(Application::Settings.Port); // Convert from little to big endian
|
|
||||||
|
|
||||||
// Try and bind the socket to the IP and port
|
|
||||||
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
|
||||||
error(("Can't bind socket!") + std::to_string(WSAGetLastError()));
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
|
||||||
exit(-1);
|
|
||||||
//return;
|
|
||||||
}
|
|
||||||
#else // unix
|
|
||||||
mUDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
|
||||||
// Create a server hint structure for the server
|
|
||||||
sockaddr_in serverAddr {};
|
|
||||||
serverAddr.sin_addr.s_addr = INADDR_ANY; //Any Local
|
|
||||||
serverAddr.sin_family = AF_INET; // Address format is IPv4
|
serverAddr.sin_family = AF_INET; // Address format is IPv4
|
||||||
serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian
|
serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian
|
||||||
|
|
||||||
// Try and bind the socket to the IP and port
|
// Try and bind the socket to the IP and port
|
||||||
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
|
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
|
||||||
error(("Can't bind socket!") + std::string(strerror(errno)));
|
beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||||
exit(-1);
|
exit(-1); // TODO: Wtf.
|
||||||
//return;
|
// return;
|
||||||
}
|
}
|
||||||
#endif
|
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good);
|
||||||
|
beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
|
||||||
info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
|
|
||||||
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
|
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
|
||||||
while (!mShutdown) {
|
while (!Application::IsShuttingDown()) {
|
||||||
try {
|
try {
|
||||||
sockaddr_in client {};
|
sockaddr_in client {};
|
||||||
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
|
std::string Data = UDPRcvFromClient(client); // Receives any data from Socket
|
||||||
size_t Pos = Data.find(':');
|
size_t Pos = Data.find(':');
|
||||||
if (Data.empty() || Pos > 2)
|
if (Data.empty() || Pos > 2)
|
||||||
continue;
|
continue;
|
||||||
@@ -106,125 +97,140 @@ void TNetwork::UDPServerMain() {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
error(("fatal: ") + std::string(e.what()));
|
beammp_error(("fatal: ") + std::string(e.what()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::TCPServerMain() {
|
void TNetwork::TCPServerMain() {
|
||||||
RegisterThread("TCPServer");
|
RegisterThread("TCPServer");
|
||||||
#ifdef WIN32
|
#if defined(BEAMMP_WINDOWS)
|
||||||
WSADATA wsaData;
|
WSADATA wsaData;
|
||||||
if (WSAStartup(514, &wsaData)) {
|
if (WSAStartup(514, &wsaData)) {
|
||||||
error("Can't start Winsock!");
|
beammp_error("Can't start Winsock! Shutting down");
|
||||||
return;
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
#endif // WINDOWS
|
||||||
sockaddr_in addr {};
|
TConnection client {};
|
||||||
addr.sin_addr.S_un.S_addr = ADDR_ANY;
|
|
||||||
addr.sin_family = AF_INET;
|
|
||||||
addr.sin_port = htons(Application::Settings.Port);
|
|
||||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
|
|
||||||
error("Can't bind socket! " + std::to_string(WSAGetLastError()));
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
|
||||||
exit(-1);
|
|
||||||
}
|
|
||||||
if (Listener == -1) {
|
|
||||||
error("Invalid listening socket");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (listen(Listener, SOMAXCONN)) {
|
|
||||||
error("listener failed " + std::to_string(GetLastError()));
|
|
||||||
//TODO Fix me leak for Listener socket
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
info("Vehicle event network online");
|
|
||||||
do {
|
|
||||||
try {
|
|
||||||
client = accept(Listener, nullptr, nullptr);
|
|
||||||
if (client == -1) {
|
|
||||||
warn("Got an invalid client socket on connect! Skipping...");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
std::thread ID(&TNetwork::Identify, this, client);
|
|
||||||
ID.detach();
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
error("fatal: " + std::string(e.what()));
|
|
||||||
}
|
|
||||||
} while (client);
|
|
||||||
|
|
||||||
CloseSocketProper(client);
|
|
||||||
WSACleanup();
|
|
||||||
#else // unix
|
|
||||||
// wondering why we need slightly different implementations of this?
|
|
||||||
// ask ms.
|
|
||||||
SOCKET client = -1;
|
|
||||||
SOCKET Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
SOCKET Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||||
int optval = 1;
|
if (Listener == BEAMMP_INVALID_SOCKET) {
|
||||||
setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
|
beammp_error("Failed to create socket: " + GetPlatformAgnosticErrorString()
|
||||||
// TODO: check optval or return value idk
|
+ ". This is a fatal error, as a socket is needed for the server to operate. Shutting down.");
|
||||||
|
Application::GracefullyShutdown();
|
||||||
|
}
|
||||||
|
#if defined(BEAMMP_WINDOWS)
|
||||||
|
const char optval = 0;
|
||||||
|
int ret = ::setsockopt(Listener, SOL_SOCKET, SO_DONTLINGER, &optval, sizeof(optval));
|
||||||
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
|
int optval = true;
|
||||||
|
int ret = ::setsockopt(Listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void*>(&optval), sizeof(optval));
|
||||||
|
#endif
|
||||||
|
// not a fatal error
|
||||||
|
if (ret < 0) {
|
||||||
|
beammp_error("Failed to set up listening socket to not linger / reuse address. "
|
||||||
|
"This may cause the socket to refuse to bind(). Error: "
|
||||||
|
+ GetPlatformAgnosticErrorString());
|
||||||
|
}
|
||||||
sockaddr_in addr {};
|
sockaddr_in addr {};
|
||||||
addr.sin_addr.s_addr = INADDR_ANY;
|
addr.sin_addr.s_addr = INADDR_ANY;
|
||||||
addr.sin_family = AF_INET;
|
addr.sin_family = AF_INET;
|
||||||
addr.sin_port = htons(uint16_t(Application::Settings.Port));
|
addr.sin_port = htons(uint16_t(Application::Settings.Port));
|
||||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
|
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) < 0) {
|
||||||
error(("Can't bind socket! ") + std::string(strerror(errno)));
|
beammp_error("bind() failed, the server cannot operate and will shut down now. "
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
"Error: "
|
||||||
exit(-1);
|
+ GetPlatformAgnosticErrorString());
|
||||||
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
if (Listener == -1) {
|
if (listen(Listener, SOMAXCONN) < 0) {
|
||||||
error(("Invalid listening socket"));
|
beammp_error("listen() failed, which is needed for the server to operate. "
|
||||||
return;
|
"Shutting down. Error: "
|
||||||
|
+ GetPlatformAgnosticErrorString());
|
||||||
|
Application::GracefullyShutdown();
|
||||||
}
|
}
|
||||||
if (listen(Listener, SOMAXCONN)) {
|
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
||||||
error(("listener failed ") + std::string(strerror(errno)));
|
beammp_info("Vehicle event network online");
|
||||||
//TODO fix me leak Listener
|
const auto ThreadCount = std::max(1, Application::Settings.DownloadThreads);
|
||||||
return;
|
beammp_debugf("Using {} download threads", ThreadCount);
|
||||||
}
|
dlhttp::AsyncContext Ctx(ThreadCount);
|
||||||
info(("Vehicle event network online"));
|
dlhttp::EndpointHandlerMap Map {
|
||||||
|
{ "/modlist", [this]() -> dlhttp::Response { return { mResourceManager.FileList() }; } },
|
||||||
|
};
|
||||||
do {
|
do {
|
||||||
try {
|
try {
|
||||||
if (mShutdown) {
|
if (Application::IsShuttingDown()) {
|
||||||
debug("shutdown during TCP wait for accept loop");
|
beammp_debug("shutdown during TCP wait for accept loop");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
client = accept(Listener, nullptr, nullptr);
|
client.SockAddrLen = sizeof(client.SockAddr);
|
||||||
if (client == -1) {
|
client.Socket = accept(Listener, &client.SockAddr, &client.SockAddrLen);
|
||||||
warn(("Got an invalid client socket on connect! Skipping..."));
|
if (client.Socket == -1) {
|
||||||
|
beammp_warn(("Got an invalid client socket on connect! Skipping..."));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// set timeout
|
||||||
|
size_t SendTimeoutMS = 30 * 1000;
|
||||||
|
#if defined(BEAMMP_WINDOWS)
|
||||||
|
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS));
|
||||||
|
#else // POSIX
|
||||||
|
struct timeval optval;
|
||||||
|
optval.tv_sec = (int)(SendTimeoutMS / 1000);
|
||||||
|
optval.tv_usec = (SendTimeoutMS % 1000) * 1000;
|
||||||
|
ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval));
|
||||||
|
#endif
|
||||||
|
if (ret < 0) {
|
||||||
|
throw std::runtime_error("setsockopt recv timeout: " + GetPlatformAgnosticErrorString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// check for http
|
||||||
|
if (dlhttp::is_http(client.Socket)) {
|
||||||
|
beammp_info("IS HTTP!");
|
||||||
|
dlhttp::handle_http(client.Socket, Ctx, Map);
|
||||||
|
} else {
|
||||||
|
beammp_info("IS NOT HTTP!");
|
||||||
|
}
|
||||||
|
|
||||||
std::thread ID(&TNetwork::Identify, this, client);
|
std::thread ID(&TNetwork::Identify, this, client);
|
||||||
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
error(("fatal: ") + std::string(e.what()));
|
beammp_error("fatal: " + std::string(e.what()));
|
||||||
}
|
}
|
||||||
} while (client);
|
} while (client.Socket != BEAMMP_INVALID_SOCKET);
|
||||||
|
|
||||||
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
beammp_debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||||
|
|
||||||
CloseSocketProper(client);
|
CloseSocketProper(client.Socket);
|
||||||
#endif
|
#ifdef BEAMMP_WINDOWS
|
||||||
|
CloseSocketProper(client.Socket);
|
||||||
|
WSACleanup();
|
||||||
|
#endif // WINDOWS
|
||||||
}
|
}
|
||||||
|
|
||||||
#undef GetObject //Fixes Windows
|
#undef GetObject // Fixes Windows
|
||||||
|
|
||||||
#include "Json.h"
|
#include "Json.h"
|
||||||
namespace json = rapidjson;
|
namespace json = rapidjson;
|
||||||
|
|
||||||
void TNetwork::Identify(SOCKET TCPSock) {
|
void TNetwork::Identify(const TConnection& client) {
|
||||||
RegisterThreadAuto();
|
RegisterThreadAuto();
|
||||||
char Code;
|
char Code;
|
||||||
if (recv(TCPSock, &Code, 1, 0) != 1) {
|
if (recv(client.Socket, &Code, 1, 0) != 1) {
|
||||||
CloseSocketProper(TCPSock);
|
CloseSocketProper(client.Socket);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (Code == 'C') {
|
if (Code == 'C') {
|
||||||
Authentication(TCPSock);
|
Authentication(client);
|
||||||
} else if (Code == 'D') {
|
} else if (Code == 'D') {
|
||||||
HandleDownload(TCPSock);
|
HandleDownload(client.Socket);
|
||||||
|
} else if (Code == 'P') {
|
||||||
|
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
|
send(client.Socket, "P", 1, MSG_NOSIGNAL);
|
||||||
|
#else
|
||||||
|
send(client.Socket, "P", 1, 0);
|
||||||
|
#endif
|
||||||
|
CloseSocketProper(client.Socket);
|
||||||
|
return;
|
||||||
} else {
|
} else {
|
||||||
CloseSocketProper(TCPSock);
|
CloseSocketProper(client.Socket);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,17 +253,35 @@ void TNetwork::HandleDownload(SOCKET TCPSock) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::Authentication(SOCKET TCPSock) {
|
static int get_ip_str(const struct sockaddr* sa, char* strBuf, size_t strBufSize) {
|
||||||
auto Client = CreateClient(TCPSock);
|
switch (sa->sa_family) {
|
||||||
|
case AF_INET:
|
||||||
|
inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), strBuf, strBufSize);
|
||||||
|
break;
|
||||||
|
case AF_INET6:
|
||||||
|
inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), strBuf, strBufSize);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
std::string Rc;
|
void TNetwork::Authentication(const TConnection& ClientConnection) {
|
||||||
info("Identifying new client...");
|
auto Client = CreateClient(ClientConnection.Socket);
|
||||||
|
char AddrBuf[INET6_ADDRSTRLEN];
|
||||||
|
get_ip_str(&ClientConnection.SockAddr, AddrBuf, sizeof(AddrBuf));
|
||||||
|
beammp_trace("This thread is ip " + std::string(AddrBuf));
|
||||||
|
Client->SetIdentifier("ip", AddrBuf);
|
||||||
|
|
||||||
|
std::string Rc; // TODO: figure out why this is not default constructed
|
||||||
|
beammp_info("Identifying new ClientConnection...");
|
||||||
|
|
||||||
Rc = TCPRcv(*Client);
|
Rc = TCPRcv(*Client);
|
||||||
|
|
||||||
if (Rc.size() > 3 && Rc.substr(0, 2) == "VC") {
|
if (Rc.size() > 3 && Rc.substr(0, 2) == "VC") {
|
||||||
Rc = Rc.substr(2);
|
Rc = Rc.substr(2);
|
||||||
if (Rc.length() > 4 || Rc != Application::ClientVersion()) {
|
if (Rc.length() > 4 || Rc != Application::ClientVersionString()) {
|
||||||
ClientKick(*Client, "Outdated Version!");
|
ClientKick(*Client, "Outdated Version!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -279,14 +303,14 @@ void TNetwork::Authentication(SOCKET TCPSock) {
|
|||||||
auto RequestString = R"({"key":")" + Rc + "\"}";
|
auto RequestString = R"({"key":")" + Rc + "\"}";
|
||||||
|
|
||||||
auto Target = "/pkToUser";
|
auto Target = "/pkToUser";
|
||||||
int ResponseCode = -1;
|
unsigned int ResponseCode = 0;
|
||||||
if (!Rc.empty()) {
|
if (!Rc.empty()) {
|
||||||
Rc = Http::POST(Application::GetBackendUrlForAuth(), Target, {}, RequestString, true, &ResponseCode);
|
Rc = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, RequestString, "application/json", &ResponseCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
json::Document AuthResponse;
|
json::Document AuthResponse;
|
||||||
AuthResponse.Parse(Rc.c_str());
|
AuthResponse.Parse(Rc.c_str());
|
||||||
if (Rc == "-1" || AuthResponse.HasParseError()) {
|
if (Rc == Http::ErrorString || AuthResponse.HasParseError()) {
|
||||||
ClientKick(*Client, "Invalid key! Please restart your game.");
|
ClientKick(*Client, "Invalid key! Please restart your game.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -301,7 +325,7 @@ void TNetwork::Authentication(SOCKET TCPSock) {
|
|||||||
Sentry.Log(SentryLevel::Info, "default", "backend returned 0 instead of json (" + std::to_string(ResponseCode) + ")");
|
Sentry.Log(SentryLevel::Info, "default", "backend returned 0 instead of json (" + std::to_string(ResponseCode) + ")");
|
||||||
} else { // Rc != "0"
|
} else { // Rc != "0"
|
||||||
ClientKick(*Client, "Backend returned invalid auth response format.");
|
ClientKick(*Client, "Backend returned invalid auth response format.");
|
||||||
error("Backend returned invalid auth response format. This should never happen.");
|
beammp_error("Backend returned invalid auth response format. This should never happen.");
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
Sentry.SetContext("auth",
|
Sentry.SetContext("auth",
|
||||||
{ { "response-body", Rc },
|
{ { "response-body", Rc },
|
||||||
@@ -319,14 +343,16 @@ void TNetwork::Authentication(SOCKET TCPSock) {
|
|||||||
Client->SetRoles(AuthResponse["roles"].GetString());
|
Client->SetRoles(AuthResponse["roles"].GetString());
|
||||||
Client->SetIsGuest(AuthResponse["guest"].GetBool());
|
Client->SetIsGuest(AuthResponse["guest"].GetBool());
|
||||||
for (const auto& ID : AuthResponse["identifiers"].GetArray()) {
|
for (const auto& ID : AuthResponse["identifiers"].GetArray()) {
|
||||||
Client->AddIdentifier(ID.GetString());
|
auto Raw = std::string(ID.GetString());
|
||||||
|
auto SepIndex = Raw.find(':');
|
||||||
|
Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ClientKick(*Client, "Invalid authentication data!");
|
ClientKick(*Client, "Invalid authentication data!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
|
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
|
||||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||||
std::shared_ptr<TClient> Cl;
|
std::shared_ptr<TClient> Cl;
|
||||||
{
|
{
|
||||||
@@ -345,18 +371,32 @@ void TNetwork::Authentication(SOCKET TCPSock) {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
auto arg = std::make_unique<TLuaArg>(TLuaArg { { Client->GetName(), Client->GetRoles(), Client->IsGuest() } });
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest());
|
||||||
std::any Res = TriggerLuaEvent("onPlayerAuth", false, nullptr, std::move(arg), true);
|
TLuaEngine::WaitForAll(Futures);
|
||||||
if (Res.type() == typeid(int) && std::any_cast<int>(Res)) {
|
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||||
|
return !Result->Error && Result->Result.is<int>() && bool(Result->Result.as<int>());
|
||||||
|
});
|
||||||
|
std::string Reason;
|
||||||
|
bool NotAllowedWithReason = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[&Reason](const std::shared_ptr<TLuaResult>& Result) -> bool {
|
||||||
|
if (!Result->Error && Result->Result.is<std::string>()) {
|
||||||
|
Reason = Result->Result.as<std::string>();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (NotAllowed) {
|
||||||
ClientKick(*Client, "you are not allowed on the server!");
|
ClientKick(*Client, "you are not allowed on the server!");
|
||||||
return;
|
return;
|
||||||
} else if (Res.type() == typeid(std::string)) {
|
} else if (NotAllowedWithReason) {
|
||||||
ClientKick(*Client, std::any_cast<std::string>(Res));
|
ClientKick(*Client, Reason);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
|
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
|
||||||
info("Identification success");
|
beammp_info("Identification success");
|
||||||
mServer.InsertClient(Client);
|
mServer.InsertClient(Client);
|
||||||
TCPClient(Client);
|
TCPClient(Client);
|
||||||
} else
|
} else
|
||||||
@@ -389,18 +429,18 @@ bool TNetwork::TCPSend(TClient& c, const std::string& Data, bool IsSync) {
|
|||||||
Sent = 0;
|
Sent = 0;
|
||||||
Size += 4;
|
Size += 4;
|
||||||
do {
|
do {
|
||||||
#ifdef WIN32
|
#if defined(BEAMMP_WINDOWS)
|
||||||
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, 0);
|
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, 0);
|
||||||
#else //WIN32
|
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, MSG_NOSIGNAL);
|
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, MSG_NOSIGNAL);
|
||||||
#endif //WIN32
|
#endif
|
||||||
if (Temp == 0) {
|
if (Temp == 0) {
|
||||||
debug("send() == 0: " + std::string(std::strerror(errno)));
|
beammp_debug("send() == 0: " + GetPlatformAgnosticErrorString());
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
return false;
|
return false;
|
||||||
} else if (Temp < 0) {
|
} else if (Temp < 0) {
|
||||||
debug("send() < 0: " + std::string(std::strerror(errno))); //TODO fix it was spamming yet everyone stayed on the server
|
beammp_debug("send() < 0: " + GetPlatformAgnosticErrorString()); // TODO fix it was spamming yet everyone stayed on the server
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
CloseSocketProper(c.GetTCPSock());
|
CloseSocketProper(c.GetTCPSock());
|
||||||
@@ -414,16 +454,12 @@ bool TNetwork::TCPSend(TClient& c, const std::string& Data, bool IsSync) {
|
|||||||
|
|
||||||
bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
|
bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
|
||||||
if (BytesRcv == 0) {
|
if (BytesRcv == 0) {
|
||||||
trace("(TCP) Connection closing...");
|
beammp_trace("(TCP) Connection closing...");
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
return false;
|
return false;
|
||||||
} else if (BytesRcv < 0) {
|
} else if (BytesRcv < 0) {
|
||||||
#ifdef WIN32
|
beammp_debug("(TCP) recv() failed: " + GetPlatformAgnosticErrorString());
|
||||||
debug(("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
|
||||||
#else // unix
|
|
||||||
debug(("(TCP) recv failed with error: ") + std::string(strerror(errno)));
|
|
||||||
#endif // WIN32
|
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
CloseSocketProper(c.GetTCPSock());
|
CloseSocketProper(c.GetTCPSock());
|
||||||
@@ -454,7 +490,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
|
|||||||
Data.resize(Header);
|
Data.resize(Header);
|
||||||
} else {
|
} else {
|
||||||
ClientKick(c, "Header size limit exceeded");
|
ClientKick(c, "Header size limit exceeded");
|
||||||
warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
|
beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
BytesRcv = 0;
|
BytesRcv = 0;
|
||||||
@@ -474,9 +510,9 @@ std::string TNetwork::TCPRcv(TClient& c) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
||||||
info("Client kicked: " + R);
|
beammp_info("Client kicked: " + R);
|
||||||
if (!TCPSend(c, "E" + R)) {
|
if (!TCPSend(c, "K" + R)) {
|
||||||
// TODO handle
|
beammp_warn("tried to kick player '" + c.GetName() + "' (id " + std::to_string(c.GetID()) + "), but was already disconnected");
|
||||||
}
|
}
|
||||||
c.SetStatus(-2);
|
c.SetStatus(-2);
|
||||||
|
|
||||||
@@ -486,15 +522,17 @@ void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
|||||||
if (c.GetDownSock())
|
if (c.GetDownSock())
|
||||||
CloseSocketProper(c.GetDownSock());
|
CloseSocketProper(c.GetDownSock());
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
||||||
|
RegisterThreadAuto();
|
||||||
while (!c.expired()) {
|
while (!c.expired()) {
|
||||||
auto Client = c.lock();
|
auto Client = c.lock();
|
||||||
if (Client->GetStatus() < 0) {
|
if (Client->GetStatus() < 0) {
|
||||||
debug("client status < 0, breaking client loop");
|
beammp_debug("client status < 0, breaking client loop");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
|
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
|
||||||
//debug("sending " + std::to_string(Client->MissedPacketQueueSize()) + " queued packets");
|
// debug("sending " + std::to_string(Client->MissedPacketQueueSize()) + " queued packets");
|
||||||
while (Client->MissedPacketQueueSize() > 0) {
|
while (Client->MissedPacketQueueSize() > 0) {
|
||||||
std::string QData {};
|
std::string QData {};
|
||||||
{ // locked context
|
{ // locked context
|
||||||
@@ -505,7 +543,7 @@ void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
|||||||
QData = Client->MissedPacketQueue().front();
|
QData = Client->MissedPacketQueue().front();
|
||||||
Client->MissedPacketQueue().pop();
|
Client->MissedPacketQueue().pop();
|
||||||
} // end locked context
|
} // end locked context
|
||||||
// debug("sending a missed packet: " + QData);
|
// beammp_debug("sending a missed packet: " + QData);
|
||||||
if (!TCPSend(*Client, QData, true)) {
|
if (!TCPSend(*Client, QData, true)) {
|
||||||
if (Client->GetStatus() > -1)
|
if (Client->GetStatus() > -1)
|
||||||
Client->SetStatus(-1);
|
Client->SetStatus(-1);
|
||||||
@@ -524,6 +562,7 @@ void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
|
void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
|
||||||
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
|
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
|
||||||
if (c.expired() || c.lock()->GetTCPSock() == -1) {
|
if (c.expired() || c.lock()->GetTCPSock() == -1) {
|
||||||
@@ -540,13 +579,13 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
|
|||||||
break;
|
break;
|
||||||
auto Client = c.lock();
|
auto Client = c.lock();
|
||||||
if (Client->GetStatus() < 0) {
|
if (Client->GetStatus() < 0) {
|
||||||
debug("client status < 0, breaking client loop");
|
beammp_debug("client status < 0, breaking client loop");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto res = TCPRcv(*Client);
|
auto res = TCPRcv(*Client);
|
||||||
if (res == "") {
|
if (res == "") {
|
||||||
debug("TCPRcv error, break client loop");
|
beammp_debug("TCPRcv error, break client loop");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
TServer::GlobalParser(c, res, mPPSMonitor, *this);
|
TServer::GlobalParser(c, res, mPPSMonitor, *this);
|
||||||
@@ -558,7 +597,7 @@ void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
|
|||||||
auto Client = c.lock();
|
auto Client = c.lock();
|
||||||
OnDisconnect(c, Client->GetStatus() == -2);
|
OnDisconnect(c, Client->GetStatus() == -2);
|
||||||
} else {
|
} else {
|
||||||
warn("client expired in TCPClient, should never happen");
|
beammp_warn("client expired in TCPClient, should never happen");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -578,10 +617,10 @@ void TNetwork::UpdatePlayer(TClient& Client) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked) {
|
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked) {
|
||||||
Assert(!ClientPtr.expired());
|
beammp_assert(!ClientPtr.expired());
|
||||||
auto LockedClientPtr = ClientPtr.lock();
|
auto LockedClientPtr = ClientPtr.lock();
|
||||||
TClient& c = *LockedClientPtr;
|
TClient& c = *LockedClientPtr;
|
||||||
info(c.GetName() + (" Connection Terminated"));
|
beammp_info(c.GetName() + (" Connection Terminated"));
|
||||||
std::string Packet;
|
std::string Packet;
|
||||||
TClient::TSetOfVehicleData VehicleData;
|
TClient::TSetOfVehicleData VehicleData;
|
||||||
{ // Vehicle Data Lock Scope
|
{ // Vehicle Data Lock Scope
|
||||||
@@ -598,7 +637,8 @@ void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked
|
|||||||
Packet = ("L") + c.GetName() + (" left the server!");
|
Packet = ("L") + c.GetName() + (" left the server!");
|
||||||
SendToAll(&c, Packet, false, true);
|
SendToAll(&c, Packet, false, true);
|
||||||
Packet.clear();
|
Packet.clear();
|
||||||
TriggerLuaEvent(("onPlayerDisconnect"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID() } }), false);
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", c.GetID());
|
||||||
|
LuaAPI::MP::Engine->ReportErrors(Futures);
|
||||||
if (c.GetTCPSock())
|
if (c.GetTCPSock())
|
||||||
CloseSocketProper(c.GetTCPSock());
|
CloseSocketProper(c.GetTCPSock());
|
||||||
if (c.GetDownSock())
|
if (c.GetDownSock())
|
||||||
@@ -627,18 +667,18 @@ int TNetwork::OpenID() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
|
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
|
||||||
Assert(!c.expired());
|
beammp_assert(!c.expired());
|
||||||
info("Client connected");
|
beammp_info("Client connected");
|
||||||
auto LockedClient = c.lock();
|
auto LockedClient = c.lock();
|
||||||
LockedClient->SetID(OpenID());
|
LockedClient->SetID(OpenID());
|
||||||
info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
|
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
|
||||||
TriggerLuaEvent("onPlayerConnecting", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID()));
|
||||||
SyncResources(*LockedClient);
|
SyncResources(*LockedClient);
|
||||||
if (LockedClient->GetStatus() < 0)
|
if (LockedClient->GetStatus() < 0)
|
||||||
return;
|
return;
|
||||||
(void)Respond(*LockedClient, "M" + Application::Settings.MapName, true); //Send the Map on connect
|
(void)Respond(*LockedClient, "M" + Application::Settings.MapName, true); // Send the Map on connect
|
||||||
info(LockedClient->GetName() + " : Connected");
|
beammp_info(LockedClient->GetName() + " : Connected");
|
||||||
TriggerLuaEvent("onPlayerJoining", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::SyncResources(TClient& c) {
|
void TNetwork::SyncResources(TClient& c) {
|
||||||
@@ -657,7 +697,7 @@ void TNetwork::SyncResources(TClient& c) {
|
|||||||
}
|
}
|
||||||
#ifndef DEBUG
|
#ifndef DEBUG
|
||||||
} catch (std::exception& e) {
|
} catch (std::exception& e) {
|
||||||
error("Exception! : " + std::string(e.what()));
|
beammp_error("Exception! : " + std::string(e.what()));
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -675,7 +715,7 @@ void TNetwork::Parse(TClient& c, const std::string& Packet) {
|
|||||||
return;
|
return;
|
||||||
case 'S':
|
case 'S':
|
||||||
if (SubCode == 'R') {
|
if (SubCode == 'R') {
|
||||||
debug("Sending Mod Info");
|
beammp_debug("Sending Mod Info");
|
||||||
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
|
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
|
||||||
if (ToSend.empty())
|
if (ToSend.empty())
|
||||||
ToSend = "-";
|
ToSend = "-";
|
||||||
@@ -690,13 +730,13 @@ void TNetwork::Parse(TClient& c, const std::string& Packet) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
||||||
info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
|
beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
|
||||||
|
|
||||||
if (!fs::path(UnsafeName).has_filename()) {
|
if (!fs::path(UnsafeName).has_filename()) {
|
||||||
if (!TCPSend(c, "CO")) {
|
if (!TCPSend(c, "CO")) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
warn("File " + UnsafeName + " is not a file!");
|
beammp_warn("File " + UnsafeName + " is not a file!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
auto FileName = fs::path(UnsafeName).filename().string();
|
auto FileName = fs::path(UnsafeName).filename().string();
|
||||||
@@ -706,7 +746,7 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
if (!TCPSend(c, "CO")) {
|
if (!TCPSend(c, "CO")) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
warn("File " + UnsafeName + " could not be accessed!");
|
beammp_warn("File " + UnsafeName + " could not be accessed!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -714,7 +754,7 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
|
|
||||||
///Wait for connections
|
/// Wait for connections
|
||||||
int T = 0;
|
int T = 0;
|
||||||
while (c.GetDownSock() < 1 && T < 50) {
|
while (c.GetDownSock() < 1 && T < 50) {
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
@@ -722,7 +762,7 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (c.GetDownSock() < 1) {
|
if (c.GetDownSock() < 1) {
|
||||||
error("Client doesn't have a download socket!");
|
beammp_error("Client doesn't have a download socket!");
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
return;
|
return;
|
||||||
@@ -732,9 +772,11 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
|
|
||||||
std::thread SplitThreads[2] {
|
std::thread SplitThreads[2] {
|
||||||
std::thread([&] {
|
std::thread([&] {
|
||||||
|
RegisterThread("SplitLoad_0");
|
||||||
SplitLoad(c, 0, MSize, false, FileName);
|
SplitLoad(c, 0, MSize, false, FileName);
|
||||||
}),
|
}),
|
||||||
std::thread([&] {
|
std::thread([&] {
|
||||||
|
RegisterThread("SplitLoad_1");
|
||||||
SplitLoad(c, MSize, Size, true, FileName);
|
SplitLoad(c, MSize, Size, true, FileName);
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
@@ -746,26 +788,75 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static std::pair<size_t /* count */, size_t /* last chunk */> SplitIntoChunks(size_t FullSize, size_t ChunkSize) {
|
||||||
|
if (FullSize < ChunkSize) {
|
||||||
|
return { 0, FullSize };
|
||||||
|
}
|
||||||
|
size_t Count = FullSize / (FullSize / ChunkSize);
|
||||||
|
size_t LastChunkSize = FullSize - (Count * ChunkSize);
|
||||||
|
return { Count, LastChunkSize };
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_CASE("SplitIntoChunks") {
|
||||||
|
size_t FullSize;
|
||||||
|
size_t ChunkSize;
|
||||||
|
SUBCASE("Normal case") {
|
||||||
|
FullSize = 1234567;
|
||||||
|
ChunkSize = 1234;
|
||||||
|
}
|
||||||
|
SUBCASE("Zero original size") {
|
||||||
|
FullSize = 0;
|
||||||
|
ChunkSize = 100;
|
||||||
|
}
|
||||||
|
SUBCASE("Equal full size and chunk size") {
|
||||||
|
FullSize = 125;
|
||||||
|
ChunkSize = 125;
|
||||||
|
}
|
||||||
|
SUBCASE("Even split") {
|
||||||
|
FullSize = 10000;
|
||||||
|
ChunkSize = 100;
|
||||||
|
}
|
||||||
|
SUBCASE("Odd split") {
|
||||||
|
FullSize = 13;
|
||||||
|
ChunkSize = 2;
|
||||||
|
}
|
||||||
|
SUBCASE("Large sizes") {
|
||||||
|
FullSize = 10 * GB;
|
||||||
|
ChunkSize = 125 * MB;
|
||||||
|
}
|
||||||
|
auto [Count, LastSize] = SplitIntoChunks(FullSize, ChunkSize);
|
||||||
|
CHECK((Count * ChunkSize) + LastSize == FullSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t* /* end ptr */ TNetwork::SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size) {
|
||||||
|
if (TCPSendRaw(c, Socket, reinterpret_cast<char*>(DataPtr), Size)) {
|
||||||
|
return DataPtr + Size;
|
||||||
|
} else {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
||||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
std::ifstream f(Name.c_str(), std::ios::binary);
|
||||||
uint32_t Split = 0x7735940; //125MB
|
auto Buf = f.rdbuf();
|
||||||
char* Data;
|
uint32_t Split = 125 * MB;
|
||||||
|
std::vector<uint8_t> Data;
|
||||||
if (Size > Split)
|
if (Size > Split)
|
||||||
Data = new char[Split];
|
Data.resize(Split);
|
||||||
else
|
else
|
||||||
Data = new char[Size];
|
Data.resize(Size);
|
||||||
SOCKET TCPSock;
|
SOCKET TCPSock;
|
||||||
if (D)
|
if (D)
|
||||||
TCPSock = c.GetDownSock();
|
TCPSock = c.GetDownSock();
|
||||||
else
|
else
|
||||||
TCPSock = c.GetTCPSock();
|
TCPSock = c.GetTCPSock();
|
||||||
info("Split load Socket " + std::to_string(TCPSock));
|
beammp_debug("Split load Socket " + std::to_string(TCPSock));
|
||||||
while (c.GetStatus() > -1 && Sent < Size) {
|
while (c.GetStatus() > -1 && Sent < Size) {
|
||||||
size_t Diff = Size - Sent;
|
size_t Diff = Size - Sent;
|
||||||
if (Diff > Split) {
|
if (Diff > Split) {
|
||||||
f.seekg(Sent, std::ios_base::beg);
|
f.seekg(Sent, std::ios_base::beg);
|
||||||
f.read(Data, Split);
|
f.read(reinterpret_cast<char*>(Data.data()), Split);
|
||||||
if (!TCPSendRaw(c, TCPSock, Data, Split)) {
|
if (!TCPSendRaw(c, TCPSock, reinterpret_cast<char*>(Data.data()), Split)) {
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
break;
|
break;
|
||||||
@@ -773,8 +864,8 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
|
|||||||
Sent += Split;
|
Sent += Split;
|
||||||
} else {
|
} else {
|
||||||
f.seekg(Sent, std::ios_base::beg);
|
f.seekg(Sent, std::ios_base::beg);
|
||||||
f.read(Data, Diff);
|
f.read(reinterpret_cast<char*>(Data.data()), Diff);
|
||||||
if (!TCPSendRaw(c, TCPSock, Data, int32_t(Diff))) {
|
if (!TCPSendRaw(c, TCPSock, reinterpret_cast<char*>(Data.data()), int32_t(Diff))) {
|
||||||
if (c.GetStatus() > -1)
|
if (c.GetStatus() > -1)
|
||||||
c.SetStatus(-1);
|
c.SetStatus(-1);
|
||||||
break;
|
break;
|
||||||
@@ -782,16 +873,18 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
|
|||||||
Sent += Diff;
|
Sent += Diff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delete[] Data;
|
|
||||||
f.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
|
bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
|
||||||
intmax_t Sent = 0;
|
intmax_t Sent = 0;
|
||||||
do {
|
do {
|
||||||
|
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||||
|
intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), MSG_NOSIGNAL);
|
||||||
|
#else
|
||||||
intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), 0);
|
intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), 0);
|
||||||
|
#endif
|
||||||
if (Temp < 1) {
|
if (Temp < 1) {
|
||||||
info("Socket Closed! " + std::to_string(socket));
|
beammp_info("Socket Closed! " + std::to_string(socket));
|
||||||
CloseSocketProper(socket);
|
CloseSocketProper(socket);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -837,7 +930,7 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
|
|||||||
// ignore error
|
// ignore error
|
||||||
(void)SendToAll(LockedClient.get(), ("JWelcome ") + LockedClient->GetName() + "!", false, true);
|
(void)SendToAll(LockedClient.get(), ("JWelcome ") + LockedClient->GetName() + "!", false, true);
|
||||||
|
|
||||||
TriggerLuaEvent(("onPlayerJoin"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID()));
|
||||||
LockedClient->SetIsSyncing(true);
|
LockedClient->SetIsSyncing(true);
|
||||||
bool Return = false;
|
bool Return = false;
|
||||||
bool res = true;
|
bool res = true;
|
||||||
@@ -873,13 +966,13 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
LockedClient->SetIsSynced(true);
|
LockedClient->SetIsSynced(true);
|
||||||
info(LockedClient->GetName() + (" is now synced!"));
|
beammp_info(LockedClient->GetName() + (" is now synced!"));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel) {
|
void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel) {
|
||||||
if (!Self)
|
if (!Self)
|
||||||
Assert(c);
|
beammp_assert(c);
|
||||||
char C = Data.at(0);
|
char C = Data.at(0);
|
||||||
bool ret = true;
|
bool ret = true;
|
||||||
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
|
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
|
||||||
@@ -901,10 +994,10 @@ void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Re
|
|||||||
} else {
|
} else {
|
||||||
Client->EnqueuePacket(Data);
|
Client->EnqueuePacket(Data);
|
||||||
}
|
}
|
||||||
//ret = SendLarge(*Client, Data);
|
// ret = SendLarge(*Client, Data);
|
||||||
} else {
|
} else {
|
||||||
Client->EnqueuePacket(Data);
|
Client->EnqueuePacket(Data);
|
||||||
//ret = TCPSend(*Client, Data);
|
// ret = TCPSend(*Client, Data);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ret = UDPSend(*Client, Data);
|
ret = UDPSend(*Client, Data);
|
||||||
@@ -942,31 +1035,17 @@ bool TNetwork::UDPSend(TClient& Client, std::string Data) const {
|
|||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize));
|
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize));
|
||||||
#ifdef WIN32
|
|
||||||
if (sendOk == -1) {
|
if (sendOk == -1) {
|
||||||
debug(("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
|
beammp_debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString());
|
||||||
if (Client.GetStatus() > -1)
|
if (Client.GetStatus() > -1)
|
||||||
Client.SetStatus(-1);
|
Client.SetStatus(-1);
|
||||||
return false;
|
return false;
|
||||||
} else if (sendOk == 0) {
|
} else if (sendOk == 0) {
|
||||||
debug(("(UDP) sendto returned 0"));
|
beammp_debug(("(UDP) sendto() returned 0"));
|
||||||
if (Client.GetStatus() > -1)
|
if (Client.GetStatus() > -1)
|
||||||
Client.SetStatus(-1);
|
Client.SetStatus(-1);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
#else // unix
|
|
||||||
if (sendOk == -1) {
|
|
||||||
debug(("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
|
|
||||||
if (Client.GetStatus() > -1)
|
|
||||||
Client.SetStatus(-1);
|
|
||||||
return false;
|
|
||||||
} else if (sendOk == 0) {
|
|
||||||
debug(("(UDP) sendto returned 0"));
|
|
||||||
if (Client.GetStatus() > -1)
|
|
||||||
Client.SetStatus(-1);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
#endif // WIN32
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -980,11 +1059,7 @@ std::string TNetwork::UDPRcvFromClient(sockaddr_in& client) const {
|
|||||||
#endif // WIN32
|
#endif // WIN32
|
||||||
|
|
||||||
if (Rcv == -1) {
|
if (Rcv == -1) {
|
||||||
#ifdef WIN32
|
beammp_error("(UDP) Error receiving from client! recvfrom() failed: " + GetPlatformAgnosticErrorString());
|
||||||
error(("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
|
|
||||||
#else // unix
|
|
||||||
error(("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
|
|
||||||
#endif // WIN32
|
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
return std::string(Ret.begin(), Ret.begin() + Rcv);
|
return std::string(Ret.begin(), Ret.begin() + Rcv);
|
||||||
|
|||||||
+11
-6
@@ -4,24 +4,29 @@
|
|||||||
|
|
||||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
TPPSMonitor::TPPSMonitor(TServer& Server)
|
||||||
: mServer(Server) {
|
: mServer(Server) {
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
||||||
Application::SetPPS("-");
|
Application::SetPPS("-");
|
||||||
Application::RegisterShutdownHandler([&] {
|
Application::RegisterShutdownHandler([&] {
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
||||||
if (mThread.joinable()) {
|
if (mThread.joinable()) {
|
||||||
mShutdown = true;
|
beammp_debug("shutting down PPSMonitor");
|
||||||
mThread.join();
|
mThread.join();
|
||||||
|
beammp_debug("shut down PPSMonitor");
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
||||||
});
|
});
|
||||||
Start();
|
Start();
|
||||||
}
|
}
|
||||||
void TPPSMonitor::operator()() {
|
void TPPSMonitor::operator()() {
|
||||||
RegisterThread("PPSMonitor");
|
RegisterThread("PPSMonitor");
|
||||||
while (!mNetwork) {
|
while (!mNetwork) {
|
||||||
// hard spi
|
// hard(-ish) spin
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
std::this_thread::yield();
|
||||||
}
|
}
|
||||||
info("PPSMonitor starting");
|
beammp_debug("PPSMonitor starting");
|
||||||
|
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
||||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
||||||
while (!mShutdown) {
|
while (!Application::IsShuttingDown()) {
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
int C = 0, V = 0;
|
int C = 0, V = 0;
|
||||||
if (mServer.ClientCount() == 0) {
|
if (mServer.ClientCount() == 0) {
|
||||||
@@ -43,7 +48,7 @@ void TPPSMonitor::operator()() {
|
|||||||
}
|
}
|
||||||
// kick on "no ping"
|
// kick on "no ping"
|
||||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||||
debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
||||||
TimedOutClients.push_back(c);
|
TimedOutClients.push_back(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#include "TPluginMonitor.h"
|
||||||
|
|
||||||
|
#include "TLuaEngine.h"
|
||||||
|
|
||||||
|
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
|
||||||
|
: mEngine(Engine)
|
||||||
|
, mPath(Path) {
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Starting);
|
||||||
|
if (!fs::exists(mPath)) {
|
||||||
|
fs::create_directories(mPath);
|
||||||
|
}
|
||||||
|
for (const auto& Entry : fs::recursive_directory_iterator(mPath)) {
|
||||||
|
// TODO: trigger an event when a subfolder file changes
|
||||||
|
if (Entry.is_regular_file()) {
|
||||||
|
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::RegisterShutdownHandler([this] {
|
||||||
|
if (mThread.joinable()) {
|
||||||
|
mThread.join();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TPluginMonitor::operator()() {
|
||||||
|
RegisterThread("PluginMonitor");
|
||||||
|
beammp_info("PluginMonitor started");
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Good);
|
||||||
|
while (!Application::IsShuttingDown()) {
|
||||||
|
std::vector<std::string> ToRemove;
|
||||||
|
for (const auto& Pair : mFileTimes) {
|
||||||
|
try {
|
||||||
|
auto CurrentTime = fs::last_write_time(Pair.first);
|
||||||
|
if (CurrentTime > Pair.second) {
|
||||||
|
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);
|
||||||
|
} else {
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// is in subfolder, dont reload, just trigger an event
|
||||||
|
beammp_debugf("File \"{}\" changed, not reloading because it's in a subdirectory. Triggering 'onFileChanged' event instead", Pair.first);
|
||||||
|
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
ToRemove.push_back(Pair.first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::SleepSafeSeconds(3);
|
||||||
|
for (const auto& File : ToRemove) {
|
||||||
|
mFileTimes.erase(File);
|
||||||
|
beammp_warnf("File \"{}\" couldn't be accessed, so it was removed from plugin hot reload monitor (probably got deleted)", File);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Shutdown);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
TResourceManager::TResourceManager() {
|
TResourceManager::TResourceManager() {
|
||||||
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||||
std::string Path = Application::Settings.Resource + "/Client";
|
std::string Path = Application::Settings.Resource + "/Client";
|
||||||
if (!fs::exists(Path))
|
if (!fs::exists(Path))
|
||||||
fs::create_directories(Path);
|
fs::create_directories(Path);
|
||||||
@@ -13,11 +14,11 @@ TResourceManager::TResourceManager() {
|
|||||||
std::string File(entry.path().string());
|
std::string File(entry.path().string());
|
||||||
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
||||||
if (File.length() - pos == 4) {
|
if (File.length() - pos == 4) {
|
||||||
std::replace(File.begin(), File.end(),'\\','/');
|
std::replace(File.begin(), File.end(), '\\', '/');
|
||||||
mFileList += File + ';';
|
mFileList += File + ';';
|
||||||
if(auto i = File.find_last_of('/'); i != std::string::npos){
|
if (auto i = File.find_last_of('/'); i != std::string::npos) {
|
||||||
++i;
|
++i;
|
||||||
File = File.substr(i,pos-i);
|
File = File.substr(i, pos - i);
|
||||||
}
|
}
|
||||||
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
||||||
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
||||||
@@ -27,6 +28,9 @@ TResourceManager::TResourceManager() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mModsLoaded)
|
if (mModsLoaded) {
|
||||||
info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#include "TScopedTimer.h"
|
||||||
|
#include "Common.h"
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer()
|
||||||
|
: mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer(const std::string& mName)
|
||||||
|
: mStartTime(std::chrono::high_resolution_clock::now())
|
||||||
|
, Name(mName) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
|
||||||
|
: OnDestroy(OnDestroy)
|
||||||
|
, mStartTime(std::chrono::high_resolution_clock::now()) {
|
||||||
|
}
|
||||||
|
|
||||||
|
TScopedTimer::~TScopedTimer() {
|
||||||
|
auto EndTime = std::chrono::high_resolution_clock::now();
|
||||||
|
auto Delta = EndTime - mStartTime;
|
||||||
|
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
|
||||||
|
if (OnDestroy) {
|
||||||
|
OnDestroy(TimeDelta);
|
||||||
|
} else {
|
||||||
|
beammp_info("Scoped timer: \"" + Name + "\" took " + std::to_string(TimeDelta) + "ms ");
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-9
@@ -12,9 +12,8 @@ TSentry::TSentry() {
|
|||||||
mValid = true;
|
mValid = true;
|
||||||
sentry_options_t* options = sentry_options_new();
|
sentry_options_t* options = sentry_options_new();
|
||||||
sentry_options_set_dsn(options, S_DSN);
|
sentry_options_set_dsn(options, S_DSN);
|
||||||
sentry_options_set_debug(options, false); // needs to always be false
|
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersionString();
|
||||||
sentry_options_set_symbolize_stacktraces(options, true);
|
sentry_options_set_symbolize_stacktraces(options, true);
|
||||||
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersion();
|
|
||||||
sentry_options_set_release(options, ReleaseString.c_str());
|
sentry_options_set_release(options, ReleaseString.c_str());
|
||||||
sentry_options_set_max_breadcrumbs(options, 10);
|
sentry_options_set_max_breadcrumbs(options, 10);
|
||||||
sentry_init(options);
|
sentry_init(options);
|
||||||
@@ -32,22 +31,22 @@ void TSentry::PrintWelcome() {
|
|||||||
if (!Application::Settings.SendErrors) {
|
if (!Application::Settings.SendErrors) {
|
||||||
mValid = false;
|
mValid = false;
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
|
||||||
} else {
|
} else {
|
||||||
info("Sentry disabled");
|
beammp_info("Sentry disabled");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
|
beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
|
||||||
} else {
|
} else {
|
||||||
info("Sentry started");
|
beammp_info("Sentry started");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (Application::Settings.SendErrorsMessageEnabled) {
|
if (Application::Settings.SendErrorsMessageEnabled) {
|
||||||
info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
|
||||||
} else {
|
} else {
|
||||||
info("Sentry disabled in unofficial build");
|
beammp_info("Sentry disabled in unofficial build");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -56,6 +55,7 @@ void TSentry::SetupUser() {
|
|||||||
if (!mValid) {
|
if (!mValid) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
|
||||||
sentry_value_t user = sentry_value_new_object();
|
sentry_value_t user = sentry_value_new_object();
|
||||||
if (Application::Settings.Key.size() == 36) {
|
if (Application::Settings.Key.size() == 36) {
|
||||||
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
|
||||||
@@ -72,7 +72,7 @@ void TSentry::Log(SentryLevel level, const std::string& logger, const std::strin
|
|||||||
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
SetContext("threads", { { "thread-name", ThreadName(true) } });
|
||||||
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
|
||||||
sentry_capture_event(Msg);
|
sentry_capture_event(Msg);
|
||||||
sentry_remove_transaction();
|
sentry_set_transaction(nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
|
||||||
|
|||||||
+93
-83
@@ -3,35 +3,39 @@
|
|||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
#include <TLuaFile.h>
|
#include <TLuaPlugin.h>
|
||||||
#include <any>
|
#include <any>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
|
#include "LuaAPI.h"
|
||||||
|
|
||||||
#undef GetObject // Fixes Windows
|
#undef GetObject // Fixes Windows
|
||||||
|
|
||||||
#include "Json.h"
|
#include "Json.h"
|
||||||
|
|
||||||
namespace json = rapidjson;
|
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||||
|
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||||
TServer::TServer(int argc, char** argv) {
|
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||||
info("BeamMP Server v" + Application::ServerVersion());
|
if (Arguments.size() > 1) {
|
||||||
if (argc > 1) {
|
Application::Settings.CustomIP = Arguments[0];
|
||||||
Application::Settings.CustomIP = argv[1];
|
|
||||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
||||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
||||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
||||||
Application::Settings.CustomIP.clear();
|
Application::Settings.CustomIP.clear();
|
||||||
warn("IP Specified is invalid! Ignoring");
|
beammp_warn("IP Specified is invalid! Ignoring");
|
||||||
} else {
|
} else {
|
||||||
info("server started with custom IP");
|
beammp_info("server started with custom IP");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||||
if (!WeakClientPtr.expired()) {
|
if (!WeakClientPtr.expired()) {
|
||||||
TClient& Client = *WeakClientPtr.lock();
|
TClient& Client = *WeakClientPtr.lock();
|
||||||
debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||||
Client.ClearCars();
|
Client.ClearCars();
|
||||||
WriteLock Lock(mClientsMutex);
|
WriteLock Lock(mClientsMutex);
|
||||||
mClients.erase(WeakClientPtr.lock());
|
mClients.erase(WeakClientPtr.lock());
|
||||||
@@ -39,7 +43,7 @@ void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
std::weak_ptr<TClient> TServer::InsertNewClient() {
|
||||||
debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
|
||||||
WriteLock Lock(mClientsMutex);
|
WriteLock Lock(mClientsMutex);
|
||||||
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
|
||||||
return *Iter;
|
return *Iter;
|
||||||
@@ -65,7 +69,7 @@ size_t TServer::ClientCount() const {
|
|||||||
|
|
||||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||||
//abort();
|
// abort();
|
||||||
}
|
}
|
||||||
if (Packet.substr(0, 4) == "ABG:") {
|
if (Packet.substr(0, 4) == "ABG:") {
|
||||||
Packet = DeComp(Packet.substr(4));
|
Packet = DeComp(Packet.substr(4));
|
||||||
@@ -82,7 +86,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
std::any Res;
|
std::any Res;
|
||||||
char Code = Packet.at(0);
|
char Code = Packet.at(0);
|
||||||
|
|
||||||
//V to Z
|
// V to Z
|
||||||
if (Code <= 90 && Code >= 86) {
|
if (Code <= 90 && Code >= 86) {
|
||||||
PPSMonitor.IncrementInternalPPS();
|
PPSMonitor.IncrementInternalPPS();
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||||
@@ -90,7 +94,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
}
|
}
|
||||||
switch (Code) {
|
switch (Code) {
|
||||||
case 'H': // initial connection
|
case 'H': // initial connection
|
||||||
trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
|
||||||
if (!Network.SyncClient(Client)) {
|
if (!Network.SyncClient(Client)) {
|
||||||
// TODO handle
|
// TODO handle
|
||||||
}
|
}
|
||||||
@@ -107,30 +111,38 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
return;
|
return;
|
||||||
case 'O':
|
case 'O':
|
||||||
if (Packet.length() > 1000) {
|
if (Packet.length() > 1000) {
|
||||||
debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
|
||||||
}
|
}
|
||||||
ParseVehicle(*LockedClient, Packet, Network);
|
ParseVehicle(*LockedClient, Packet, Network);
|
||||||
return;
|
return;
|
||||||
case 'J':
|
case 'J':
|
||||||
trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
case 'C':
|
case 'C': {
|
||||||
trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
||||||
break;
|
break;
|
||||||
Res = TriggerLuaEvent("onChatMessage", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }), true);
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
|
||||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1)); // FIXME: this needs to be adjusted once lua is merged
|
TLuaEngine::WaitForAll(Futures);
|
||||||
if (std::any_cast<int>(Res))
|
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.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;
|
break;
|
||||||
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
case 'E':
|
case 'E':
|
||||||
trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
HandleEvent(*LockedClient, Packet);
|
HandleEvent(*LockedClient, Packet);
|
||||||
return;
|
return;
|
||||||
case 'N':
|
case 'N':
|
||||||
trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||||
return;
|
return;
|
||||||
default:
|
default:
|
||||||
@@ -138,48 +150,38 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::HandleEvent(TClient& c, const std::string& Data) {
|
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||||
std::stringstream ss(Data);
|
// E:Name:Data
|
||||||
std::string t, Name;
|
// Data is allowed to have ':'
|
||||||
int a = 0;
|
auto NameDataSep = RawData.find(':', 2);
|
||||||
while (std::getline(ss, t, ':')) {
|
if (NameDataSep == std::string::npos) {
|
||||||
switch (a) {
|
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||||
case 1:
|
|
||||||
Name = t;
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
TriggerLuaEvent(Name, false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), t } }), false);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (a == 2)
|
|
||||||
break;
|
|
||||||
a++;
|
|
||||||
}
|
}
|
||||||
|
std::string Name = RawData.substr(2, NameDataSep - 2);
|
||||||
|
std::string Data = RawData.substr(NameDataSep + 1);
|
||||||
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
||||||
rapidjson::Document Car;
|
try {
|
||||||
Car.Parse(CarJson.c_str(), CarJson.size());
|
auto Car = nlohmann::json::parse(CarJson);
|
||||||
if (Car.HasParseError()) {
|
const std::string jbm = "jbm";
|
||||||
error("Failed to parse vehicle data -> " + CarJson);
|
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
|
||||||
} else if (Car["jbm"].IsString() && std::string(Car["jbm"].GetString()) == "unicycle") {
|
return true;
|
||||||
return true;
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
||||||
|
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
|
||||||
if (c.GetUnicycleID() > -1 && (c.GetCarCount() - 1) < Application::Settings.MaxCars) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IsUnicycle(c, CarJson)) {
|
|
||||||
c.SetUnicycleID(ID);
|
c.SetUnicycleID(ID);
|
||||||
return true;
|
return true;
|
||||||
|
} else {
|
||||||
|
return c.GetCarCount() < Application::Settings.MaxCars;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Application::Settings.MaxCars > c.GetCarCount();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||||
@@ -190,18 +192,23 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
int PID = -1;
|
int PID = -1;
|
||||||
int VID = -1, Pos;
|
int VID = -1, Pos;
|
||||||
std::string Data = Packet.substr(3), pid, vid;
|
std::string Data = Packet.substr(3), pid, vid;
|
||||||
switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
|
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||||
case 's':
|
case 's':
|
||||||
trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
if (Data.at(0) == '0') {
|
if (Data.at(0) == '0') {
|
||||||
int CarID = c.GetOpenCarID();
|
int CarID = c.GetOpenCarID();
|
||||||
debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
|
||||||
|
|
||||||
std::string CarJson = Packet.substr(5);
|
std::string CarJson = Packet.substr(5);
|
||||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||||
auto Res = TriggerLuaEvent(("onVehicleSpawn"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), CarID, Packet.substr(3) } }), true);
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
|
||||||
|
TLuaEngine::WaitForAll(Futures);
|
||||||
|
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||||
|
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||||
|
});
|
||||||
|
|
||||||
if (ShouldSpawn(c, CarJson, CarID) && std::any_cast<int>(Res) == 0) {
|
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||||
c.AddNewCar(CarID, Packet);
|
c.AddNewCar(CarID, Packet);
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
} else {
|
} else {
|
||||||
@@ -212,12 +219,12 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
if (!Network.Respond(c, Destroy, true)) {
|
if (!Network.Respond(c, Destroy, true)) {
|
||||||
// TODO: handle
|
// TODO: handle
|
||||||
}
|
}
|
||||||
debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'c':
|
case 'c':
|
||||||
trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Data.find('-'));
|
pid = Data.substr(0, Data.find('-'));
|
||||||
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
@@ -225,14 +232,17 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
VID = stoi(vid);
|
VID = stoi(vid);
|
||||||
}
|
}
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
auto Res = TriggerLuaEvent(("onVehicleEdited"), false, nullptr,
|
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Packet.substr(3) } }),
|
TLuaEngine::WaitForAll(Futures);
|
||||||
true);
|
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
||||||
|
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||||
|
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||||
|
});
|
||||||
|
|
||||||
auto FoundPos = Packet.find('{');
|
auto FoundPos = Packet.find('{');
|
||||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||||
&& std::any_cast<int>(Res) == 0) {
|
&& !ShouldntAllow) {
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
Apply(c, VID, Packet);
|
Apply(c, VID, Packet);
|
||||||
} else {
|
} else {
|
||||||
@@ -248,7 +258,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'd':
|
case 'd':
|
||||||
trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
pid = Data.substr(0, Data.find('-'));
|
pid = Data.substr(0, Data.find('-'));
|
||||||
vid = Data.substr(Data.find('-') + 1);
|
vid = Data.substr(Data.find('-') + 1);
|
||||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||||
@@ -260,14 +270,14 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
c.SetUnicycleID(-1);
|
c.SetUnicycleID(-1);
|
||||||
}
|
}
|
||||||
Network.SendToAll(nullptr, Packet, true, true);
|
Network.SendToAll(nullptr, Packet, true, true);
|
||||||
TriggerLuaEvent(("onVehicleDeleted"), false, nullptr,
|
// TODO: should this trigger on all vehicle deletions?
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID } }), false);
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||||
c.DeleteCar(VID);
|
c.DeleteCar(VID);
|
||||||
debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 'r':
|
case 'r':
|
||||||
trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Pos = int(Data.find('-'));
|
Pos = int(Data.find('-'));
|
||||||
pid = Data.substr(0, Pos++);
|
pid = Data.substr(0, Pos++);
|
||||||
vid = Data.substr(Pos, Data.find(':') - Pos);
|
vid = Data.substr(Pos, Data.find(':') - Pos);
|
||||||
@@ -279,18 +289,19 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
|
|
||||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||||
Data = Data.substr(Data.find('{'));
|
Data = Data.substr(Data.find('{'));
|
||||||
TriggerLuaEvent("onVehicleReset", false, nullptr,
|
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||||
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Data } }),
|
|
||||||
false);
|
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
case 't':
|
case 't':
|
||||||
trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||||
Network.SendToAll(&c, Packet, false, true);
|
Network.SendToAll(&c, Packet, false, true);
|
||||||
return;
|
return;
|
||||||
|
case 'm':
|
||||||
|
Network.SendToAll(&c, Packet, true, true);
|
||||||
|
return;
|
||||||
default:
|
default:
|
||||||
trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -298,13 +309,13 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
|||||||
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
||||||
auto FoundPos = pckt.find('{');
|
auto FoundPos = pckt.find('{');
|
||||||
if (FoundPos == std::string::npos) {
|
if (FoundPos == std::string::npos) {
|
||||||
error("Malformed packet received, no '{' found");
|
beammp_error("Malformed packet received, no '{' found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
std::string Packet = pckt.substr(FoundPos);
|
std::string Packet = pckt.substr(FoundPos);
|
||||||
std::string VD = c.GetCarData(VID);
|
std::string VD = c.GetCarData(VID);
|
||||||
if (VD.empty()) {
|
if (VD.empty()) {
|
||||||
error("Tried to apply change to vehicle that does not exist");
|
beammp_error("Tried to apply change to vehicle that does not exist");
|
||||||
auto Lock = Sentry.CreateExclusiveContext();
|
auto Lock = Sentry.CreateExclusiveContext();
|
||||||
Sentry.SetContext("vehicle-change",
|
Sentry.SetContext("vehicle-change",
|
||||||
{ { "packet", Packet },
|
{ { "packet", Packet },
|
||||||
@@ -321,19 +332,18 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|||||||
Sentry.SetContext("vehicle-change-packet",
|
Sentry.SetContext("vehicle-change-packet",
|
||||||
{ { "packet", VD } });
|
{ { "packet", VD } });
|
||||||
Sentry.LogError("malformed packet", _file_basename, _line);
|
Sentry.LogError("malformed packet", _file_basename, _line);
|
||||||
error("Malformed packet received, no '{' found");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
VD = VD.substr(FoundPos);
|
VD = VD.substr(FoundPos);
|
||||||
rapidjson::Document Veh, Pack;
|
rapidjson::Document Veh, Pack;
|
||||||
Veh.Parse(VD.c_str());
|
Veh.Parse(VD.c_str());
|
||||||
if (Veh.HasParseError()) {
|
if (Veh.HasParseError()) {
|
||||||
error("Could not get vehicle config!");
|
beammp_error("Could not get vehicle config!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Pack.Parse(Packet.c_str());
|
Pack.Parse(Packet.c_str());
|
||||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
if (Pack.HasParseError() || Pack.IsNull()) {
|
||||||
error("Could not get active vehicle config!");
|
beammp_error("Could not get active vehicle config!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -351,7 +361,7 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
||||||
debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
||||||
WriteLock Lock(mClientsMutex); //TODO why is there 30+ threads locked here
|
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||||
(void)mClients.insert(NewClient);
|
(void)mClients.insert(NewClient);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -6,9 +6,9 @@
|
|||||||
TVehicleData::TVehicleData(int ID, std::string Data)
|
TVehicleData::TVehicleData(int ID, std::string Data)
|
||||||
: mID(ID)
|
: mID(ID)
|
||||||
, mData(std::move(Data)) {
|
, mData(std::move(Data)) {
|
||||||
trace("vehicle " + std::to_string(mID) + " constructed");
|
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
|
||||||
}
|
}
|
||||||
|
|
||||||
TVehicleData::~TVehicleData() {
|
TVehicleData::~TVehicleData() {
|
||||||
trace("vehicle " + std::to_string(mID) + " destroyed");
|
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
|
||||||
}
|
}
|
||||||
|
|||||||
+189
-51
@@ -1,71 +1,209 @@
|
|||||||
#include "TSentry.h"
|
#include "TSentry.h"
|
||||||
|
|
||||||
|
#include "ArgsParser.h"
|
||||||
#include "Common.h"
|
#include "Common.h"
|
||||||
#include "CustomAssert.h"
|
#include "CustomAssert.h"
|
||||||
#include "Http.h"
|
#include "Http.h"
|
||||||
|
#include "LuaAPI.h"
|
||||||
#include "SignalHandling.h"
|
#include "SignalHandling.h"
|
||||||
#include "TConfig.h"
|
#include "TConfig.h"
|
||||||
#include "THeartbeatThread.h"
|
#include "THeartbeatThread.h"
|
||||||
#include "TLuaEngine.h"
|
#include "TLuaEngine.h"
|
||||||
#include "TNetwork.h"
|
#include "TNetwork.h"
|
||||||
#include "TPPSMonitor.h"
|
#include "TPPSMonitor.h"
|
||||||
|
#include "TPluginMonitor.h"
|
||||||
#include "TResourceManager.h"
|
#include "TResourceManager.h"
|
||||||
|
#include "TScopedTimer.h"
|
||||||
#include "TServer.h"
|
#include "TServer.h"
|
||||||
#include "../include/watchdog/watchdog.h"
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
// this is provided by the build system, leave empty for source builds
|
static const std::string sCommandlineArguments = R"(
|
||||||
// global, yes, this is ugly, no, it cant be done another way
|
USAGE:
|
||||||
TSentry Sentry {};
|
BeamMP-Server [arguments]
|
||||||
|
|
||||||
|
ARGUMENTS:
|
||||||
|
--help
|
||||||
|
Displays this help and exits.
|
||||||
|
--config=/path/to/ServerConfig.toml
|
||||||
|
Absolute or relative path to the
|
||||||
|
Server Config file, including the
|
||||||
|
filename. For paths and filenames with
|
||||||
|
spaces, put quotes around the path.
|
||||||
|
--working-directory=/path/to/folder
|
||||||
|
Sets the working directory of the Server.
|
||||||
|
All paths are considered relative to this,
|
||||||
|
including the path given in --config.
|
||||||
|
--version
|
||||||
|
Prints version info and exits.
|
||||||
|
|
||||||
|
EXAMPLES:
|
||||||
|
BeamMP-Server --config=../MyWestCoastServerConfig.toml
|
||||||
|
Runs the BeamMP-Server and uses the server config file
|
||||||
|
which is one directory above it and is named
|
||||||
|
'MyWestCoastServerConfig.toml'.
|
||||||
|
)";
|
||||||
|
|
||||||
|
struct MainArguments {
|
||||||
|
int argc {};
|
||||||
|
char** argv {};
|
||||||
|
std::vector<std::string_view> List;
|
||||||
|
std::string InvokedAs;
|
||||||
|
};
|
||||||
|
|
||||||
|
int BeamMPServerMain(MainArguments Arguments);
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
#ifdef WIN32
|
MainArguments Args { argc, argv, {}, argv[0] };
|
||||||
watchdog_init("watchdog_crash.log", nullptr);
|
Args.List.reserve(argc);
|
||||||
#endif
|
for (int i = 1; i < argc; ++i) {
|
||||||
try {
|
Args.List.push_back(argv[i]);
|
||||||
setlocale(LC_ALL, "C");
|
|
||||||
|
|
||||||
SetupSignalHandlers();
|
|
||||||
|
|
||||||
bool Shutdown = false;
|
|
||||||
Application::RegisterShutdownHandler([&Shutdown] { Shutdown = true; });
|
|
||||||
|
|
||||||
TServer Server(argc, argv);
|
|
||||||
TConfig Config;
|
|
||||||
|
|
||||||
if (Config.Failed()) {
|
|
||||||
info("Closing in 10 seconds");
|
|
||||||
// loop to make it possible to ctrl+c instead
|
|
||||||
for (size_t i = 0; i < 20; ++i) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
||||||
}
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
RegisterThread("Main");
|
|
||||||
|
|
||||||
trace("Running in debug mode on a debug build");
|
|
||||||
|
|
||||||
Sentry.SetupUser();
|
|
||||||
Sentry.PrintWelcome();
|
|
||||||
TResourceManager ResourceManager;
|
|
||||||
TPPSMonitor PPSMonitor(Server);
|
|
||||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
|
||||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
|
||||||
TLuaEngine LuaEngine(Server, Network);
|
|
||||||
PPSMonitor.SetNetwork(Network);
|
|
||||||
Application::Console().InitializeLuaConsole(LuaEngine);
|
|
||||||
Application::CheckForUpdates();
|
|
||||||
|
|
||||||
// TODO: replace
|
|
||||||
while (!Shutdown) {
|
|
||||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
|
||||||
}
|
|
||||||
info("Shutdown.");
|
|
||||||
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
error(e.what());
|
|
||||||
Sentry.LogException(e, _file_basename, _line);
|
|
||||||
}
|
}
|
||||||
|
int MainRet = 0;
|
||||||
|
try {
|
||||||
|
MainRet = BeamMPServerMain(std::move(Args));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
|
||||||
|
beammp_error(e.what());
|
||||||
|
Sentry.LogException(e, _file_basename, _line);
|
||||||
|
MainRet = -1;
|
||||||
|
}
|
||||||
|
std::exit(MainRet);
|
||||||
|
}
|
||||||
|
|
||||||
|
int BeamMPServerMain(MainArguments Arguments) {
|
||||||
|
setlocale(LC_ALL, "C");
|
||||||
|
Application::InitializeConsole();
|
||||||
|
ArgsParser Parser;
|
||||||
|
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||||
|
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||||
|
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
|
||||||
|
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
|
||||||
|
Parser.Parse(Arguments.List);
|
||||||
|
if (!Parser.Verify()) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (Parser.FoundArgument({ "help" })) {
|
||||||
|
Application::Console().Internal().set_prompt("");
|
||||||
|
Application::Console().WriteRaw(sCommandlineArguments);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (Parser.FoundArgument({ "version" })) {
|
||||||
|
Application::Console().Internal().set_prompt("");
|
||||||
|
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string ConfigPath = "ServerConfig.toml";
|
||||||
|
if (Parser.FoundArgument({ "config" })) {
|
||||||
|
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||||
|
if (MaybeConfigPath.has_value()) {
|
||||||
|
ConfigPath = MaybeConfigPath.value();
|
||||||
|
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Parser.FoundArgument({ "working-directory" })) {
|
||||||
|
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
|
||||||
|
if (MaybeWorkingDirectory.has_value()) {
|
||||||
|
beammp_info("Custom working directory requested via commandline arguments: '" + MaybeWorkingDirectory.value() + "'");
|
||||||
|
try {
|
||||||
|
fs::current_path(fs::path(MaybeWorkingDirectory.value()));
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
beammp_errorf("Could not set working directory to '{}': {}", MaybeWorkingDirectory.value(), e.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||||
|
|
||||||
|
Application::Console().StartLoggingToFile();
|
||||||
|
|
||||||
|
SetupSignalHandlers();
|
||||||
|
|
||||||
|
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);
|
||||||
|
TConfig Config(ConfigPath);
|
||||||
|
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||||
|
LuaEngine->SetServer(&Server);
|
||||||
|
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||||
|
|
||||||
|
if (Config.Failed()) {
|
||||||
|
beammp_info("Closing in 10 seconds");
|
||||||
|
// loop to make it possible to ctrl+c instead
|
||||||
|
for (size_t i = 0; i < 20; ++i) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
RegisterThread("Main");
|
||||||
|
|
||||||
|
beammp_trace("Running in debug mode on a debug build");
|
||||||
|
Sentry.SetupUser();
|
||||||
|
Sentry.PrintWelcome();
|
||||||
|
TResourceManager ResourceManager;
|
||||||
|
TPPSMonitor PPSMonitor(Server);
|
||||||
|
THeartbeatThread Heartbeat(ResourceManager, Server);
|
||||||
|
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
||||||
|
LuaEngine->SetNetwork(&Network);
|
||||||
|
PPSMonitor.SetNetwork(Network);
|
||||||
|
Application::CheckForUpdates();
|
||||||
|
|
||||||
|
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||||
|
|
||||||
|
if (Application::Settings.HTTPServerEnabled) {
|
||||||
|
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Good);
|
||||||
|
RegisterThread("Main(Waiting)");
|
||||||
|
|
||||||
|
std::set<std::string> IgnoreSubsystems {
|
||||||
|
"UpdateCheck" // Ignore as not to confuse users (non-vital system)
|
||||||
|
};
|
||||||
|
|
||||||
|
bool FullyStarted = false;
|
||||||
|
while (!Shutdown) {
|
||||||
|
if (!FullyStarted) {
|
||||||
|
FullyStarted = true;
|
||||||
|
bool WithErrors = false;
|
||||||
|
std::string SystemsBadList {};
|
||||||
|
auto Statuses = Application::GetSubsystemStatuses();
|
||||||
|
for (const auto& NameStatusPair : Statuses) {
|
||||||
|
if (IgnoreSubsystems.count(NameStatusPair.first) > 0) {
|
||||||
|
continue; // ignore
|
||||||
|
}
|
||||||
|
if (NameStatusPair.second == Application::Status::Starting) {
|
||||||
|
FullyStarted = false;
|
||||||
|
} else if (NameStatusPair.second == Application::Status::Bad) {
|
||||||
|
SystemsBadList += NameStatusPair.first + ", ";
|
||||||
|
WithErrors = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// remove ", "
|
||||||
|
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
|
||||||
|
if (FullyStarted) {
|
||||||
|
if (!WithErrors) {
|
||||||
|
beammp_info("ALL SYSTEMS STARTED SUCCESSFULLY, EVERYTHING IS OKAY");
|
||||||
|
} else {
|
||||||
|
beammp_error("STARTUP NOT SUCCESSFUL, SYSTEMS " + SystemsBadList + " HAD ERRORS. THIS MAY OR MAY NOT CAUSE ISSUES.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
|
}
|
||||||
|
Application::SetSubsystemStatus("Main", Application::Status::Shutdown);
|
||||||
|
beammp_info("Shutdown.");
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#define DOCTEST_CONFIG_IMPLEMENT
|
||||||
|
#include <doctest/doctest.h>
|
||||||
|
|
||||||
|
#include <Common.h>
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
doctest::Context context;
|
||||||
|
|
||||||
|
// Application::InitializeConsole();
|
||||||
|
|
||||||
|
context.applyCommandLine(argc, argv);
|
||||||
|
|
||||||
|
int res = context.run(); // run
|
||||||
|
|
||||||
|
if (context.shouldExit()) // important - query flags (and --exit) rely on the user doing this
|
||||||
|
return res; // propagate the result of the tests
|
||||||
|
|
||||||
|
int client_stuff_return_code = 0;
|
||||||
|
// your program - if the testing framework is integrated in your production code
|
||||||
|
|
||||||
|
return res + client_stuff_return_code; // the result from doctest is propagated here as well
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user