Compare commits

..

4 Commits

Author SHA1 Message Date
Lion Kortlepel 5f456584a8 use lua 5.3.6 for static build 2022-09-29 11:19:20 +02:00
Lion Kortlepel b88b64cd0e update docker-build.sh to add an option to run-only 2022-09-28 00:01:09 +02:00
Lion Kortlepel dccdd3f5f2 add ability to change openssl and zlib 2022-09-27 23:46:19 +02:00
Lion Kortlepel ae38f01fdc add initial docker static build container 2022-09-27 23:41:47 +02:00
23 changed files with 712 additions and 710 deletions
+13 -8
View File
@@ -1,13 +1,18 @@
name: CMake Linux Build name: CMake Linux Build
on: [push] on:
push:
pull_request:
types: [opened, reopened]
pull_request_review:
types: [submitted]
env: env:
BUILD_TYPE: Release BUILD_TYPE: Release
jobs: jobs:
linux-build: linux-build:
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@@ -20,7 +25,7 @@ jobs:
run: | run: |
echo ${#beammp_sentry_url} echo ${#beammp_sentry_url}
sudo apt-get update sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10 libboost1.74-all-dev sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
- name: Create Build Environment - name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux run: cmake -E make_directory ${{github.workspace}}/build-linux
@@ -56,23 +61,23 @@ jobs:
run-tests: run-tests:
needs: linux-build needs: linux-build
runs-on: ubuntu-22.04 runs-on: ubuntu-20.04
steps: steps:
- uses: actions/download-artifact@master - uses: actions/download-artifact@master
with: with:
name: BeamMP-Server-linux-tests name: BeamMP-Server-linux-tests
path: ${{github.workspace}} path: ${{github.workspace}}
- name: Install Runtime Dependencies - name: Install Runtime Dependencies
shell: bash shell: bash
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y liblua5.3-0 libssl3 curl sudo apt-get install -y liblua5.3 openssl
- name: Test - name: Test
working-directory: ${{github.workspace}} working-directory: ${{github.workspace}}
shell: bash shell: bash
run: | run: |
chmod +x ./BeamMP-Server-tests chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests ./BeamMP-Server-tests
+14 -10
View File
@@ -1,6 +1,11 @@
name: CMake Windows Build name: CMake Windows Build
on: [push] on:
push:
pull_request:
types: [opened, reopened]
pull_request_review:
types: [submitted]
env: env:
BUILD_TYPE: Release BUILD_TYPE: Release
@@ -8,20 +13,20 @@ env:
jobs: jobs:
windows-build: windows-build:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
with: with:
submodules: 'recursive' submodules: "recursive"
- name: Restore artifacts, or run vcpkg, build and cache artifacts - name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@v7 uses: lukka/run-vcpkg@v7
id: runvcpkg id: runvcpkg
with: with:
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl' vcpkgArguments: "lua zlib rapidjson openssl websocketpp curl"
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg' vcpkgDirectory: "${{ runner.workspace }}/b/vcpkg"
vcpkgGitCommitId: "16ee2ecb31788c336ace8bb14c21801efb6836e4" vcpkgGitCommitId: "a106de33bbee694e3be6243718aa2a549a692832"
vcpkgTriplet: 'x64-windows-static' vcpkgTriplet: "x64-windows-static"
- name: Create Build Environment - name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows run: cmake -E make_directory ${{github.workspace}}/build-windows
@@ -49,10 +54,9 @@ jobs:
shell: bash shell: bash
run: | run: |
cmake --build . --config Debug cmake --build . --config Debug
- name: Archive debug artifacts - name: Archive debug artifacts
uses: actions/upload-artifact@v2 uses: actions/upload-artifact@v2
with: with:
name: BeamMP-Server-debug.exe name: BeamMP-Server-debug.exe
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
+3 -3
View File
@@ -32,7 +32,7 @@ jobs:
upload-release-files-linux: upload-release-files-linux:
name: Upload Linux Release Files name: Upload Linux Release Files
runs-on: ubuntu-22.04 runs-on: ubuntu-latest
needs: create-release needs: create-release
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@@ -42,7 +42,7 @@ jobs:
- name: Install Dependencies - name: Install Dependencies
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev libboost-dev libboost1.74-all-dev libboost1.74-dev sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
- name: Create Build Environment - name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux run: cmake -E make_directory ${{github.workspace}}/build-linux
@@ -85,7 +85,7 @@ jobs:
with: with:
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl' vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg' vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '16ee2ecb31788c336ace8bb14c21801efb6836e4' vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
vcpkgTriplet: 'x64-windows-static' vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment - name: Create Build Environment
+30 -26
View File
@@ -28,8 +28,6 @@ set(SENTRY_BUILD_SHARED_LIBS OFF)
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1) add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
option(WIN32_STATIC_RUNTIME "Build statically-linked runtime on windows (don't touch unless you know what you're doing)" ON)
# ------------------------ APPLE --------------------------------- # ------------------------ APPLE ---------------------------------
if(APPLE) if(APPLE)
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6) if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
@@ -49,13 +47,14 @@ if(APPLE)
endif() endif()
# ------------------------ WINDOWS --------------------------------- # ------------------------ WINDOWS ---------------------------------
elseif (WIN32) elseif (WIN32)
if (WIN32_STATIC_RUNTIME) # this has to happen before sentry, so that crashpad on windows links with these settings.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") message(STATUS "MSVC -> forcing use of statically-linked runtime.")
endif() STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
# ------------------------ UNIX ------------------------------------ STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
# ------------------------ LINUX ---------------------------------
elseif (UNIX) elseif (UNIX)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
option(SANITIZE "Turns on thread and UB sanitizers" OFF) option(SANITIZE "Turns on thread and UB sanitizers" OFF)
if (SANITIZE) if (SANITIZE)
message(STATUS "sanitize is ON") message(STATUS "sanitize is ON")
@@ -80,6 +79,9 @@ add_subdirectory("deps/sentry-native")
# ------------------------ C++ SETUP --------------------------------- # ------------------------ C++ SETUP ---------------------------------
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
if (MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
endif ()
# ------------------------ DEPENDENCIES ------------------------------ # ------------------------ DEPENDENCIES ------------------------------
message(STATUS "Adding local source dependencies") message(STATUS "Adding local source dependencies")
@@ -88,12 +90,27 @@ add_subdirectory(deps)
# ------------------------ VARIABLES --------------------------------- # ------------------------ VARIABLES ---------------------------------
include(FindLua) option(FIND_OPENSSL "Whether or not to find openssl automatically (keep on unless you know what you're doing)" ON)
option(FIND_ZLIB "Whether or not to find zlib automatically (keep on unless you know what you're doing)" ON)
include(FindOpenSSL) include(FindOpenSSL)
if (${FIND_OPENSSL})
set(OPENSSL_CRYPTO OpenSSL::Crypto)
set(OPENSSL_SSL OpenSSL::SSL)
else()
message(STATUS "Using custom openssl libs: ${OPENSSL_CRYPTO} ${OPENSSL_SSL}")
endif()
include(FindLua)
include(FindThreads) include(FindThreads)
include(FindZLIB) include(FindZLIB)
find_package(Boost 1.70 REQUIRED COMPONENTS system) if (${FIND_ZLIB})
set(ZLIB_ZLIB ZLIB::ZLIB)
else()
message(STATUS "Using custom zlib: ${ZLIB_ZLIB}")
endif()
set(BeamMP_Sources set(BeamMP_Sources
include/TConsole.h src/TConsole.cpp include/TConsole.h src/TConsole.cpp
@@ -117,7 +134,6 @@ set(BeamMP_Sources
include/ArgsParser.h src/ArgsParser.cpp include/ArgsParser.h src/ArgsParser.cpp
include/TPluginMonitor.h src/TPluginMonitor.cpp include/TPluginMonitor.h src/TPluginMonitor.cpp
include/Environment.h include/Environment.h
include/BoostAliases.h
) )
set(BeamMP_Includes set(BeamMP_Includes
@@ -136,10 +152,6 @@ set(BeamMP_Definitions
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}" SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
) )
if (WIN32)
list(APPEND BeamMP_Definitions _WIN32_WINNT=0x0601)
list(APPEND BeamMP_Definitions _CRT_SECURE_NO_WARNINGS)
endif()
if (UNIX) if (UNIX)
set(BeamMP_CompileOptions set(BeamMP_CompileOptions
-Wall -Wall
@@ -165,31 +177,23 @@ if (UNIX)
-Werror=switch-default -Werror=switch-default
-Werror=old-style-cast -Werror=old-style-cast
-Werror=overloaded-virtual -Werror=overloaded-virtual
-Werror=zero-as-null-pointer-constant
-Werror=overloaded-virtual -Werror=overloaded-virtual
-Werror=missing-include-dirs -Werror=missing-include-dirs
-Werror=unused-result -Werror=unused-result
-fstack-protector -fstack-protector
-Wzero-as-null-pointer-constant
)
else()
set(BeamMP_CompileOptions
/bigobj
/INCREMENTAL:NO /NODEFAULTLIB:MSVCRT /NODEFAULTLIB:LIBCMT
) )
endif() endif()
set(BeamMP_Libraries set(BeamMP_Libraries
Boost::boost
Boost::system
doctest::doctest doctest::doctest
OpenSSL::SSL ${OPENSSL_SSL}
OpenSSL::Crypto ${OPENSSL_CRYPTO}
sol2::sol2 sol2::sol2
fmt::fmt fmt::fmt
Threads::Threads Threads::Threads
ZLIB::ZLIB ${ZLIB_ZLIB}
${LUA_LIBRARIES} ${LUA_LIBRARIES}
commandline commandline
sentry sentry
-12
View File
@@ -1,10 +1,3 @@
# v3.1.1
- FIXED bug which caused GetPlayerIdentifiers, GetPlayerName, etc not to work in `onPlayerDisconnect`
- FIXED some issues which could cause the server to crash when receiving malformed data
- FIXED a bug which caused a server to crash during authentication when receiving malformed data
- FIXED minor vulnerability in chat message handling
- FIXED a minor formatting bug in the `status` command
# v3.1.0 # v3.1.0
@@ -17,9 +10,6 @@
- ADDED error messages to some lua functions - ADDED error messages to some lua functions
- ADDED HOME and END button working in console - ADDED HOME and END button working in console
- ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON - ADDED `MP.TriggerClientEventJson()` which takes a table as the data argument and sends it as JSON
- ADDED identifiers (beammp id, ip) to onPlayerAuth (4th argument)
- ADDED more network debug logging
- CHANGED all networking to be more stable, performant, and safe
- FIXED `ip` in MP.GetPlayerIdentifiers - FIXED `ip` in MP.GetPlayerIdentifiers
- FIXED issue with client->server events which contain `:` - FIXED issue with client->server events which contain `:`
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink - FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
@@ -28,8 +18,6 @@
- FIXED bug which caused hot-reload not to report syntax errors - FIXED bug which caused hot-reload not to report syntax errors
- FIXED missing error messages on some event handler calls - FIXED missing error messages on some event handler calls
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua - FIXED vehicles not deleting for all players if an edit was cancelled by Lua
- FIXED server not handling binary UDP packets properly
- REMOVED "Backend response failed to parse as valid json" message
# v3.0.2 # v3.0.2
+11
View File
@@ -0,0 +1,11 @@
FROM lionkor/alpine-static-cpp:latest
ARG LUA_V=5.3.6
RUN apk update && apk --no-cache add python3 git lua zlib-static openssl curl rapidjson curl-dev wget readline-static
RUN apk --no-cache add openssl-libs-static curl-static readline-dev
RUN wget "https://www.lua.org/ftp/lua-${LUA_V}.tar.gz"; tar xzvf lua-${LUA_V}.tar.gz; mv "lua-${LUA_V}" /lua; rm lua-${LUA_V}.tar.gz
RUN cd /lua; make all -j linux; cd ..
+24 -93
View File
@@ -29,7 +29,7 @@ These values are guesstimated and are subject to change with each release.
## Contributing ## Contributing
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" or "good first issue" label or with nobody assigned. TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned.
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas. To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
@@ -39,7 +39,7 @@ If you need support with understanding the codebase, please write us in the Disc
## About Building from Source ## About Building from Source
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.1.0`. We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`.
## Supported Operating Systems ## Supported Operating Systems
@@ -51,7 +51,7 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
## Build Instructions ## Build Instructions
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__** **__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)). Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
@@ -59,105 +59,35 @@ Currently only Linux and Windows are supported (generally). See [Releases](https
#### Windows #### Windows
There are **no runtime libraries** needed for Windows.
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/). Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
Dependencies for **Windows** can be installed with `vcpkg`. Dependencies for **Windows** can be installed with `vcpkg`.
These are: These are:
``` ```
lua zlib rapidjson openssl websocketpp curl lua
zlib
rapidjson
openssl
websocketpp
curl
``` ```
The triplet we use for releases is `x64-windows-static`.
#### Linux #### Linux
We recommend Ubuntu 22.04 or Arch Linux. Any Linux distribution will work, but you have to figure out the package names yourself (please feel free to PR in a change to this README with that info). Runtime dependencies - you want to find packages for:
- libz
- rapidjson
- lua5.3
- ssl / openssl
- websocketpp
- curl (with ssl support)
##### Runtime Dependencies Build-time dependencies are:
These are needed to *run* the server.
<details>
<summary>
Ubuntu 22.04
</summary>
`apt-get install` the following libraries:
```
liblua5.3-0
libssl3
curl
```
</details>
<details>
<summary>
Arch Linux
</summary>
`pacman -Syu` the following libraries:
```
lua53
openssl
curl
```
</details>
##### Build Dependencies
These are needed for you to *build* the server, in addition to the [runtime dependencies](#runtime-dependencies).
<details>
<summary>
Ubuntu 22.04
</summary>
`apt-get install` the following libraries and programs:
``` ```
git git
libz-dev make
rapidjson-dev
liblua5.3
libssl-dev
libwebsocketpp-dev
libcurl4-openssl-dev
cmake
g++-10
libboost1.74-all-dev
libssl3
curl
```
</details>
<details>
<summary>
Arch Linux
</summary>
`pacman -Syu` the following libraries and programs:
```
lua53
openssl
curl
git
cmake cmake
g++ g++
cmake
zlib
boost
websocketpp
```
</details>
#### macOS
Dependencies for **macOS** can be installed with homebrew.
```
brew install lua@5.3 rapidjson websocketpp cmake openssl@1.1
```
Some packages are included in **macOS** but you might want to install homebrew versions.
```
brew install curl zlib git make
``` ```
### How to build ### How to build
@@ -165,12 +95,13 @@ brew install curl zlib git make
On Windows, use git-bash for these commands. On Linux, these should work in your shell. On Windows, use git-bash for these commands. On Linux, these should work in your shell.
1. Make sure you have all [prerequisites](#prerequisites) installed 1. Make sure you have all [prerequisites](#prerequisites) installed
2. Clone the repository in a location of your choice with `git clone https://github.com/BeamMP/BeamMP-Server` . 2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`. 3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
4. Checkout the branch or tag of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags). 4. Checkout the branch of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`). This may take some time, and will update all submodules and prepare the build. 5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
7. Run `make -j` . This step will take some time and will use a lot of CPU and RAM. Remove the `-j` if you run out of memory. *If you change something in the source code, you only have to re-run this step.* 6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
8. You now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server. 7. Run `make`
8. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.* *tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# usage:
# ./docker-build.sh
# builds the image, and then runs it
# ./docker-build.sh run
# only runs it
set -e
if [ "$1" != "run" ]
then
git submodule update --init --recursive
docker build . --tag beammp-static
fi
docker run -v $(pwd):/root -it --rm beammp-static sh -c "cd root; cmake . -B build -DGIT_SUBMODULE=OFF -DLUA_INCLUDE_DIR=/lua/src -DSOL2_SINGLE=ON -DFIND_OPENSSL=OFF -DOPENSSL_CRYPTO=\"/usr/lib/libcrypto.a\" -DOPENSSL_SSL=\"/usr/lib/libssl.a\" -DFIND_ZLIB=OFF -DZLIB_ZLIB=/lib/libz.a -DCURL_FOUND=ON -DCURL_LIBRARIES=\"/usr/lib/libcurl.a\" -DLUA_LIBRARIES=\"/lua/src/liblua.a\" -DSENTRY_BACKEND=none -DSENTRY_TRANSPORT=none; make -C build -j BeamMP-Server"
# try to chown the build directory afterwards
sudo chown -R "$USER":"$USER" build
-6
View File
@@ -1,6 +0,0 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
using namespace boost::asio;
+19 -23
View File
@@ -7,7 +7,6 @@
#include <string> #include <string>
#include <unordered_set> #include <unordered_set>
#include "BoostAliases.h"
#include "Common.h" #include "Common.h"
#include "Compat.h" #include "Compat.h"
#include "VehicleData.h" #include "VehicleData.h"
@@ -20,8 +19,9 @@ class TServer;
#endif // WINDOWS #endif // WINDOWS
struct TConnection final { struct TConnection final {
ip::tcp::socket Socket; SOCKET Socket;
ip::tcp::endpoint SockAddr; struct sockaddr SockAddr;
socklen_t SockAddrLen;
}; };
class TClient final { class TClient final {
@@ -33,9 +33,8 @@ public:
std::unique_lock<std::mutex> Lock; std::unique_lock<std::mutex> Lock;
}; };
TClient(TServer& Server, ip::tcp::socket&& Socket); explicit TClient(TServer& Server);
TClient(const TClient&) = delete; TClient(const TClient&) = delete;
~TClient();
TClient& operator=(const TClient&) = delete; TClient& operator=(const TClient&) = delete;
void AddNewCar(int Ident, const std::string& Data); void AddNewCar(int Ident, const std::string& Data);
@@ -47,20 +46,16 @@ public:
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; } void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
std::string GetCarData(int Ident); std::string GetCarData(int Ident);
std::string GetCarPositionRaw(int Ident); std::string GetCarPositionRaw(int Ident);
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; } void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); } void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); } void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
void Disconnect(std::string_view Reason); void SetStatus(int Status) { mStatus = Status; }
bool IsDisconnected() const { return !mSocket.is_open(); }
// locks // locks
void DeleteCar(int Ident); void DeleteCar(int Ident);
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; } [[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; } [[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; } [[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; } [[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
[[nodiscard]] std::string GetRoles() const { return mRole; } [[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; } [[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; } void SetUnicycleID(int ID) { mUnicycleID = ID; }
@@ -68,6 +63,7 @@ public:
[[nodiscard]] int GetOpenCarID() const; [[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const; [[nodiscard]] int GetCarCount() const;
void ClearCars(); void ClearCars();
[[nodiscard]] int GetStatus() const { return mStatus; }
[[nodiscard]] int GetID() const { return mID; } [[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; } [[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; } [[nodiscard]] bool IsConnected() const { return mIsConnected; }
@@ -77,9 +73,9 @@ public:
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; } void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; } void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; } void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::vector<uint8_t>& Packet); void EnqueuePacket(const std::string& Packet);
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; } [[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; } [[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); } [[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; } [[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; } void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
@@ -95,7 +91,7 @@ private:
bool mIsSynced = false; bool mIsSynced = false;
bool mIsSyncing = false; bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex; mutable std::mutex mMissedPacketsMutex;
std::queue<std::vector<uint8_t>> mPacketsSync; std::queue<std::string> mPacketsSync;
std::unordered_map<std::string, std::string> mIdentifiers; std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false; bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex; mutable std::mutex mVehicleDataMutex;
@@ -103,12 +99,12 @@ private:
TSetOfVehicleData mVehicleData; TSetOfVehicleData mVehicleData;
SparseArray<std::string> mVehiclePosition; SparseArray<std::string> mVehiclePosition;
std::string mName = "Unknown Client"; std::string mName = "Unknown Client";
ip::tcp::socket mSocket; SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
ip::tcp::socket mDownSocket; sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
ip::udp::endpoint mUDPAddress {};
int mUnicycleID = -1; int mUnicycleID = -1;
std::string mRole; std::string mRole;
std::string mDID; std::string mDID;
int mStatus = 0;
int mID = -1; int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime; std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
}; };
+2 -2
View File
@@ -80,7 +80,7 @@ public:
static TConsole& Console() { return *mConsole; } static TConsole& Console() { return *mConsole; }
static std::string ServerVersionString(); static std::string ServerVersionString();
static const Version& ServerVersion() { return mVersion; } static const Version& ServerVersion() { return mVersion; }
static uint8_t ClientMajorVersion() { return 2; } static std::string ClientVersionString() { return "2.0"; }
static std::string PPS() { return mPPS; } static std::string PPS() { return mPPS; }
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; } static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
@@ -137,7 +137,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, 1, 2 }; static inline Version mVersion { 3, 1, 0 };
}; };
std::string ThreadName(bool DebugModeOverride = false); std::string ThreadName(bool DebugModeOverride = false);
+31
View File
@@ -5,23 +5,54 @@
// ======================= UNIX ======================== // ======================= UNIX ========================
#ifdef BEAMMP_LINUX #ifdef BEAMMP_LINUX
#include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/socket.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
using SOCKET = int;
using DWORD = unsigned long;
using PDWORD = unsigned long*;
using LPDWORD = unsigned long*;
char _getch(); char _getch();
inline void CloseSocketProper(int TheSocket) {
shutdown(TheSocket, SHUT_RDWR);
close(TheSocket);
}
#endif // unix #endif // unix
// ======================= APPLE ======================== // ======================= APPLE ========================
#ifdef BEAMMP_APPLE #ifdef BEAMMP_APPLE
#include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/socket.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
using SOCKET = int;
using DWORD = unsigned long;
using PDWORD = unsigned long*;
using LPDWORD = unsigned long*;
char _getch(); char _getch();
inline void CloseSocketProper(int TheSocket) {
shutdown(TheSocket, SHUT_RDWR);
close(TheSocket);
}
#endif // unix #endif // unix
// ======================= WINDOWS ======================= // ======================= WINDOWS =======================
#ifdef BEAMMP_WINDOWS #ifdef BEAMMP_WINDOWS
#include <conio.h> #include <conio.h>
#include <winsock2.h>
inline void CloseSocketProper(SOCKET TheSocket) {
shutdown(TheSocket, 2); // 2 == SD_BOTH
closesocket(TheSocket);
}
#endif // WIN32 #endif // WIN32
#ifdef INVALID_SOCKET
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
#else
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
#endif
+3 -4
View File
@@ -25,12 +25,11 @@ namespace fs = std::filesystem;
/** /**
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args * std::variant means, that TLuaArgTypes may be one of the Types listed as template args
*/ */
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>; using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>;
static constexpr size_t TLuaArgTypes_String = 0; static constexpr size_t TLuaArgTypes_String = 0;
static constexpr size_t TLuaArgTypes_Int = 1; static constexpr size_t TLuaArgTypes_Int = 1;
static constexpr size_t TLuaArgTypes_VariadicArgs = 2; static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
static constexpr size_t TLuaArgTypes_Bool = 3; static constexpr size_t TLuaArgTypes_Bool = 3;
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
class TLuaPlugin; class TLuaPlugin;
@@ -76,7 +75,7 @@ public:
}; };
TLuaEngine(); TLuaEngine();
virtual ~TLuaEngine() noexcept { ~TLuaEngine() noexcept {
beammp_debug("Lua Engine terminated"); beammp_debug("Lua Engine terminated");
} }
@@ -198,7 +197,7 @@ private:
public: public:
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine); StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
StateThreadData(const StateThreadData&) = delete; StateThreadData(const StateThreadData&) = delete;
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); } ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
+17 -21
View File
@@ -1,11 +1,8 @@
#pragma once #pragma once
#include "BoostAliases.h"
#include "Compat.h" #include "Compat.h"
#include "TResourceManager.h" #include "TResourceManager.h"
#include "TServer.h" #include "TServer.h"
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/udp.hpp>
struct TConnection; struct TConnection;
@@ -13,18 +10,19 @@ class TNetwork {
public: public:
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager); TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false); [[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false); [[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false); [[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock); std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
std::vector<uint8_t> TCPRcv(TClient& c); std::string TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R); void ClientKick(TClient& c, const std::string& R);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c); [[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(TConnection&& client); void Identify(const TConnection& client);
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection); void Authentication(const TConnection& ClientConnection);
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
void SyncResources(TClient& c); void SyncResources(TClient& c);
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data); [[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel); void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
void UpdatePlayer(TClient& Client); void UpdatePlayer(TClient& Client);
private: private:
@@ -33,23 +31,21 @@ private:
TServer& mServer; TServer& mServer;
TPPSMonitor& mPPSMonitor; TPPSMonitor& mPPSMonitor;
ip::udp::socket mUDPSock; SOCKET mUDPSock {};
TResourceManager& mResourceManager; TResourceManager& mResourceManager;
std::thread mUDPThread; std::thread mUDPThread;
std::thread mTCPThread; std::thread mTCPThread;
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint); std::string UDPRcvFromClient(sockaddr_in& client) const;
void HandleDownload(TConnection&& TCPSock); void HandleDownload(SOCKET TCPSock);
void OnConnect(const std::weak_ptr<TClient>& c); void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::weak_ptr<TClient>& c); void TCPClient(const std::weak_ptr<TClient>& c);
void Looper(const std::weak_ptr<TClient>& c); void Looper(const std::weak_ptr<TClient>& c);
int OpenID(); int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr); void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
void Parse(TClient& c, const std::vector<uint8_t>& Packet); void Parse(TClient& c, const std::string& 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); static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name); static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size); static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
}; };
std::vector<uint8_t> StringToVector(const std::string& Str);
+3 -16
View File
@@ -8,8 +8,6 @@
#include <mutex> #include <mutex>
#include <unordered_set> #include <unordered_set>
#include "BoostAliases.h"
class TClient; class TClient;
class TNetwork; class TNetwork;
class TPPSMonitor; class TPPSMonitor;
@@ -21,22 +19,19 @@ public:
TServer(const std::vector<std::string_view>& Arguments); TServer(const std::vector<std::string_view>& Arguments);
void InsertClient(const std::shared_ptr<TClient>& Ptr); void InsertClient(const std::shared_ptr<TClient>& Ptr);
std::weak_ptr<TClient> InsertNewClient();
void RemoveClient(const std::weak_ptr<TClient>&); void RemoveClient(const std::weak_ptr<TClient>&);
// in Fn, return true to continue, return false to break // in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn); void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
size_t ClientCount() const; size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network); static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data); static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; } RWMutex& GetClientMutex() const { return mClientsMutex; }
const TScopedTimer UptimeTimer; const TScopedTimer UptimeTimer;
// asio io context
io_context& IoCtx() { return mIoCtx; }
private: private:
io_context mIoCtx {};
TClientSet mClients; TClientSet mClients;
mutable RWMutex mClientsMutex; mutable RWMutex mClientsMutex;
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network); static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
@@ -45,11 +40,3 @@ private:
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); static void HandlePosition(TClient& c, const std::string& Packet);
}; };
struct BufferView {
uint8_t* Data { nullptr };
size_t Size { 0 };
const uint8_t* data() const { return Data; }
uint8_t* data() { return Data; }
size_t size() const { return Size; }
};
+6 -24
View File
@@ -6,7 +6,6 @@
#include <optional> #include <optional>
void TClient::DeleteCar(int Ident) { void TClient::DeleteCar(int Ident) {
// TODO: Send delete packets
std::unique_lock lock(mVehicleDataMutex); std::unique_lock lock(mVehicleDataMutex);
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) { auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
return Ident == elem.ID(); return Ident == elem.ID();
@@ -50,27 +49,16 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
std::string TClient::GetCarPositionRaw(int Ident) { std::string TClient::GetCarPositionRaw(int Ident) {
std::unique_lock lock(mVehiclePositionMutex); std::unique_lock lock(mVehiclePositionMutex);
try { try
{
return mVehiclePosition.at(Ident); return mVehiclePosition.at(Ident);
} catch (const std::out_of_range& oor) { }
catch (const std::out_of_range& oor) {
return ""; return "";
} }
return ""; return "";
} }
void TClient::Disconnect(std::string_view Reason) {
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
boost::system::error_code ec;
mSocket.shutdown(socket_base::shutdown_both, ec);
if (ec) {
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
}
mSocket.close(ec);
if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message());
}
}
void TClient::SetCarPosition(int Ident, const std::string& Data) { void TClient::SetCarPosition(int Ident, const std::string& Data) {
std::unique_lock lock(mVehiclePositionMutex); std::unique_lock lock(mVehiclePositionMutex);
mVehiclePosition[Ident] = Data; mVehiclePosition[Ident] = Data;
@@ -110,22 +98,16 @@ TServer& TClient::Server() const {
return mServer; return mServer;
} }
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) { void TClient::EnqueuePacket(const std::string& Packet) {
std::unique_lock Lock(mMissedPacketsMutex); std::unique_lock Lock(mMissedPacketsMutex);
mPacketsSync.push(Packet); mPacketsSync.push(Packet);
} }
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket) TClient::TClient(TServer& Server)
: mServer(Server) : mServer(Server)
, mSocket(std::move(Socket))
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
, mLastPingTime(std::chrono::high_resolution_clock::now()) { , mLastPingTime(std::chrono::high_resolution_clock::now()) {
} }
TClient::~TClient() {
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
}
void TClient::UpdatePingTime() { void TClient::UpdatePingTime() {
mLastPingTime = std::chrono::high_resolution_clock::now(); mLastPingTime = std::chrono::high_resolution_clock::now();
} }
+6 -6
View File
@@ -116,7 +116,7 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) { static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
std::string Packet = "E:" + EventName + ":" + Data; std::string Packet = "E:" + EventName + ":" + Data;
if (PlayerID == -1) { if (PlayerID == -1) {
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true); LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
return { true, "" }; return { true, "" };
} else { } else {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
@@ -125,7 +125,7 @@ static inline std::pair<bool, std::string> InternalTriggerClientEvent(int Player
return { false, "Invalid Player ID" }; return { false, "Invalid Player ID" };
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!LuaAPI::MP::Engine->Network().Respond(*c, 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().ClientKick(*c, "Disconnected after failing to receive packets");
return { false, "Respond failed, dropping client" }; return { false, "Respond failed, dropping client" };
@@ -155,7 +155,7 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
std::string Packet = "C:Server: " + Message; std::string Packet = "C:Server: " + Message;
if (ID == -1) { if (ID == -1) {
LogChatMessage("<Server> (to everyone) ", -1, Message); LogChatMessage("<Server> (to everyone) ", -1, Message);
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true); Engine->Network().SendToAll(nullptr, Packet, true, true);
Result.first = true; Result.first = true;
} else { } else {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
@@ -167,7 +167,7 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
return Result; return Result;
} }
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message); LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) { if (!Engine->Network().Respond(*c, 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? // TODO: should we return an error here?
} }
@@ -194,7 +194,7 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) { if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true); Engine->Network().SendToAll(nullptr, Destroy, true, true);
c->DeleteCar(VID); c->DeleteCar(VID);
Result.first = true; Result.first = true;
} else { } else {
@@ -526,7 +526,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path"); beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
return; return;
} }
std::string key {}; std::string key{};
switch (left.get_type()) { switch (left.get_type()) {
case sol::type::lua_nil: case sol::type::lua_nil:
case sol::type::none: case sol::type::none:
+5 -6
View File
@@ -198,10 +198,10 @@ bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min,
return EnsureArgsCount(args, min); return EnsureArgsCount(args, min);
} else { } else {
if (args.size() > max) { if (args.size() > max) {
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead."); Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
return false; return false;
} else if (args.size() < min) { } else if (args.size() < min) {
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead."); Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead.");
return false; return false;
} }
} }
@@ -350,10 +350,9 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
} }
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 1, 2)) { if (!EnsureArgsCount(args, 0)) {
return; return;
} }
} }
void TConsole::Command_Say(const std::string& FullCmd) { void TConsole::Command_Say(const std::string& FullCmd) {
@@ -479,12 +478,12 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n" << "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
<< "\tSubsystems:\n" << "\tSubsystems:\n"
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n" << "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n" << "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
<< "\t\tGood: [ " << SystemsGoodList << " ]\n" << "\t\tGood: [ " << SystemsGoodList << " ]\n"
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n" << "\t\tStarting: [ " << SystemsStartingList << " ]\n"
<< "\t\tBad: [ " << SystemsBadList << " ]\n" << "\t\tBad: [ " << SystemsBadList << " ]\n"
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n" << "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n" << "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
<< ""; << "";
Application::Console().WriteRaw(Status.str()); Application::Console().WriteRaw(Status.str());
+7 -2
View File
@@ -40,6 +40,10 @@ void THeartbeatThread::operator()() {
Body += "&ip=" + Application::Settings.CustomIP; Body += "&ip=" + Application::Settings.CustomIP;
} }
Body += "&pps=" + Application::PPS();
beammp_trace("heartbeat body: '" + Body + "'");
auto SentryReportError = [&](const std::string& transaction, int status) { auto SentryReportError = [&](const std::string& transaction, int status) {
auto Lock = Sentry.CreateExclusiveContext(); auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("heartbeat", Sentry.SetContext("heartbeat",
@@ -57,10 +61,11 @@ void THeartbeatThread::operator()() {
bool Ok = false; bool Ok = false;
for (const auto& Url : Application::GetBackendUrlsInOrder()) { for (const auto& Url : Application::GetBackendUrlsInOrder()) {
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } }); T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
beammp_trace(T);
Doc.Parse(T.data(), T.size()); Doc.Parse(T.data(), T.size());
if (Doc.HasParseError() || !Doc.IsObject()) { if (Doc.HasParseError() || !Doc.IsObject()) {
if (!Application::Settings.Private) { if (!Application::Settings.Private) {
beammp_trace("Backend response failed to parse as valid json"); beammp_error("Backend response failed to parse as valid json");
beammp_trace("Response was: `" + T + "`"); beammp_trace("Response was: `" + T + "`");
} }
Sentry.SetContext("JSON Response", { { "reponse", T } }); Sentry.SetContext("JSON Response", { { "reponse", T } });
@@ -143,7 +148,7 @@ std::string THeartbeatThread::GenerateCall() {
<< "&map=" << Application::Settings.MapName << "&map=" << Application::Settings.MapName
<< "&private=" << (Application::Settings.Private ? "true" : "false") << "&private=" << (Application::Settings.Private ? "true" : "false")
<< "&version=" << Application::ServerVersionString() << "&version=" << Application::ServerVersionString()
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf. << "&clientversion=" << Application::ClientVersionString()
<< "&name=" << Application::Settings.ServerName << "&name=" << Application::Settings.ServerName
<< "&modlist=" << mResourceManager.TrimmedList() << "&modlist=" << mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.MaxModSize() << "&modstotalsize=" << mResourceManager.MaxModSize()
+9 -17
View File
@@ -4,7 +4,6 @@
#include "Http.h" #include "Http.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaPlugin.h" #include "TLuaPlugin.h"
#include "sol/object.hpp"
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
@@ -418,6 +417,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
if (Fn.valid()) { if (Fn.valid()) {
auto LuaResult = Fn(EventArgs); auto LuaResult = Fn(EventArgs);
auto Result = std::make_shared<TLuaResult>(); auto Result = std::make_shared<TLuaResult>();
Result->Ready = true;
if (LuaResult.valid()) { if (LuaResult.valid()) {
Result->Error = false; Result->Error = false;
Result->Result = LuaResult; Result->Result = LuaResult;
@@ -425,7 +425,6 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
Result->Error = true; Result->Error = true;
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid"; Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
} }
Result->Ready = true;
Return.push_back(Result); Return.push_back(Result);
} }
} }
@@ -585,25 +584,27 @@ std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionR
std::string VehiclePos = Client->GetCarPositionRaw(VID); std::string VehiclePos = Client->GetCarPositionRaw(VID);
if (VehiclePos.empty()) { if (VehiclePos.empty()) {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found")); //return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
Result.second = "Vehicle not found"; Result.second = "Vehicle not found";
return Result; return Result;
} }
sol::table t = Lua_JsonDecode(VehiclePos); sol::table t = Lua_JsonDecode(VehiclePos);
if (t == sol::lua_nil) { if (t == sol::lua_nil){
Result.second = "Packet decode failed"; Result.second = "Packet decode failed";
} }
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil)); //return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
Result.first = t; Result.first = t;
return Result; return Result;
} else { }
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired")); else {
//return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
Result.second = "Client expired"; Result.second = "Client expired";
return Result; return Result;
} }
} }
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) { sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
auto table = mStateView.create_table(); auto table = mStateView.create_table();
constexpr const char* InternalClient = "__InternalClient"; constexpr const char* InternalClient = "__InternalClient";
@@ -947,6 +948,7 @@ void TLuaEngine::StateThreadData::operator()() {
} }
sol::state_view StateView(mState); sol::state_view StateView(mState);
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName); auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
S.second->Ready = true;
if (Res.valid()) { if (Res.valid()) {
S.second->Error = false; S.second->Error = false;
S.second->Result = std::move(Res); S.second->Result = std::move(Res);
@@ -955,7 +957,6 @@ void TLuaEngine::StateThreadData::operator()() {
sol::error Err = Res; sol::error Err = Res;
S.second->ErrorMessage = Err.what(); S.second->ErrorMessage = Err.what();
} }
S.second->Ready = true;
} }
} }
{ // StateFunctionQueue Scope { // StateFunctionQueue Scope
@@ -993,15 +994,6 @@ void TLuaEngine::StateThreadData::operator()() {
case TLuaArgTypes_Bool: case TLuaArgTypes_Bool:
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg))); LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
break; break;
case TLuaArgTypes_StringStringMap: {
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
auto Table = StateView.create_table();
for (const auto& [k, v] : Map) {
Table[k] = v;
}
LuaArgs.push_back(sol::make_object(StateView, Table));
break;
}
default: default:
beammp_error("Unknown argument type, passed as nil"); beammp_error("Unknown argument type, passed as nil");
break; break;
+431 -352
View File
File diff suppressed because it is too large Load Diff
+55 -78
View File
@@ -1,11 +1,9 @@
#include "TServer.h" #include "TServer.h"
#include "Client.h" #include "Client.h"
#include "Common.h" #include "Common.h"
#include "CustomAssert.h"
#include "TNetwork.h" #include "TNetwork.h"
#include "TPPSMonitor.h" #include "TPPSMonitor.h"
#include <TLuaPlugin.h> #include <TLuaPlugin.h>
#include <algorithm>
#include <any> #include <any>
#include <sstream> #include <sstream>
@@ -95,20 +93,20 @@ TServer::TServer(const std::vector<std::string_view>& Arguments) {
} }
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) { void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
std::shared_ptr<TClient> LockedClientPtr { nullptr }; if (!WeakClientPtr.expired()) {
try { TClient& Client = *WeakClientPtr.lock();
LockedClientPtr = WeakClientPtr.lock(); beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
} catch (const std::exception&) { Client.ClearCars();
// silently fail, as there's nothing to do WriteLock Lock(mClientsMutex);
return; mClients.erase(WeakClientPtr.lock());
} }
beammp_assert(LockedClientPtr != nullptr); }
TClient& Client = *LockedClientPtr;
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")"); std::weak_ptr<TClient> TServer::InsertNewClient() {
// TODO: Send delete packets for all cars beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
Client.ClearCars();
WriteLock Lock(mClientsMutex); WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock()); auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
return *Iter;
} }
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) { void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
@@ -129,11 +127,12 @@ 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::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
constexpr std::string_view ABG = "ABG:"; if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) { // abort();
Packet.erase(Packet.begin(), Packet.begin() + ABG.size()); }
Packet = DeComp(Packet); if (Packet.substr(0, 4) == "ABG:") {
Packet = DeComp(Packet.substr(4));
} }
if (Packet.empty()) { if (Packet.empty()) {
return; return;
@@ -147,8 +146,6 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
std::any Res; std::any Res;
char Code = Packet.at(0); char Code = Packet.at(0);
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
// V to Y // V to Y
if (Code <= 89 && Code >= 86) { if (Code <= 89 && Code >= 86) {
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
@@ -157,40 +154,38 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
} }
switch (Code) { switch (Code) {
case 'H': // initial connection case 'H': // initial connection
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
if (!Network.SyncClient(Client)) { if (!Network.SyncClient(Client)) {
// TODO handle // TODO handle
} }
return; return;
case 'p': case 'p':
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) { if (!Network.Respond(*LockedClient, ("p"), false)) {
// failed to send // failed to send
LockedClient->Disconnect("Failed to send ping"); if (LockedClient->GetStatus() > -1) {
LockedClient->SetStatus(-1);
}
} else { } else {
Network.UpdatePlayer(*LockedClient); Network.UpdatePlayer(*LockedClient);
} }
return; return;
case 'O': case 'O':
if (Packet.size() > 1000) { if (Packet.length() > 1000) {
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size())); beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
} }
ParseVehicle(*LockedClient, StringPacket, Network); ParseVehicle(*LockedClient, Packet, Network);
return;
case 'J':
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
case 'C': { case 'C': {
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end()) beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break; break;
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size()); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
std::string Message = "";
const auto ColonPos = PacketAsString.find(':', 3);
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
Message = PacketAsString.substr(ColonPos + 2);
}
if (Message.empty()) {
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
return;
}
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
TLuaEngine::WaitForAll(Futures); TLuaEngine::WaitForAll(Futures);
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1)); LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.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,12 +194,12 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
})) { })) {
break; break;
} }
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message); Network.SendToAll(nullptr, Packet, true, true);
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
return; return;
} }
case 'E': case 'E':
HandleEvent(*LockedClient, StringPacket); beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
HandleEvent(*LockedClient, Packet);
return; return;
case 'N': case 'N':
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")"); beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
@@ -213,7 +208,8 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
case 'Z': // position packet case 'Z': // position packet
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
HandlePosition(*LockedClient, StringPacket);
HandlePosition(*LockedClient, Packet);
default: default:
return; return;
} }
@@ -222,10 +218,6 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uin
void TServer::HandleEvent(TClient& c, const std::string& RawData) { void TServer::HandleEvent(TClient& c, const std::string& RawData) {
// E:Name:Data // E:Name:Data
// Data is allowed to have ':' // Data is allowed to have ':'
if (RawData.size() < 2) {
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
return;
}
auto NameDataSep = RawData.find(':', 2); auto NameDataSep = RawData.find(':', 2);
if (NameDataSep == std::string::npos) { if (NameDataSep == std::string::npos) {
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'"); beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
@@ -243,7 +235,7 @@ bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
return true; return true;
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'."); beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
} }
return false; return false;
} }
@@ -258,7 +250,7 @@ bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
} }
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) { void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
if (Pckt.length() < 6) if (Pckt.length() < 4)
return; return;
std::string Packet = Pckt; std::string Packet = Pckt;
char Code = Packet.at(1); char Code = Packet.at(1);
@@ -267,10 +259,10 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
std::string Data = Packet.substr(3), pid, vid; std::string Data = Packet.substr(3), pid, vid;
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
case 's': case 's':
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size()); beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Data.at(0) == '0') { if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID(); int CarID = c.GetOpenCarID();
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID); beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
std::string CarJson = Packet.substr(5); std::string CarJson = Packet.substr(5);
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson; Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
@@ -283,16 +275,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) { if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
c.AddNewCar(CarID, Packet); c.AddNewCar(CarID, Packet);
Network.SendToAll(nullptr, StringToVector(Packet), true, true); Network.SendToAll(nullptr, Packet, true, true);
} else { } else {
if (!Network.Respond(c, StringToVector(Packet), true)) { if (!Network.Respond(c, Packet, true)) {
// TODO: handle // TODO: handle
} }
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID); std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, StringToVector(Destroy), true)) { if (!Network.Respond(c, Destroy, true)) {
// TODO: handle // TODO: handle
} }
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID); beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
} }
} }
return; return;
@@ -314,14 +306,14 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos))) if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& !ShouldntAllow) { && !ShouldntAllow) {
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, Packet, false, true);
Apply(c, VID, Packet); Apply(c, VID, Packet);
} else { } else {
if (c.GetUnicycleID() == VID) { if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1); c.SetUnicycleID(-1);
} }
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
Network.SendToAll(nullptr, StringToVector(Destroy), true, true); Network.SendToAll(nullptr, Destroy, true, true);
c.DeleteCar(VID); c.DeleteCar(VID);
} }
} }
@@ -329,7 +321,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
case 'd': { case 'd': {
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1))); auto MaybePidVid = GetPidVid(Data);
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
@@ -337,7 +329,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (c.GetUnicycleID() == VID) { if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1); c.SetUnicycleID(-1);
} }
Network.SendToAll(nullptr, StringToVector(Packet), true, true); Network.SendToAll(nullptr, Packet, true, true);
// TODO: should this trigger on all vehicle deletions? // TODO: should this trigger on all vehicle deletions?
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
c.DeleteCar(VID); c.DeleteCar(VID);
@@ -347,7 +339,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
case 'r': { case 'r': {
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1))); auto MaybePidVid = GetPidVid(Data);
if (MaybePidVid) { if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value(); std::tie(PID, VID) = MaybePidVid.value();
} }
@@ -355,16 +347,16 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
Data = Data.substr(Data.find('{')); Data = Data.substr(Data.find('{'));
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data)); LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, Packet, false, true);
} }
return; return;
} }
case 't': case 't':
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(&c, StringToVector(Packet), false, true); Network.SendToAll(&c, Packet, false, true);
return; return;
case 'm': case 'm':
Network.SendToAll(&c, StringToVector(Packet), true, true); Network.SendToAll(&c, Packet, true, true);
return; return;
default: default:
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")"))); beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
@@ -433,24 +425,10 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
} }
void TServer::HandlePosition(TClient& c, const std::string& Packet) { void TServer::HandlePosition(TClient& c, const std::string& Packet) {
if (Packet.size() < 3) {
// invalid packet
return;
}
// Zp:serverVehicleID:data // Zp:serverVehicleID:data
// Zp:0:data
std::string withoutCode = Packet.substr(3); std::string withoutCode = Packet.substr(3);
auto NameDataSep = withoutCode.find(':', 2); 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); std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
if (NameDataSep + 1 > withoutCode.size()) {
// invalid packet
return;
}
std::string Data = withoutCode.substr(NameDataSep + 1); std::string Data = withoutCode.substr(NameDataSep + 1);
// parse veh ID // parse veh ID
@@ -458,7 +436,6 @@ void TServer::HandlePosition(TClient& c, const std::string& Packet) {
if (MaybePidVid) { if (MaybePidVid) {
int PID = -1; int PID = -1;
int VID = -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(); std::tie(PID, VID) = MaybePidVid.value();
c.SetCarPosition(VID, Data); c.SetCarPosition(VID, Data);