Compare commits

...
Author SHA1 Message Date
Lion Kortlepel 443871ec0f remove usages of weak_ptr 2024-01-11 14:30:25 +01:00
Lion Kortlepel 130e1acdb3 refactor client disconnect, client interation
anywhere a client is disconnected, TNetwork::Disconnect is called now.
Nothing else is valid.
ForEachClientWeak() was fully removed.
2024-01-11 14:14:34 +01:00
Lion Kortlepel aa29d04b60 remove unused TVehicleDataLockPair 2024-01-11 14:14:34 +01:00
Lion Kortlepel b9f73f77c3 major refactor of Client and Server
this refactor includes changes to TClient:

- all member fields are now public, but protected with Sync (an alias
  for boost::synchronized_value
- removed all (now) obsolete getters and setters

changes to TServer and TNetwork:

- thread-safe ID generation, previously it was possible for there to be
  ID duplicates. this is now solved by moving id generation and
  assignment into the same mutex locked context.
- deprecated ForEachClientWeak and replaced some usages of it with
  ForEachClient, getting rid of the weak_ptr shit in most places
- implemented a bunch of new functions for getting rid of more weak_ptr
  everywhere
2024-01-11 14:14:31 +01:00
Lion Kortlepel c6aa7776fc make update message adjustable by provider 2024-01-09 17:41:05 +01:00
Lion b0f5976121 Update release.yml to fix release message 2024-01-09 15:35:47 +01:00
Lion Kortlepel 1bd47fa649 add noninteractive flag for debian/ubuntu 2024-01-09 15:35:47 +01:00
Lion Kortlepel 0e924d0d51 fix bootstrap call 2024-01-09 15:35:47 +01:00
Lion Kortlepel 70a7a41882 add vcpkg bootstrap step 2024-01-09 15:35:47 +01:00
Lion Kortlepel 6ee816d10d add lua to vcpkg dependencies on windows 2024-01-09 15:35:47 +01:00
Lion Kortlepel 8695413211 add ubuntu 20.04, debian 12 scripts 2024-01-09 15:35:47 +01:00
Lion Kortlepel 52c5a995cc fix wrong action dependency 2024-01-09 15:35:47 +01:00
Lion Kortlepel 9d5568dc56 make all ci/cd build actions matrix generic 2024-01-09 15:35:47 +01:00
Lion c62a1b6add add arm64 builds to github actions
Update linux.yml to build ARM64 binaries for debian11

update linux.yml to fix incorrect runs-on tags

add ubuntu 22.04 arm64 build

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update 2-configure.sh

Update 2-configure.sh

Update 1-install-deps.sh

Update 1-install-deps.sh

Update 2-configure.sh

Update 2-configure.sh

Update linux.yml

use get-cmake

update vcpkg

force arm64 triplet
2024-01-09 15:35:47 +01:00
Lion Kortlepel 4228e18c90 reset default ID to 0 2024-01-09 15:34:33 +01:00
Lion Kortlepel 023e968302 refactor position packet handling, add regression tests 2024-01-09 15:34:33 +01:00
Lion Kortlepel a4eb10b6a4 fix MP.GetPositionRaw 2024-01-09 15:34:33 +01:00
Lion Kortlepel 0166e488d0 fix calling GlobalParser as static 2024-01-09 15:34:33 +01:00
Lion Kortlepel 0836fd3af8 fix bug in HandlePosition which caused the vehicle position not to be
saved properly
2024-01-09 15:34:33 +01:00
Lion Kortlepel 9791b8875c fix wrong order of SendErrorsShowMessage and SendErrors 2024-01-09 15:34:16 +01:00
Lion 01e8a1644a Bump version to v3.2.2 (#253) 2024-01-08 19:40:00 +01:00
Lion Kortlepel cebb2634a1 bump version 2024-01-08 17:43:54 +01:00
Lion 21a7ca1b64 Update README.md to remove mention of scripts and add ARM instructions (#243) 2023-12-30 15:07:39 +01:00
Lion bd4ab2b10d Update README.md 2023-12-30 10:22:12 +01:00
Lion 1cdc8e8f48 bump version number (#241) 2023-12-29 01:43:40 +01:00
Lion Kortlepel 1f72a45231 bump version number 2023-12-29 01:43:03 +01:00
Lion 002223afda Fix Server.log empty when stdout or stdin redirected (#235) 2023-12-28 21:27:44 +01:00
Lion Kortlepel ecc79b1918 update commandline to fix redirect issue 2023-12-28 21:23:31 +01:00
42 changed files with 772 additions and 599 deletions

No files matched your search

+58 -29
View File
@@ -2,16 +2,33 @@ name: Linux
on: [push] on: [push]
env: env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_FORCE_SYSTEM_BINARIES: 1
CMAKE_BUILD_TYPE: "Release" CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs: jobs:
debian-11-build: x86_64-matrix:
runs-on: ubuntu-latest runs-on: ubuntu-22.04
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: debian:11 image: ${{ matrix.distro }}:${{ matrix.version }}
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -30,43 +47,59 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/debian-11/1.5-git-safe.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/debian-11/3-build.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Archive server artifact - name: Archive server artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-debian name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
path: ./bin/BeamMP-Server path: ./bin/BeamMP-Server
- name: Archive server debug info artifact - name: Archive server debug info artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-debian.debug name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
path: ./bin/BeamMP-Server.debug path: ./bin/BeamMP-Server.debug
- name: Build Tests - name: Build Tests
run: bash ./scripts/debian-11/3-build-tests.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
- name: Install Runtime Dependencies - name: Install Runtime Dependencies
run: bash ./scripts/debian-11/4-install-runtime-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
- name: Test - name: Test
run: ./bin/BeamMP-Server-tests run: ./bin/BeamMP-Server-tests
ubuntu-22-04-build: arm64-matrix:
runs-on: ubuntu-latest runs-on: [Linux, ARM64]
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: ubuntu:22.04 image: ${{ matrix.distro }}:${{ matrix.version }}
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -85,39 +118,35 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/ubuntu-22.04/3-build.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Archive server artifact - name: Archive server artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-ubuntu name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
path: ./bin/BeamMP-Server path: ./bin/BeamMP-Server
- name: Archive server debug info artifact - name: Archive server debug info artifact
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-ubuntu.debug name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
path: ./bin/BeamMP-Server.debug path: ./bin/BeamMP-Server.debug
- name: Build Tests - name: Build Tests
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
- name: Install Runtime Dependencies - name: Install Runtime Dependencies
run: bash ./scripts/ubuntu-22.04/4-install-runtime-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
- name: Test - name: Test
run: ./bin/BeamMP-Server-tests run: ./bin/BeamMP-Server-tests
+52 -29
View File
@@ -8,6 +8,7 @@ on:
env: env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release" CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs: jobs:
create-release: create-release:
@@ -27,18 +28,30 @@ jobs:
draft: false draft: false
prerelease: true prerelease: true
body: | body: |
Files included in this release: Files included in this release are:
- `BeamMP-Server.exe` is the windows build. You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this. - `BeamMP-Server.$DISTRO.$DISTROVERSION.$ARCH` for linux builds, for example `BeamMP-Server.debian.11.x86_64` for the Debian 11 build for x86_64. All require `liblua5.3` to be installed.
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`. - `BeamMP-Server.exe` for the Windows build (x86_64). You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this.
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
upload-release-files-debian-11: x86_64-matrix:
name: Build and upload Debian 11 Release Files
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
needs: create-release needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container: container:
image: debian:11 image: ${{ matrix.distro }}:${{ matrix.version }}
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -57,21 +70,16 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/debian-11/1.5-git-safe.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/debian-11/3-build.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Upload Release Asset - name: Upload Release Asset
id: upload-release-asset id: upload-release-asset
@@ -79,9 +87,9 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server asset_path: ./bin/BeamMP-Server
asset_name: BeamMP-Server-debian
asset_content_type: application/x-elf asset_content_type: application/x-elf
- name: Upload Debug Info - name: Upload Debug Info
@@ -90,18 +98,33 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug asset_path: ./bin/BeamMP-Server.debug
asset_name: debuginfo-debian.debug
asset_content_type: application/x-elf asset_content_type: application/x-elf
upload-release-files-ubuntu-22-04: arm64-matrix:
name: Build and upload Ubuntu 22.04 Release Files runs-on: [Linux, ARM64]
runs-on: ubuntu-22.04
needs: create-release needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
container: container:
image: ubuntu:22.04 image: ${{ matrix.distro }}:${{ matrix.version }}
steps: steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables - name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6 uses: actions/github-script@v6
with: with:
@@ -120,16 +143,16 @@ jobs:
- name: Git config safe directory - name: Git config safe directory
shell: bash shell: bash
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies - name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment - name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake' run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server - name: Build Server
run: bash ./scripts/ubuntu-22.04/3-build.sh run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Upload Release Asset - name: Upload Release Asset
id: upload-release-asset id: upload-release-asset
@@ -137,9 +160,9 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server asset_path: ./bin/BeamMP-Server
asset_name: BeamMP-Server-ubuntu
asset_content_type: application/x-elf asset_content_type: application/x-elf
- name: Upload Debug Info - name: Upload Debug Info
@@ -148,9 +171,9 @@ jobs:
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }} upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug asset_path: ./bin/BeamMP-Server.debug
asset_name: debuginfo-ubuntu.debug
asset_content_type: application/x-elf asset_content_type: application/x-elf
upload-release-files-windows: upload-release-files-windows:
+2
View File
@@ -48,6 +48,7 @@ set(PRJ_HEADERS
include/TScopedTimer.h include/TScopedTimer.h
include/TServer.h include/TServer.h
include/VehicleData.h include/VehicleData.h
include/Env.h
) )
# add all source files (.cpp) to this, except the one with main() # add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES set(PRJ_SOURCES
@@ -70,6 +71,7 @@ set(PRJ_SOURCES
src/TScopedTimer.cpp src/TScopedTimer.cpp
src/TServer.cpp src/TServer.cpp
src/VehicleData.cpp src/VehicleData.cpp
src/Env.cpp
) )
find_package(Lua REQUIRED) find_package(Lua REQUIRED)
+6 -4
View File
@@ -52,20 +52,22 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
On Linux, you need some dependencies to **build** the server (on Windows, you don't): On Linux, you need some dependencies to **build** the server (on Windows, you don't):
For Debian, Ubuntu and others you can find scripts that do this in `scripts/`.
``` ```
liblua5.3-dev curl zip unzip tar cmake make git g++ liblua5.3-dev curl zip unzip tar cmake make git g++
``` ```
The names of each package may change depending on your platform. See in `scripts/` or use a search engine to find out what they're called for you. You can install these with your distribution's package manager. You will need sudo or need root for ONLY this step.
The names of each package may change depending on your platform.
If you are building for ARM (like aarch64), you need to run `export VCPKG_FORCE_SYSTEM_BINARIES=1` before the following commands.
You can build on **Windows, Linux** or other platforms by following these steps: You can build on **Windows, Linux** or other platforms by following these steps:
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`. 1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
2. Go into the directory `cd BeamMP-Server`. 2. Go into the directory `cd BeamMP-Server`.
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth. 3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
4. Build via `cmake --build bin --parallel -t BeamMP-Server`. 4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
5. Your executable can be found in `bin/`. 5. Your executable can be found in `bin/`.
When you make changes to the code, you only have to run step 4 again. When you make changes to the code, you only have to run step 4 again.
+32 -60
View File
@@ -10,6 +10,8 @@
#include "BoostAliases.h" #include "BoostAliases.h"
#include "Common.h" #include "Common.h"
#include "Compat.h" #include "Compat.h"
#include "RWMutex.h"
#include "Sync.h"
#include "VehicleData.h" #include "VehicleData.h"
class TServer; class TServer;
@@ -28,11 +30,6 @@ class TClient final {
public: public:
using TSetOfVehicleData = std::vector<TVehicleData>; using TSetOfVehicleData = std::vector<TVehicleData>;
struct TVehicleDataLockPair {
TSetOfVehicleData* VehicleData;
std::unique_lock<std::mutex> Lock;
};
TClient(TServer& Server, ip::tcp::socket&& Socket); TClient(TServer& Server, ip::tcp::socket&& Socket);
TClient(const TClient&) = delete; TClient(const TClient&) = delete;
~TClient(); ~TClient();
@@ -41,76 +38,51 @@ public:
void AddNewCar(int Ident, const std::string& Data); void AddNewCar(int Ident, const std::string& Data);
void SetCarData(int Ident, const std::string& Data); void SetCarData(int Ident, const std::string& Data);
void SetCarPosition(int Ident, const std::string& Data); void SetCarPosition(int Ident, const std::string& Data);
TVehicleDataLockPair GetAllCars();
void SetName(const std::string& Name) { mName = Name; } void SetName(const std::string& NewName) { Name = NewName; }
void SetRoles(const std::string& Role) { mRole = Role; } void SetRoles(const std::string& NewRole) { Role = NewRole; }
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; } void SetIdentifier(const std::string& key, const std::string& value);
std::string GetCarData(int Ident); std::string GetCarData(int Ident);
std::string GetCarPositionRaw(int Ident); std::string GetCarPositionRaw(int Ident);
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; } bool IsDisconnected() const { return !TCPSocket->is_open(); }
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
void Disconnect(std::string_view Reason);
bool IsDisconnected() const { return !mSocket.is_open(); }
// locks // locks
void DeleteCar(int Ident); void DeleteCar(int Ident);
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
[[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; }
void SetID(int ID) { mID = ID; }
[[nodiscard]] int GetOpenCarID() const; [[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const; [[nodiscard]] int GetCarCount() const;
void ClearCars(); void ClearCars();
[[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::vector<uint8_t>& Packet); void EnqueuePacket(const std::vector<uint8_t>& Packet);
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; } void SetIsConnected(bool NewIsConnected) { IsConnected = NewIsConnected; }
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
[[nodiscard]] TServer& Server() const; [[nodiscard]] TServer& Server() const;
void UpdatePingTime(); void UpdatePingTime();
int SecondsSinceLastPing(); int SecondsSinceLastPing();
Sync<bool> IsConnected = false;
Sync<bool> IsSynced = false;
Sync<bool> IsSyncing = false;
Sync<std::unordered_map<std::string, std::string>> Identifiers;
Sync<ip::tcp::socket> TCPSocket;
Sync<ip::tcp::socket> DownSocket;
Sync<ip::udp::endpoint> UDPAddress {};
Sync<int> UnicycleID = -1;
Sync<std::string> Role;
Sync<std::string> DID;
Sync<int> ID = -1;
Sync<bool> IsGuest = false;
Sync<std::string> Name = std::string("Unknown Client");
Sync<TSetOfVehicleData> VehicleData;
Sync<SparseArray<std::string>> VehiclePosition;
Sync<std::queue<std::vector<uint8_t>>> MissedPacketsQueue;
Sync<std::chrono::time_point<std::chrono::high_resolution_clock>> LastPingTime;
friend class TNetwork;
private: private:
/// ONLY call after the client has been cleaned up, all cars deleted, etc.
void CloseSockets(std::string_view Reason);
void InsertVehicle(int ID, const std::string& Data); void InsertVehicle(int ID, const std::string& Data);
TServer& mServer; TServer& mServer;
bool mIsConnected = false;
bool mIsSynced = false;
bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex;
std::queue<std::vector<uint8_t>> mPacketsSync;
std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex;
mutable std::mutex mVehiclePositionMutex;
TSetOfVehicleData mVehicleData;
SparseArray<std::string> mVehiclePosition;
std::string mName = "Unknown Client";
ip::tcp::socket mSocket;
ip::tcp::socket mDownSocket;
ip::udp::endpoint mUDPAddress {};
int mUnicycleID = -1;
std::string mRole;
std::string mDID;
int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
}; };
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID); std::optional<std::shared_ptr<TClient>> GetClient(class TServer& Server, int ID);
+1 -1
View File
@@ -134,7 +134,7 @@ private:
static inline std::mutex mShutdownHandlersMutex {}; static inline std::mutex mShutdownHandlersMutex {};
static inline std::deque<TShutdownHandler> mShutdownHandlers {}; static inline std::deque<TShutdownHandler> mShutdownHandlers {};
static inline Version mVersion { 3, 2, 0 }; static inline Version mVersion { 3, 2, 2 };
}; };
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out); void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <optional>
#include <string>
namespace Env {
enum class Key {
// provider settings
PROVIDER_UPDATE_MESSAGE,
};
std::optional<std::string> Get(Key key);
std::string_view ToString(Key key);
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <boost/thread/synchronized_value.hpp>
/// This header provides convenience aliases for synchronization primitives.
template<typename T>
using Sync = boost::synchronized_value<T>;
+2 -1
View File
@@ -220,6 +220,8 @@ private:
// Debug functions, slow // Debug functions, slow
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue(); std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue(); std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
sol::table Lua_JsonDecode(const std::string& str);
private: private:
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs); sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
@@ -230,7 +232,6 @@ private:
sol::table Lua_GetPlayerVehicles(int ID); sol::table Lua_GetPlayerVehicles(int ID);
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID); std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port); sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
sol::table Lua_JsonDecode(const std::string& str);
int Lua_GetPlayerIDByName(const std::string& Name); int Lua_GetPlayerIDByName(const std::string& Name);
sol::table Lua_FS_ListFiles(const std::string& Path); sol::table Lua_FS_ListFiles(const std::string& Path);
sol::table Lua_FS_ListDirectories(const std::string& Path); sol::table Lua_FS_ListDirectories(const std::string& Path);
+8 -7
View File
@@ -19,6 +19,9 @@ public:
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock); std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
std::vector<uint8_t> TCPRcv(TClient& c); std::vector<uint8_t> TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R); void ClientKick(TClient& c, const std::string& R);
void Disconnect(const std::shared_ptr<TClient>& ClientPtr);
void Disconnect(const std::weak_ptr<TClient>& ClientPtr);
void Disconnect(TClient& Client);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c); [[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(TConnection&& client); void Identify(TConnection&& client);
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection); std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
@@ -41,15 +44,13 @@ private:
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint); std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
void HandleDownload(TConnection&& TCPSock); void HandleDownload(TConnection&& TCPSock);
void OnConnect(const std::weak_ptr<TClient>& c); void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::weak_ptr<TClient>& c); void TCPClient(const std::shared_ptr<TClient>& c);
void Looper(const std::weak_ptr<TClient>& c); void Looper(const std::shared_ptr<TClient>& c);
int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
void Parse(TClient& c, const std::vector<uint8_t>& Packet); void Parse(TClient& c, const std::vector<uint8_t>& Packet);
void SendFile(TClient& c, const std::string& Name); void SendFile(TClient& c, const std::string& Name);
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size); bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name); void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size); const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
}; };
std::string HashPassword(const std::string& str); std::string HashPassword(const std::string& str);
+7 -3
View File
@@ -22,14 +22,18 @@ public:
void InsertClient(const std::shared_ptr<TClient>& Ptr); void InsertClient(const std::shared_ptr<TClient>& Ptr);
void RemoveClient(const std::weak_ptr<TClient>&); void RemoveClient(const std::weak_ptr<TClient>&);
void RemoveClient(TClient&);
// in Fn, return true to continue, return false to break // in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn); void ForEachClient(const std::function<bool(const std::shared_ptr<TClient>&)> Fn);
size_t ClientCount() const; size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network); void GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data); static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; } RWMutex& GetClientMutex() const { return mClientsMutex; }
// thread-safe ID lookup & claim
void ClaimFreeIDFor(TClient& Client);
const TScopedTimer UptimeTimer; const TScopedTimer UptimeTimer;
// asio io context // asio io context
@@ -43,7 +47,7 @@ private:
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID); static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson); static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt); static void Apply(TClient& c, int VID, const std::string& pckt);
static void HandlePosition(TClient& c, const std::string& Packet); void HandlePosition(TClient& c, const std::string& Packet);
}; };
struct BufferView { struct BufferView {
+1 -1
View File
@@ -4,4 +4,4 @@ set -ex
apt-get update -y apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+2
View File
@@ -2,4 +2,6 @@
set -ex set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+1 -1
View File
@@ -4,4 +4,4 @@ set -ex
apt-get update -y apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+2
View File
@@ -2,4 +2,6 @@
set -ex set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
Regular → Executable
+2
View File
@@ -2,4 +2,6 @@
set -ex set -ex
./vcpkg/vcpkg add port lua
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
+50 -49
View File
@@ -7,29 +7,28 @@
void TClient::DeleteCar(int Ident) { void TClient::DeleteCar(int Ident) {
// TODO: Send delete packets // TODO: Send delete packets
std::unique_lock lock(mVehicleDataMutex); auto VehData = VehicleData.synchronize();
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) { auto iter = std::find_if(VehData->begin(), VehData->end(), [&](auto& elem) {
return Ident == elem.ID(); return Ident == elem.ID();
}); });
if (iter != mVehicleData.end()) { if (iter != VehData->end()) {
mVehicleData.erase(iter); VehData->erase(iter);
} else { } else {
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)"); beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
} }
} }
void TClient::ClearCars() { void TClient::ClearCars() {
std::unique_lock lock(mVehicleDataMutex); VehicleData->clear();
mVehicleData.clear();
} }
int TClient::GetOpenCarID() const { int TClient::GetOpenCarID() const {
int OpenID = 0; int OpenID = 0;
bool found; bool found;
std::unique_lock lock(mVehicleDataMutex); auto VehData = VehicleData.synchronize();
do { do {
found = true; found = true;
for (auto& v : mVehicleData) { for (auto& v : *VehData) {
if (v.ID() == OpenID) { if (v.ID() == OpenID) {
OpenID++; OpenID++;
found = false; found = false;
@@ -40,46 +39,49 @@ int TClient::GetOpenCarID() const {
} }
void TClient::AddNewCar(int Ident, const std::string& Data) { void TClient::AddNewCar(int Ident, const std::string& Data) {
std::unique_lock lock(mVehicleDataMutex); VehicleData->emplace_back(Ident, Data);
mVehicleData.emplace_back(Ident, Data);
}
TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
} }
std::string TClient::GetCarPositionRaw(int Ident) { std::string TClient::GetCarPositionRaw(int Ident) {
std::unique_lock lock(mVehiclePositionMutex);
try { try {
return mVehiclePosition.at(size_t(Ident)); return VehiclePosition->at(size_t(Ident));
} catch (const std::out_of_range& oor) { } catch (const std::out_of_range& oor) {
beammp_debugf("GetCarPositionRaw failed for id {}, as that car doesn't exist on client id {}: {}", Ident, int(ID), oor.what());
return ""; return "";
} }
return "";
} }
void TClient::Disconnect(std::string_view Reason) { void TClient::CloseSockets(std::string_view Reason) {
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason); auto LockedSocket = TCPSocket.synchronize();
beammp_debugf("Disconnecting client {} for reason: {}", int(ID), Reason);
boost::system::error_code ec; boost::system::error_code ec;
mSocket.shutdown(socket_base::shutdown_both, ec); LockedSocket->shutdown(socket_base::shutdown_both, ec);
if (ec) { if (ec) {
beammp_debugf("Failed to shutdown client socket: {}", ec.message()); beammp_debugf("Failed to shutdown client socket of client {}: {}", ID.get(), ec.message());
} }
mSocket.close(ec); LockedSocket->close(ec);
if (ec) { if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message()); beammp_debugf("Failed to close client socket of client {}: {}", ID.get(), ec.message());
}
DownSocket->shutdown(socket_base::shutdown_both, ec);
if (ec) {
beammp_debugf("Failed to shutdown client download socket of client {}: {}", ID.get(), ec.message());
}
DownSocket->close(ec);
if (ec) {
beammp_debugf("Failed to close client download socket of client {}: {}", ID.get(), ec.message());
} }
} }
void TClient::SetCarPosition(int Ident, const std::string& Data) { void TClient::SetCarPosition(int Ident, const std::string& Data) {
std::unique_lock lock(mVehiclePositionMutex); // ugly but this is c++ so
mVehiclePosition[size_t(Ident)] = Data; VehiclePosition->operator[](size_t(Ident)) = Data;
} }
std::string TClient::GetCarData(int Ident) { std::string TClient::GetCarData(int Ident) {
{ // lock { // lock
std::unique_lock lock(mVehicleDataMutex); auto Lock = VehicleData.synchronize();
for (auto& v : mVehicleData) { for (auto& v : *Lock) {
if (v.ID() == Ident) { if (v.ID() == Ident) {
return v.Data(); return v.Data();
} }
@@ -91,8 +93,8 @@ std::string TClient::GetCarData(int Ident) {
void TClient::SetCarData(int Ident, const std::string& Data) { void TClient::SetCarData(int Ident, const std::string& Data) {
{ // lock { // lock
std::unique_lock lock(mVehicleDataMutex); auto Lock = VehicleData.synchronize();
for (auto& v : mVehicleData) { for (auto& v : *Lock) {
if (v.ID() == Ident) { if (v.ID() == Ident) {
v.SetData(Data); v.SetData(Data);
return; return;
@@ -103,7 +105,7 @@ void TClient::SetCarData(int Ident, const std::string& Data) {
} }
int TClient::GetCarCount() const { int TClient::GetCarCount() const {
return int(mVehicleData.size()); return int(VehicleData->size());
} }
TServer& TClient::Server() const { TServer& TClient::Server() const {
@@ -111,43 +113,42 @@ TServer& TClient::Server() const {
} }
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) { void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
std::unique_lock Lock(mMissedPacketsMutex); MissedPacketsQueue->push(Packet);
mPacketsSync.push(Packet);
} }
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket) TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
: mServer(Server) : TCPSocket(std::move(Socket))
, mSocket(std::move(Socket)) , DownSocket(ip::tcp::socket(Server.IoCtx()))
, mDownSocket(ip::tcp::socket(Server.IoCtx())) , LastPingTime(std::chrono::high_resolution_clock::now())
, mLastPingTime(std::chrono::high_resolution_clock::now()) { , mServer(Server) {
} }
TClient::~TClient() { TClient::~TClient() {
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName()); beammp_debugf("client destroyed: {} ('{}')", ID.get(), Name.get());
} }
void TClient::UpdatePingTime() { void TClient::UpdatePingTime() {
mLastPingTime = std::chrono::high_resolution_clock::now(); LastPingTime = std::chrono::high_resolution_clock::now();
} }
int TClient::SecondsSinceLastPing() { int TClient::SecondsSinceLastPing() {
auto seconds = std::chrono::duration_cast<std::chrono::seconds>( auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - mLastPingTime) std::chrono::high_resolution_clock::now() - LastPingTime.get())
.count(); .count();
return int(seconds); return int(seconds);
} }
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) { std::optional<std::shared_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt }; std::optional<std::shared_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool { Server.ForEachClient([ID, &MaybeClient](const auto& Client) -> bool {
ReadLock Lock(Server.GetClientMutex()); if (Client->ID.get() == ID) {
if (!CPtr.expired()) { MaybeClient = Client;
auto C = CPtr.lock(); return false;
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
} }
return true; return true;
}); });
return MaybeClient; return MaybeClient;
} }
void TClient::SetIdentifier(const std::string& key, const std::string& value) {
// I know this is bad, but what can ya do
Identifiers->operator[](key) = value;
}
+7 -2
View File
@@ -1,8 +1,10 @@
#include "Common.h" #include "Common.h"
#include "Env.h"
#include "TConsole.h" #include "TConsole.h"
#include <array> #include <array>
#include <charconv> #include <charconv>
#include <fmt/core.h>
#include <iostream> #include <iostream>
#include <map> #include <map>
#include <regex> #include <regex>
@@ -201,8 +203,11 @@ void Application::CheckForUpdates() {
auto MyVersion = ServerVersion(); auto MyVersion = ServerVersion();
auto RemoteVersion = Version(VersionStrToInts(Response)); auto RemoteVersion = Version(VersionStrToInts(Response));
if (IsOutdated(MyVersion, RemoteVersion)) { if (IsOutdated(MyVersion, RemoteVersion)) {
std::string RealVersionString = RemoteVersion.AsString(); std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET)); const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
} else { } else {
if (FirstTime) { if (FirstTime) {
beammp_info("Server up-to-date!"); beammp_info("Server up-to-date!");
+20
View File
@@ -0,0 +1,20 @@
#include "Env.h"
#include <optional>
std::optional<std::string> Env::Get(Env::Key key) {
auto StrKey = ToString(key);
auto Value = std::getenv(StrKey.data());
if (!Value || std::string_view(Value).empty()) {
return std::nullopt;
}
return Value;
}
std::string_view Env::ToString(Env::Key key) {
switch (key) {
case Key::PROVIDER_UPDATE_MESSAGE:
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
break;
}
return "";
}
+17 -16
View File
@@ -120,14 +120,14 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
return { true, "" }; return { true, "" };
} else { } else {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient) {
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID); beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
return { false, "Invalid Player ID" }; return { false, "Invalid Player ID" };
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID); beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets"); LuaAPI::MP::Engine->Network().Disconnect(*c);
return { false, "Respond failed, dropping client" }; return { false, "Respond failed, dropping client" };
} }
return { true, "" }; return { true, "" };
@@ -141,11 +141,11 @@ std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) { std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient) {
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID); beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
return { false, "Player does not exist" }; return { false, "Player does not exist" };
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason")); LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" }; return { true, "" };
} }
@@ -159,17 +159,18 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
Result.first = true; Result.first = true;
} else { } else {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
if (!c->IsSynced()) { if (!c->IsSynced) {
Result.first = false; Result.first = false;
Result.second = "Player still syncing data"; Result.second = "Player still syncing data";
return Result; return Result;
} }
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message); LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message);
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID); beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
// TODO: should we return an error here? beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get());
Engine->Network().Disconnect(c);
} }
Result.first = true; Result.first = true;
} else { } else {
@@ -185,13 +186,13 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) { std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
std::pair<bool, std::string> Result; std::pair<bool, std::string> Result;
auto MaybeClient = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient) {
beammp_lua_error("RemoveVehicle invalid Player ID"); beammp_lua_error("RemoveVehicle invalid Player ID");
Result.first = false; Result.first = false;
Result.second = "Invalid Player ID"; Result.second = "Invalid Player ID";
return Result; return Result;
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
if (!c->GetCarData(VID).empty()) { if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true); Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
@@ -274,8 +275,8 @@ void LuaAPI::MP::Sleep(size_t Ms) {
bool LuaAPI::MP::IsPlayerConnected(int ID) { bool LuaAPI::MP::IsPlayerConnected(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
return MaybeClient.value().lock()->IsConnected(); return MaybeClient.value()->IsConnected.get();
} else { } else {
return false; return false;
} }
@@ -283,8 +284,8 @@ bool LuaAPI::MP::IsPlayerConnected(int ID) {
bool LuaAPI::MP::IsPlayerGuest(int ID) { bool LuaAPI::MP::IsPlayerGuest(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
return MaybeClient.value().lock()->IsGuest(); return MaybeClient.value()->IsGuest.get();
} else { } else {
return false; return false;
} }
+3 -3
View File
@@ -120,9 +120,9 @@ void TConfig::FlushToFile() {
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages; data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless."); SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors; data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here"); SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled; data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`"); SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
std::stringstream Ss; std::stringstream Ss;
Ss << "# This is the BeamMP-Server config file.\n" Ss << "# This is the BeamMP-Server config file.\n"
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n" "# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
@@ -313,6 +313,6 @@ std::string TConfig::TagsAsPrettyArray() const {
for (size_t i = 0; i < TagsArray.size() - 1; ++i) { for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
Pretty += '\"' + TagsArray[i] + "\", "; Pretty += '\"' + TagsArray[i] + "\", ";
} }
Pretty += '\"' + TagsArray.at(TagsArray.size()-1) + "\""; Pretty += '\"' + TagsArray.at(TagsArray.size() - 1) + "\"";
return Pretty; return Pretty;
} }
+16 -25
View File
@@ -266,15 +266,12 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); }); std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1); return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
}; };
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
if (!Client.expired()) { if (NameCompare(Client->Name.get(), Name)) {
auto locked = Client.lock(); mLuaEngine->Network().ClientKick(*Client, Reason);
if (NameCompare(locked->GetName(), Name)) {
mLuaEngine->Network().ClientKick(*locked, Reason);
Kicked = true; Kicked = true;
return false; return false;
} }
}
return true; return true;
}); });
if (!Kicked) { if (!Kicked) {
@@ -364,13 +361,10 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
} else { } else {
std::stringstream ss; std::stringstream ss;
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl; ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
if (!Client.expired()) { ss << std::left << std::setw(25) << Client->Name.get()
auto locked = Client.lock(); << std::setw(6) << Client->ID.get()
ss << std::left << std::setw(25) << locked->GetName() << std::setw(6) << Client->GetCarCount() << "\n";
<< std::setw(6) << locked->GetID()
<< std::setw(6) << locked->GetCarCount() << "\n";
}
return true; return true;
}); });
auto Str = ss.str(); auto Str = ss.str();
@@ -391,18 +385,15 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
size_t SyncingCount = 0; size_t SyncingCount = 0;
size_t MissedPacketQueueSum = 0; size_t MissedPacketQueueSum = 0;
int LargestSecondsSinceLastPing = 0; int LargestSecondsSinceLastPing = 0;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](std::shared_ptr<TClient> Client) -> bool {
if (!Client.expired()) { CarCount += size_t(Client->GetCarCount());
auto Locked = Client.lock(); ConnectedCount += Client->IsConnected ? 1 : 0;
CarCount += Locked->GetCarCount(); GuestCount += Client->IsGuest ? 1 : 0;
ConnectedCount += Locked->IsConnected() ? 1 : 0; SyncedCount += Client->IsSynced ? 1 : 0;
GuestCount += Locked->IsGuest() ? 1 : 0; SyncingCount += Client->IsSyncing ? 1 : 0;
SyncedCount += Locked->IsSynced() ? 1 : 0; MissedPacketQueueSum += Client->MissedPacketsQueue->size();
SyncingCount += Locked->IsSyncing() ? 1 : 0; if (Client->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
MissedPacketQueueSum += Locked->MissedPacketQueueSize(); LargestSecondsSinceLastPing = Client->SecondsSinceLastPing();
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
}
} }
return true; return true;
}); });
+2 -5
View File
@@ -153,11 +153,8 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
} }
std::string THeartbeatThread::GetPlayers() { std::string THeartbeatThread::GetPlayers() {
std::string Return; std::string Return;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::shared_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex()); Return += ClientPtr->Name.get() + ";";
if (!ClientPtr.expired()) {
Return += ClientPtr.lock()->GetName() + ";";
}
return true; return true;
}); });
return Return; return Return;
+21 -31
View File
@@ -480,13 +480,13 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
auto IDs = MaybeClient.value().lock()->GetIdentifiers(); auto IDs = MaybeClient.value()->Identifiers.synchronize();
if (IDs.empty()) { if (IDs->empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::table Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
for (const auto& Pair : IDs) { for (const auto& Pair : *IDs) {
Result[Pair.first] = Pair.second; Result[Pair.first] = Pair.second;
} }
return Result; return Result;
@@ -497,11 +497,8 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() { sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
sol::table Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
if (!Client.expired()) { Result[Client->ID.get()] = Client->Name.get();
auto locked = Client.lock();
Result[locked->GetID()] = locked->GetName();
}
return true; return true;
}); });
return Result; return Result;
@@ -509,13 +506,10 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) { int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
int Id = -1; int Id = -1;
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool { mEngine->mServer->ForEachClient([&Id, &Name](const std::shared_ptr<TClient>& Client) -> bool {
if (!Client.expired()) { if (Client->Name.get() == Name) {
auto locked = Client.lock(); Id = Client->ID.get();
if (locked->GetName() == Name) { return false;
Id = locked->GetID();
return false;
}
} }
return true; return true;
}); });
@@ -550,8 +544,8 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) { std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
return MaybeClient.value().lock()->GetName(); return MaybeClient.value()->Name.get();
} else { } else {
return ""; return "";
} }
@@ -559,19 +553,15 @@ std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
auto Client = MaybeClient.value().lock(); auto Client = MaybeClient.value();
TClient::TSetOfVehicleData VehicleData; auto VehicleData = Client->VehicleData.synchronize();
{ // Vehicle Data Lock Scope if (VehicleData->empty()) {
auto LockedData = Client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (VehicleData.empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::state_view StateView(mState); sol::state_view StateView(mState);
sol::table Result = StateView.create_table(); sol::table Result = StateView.create_table();
for (const auto& v : VehicleData) { for (const auto& v : *VehicleData) {
Result[v.ID()] = v.Data().substr(3); Result[v.ID()] = v.Data().substr(3);
} }
return Result; return Result;
@@ -582,8 +572,8 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) { std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
std::pair<sol::table, std::string> Result; std::pair<sol::table, std::string> Result;
auto MaybeClient = GetClient(mEngine->Server(), PID); auto MaybeClient = GetClient(mEngine->Server(), PID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
auto Client = MaybeClient.value().lock(); auto Client = MaybeClient.value();
std::string VehiclePos = Client->GetCarPositionRaw(VID); std::string VehiclePos = Client->GetCarPositionRaw(VID);
if (VehiclePos.empty()) { if (VehiclePos.empty()) {
@@ -601,7 +591,7 @@ std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionR
return Result; return Result;
} else { } else {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired")); // return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
Result.second = "Client expired"; Result.second = "No such player";
return Result; return Result;
} }
} }
@@ -1083,7 +1073,7 @@ void TLuaResult::MarkAsReady() {
void TLuaResult::WaitUntilReady() { void TLuaResult::WaitUntilReady() {
std::unique_lock readyLock(*this->ReadyMutex); std::unique_lock readyLock(*this->ReadyMutex);
// wait if not ready yet // wait if not ready yet
if(!this->Ready) if (!this->Ready)
this->ReadyCondition->wait(readyLock); this->ReadyCondition->wait(readyLock);
} }
+188 -239
View File
@@ -9,6 +9,7 @@
#include <array> #include <array>
#include <boost/asio/ip/address.hpp> #include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp> #include <boost/asio/ip/address_v4.hpp>
#include <boost/thread/synchronized_value.hpp>
#include <cstring> #include <cstring>
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option; typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option;
@@ -35,10 +36,8 @@ TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& R
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting); Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
beammp_debug("Kicking all players due to shutdown"); beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool { Server.ForEachClient([&](std::shared_ptr<TClient> Client) -> bool {
if (!client.expired()) { ClientKick(*Client, "Server shutdown");
ClientKick(*client.lock(), "Server shutdown");
}
return true; return true;
}); });
}); });
@@ -87,23 +86,13 @@ void TNetwork::UDPServerMain() {
if (Data.empty() || Pos > Data.begin() + 2) if (Data.empty() || Pos > Data.begin() + 2)
continue; continue;
uint8_t ID = uint8_t(Data.at(0)) - 1; uint8_t ID = uint8_t(Data.at(0)) - 1;
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool { mServer.ForEachClient([&](std::shared_ptr<TClient> Client) -> bool {
std::shared_ptr<TClient> Client; if (Client->ID == ID) {
{ Client->UDPAddress = client;
ReadLock Lock(mServer.GetClientMutex()); Client->IsConnected = true;
if (!ClientPtr.expired()) {
Client = ClientPtr.lock();
} else
return true;
}
if (Client->GetID() == ID) {
Client->SetUDPAddr(client);
Client->SetIsConnected(true);
Data.erase(Data.begin(), Data.begin() + 2); Data.erase(Data.begin(), Data.begin() + 2);
TServer::GlobalParser(ClientPtr, std::move(Data), mPPSMonitor, *this); mServer.GlobalParser(Client, std::move(Data), mPPSMonitor, *this);
} }
return true; return true;
}); });
} catch (const std::exception& e) { } catch (const std::exception& e) {
@@ -191,8 +180,8 @@ void TNetwork::Identify(TConnection&& RawConnection) {
} else { } else {
beammp_errorf("Invalid code got in Identify: '{}'", Code); beammp_errorf("Invalid code got in Identify: '{}'", Code);
} }
} catch(const std::exception& e) { } catch (const std::exception& e) {
beammp_errorf("Error during handling of code {} - client left in invalid state, closing socket", Code); beammp_errorf("Error during handling of code {}->client left in invalid state, closing socket", Code);
boost::system::error_code ec; boost::system::error_code ec;
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec); RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
if (ec) { if (ec) {
@@ -215,16 +204,11 @@ void TNetwork::HandleDownload(TConnection&& Conn) {
return; return;
} }
auto ID = uint8_t(D); auto ID = uint8_t(D);
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { auto Client = GetClient(mServer, ID);
ReadLock Lock(mServer.GetClientMutex()); if (Client.has_value()) {
if (!ClientPtr.expired()) { auto New = Sync<ip::tcp::socket>(std::move(Conn.Socket));
auto c = ClientPtr.lock(); Client.value()->DownSocket.swap(New);
if (c->GetID() == ID) { }
c->SetDownSock(std::move(Conn.Socket));
}
}
return true;
});
} }
std::string HashPassword(const std::string& str) { std::string HashPassword(const std::string& str) {
@@ -260,8 +244,9 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
if (!TCPSend(*Client, StringToVector("A"))) { //changed to A for Accepted version if (!TCPSend(*Client, StringToVector("A"))) { // changed to A for Accepted version
// TODO: handle Disconnect(Client);
return nullptr;
} }
Data = TCPRcv(*Client); Data = TCPRcv(*Client);
@@ -273,8 +258,8 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
std::string key(reinterpret_cast<const char*>(Data.data()), Data.size()); std::string key(reinterpret_cast<const char*>(Data.data()), Data.size());
nlohmann::json AuthReq{}; nlohmann::json AuthReq {};
std::string AuthResStr{}; std::string AuthResStr {};
try { try {
AuthReq = nlohmann::json { AuthReq = nlohmann::json {
{ "key", key } { "key", key }
@@ -298,7 +283,7 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
Client->SetName(AuthRes["username"]); Client->SetName(AuthRes["username"]);
Client->SetRoles(AuthRes["roles"]); Client->SetRoles(AuthRes["roles"]);
Client->SetIsGuest(AuthRes["guest"]); Client->IsGuest = AuthRes["guest"];
for (const auto& ID : AuthRes["identifiers"]) { for (const auto& ID : AuthRes["identifiers"]) {
auto Raw = std::string(ID); auto Raw = std::string(ID);
auto SepIndex = Raw.find(':'); auto SepIndex = Raw.find(':');
@@ -316,41 +301,33 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
return nullptr; return nullptr;
} }
if(!Application::Settings.Password.empty()) { // ask password if (!Application::Settings.Password.empty()) { // ask password
if(!TCPSend(*Client, StringToVector("S"))) { if (!TCPSend(*Client, StringToVector("S"))) {
// TODO: handle Disconnect(Client);
return {};
} }
beammp_info("Waiting for password"); beammp_info("Waiting for password");
Data = TCPRcv(*Client); Data = TCPRcv(*Client);
std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size()); std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size());
if(Pass != HashPassword(Application::Settings.Password)) { if (Pass != HashPassword(Application::Settings.Password)) {
beammp_debug(Client->GetName() + " attempted to connect with a wrong password"); beammp_debug(Client->Name.get() + " attempted to connect with a wrong password");
ClientKick(*Client, "Wrong password!"); ClientKick(*Client, "Wrong password!");
return {}; return {};
} else { } else {
beammp_debug(Client->GetName() + " used the correct password"); beammp_debug(Client->Name.get() + " used the correct password");
} }
} }
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles()); beammp_debug("Name-> " + Client->Name.get() + ", Guest-> " + std::to_string(Client->IsGuest.get()) + ", Roles-> " + Client->Role.get());
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::shared_ptr<TClient>& Cl) -> bool {
std::shared_ptr<TClient> Cl; if (Cl->Name.get() == Client->Name.get() && Cl->IsGuest == Client->IsGuest) {
{ Disconnect(Cl);
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Cl = ClientPtr.lock();
} else
return true;
}
if (Cl->GetName() == Client->GetName() && Cl->IsGuest() == Client->IsGuest()) {
Cl->Disconnect("Stale Client (not a real player)");
return false; return false;
} }
return true; return true;
}); });
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers()); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->Name.get(), Client->Role.get(), Client->IsGuest.get(), Client->Identifiers.get());
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(), bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -377,7 +354,13 @@ std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) { if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
beammp_info("Identification success"); beammp_info("Identification success");
mServer.InsertClient(Client); mServer.InsertClient(Client);
TCPClient(Client); try {
TCPClient(Client);
} catch (const std::exception& e) {
beammp_infof("Client {} disconnected: {}", Client->ID.get(), e.what());
Disconnect(Client);
return {};
}
} else { } else {
ClientKick(*Client, "Server full!"); ClientKick(*Client, "Server full!");
} }
@@ -392,7 +375,7 @@ std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) { bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) {
if (!IsSync) { if (!IsSync) {
if (c.IsSyncing()) { if (c.IsSyncing) {
if (!Data.empty()) { if (!Data.empty()) {
if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') { if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') {
c.EnqueuePacket(Data); c.EnqueuePacket(Data);
@@ -402,8 +385,6 @@ bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync
} }
} }
auto& Sock = c.GetTCPSock();
/* /*
* our TCP protocol sends a header of 4 bytes, followed by the data. * our TCP protocol sends a header of 4 bytes, followed by the data.
* *
@@ -418,10 +399,10 @@ bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync
std::memcpy(ToSend.data(), &Size, sizeof(Size)); std::memcpy(ToSend.data(), &Size, sizeof(Size));
std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size()); std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size());
boost::system::error_code ec; boost::system::error_code ec;
write(Sock, buffer(ToSend), ec); write(*c.TCPSocket.synchronize(), buffer(ToSend), ec);
if (ec) { if (ec) {
beammp_debugf("write(): {}", ec.message()); beammp_debugf("write(): {}", ec.message());
c.Disconnect("write() failed"); Disconnect(c);
return false; return false;
} }
c.UpdatePingTime(); c.UpdatePingTime();
@@ -435,11 +416,10 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
} }
int32_t Header {}; int32_t Header {};
auto& Sock = c.GetTCPSock();
boost::system::error_code ec; boost::system::error_code ec;
std::array<uint8_t, sizeof(Header)> HeaderData; std::array<uint8_t, sizeof(Header)> HeaderData;
read(Sock, buffer(HeaderData), ec); read(*c.TCPSocket.synchronize(), buffer(HeaderData), ec);
if (ec) { if (ec) {
// TODO: handle this case (read failed) // TODO: handle this case (read failed)
beammp_debugf("TCPRcv: Reading header failed: {}", ec.message()); beammp_debugf("TCPRcv: Reading header failed: {}", ec.message());
@@ -448,8 +428,8 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
Header = *reinterpret_cast<int32_t*>(HeaderData.data()); Header = *reinterpret_cast<int32_t*>(HeaderData.data());
if (Header < 0) { if (Header < 0) {
ClientKick(c, "Invalid packet - header negative"); ClientKick(c, "Invalid packet->header negative");
beammp_errorf("Client {} send negative TCP header, ignoring packet", c.GetID()); beammp_errorf("Client {} send negative TCP header, ignoring packet", c.ID.get());
return {}; return {};
} }
@@ -459,10 +439,10 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
Data.resize(Header); Data.resize(Header);
} else { } else {
ClientKick(c, "Header size limit exceeded"); ClientKick(c, "Header size limit exceeded");
beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client."); beammp_warn("Client " + c.Name.get() + " (" + std::to_string(c.ID.get()) + ") sent header of >100MB->assuming malicious intent and disconnecting the client.");
return {}; return {};
} }
auto N = read(Sock, buffer(Data), ec); auto N = read(*c.TCPSocket.synchronize(), buffer(Data), ec);
if (ec) { if (ec) {
// TODO: handle this case properly // TODO: handle this case properly
beammp_debugf("TCPRcv: Reading data failed: {}", ec.message()); beammp_debugf("TCPRcv: Reading data failed: {}", ec.message());
@@ -485,37 +465,30 @@ std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
void TNetwork::ClientKick(TClient& c, const std::string& R) { void TNetwork::ClientKick(TClient& c, const std::string& R) {
beammp_info("Client kicked: " + R); beammp_info("Client kicked: " + R);
if (!TCPSend(c, StringToVector("K" + R))) { if (!TCPSend(c, StringToVector("K" + R))) {
beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.GetName(), c.GetID()); beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.Name.get(), c.ID.get());
} }
c.Disconnect("Kicked"); Disconnect(c);
} }
void TNetwork::Looper(const std::weak_ptr<TClient>& c) { void TNetwork::Looper(const std::shared_ptr<TClient>& Client) {
RegisterThreadAuto(); RegisterThreadAuto();
while (!c.expired()) { while (!Client->IsDisconnected()) {
auto Client = c.lock(); if (!Client->IsSyncing.get() && Client->IsSynced.get() && Client->MissedPacketsQueue->size() != 0) {
if (Client->IsDisconnected()) { while (Client->MissedPacketsQueue->size() > 0) {
beammp_debug("client is disconnected, breaking client loop");
break;
}
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
// debug("sending " + std::to_string(Client->MissedPacketQueueSize()) + " queued packets");
while (Client->MissedPacketQueueSize() > 0) {
std::vector<uint8_t> QData {}; std::vector<uint8_t> QData {};
{ // locked context { // locked context
std::unique_lock lock(Client->MissedPacketQueueMutex()); auto Lock = Client->MissedPacketsQueue;
if (Client->MissedPacketQueueSize() <= 0) { if (Lock->size() <= 0) {
break; break;
} }
QData = Client->MissedPacketQueue().front(); QData = Lock->front();
Client->MissedPacketQueue().pop(); Lock->pop();
} // end locked context } // end locked context
// beammp_debug("sending a missed packet: " + QData);
if (!TCPSend(*Client, QData, true)) { if (!TCPSend(*Client, QData, true)) {
Client->Disconnect("Failed to TCPSend while clearing the missed packet queue"); Disconnect(Client);
std::unique_lock lock(Client->MissedPacketQueueMutex()); auto Lock = Client->MissedPacketsQueue;
while (!Client->MissedPacketQueue().empty()) { while (!Lock->empty()) {
Client->MissedPacketQueue().pop(); Lock->pop();
} }
break; break;
} }
@@ -526,54 +499,38 @@ void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
} }
} }
void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) { void TNetwork::TCPClient(const std::shared_ptr<TClient>& c) {
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
if (c.expired() || !c.lock()->GetTCPSock().is_open()) {
mServer.RemoveClient(c);
return;
}
OnConnect(c); OnConnect(c);
RegisterThread("(" + std::to_string(c.lock()->GetID()) + ") \"" + c.lock()->GetName() + "\""); RegisterThread("(" + std::to_string(c->ID.get()) + ") \"" + c->Name.get() + "\"");
std::thread QueueSync(&TNetwork::Looper, this, c); std::thread QueueSync(&TNetwork::Looper, this, c);
while (true) { while (true) {
if (c.expired()) if (c->IsDisconnected()) {
break;
auto Client = c.lock();
if (Client->IsDisconnected()) {
beammp_debug("client status < 0, breaking client loop"); beammp_debug("client status < 0, breaking client loop");
break; break;
} }
auto res = TCPRcv(*Client); auto res = TCPRcv(*c);
if (res.empty()) { if (res.empty()) {
beammp_debug("TCPRcv empty"); beammp_debug("TCPRcv empty");
Client->Disconnect("TCPRcv failed"); Disconnect(c);
break; break;
} }
TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this); mServer.GlobalParser(c, std::move(res), mPPSMonitor, *this);
} }
if (QueueSync.joinable()) if (QueueSync.joinable())
QueueSync.join(); QueueSync.join();
if (!c.expired()) { Disconnect(c);
auto Client = c.lock();
OnDisconnect(c);
} else {
beammp_warn("client expired in TCPClient, should never happen");
}
} }
void TNetwork::UpdatePlayer(TClient& Client) { void TNetwork::UpdatePlayer(TClient& Client) {
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":"; std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
ReadLock Lock(mServer.GetClientMutex()); ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) { Packet += Client->Name.get() + ",";
auto c = ClientPtr.lock();
Packet += c->GetName() + ",";
}
return true; return true;
}); });
Packet = Packet.substr(0, Packet.length() - 1); Packet = Packet.substr(0, Packet.length() - 1);
@@ -581,74 +538,66 @@ void TNetwork::UpdatePlayer(TClient& Client) {
//(void)Respond(Client, Packet, true); //(void)Respond(Client, Packet, true);
} }
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) { void TNetwork::Disconnect(const std::weak_ptr<TClient>& ClientPtr) {
// this is how one checks that the ClientPtr is not empty (as opposed to expired)
if (ClientPtr.owner_before(std::weak_ptr<TClient> {})) {
return;
}
std::shared_ptr<TClient> LockedClientPtr { nullptr }; std::shared_ptr<TClient> LockedClientPtr { nullptr };
try { try {
LockedClientPtr = ClientPtr.lock(); LockedClientPtr = ClientPtr.lock();
} catch (const std::exception&) { } catch (const std::exception&) {
beammp_warn("Client expired in OnDisconnect, this is unexpected"); beammp_warn("Client expired in CloseSockets, this is unexpected");
return; return;
} }
beammp_assert(LockedClientPtr != nullptr); beammp_assert(LockedClientPtr != nullptr);
TClient& c = *LockedClientPtr; TClient& c = *LockedClientPtr;
beammp_info(c.GetName() + (" Connection Terminated")); Disconnect(c);
std::string Packet;
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = c.GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
for (auto& v : VehicleData) {
Packet = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(v.ID());
SendToAll(&c, StringToVector(Packet), false, true);
}
Packet = ("L") + c.GetName() + (" left the server!");
SendToAll(&c, StringToVector(Packet), false, true);
Packet.clear();
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", c.GetID());
LuaAPI::MP::Engine->WaitForAll(Futures);
c.Disconnect("Already Disconnected (OnDisconnect)");
mServer.RemoveClient(ClientPtr);
} }
void TNetwork::Disconnect(TClient& Client) {
int TNetwork::OpenID() { beammp_info(Client.Name.get() + (" Connection Terminated"));
int ID = 0; std::string Packet;
bool found; {
do { auto Locked = Client.VehicleData.synchronize();
found = true; for (auto& v : *Locked) {
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", Client.ID.get(), v.ID()));
ReadLock Lock(mServer.GetClientMutex()); Packet = "Od:" + std::to_string(Client.ID.get()) + "-" + std::to_string(v.ID());
if (!ClientPtr.expired()) { SendToAll(&Client, StringToVector(Packet), false, true);
auto c = ClientPtr.lock(); }
if (c->GetID() == ID) { }
found = false; Packet = ("L") + Client.Name.get() + (" left the server!");
ID++; SendToAll(&Client, StringToVector(Packet), false, true);
} Packet.clear();
} auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", Client.ID.get());
return true; TLuaEngine::WaitForAll(Futures);
}); Client.CloseSockets("Normal disconnect");
} while (!found); mServer.RemoveClient(Client);
return ID; }
void TNetwork::Disconnect(const std::shared_ptr<TClient>& ClientPtr) {
if (ClientPtr == nullptr) {
return;
}
Disconnect(*ClientPtr);
} }
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) { void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
beammp_assert(!c.expired()); beammp_assert(!c.expired());
beammp_info("Client connected"); beammp_info("Client connected");
auto LockedClient = c.lock(); auto LockedClient = c.lock();
LockedClient->SetID(OpenID()); mServer.ClaimFreeIDFor(*LockedClient);
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName()); beammp_info("Assigned ID " + std::to_string(LockedClient->ID.get()) + " to " + LockedClient->Name.get());
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->ID.get()));
SyncResources(*LockedClient); SyncResources(*LockedClient);
if (LockedClient->IsDisconnected()) if (LockedClient->IsDisconnected())
return; return;
(void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect (void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
beammp_info(LockedClient->GetName() + " : Connected"); beammp_info(LockedClient->Name.get() + " : Connected");
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->ID.get()));
} }
void TNetwork::SyncResources(TClient& c) { void TNetwork::SyncResources(TClient& c) {
if (!TCPSend(c, StringToVector("P" + std::to_string(c.GetID())))) { if (!TCPSend(c, StringToVector("P" + std::to_string(c.ID.get())))) {
// TODO handle throw std::runtime_error("Failed to send 'P' to client");
} }
std::vector<uint8_t> Data; std::vector<uint8_t> Data;
while (!c.IsDisconnected()) { while (!c.IsDisconnected()) {
@@ -680,7 +629,7 @@ void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
if (ToSend.empty()) if (ToSend.empty())
ToSend = "-"; ToSend = "-";
if (!TCPSend(c, StringToVector(ToSend))) { if (!TCPSend(c, StringToVector(ToSend))) {
// TODO: error throw std::runtime_error("Failed to send packet to client");
} }
} }
return; return;
@@ -690,11 +639,12 @@ void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
} }
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) { void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/'))); beammp_info(c.Name.get() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
if (!fs::path(UnsafeName).has_filename()) { if (!fs::path(UnsafeName).has_filename()) {
if (!TCPSend(c, StringToVector("CO"))) { if (!TCPSend(c, StringToVector("CO"))) {
// TODO: handle Disconnect(c);
return;
} }
beammp_warn("File " + UnsafeName + " is not a file!"); beammp_warn("File " + UnsafeName + " is not a file!");
return; return;
@@ -704,27 +654,29 @@ void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
if (!std::filesystem::exists(FileName)) { if (!std::filesystem::exists(FileName)) {
if (!TCPSend(c, StringToVector("CO"))) { if (!TCPSend(c, StringToVector("CO"))) {
// TODO: handle Disconnect(c);
return;
} }
beammp_warn("File " + UnsafeName + " could not be accessed!"); beammp_warn("File " + UnsafeName + " could not be accessed!");
return; return;
} }
if (!TCPSend(c, StringToVector("AG"))) { if (!TCPSend(c, StringToVector("AG"))) {
// TODO: handle Disconnect(c);
return;
} }
/// Wait for connections /// Wait for connections
int T = 0; int T = 0;
while (!c.GetDownSock().is_open() && T < 50) { while (!c.DownSocket->is_open() && T < 50) {
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
T++; T++;
} }
if (!c.GetDownSock().is_open()) { if (!c.DownSocket->is_open()) {
beammp_error("Client doesn't have a download socket!"); beammp_error("Client doesn't have a download socket!");
if (!c.IsDisconnected()) if (!c.IsDisconnected())
c.Disconnect("Missing download socket"); Disconnect(c);
return; return;
} }
@@ -804,31 +756,54 @@ void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std
Data.resize(Split); Data.resize(Split);
else else
Data.resize(Size); Data.resize(Size);
ip::tcp::socket* TCPSock { nullptr };
if (D) if (D) {
TCPSock = &c.GetDownSock(); auto TCPSock = c.DownSocket.synchronize();
else while (!c.IsDisconnected() && Sent < Size) {
TCPSock = &c.GetTCPSock(); size_t Diff = Size - Sent;
while (!c.IsDisconnected() && Sent < Size) { if (Diff > Split) {
size_t Diff = Size - Sent; f.seekg(Sent, std::ios_base::beg);
if (Diff > Split) { f.read(reinterpret_cast<char*>(Data.data()), Split);
f.seekg(Sent, std::ios_base::beg); if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
f.read(reinterpret_cast<char*>(Data.data()), Split); if (!c.IsDisconnected())
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) { Disconnect(c);
if (!c.IsDisconnected()) break;
c.Disconnect("TCPSendRaw failed in mod download (1)"); }
break; Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Diff);
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Diff;
} }
Sent += Split; }
} else { } else {
f.seekg(Sent, std::ios_base::beg); auto TCPSock = c.TCPSocket.synchronize();
f.read(reinterpret_cast<char*>(Data.data()), Diff); while (!c.IsDisconnected() && Sent < Size) {
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) { size_t Diff = Size - Sent;
if (!c.IsDisconnected()) if (Diff > Split) {
c.Disconnect("TCPSendRaw failed in mod download (2)"); f.seekg(Sent, std::ios_base::beg);
break; f.read(reinterpret_cast<char*>(Data.data()), Split);
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Diff);
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (!c.IsDisconnected())
Disconnect(c);
break;
}
Sent += Diff;
} }
Sent += Diff;
} }
} }
} }
@@ -869,36 +844,24 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
return false; return false;
} }
auto LockedClient = c.lock(); auto LockedClient = c.lock();
if (LockedClient->IsSynced()) if (LockedClient->IsSynced.get())
return true; return true;
// Syncing, later set isSynced // Syncing, later set isSynced
// after syncing is done, we apply all packets they missed // after syncing is done, we apply all packets they missed
if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->GetName()), true)) { if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->Name.get()), true)) {
return false; return false;
} }
// ignore error // ignore error
(void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->GetName() + "!"), false, true); (void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->Name.get() + "!"), false, true);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID())); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->ID.get()));
LockedClient->SetIsSyncing(true); LockedClient->IsSyncing = true;
bool Return = false; bool Return = false;
bool res = true; bool res = true;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
std::shared_ptr<TClient> client; auto VehicleData = Client->VehicleData.synchronize();
{ if (Client != LockedClient) {
ReadLock Lock(mServer.GetClientMutex()); for (auto& v : *VehicleData) {
if (!ClientPtr.expired()) {
client = ClientPtr.lock();
} else
return true;
}
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (client != LockedClient) {
for (auto& v : VehicleData) {
if (LockedClient->IsDisconnected()) { if (LockedClient->IsDisconnected()) {
Return = true; Return = true;
res = false; res = false;
@@ -910,32 +873,22 @@ bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
return true; return true;
}); });
LockedClient->SetIsSyncing(false); LockedClient->IsSyncing = false;
if (Return) { if (Return) {
return res; return res;
} }
LockedClient->SetIsSynced(true); LockedClient->IsSynced = true;
beammp_info(LockedClient->GetName() + (" is now synced!")); beammp_info(LockedClient->Name.get() + (" is now synced!"));
return true; return true;
} }
void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) { void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) {
if (!Self) if (!Self)
beammp_assert(c); beammp_assert(c);
char C = Data.at(0); char C = static_cast<char>(Data.at(0));
bool ret = true; mServer.ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
std::shared_ptr<TClient> Client;
try {
ReadLock Lock(mServer.GetClientMutex());
Client = ClientPtr.lock();
} catch (const std::exception&) {
// continue
beammp_warn("Client expired, shouldn't happen - if a client disconnected recently, you can ignore this");
return true;
}
if (Self || Client.get() != c) { if (Self || Client.get() != c) {
if (Client->IsSynced() || Client->IsSyncing()) { if (Client->IsSynced || Client->IsSyncing) {
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') { if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
if (C == 'O' || C == 'T' || Data.size() > 1000) { if (C == 'O' || C == 'T' || Data.size() > 1000) {
if (Data.size() > 400) { if (Data.size() > 400) {
@@ -945,42 +898,38 @@ void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self
} else { } else {
Client->EnqueuePacket(Data); Client->EnqueuePacket(Data);
} }
// ret = SendLarge(*Client, Data);
} else { } else {
Client->EnqueuePacket(Data); Client->EnqueuePacket(Data);
// ret = TCPSend(*Client, Data);
} }
} else { } else {
ret = UDPSend(*Client, Data); if (!UDPSend(*Client, Data)) {
Disconnect(Client);
}
} }
} }
} }
return true; return true;
}); });
if (!ret) {
// TODO: handle
}
return;
} }
bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) { bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
if (!Client.IsConnected() || Client.IsDisconnected()) { if (!Client.IsConnected || Client.IsDisconnected()) {
// this can happen if we try to send a packet to a client that is either // this can happen if we try to send a packet to a client that is either
// 1. not yet fully connected, or // 1. not yet fully connected, or
// 2. disconnected and not yet fully removed // 2. disconnected and not yet fully removed
// this is fine can can be ignored :^) // this is fine can can be ignored :^)
return true; return true;
} }
const auto Addr = Client.GetUDPAddr(); const auto Addr = Client.UDPAddress;
if (Data.size() > 400) { if (Data.size() > 400) {
CompressProperly(Data); CompressProperly(Data);
} }
boost::system::error_code ec; boost::system::error_code ec;
mUDPSock.send_to(buffer(Data), Addr, 0, ec); mUDPSock.send_to(buffer(Data), *Addr, 0, ec);
if (ec) { if (ec) {
beammp_debugf("UDP sendto() failed: {}", ec.message()); beammp_debugf("UDP sendto() failed: {}", ec.message());
if (!Client.IsDisconnected()) if (!Client.IsDisconnected())
Client.Disconnect("UDP send failed"); Disconnect(Client);
return false; return false;
} }
return true; return true;
+2 -10
View File
@@ -33,22 +33,14 @@ void TPPSMonitor::operator()() {
Application::SetPPS("-"); Application::SetPPS("-");
continue; continue;
} }
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { mServer.ForEachClient([&](const std::shared_ptr<TClient>& c) -> bool {
std::shared_ptr<TClient> c;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
c = ClientPtr.lock();
} else
return true;
}
if (c->GetCarCount() > 0) { if (c->GetCarCount() > 0) {
C++; C++;
V += c->GetCarCount(); V += c->GetCarCount();
} }
// kick on "no ping" // kick on "no ping"
if (c->SecondsSinceLastPing() > (20 * 60)) { if (c->SecondsSinceLastPing() > (20 * 60)) {
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS()); beammp_debug("client " + std::string("(") + std::to_string(c->ID.get()) + ")" + c->Name.get() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
TimedOutClients.push_back(c); TimedOutClients.push_back(c);
} }
+148 -74
View File
@@ -7,6 +7,7 @@
#include <TLuaPlugin.h> #include <TLuaPlugin.h>
#include <algorithm> #include <algorithm>
#include <any> #include <any>
#include <optional>
#include <sstream> #include <sstream>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -51,6 +52,30 @@ TEST_CASE("GetPidVid") {
CHECK_EQ(pid, 10); CHECK_EQ(pid, 10);
CHECK_EQ(vid, 12); CHECK_EQ(vid, 12);
} }
SUBCASE("Valid doubledigit 2") {
const auto MaybePidVid = GetPidVid("10-2");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 10);
CHECK_EQ(vid, 2);
}
SUBCASE("Valid doubledigit 3") {
const auto MaybePidVid = GetPidVid("33-23");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 33);
CHECK_EQ(vid, 23);
}
SUBCASE("Valid doubledigit 4") {
const auto MaybePidVid = GetPidVid("3-23");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 3);
CHECK_EQ(vid, 23);
}
SUBCASE("Empty string") { SUBCASE("Empty string") {
const auto MaybePidVid = GetPidVid(""); const auto MaybePidVid = GetPidVid("");
CHECK(!MaybePidVid); CHECK(!MaybePidVid);
@@ -93,7 +118,17 @@ TServer::TServer(const std::vector<std::string_view>& Arguments) {
} }
Application::SetSubsystemStatus("Server", Application::Status::Good); Application::SetSubsystemStatus("Server", Application::Status::Good);
} }
void TServer::RemoveClient(TClient& Client) {
beammp_debug("removing client " + Client.Name.get() + " (" + std::to_string(ClientCount()) + ")");
Client.ClearCars();
WriteLock Lock(mClientsMutex);
// erase all clients whose id matches, and those who have expired
std::erase_if(mClients,
[&](const std::weak_ptr<TClient>& C) {
return C.expired()
|| C.lock()->ID.get() == Client.ID.get();
});
}
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) { void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
std::shared_ptr<TClient> LockedClientPtr { nullptr }; std::shared_ptr<TClient> LockedClientPtr { nullptr };
try { try {
@@ -104,14 +139,26 @@ void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
} }
beammp_assert(LockedClientPtr != nullptr); beammp_assert(LockedClientPtr != nullptr);
TClient& Client = *LockedClientPtr; TClient& Client = *LockedClientPtr;
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")"); RemoveClient(Client);
// TODO: Send delete packets for all cars
Client.ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock());
} }
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) { void TServer::ClaimFreeIDFor(TClient& ClientToChange) {
ReadLock lock(mClientsMutex);
int ID = 0;
bool found = true;
do {
found = true;
for (const auto& Client : mClients) {
if (Client->ID.get() == ID) {
found = false;
++ID;
}
}
} while (!found);
ClientToChange.ID = ID;
}
void TServer::ForEachClient(const std::function<bool(const std::shared_ptr<TClient>&)> Fn) {
decltype(mClients) Clients; decltype(mClients) Clients;
{ {
ReadLock lock(mClientsMutex); ReadLock lock(mClientsMutex);
@@ -129,7 +176,7 @@ size_t TServer::ClientCount() const {
return mClients.size(); return mClients.size();
} }
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) { void TServer::GlobalParser(const std::shared_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
constexpr std::string_view ABG = "ABG:"; constexpr std::string_view ABG = "ABG:";
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) { if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
Packet.erase(Packet.begin(), Packet.begin() + ABG.size()); Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
@@ -139,11 +186,6 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
return; return;
} }
if (Client.expired()) {
return;
}
auto LockedClient = Client.lock();
std::any Res; std::any Res;
char Code = Packet.at(0); char Code = Packet.at(0);
@@ -152,7 +194,7 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
// V to Y // V to Y
if (Code <= 89 && Code >= 86) { if (Code <= 89 && Code >= 86) {
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(Client.get(), Packet, false, false);
return; return;
} }
switch (Code) { switch (Code) {
@@ -162,18 +204,18 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
} }
return; return;
case 'p': case 'p':
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) { if (!Network.Respond(*Client, StringToVector("p"), false)) {
// failed to send // failed to send
LockedClient->Disconnect("Failed to send ping"); Network.Disconnect(Client);
} else { } else {
Network.UpdatePlayer(*LockedClient); Network.UpdatePlayer(*Client);
} }
return; return;
case 'O': case 'O':
if (Packet.size() > 1000) { if (Packet.size() > 1000) {
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size())); beammp_debug(("Received data from: ") + Client->Name.get() + (" Size: ") + std::to_string(Packet.size()));
} }
ParseVehicle(*LockedClient, StringPacket, Network); ParseVehicle(*Client, StringPacket, Network);
return; return;
case 'C': { case 'C': {
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end()) if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
@@ -185,12 +227,12 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
Message = PacketAsString.substr(ColonPos + 2); Message = PacketAsString.substr(ColonPos + 2);
} }
if (Message.empty()) { if (Message.empty()) {
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID()); beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", Client->Name.get(), Client->ID.get());
return; return;
} }
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", Client->ID.get(), Client->Name.get(), Message);
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1)); LogChatMessage(Client->Name.get(), Client->ID.get(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
if (std::any_of(Futures.begin(), Futures.end(), if (std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Elem) { [](const std::shared_ptr<TLuaResult>& Elem) {
return !Elem->Error return !Elem->Error
@@ -199,21 +241,22 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
})) { })) {
break; break;
} }
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message); std::string SanitizedPacket = fmt::format("C:{}: {}", Client->Name.get(), Message);
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true); Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
return; return;
} }
case 'E': case 'E':
HandleEvent(*LockedClient, StringPacket); HandleEvent(*Client, StringPacket);
return; return;
case 'N': case 'N':
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")"); beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true); Network.SendToAll(Client.get(), Packet, false, true);
return; return;
case 'Z': // position packet case 'Z': // position packet
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(Client.get(), Packet, false, false);
HandlePosition(*LockedClient, StringPacket); HandlePosition(*Client, StringPacket);
return;
default: default:
return; return;
} }
@@ -223,7 +266,7 @@ void TServer::HandleEvent(TClient& c, const std::string& RawData) {
// E:Name:Data // E:Name:Data
// Data is allowed to have ':' // Data is allowed to have ':'
if (RawData.size() < 2) { if (RawData.size() < 2) {
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID()); beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.Name.get(), c.ID.get());
return; return;
} }
auto NameDataSep = RawData.find(':', 2); auto NameDataSep = RawData.find(':', 2);
@@ -232,7 +275,7 @@ void TServer::HandleEvent(TClient& c, const std::string& RawData) {
} }
std::string Name = RawData.substr(2, NameDataSep - 2); std::string Name = RawData.substr(2, NameDataSep - 2);
std::string Data = RawData.substr(NameDataSep + 1); std::string Data = RawData.substr(NameDataSep + 1);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.ID.get(), Data));
} }
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) { bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
@@ -243,14 +286,15 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
return true; return true;
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'."); beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.ID.get()) + ": '" + 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) { auto UnicycleID = c.UnicycleID.synchronize();
c.SetUnicycleID(ID); if (IsUnicycle(c, CarJson) && *UnicycleID < 0) {
*UnicycleID = ID;
return true; return true;
} else { } else {
return c.GetCarCount() < Application::Settings.MaxCars; return c.GetCarCount() < Application::Settings.MaxCars;
@@ -270,11 +314,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size()); beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
if (Data.at(0) == '0') { if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID(); int CarID = c.GetOpenCarID();
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID); beammp_debugf("'{}' created a car with ID {}", c.Name.get(), 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.Role.get() + ":" + c.Name.get() + ":" + std::to_string(c.ID.get()) + "-" + std::to_string(CarID) + ":" + CarJson;
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3)); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.ID.get(), CarID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(), bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -288,11 +332,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (!Network.Respond(c, StringToVector(Packet), true)) { if (!Network.Respond(c, StringToVector(Packet), true)) {
// TODO: handle // TODO: handle
} }
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID); std::string Destroy = "Od:" + std::to_string(c.ID.get()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, StringToVector(Destroy), true)) { if (!Network.Respond(c, StringToVector(Destroy), true)) {
// TODO: handle // TODO: handle
} }
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID); beammp_debugf("{} (force : car limit/lua) removed ID {}", c.Name.get(), CarID);
} }
} }
return; return;
@@ -302,8 +346,8 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.ID.get()) {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3)); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.ID.get(), VID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(), bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) { [](const std::shared_ptr<TLuaResult>& Result) {
@@ -312,15 +356,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
auto FoundPos = Packet.find('{'); auto FoundPos = Packet.find('{');
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos))) auto UnicycleID = c.UnicycleID.synchronize();
if ((*UnicycleID != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& !ShouldntAllow) { && !ShouldntAllow) {
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, StringToVector(Packet), false, true);
Apply(c, VID, Packet); Apply(c, VID, Packet);
} else { } else {
if (c.GetUnicycleID() == VID) { if (*UnicycleID == VID) {
c.SetUnicycleID(-1); *UnicycleID = -1;
} }
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(c.ID.get()) + "-" + std::to_string(VID);
Network.SendToAll(nullptr, StringToVector(Destroy), true, true); Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
c.DeleteCar(VID); c.DeleteCar(VID);
} }
@@ -333,15 +378,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.ID.get()) {
if (c.GetUnicycleID() == VID) { auto UnicycleID = c.UnicycleID.synchronize();
c.SetUnicycleID(-1); if (*UnicycleID == VID) {
*UnicycleID = -1;
} }
Network.SendToAll(nullptr, StringToVector(Packet), true, true); Network.SendToAll(nullptr, StringToVector(Packet), true, true);
// TODO: should this trigger on all vehicle deletions? // TODO: should this trigger on all vehicle deletions?
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.ID.get(), VID));
c.DeleteCar(VID); c.DeleteCar(VID);
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID)); beammp_debug(c.Name.get() + (" deleted car with ID ") + std::to_string(VID));
} }
return; return;
} }
@@ -352,9 +398,9 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.ID.get()) {
Data = Data.substr(Data.find('{')); Data = Data.substr(Data.find('{'));
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.ID.get(), VID, Data));
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, StringToVector(Packet), false, true);
} }
return; return;
@@ -388,7 +434,7 @@ void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
FoundPos = VD.find('{'); FoundPos = VD.find('{');
if (FoundPos == std::string::npos) { if (FoundPos == std::string::npos) {
return; return;
} }
VD = VD.substr(FoundPos); VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack; rapidjson::Document Veh, Pack;
@@ -422,35 +468,63 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
(void)mClients.insert(NewClient); (void)mClients.insert(NewClient);
} }
void TServer::HandlePosition(TClient& c, const std::string& Packet) { struct PidVidData {
int PID;
int VID;
std::string Data;
};
static std::optional<PidVidData> ParsePositionPacket(const std::string& Packet) {
if (Packet.size() < 3) { if (Packet.size() < 3) {
// invalid packet // invalid packet
return; return std::nullopt;
} }
// Zp:serverVehicleID:data // Zp:PID-VID:DATA
// Zp:0:data
std::string withoutCode = Packet.substr(3); std::string withoutCode = Packet.substr(3);
auto NameDataSep = withoutCode.find(':', 2);
if (NameDataSep == std::string::npos || NameDataSep < 2) {
// invalid packet
return;
}
// FIXME: ensure that -2 does what it should... it seems weird.
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
if (NameDataSep + 1 > withoutCode.size()) {
// invalid packet
return;
}
std::string Data = withoutCode.substr(NameDataSep + 1);
// parse veh ID // parse veh ID
auto MaybePidVid = GetPidVid(ServerVehicleID); if (auto DataBeginPos = withoutCode.find('{'); DataBeginPos != std::string::npos && DataBeginPos != 0) {
if (MaybePidVid) { // separator is :{, so position of { minus one
int PID = -1; auto PidVidOnly = withoutCode.substr(0, DataBeginPos - 1);
int VID = -1; auto MaybePidVid = GetPidVid(PidVidOnly);
// FIXME: check that the VID and PID are valid, so that we don't waste memory if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); int PID = -1;
int VID = -1;
// FIXME: check that the VID and PID are valid, so that we don't waste memory
std::tie(PID, VID) = MaybePidVid.value();
c.SetCarPosition(VID, Data); std::string Data = withoutCode.substr(DataBeginPos);
return PidVidData {
.PID = PID,
.VID = VID,
.Data = Data,
};
} else {
// invalid packet
return std::nullopt;
}
}
// invalid packet
return std::nullopt;
}
TEST_CASE("ParsePositionPacket") {
const auto TestData = R"({"tim":10.428000331623,"vel":[-2.4171722121385e-05,-9.7184734153252e-06,-7.6420763232237e-06],"rot":[-0.0001296154171915,0.0031575385950029,0.98994906610295,0.14138903660382],"rvel":[5.3640324636461e-05,-9.9824529946024e-05,5.1664064641372e-05],"pos":[-0.27281248907838,-0.20515357944633,0.49695488960431],"ping":0.032999999821186})";
SUBCASE("All the pids and vids") {
for (int pid = 0; pid < 100; ++pid) {
for (int vid = 0; vid < 100; ++vid) {
std::optional<PidVidData> MaybeRes = ParsePositionPacket(fmt::format("Zp:{}-{}:{}", pid, vid, TestData));
CHECK(MaybeRes.has_value());
CHECK_EQ(MaybeRes.value().PID, pid);
CHECK_EQ(MaybeRes.value().VID, vid);
CHECK_EQ(MaybeRes.value().Data, TestData);
}
}
}
}
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
if (auto Parsed = ParsePositionPacket(Packet); Parsed.has_value()) {
c.SetCarPosition(Parsed.value().VID, Parsed.value().Data);
} }
} }
+1 -1
Submodule vcpkg updated: 72010900b7...8397227251.
+7 -7
View File
@@ -2,18 +2,18 @@
"name": "server", "name": "server",
"version-string": "0.1.0", "version-string": "0.1.0",
"dependencies": [ "dependencies": [
"fmt",
"doctest",
"boost-asio", "boost-asio",
"boost-variant",
"boost-spirit", "boost-spirit",
"boost-uuid", "boost-uuid",
"boost-variant",
"cpp-httplib", "cpp-httplib",
"toml11", "doctest",
"fmt",
"libzip", "libzip",
"rapidjson",
"nlohmann-json", "nlohmann-json",
"openssl", "openssl",
"sol2" "rapidjson",
"sol2",
"toml11"
] ]
} }