mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-13 10:13:42 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 39badf432d | |||
| 03307e71fb |
@@ -1 +0,0 @@
|
||||
patreon: BeamMP
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: "[Bug] Enter issue title here"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
labels: feature
|
||||
title: "[Feature Request]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
+68
-70
@@ -2,33 +2,15 @@ name: Linux
|
||||
|
||||
on: [push]
|
||||
|
||||
|
||||
env:
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
DEBIAN_FRONTEND: "noninteractive"
|
||||
|
||||
jobs:
|
||||
x86_64-matrix:
|
||||
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
|
||||
debian-11-build:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
image: debian:11
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -47,59 +29,37 @@ jobs:
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||
|
||||
- name: Install Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||
|
||||
- name: Create Build Environment
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
|
||||
- name: Build Server
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
run: bash ./scripts/debian-11/3-build.sh
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
name: BeamMP-Server-debian
|
||||
path: ./bin/BeamMP-Server
|
||||
|
||||
- name: Archive server debug info artifact
|
||||
- name: Build Tests
|
||||
run: bash ./scripts/debian-11/3-build-tests.sh
|
||||
|
||||
- name: Archive server tests artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
path: ./bin/BeamMP-Server.debug
|
||||
name: BeamMP-Server-debian-tests
|
||||
path: ./bin/BeamMP-Server-tests
|
||||
|
||||
- name: Build Tests
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
|
||||
|
||||
- name: Test
|
||||
run: ./bin/BeamMP-Server-tests
|
||||
|
||||
arm64-matrix:
|
||||
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
|
||||
ubuntu-22-04-build:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
image: ubuntu:22.04
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -118,35 +78,73 @@ jobs:
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||
|
||||
- name: Install Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||
|
||||
- name: Setup vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
runVcpkgInstall: true
|
||||
|
||||
- name: Create Build Environment
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
|
||||
- name: Build Server
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||
|
||||
- name: Archive server artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
name: BeamMP-Server-ubuntu
|
||||
path: ./bin/BeamMP-Server
|
||||
|
||||
- name: Build Tests
|
||||
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
|
||||
|
||||
- name: Archive server debug info artifact
|
||||
- name: Archive server tests artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
path: ./bin/BeamMP-Server.debug
|
||||
|
||||
- name: Build Tests
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||
name: BeamMP-Server-ubuntu-tests
|
||||
path: ./bin/BeamMP-Server-tests
|
||||
|
||||
run-debian-11-tests:
|
||||
needs: debian-11-build
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: debian:11
|
||||
steps:
|
||||
- uses: actions/download-artifact@master
|
||||
with:
|
||||
name: BeamMP-Server-debian-tests
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
|
||||
run: |
|
||||
apt-get update -y
|
||||
apt-get install -y liblua5.3-0
|
||||
|
||||
- name: Test
|
||||
run: ./bin/BeamMP-Server-tests
|
||||
run: |
|
||||
chmod +x ./BeamMP-Server-tests
|
||||
./BeamMP-Server-tests
|
||||
|
||||
run-ubuntu-22-04-tests:
|
||||
needs: ubuntu-22-04-build
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ubuntu:22.04
|
||||
steps:
|
||||
- uses: actions/download-artifact@master
|
||||
with:
|
||||
name: BeamMP-Server-ubuntu-tests
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
run: |
|
||||
apt-get update -y
|
||||
apt-get install -y liblua5.3-0
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
chmod +x ./BeamMP-Server-tests
|
||||
./BeamMP-Server-tests
|
||||
@@ -7,8 +7,6 @@ on:
|
||||
|
||||
env:
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
DEBIAN_FRONTEND: "noninteractive"
|
||||
|
||||
jobs:
|
||||
create-release:
|
||||
@@ -28,30 +26,18 @@ jobs:
|
||||
draft: false
|
||||
prerelease: true
|
||||
body: |
|
||||
Files included in this release are:
|
||||
- `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.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.
|
||||
Files included in this release:
|
||||
- `BeamMP-Server.exe` is the windows build.
|
||||
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`.
|
||||
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
|
||||
|
||||
x86_64-matrix:
|
||||
upload-release-files-debian-11:
|
||||
name: Build and upload Debian 11 Release Files
|
||||
runs-on: ubuntu-22.04
|
||||
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:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
image: debian:11
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -70,16 +56,21 @@ jobs:
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
run: bash ./scripts/debian-11/1.5-git-safe.sh
|
||||
|
||||
- name: Install Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
run: bash ./scripts/debian-11/1-install-deps.sh
|
||||
|
||||
- name: Setup vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
runVcpkgInstall: true
|
||||
|
||||
- name: Create Build Environment
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
|
||||
- name: Build Server
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
run: bash ./scripts/debian-11/3-build.sh
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
@@ -87,45 +78,18 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||
asset_path: ./bin/BeamMP-Server
|
||||
asset_name: BeamMP-Server-debian
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
- name: Upload Debug Info
|
||||
id: upload-debug-info
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||
asset_path: ./bin/BeamMP-Server.debug
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
arm64-matrix:
|
||||
runs-on: [Linux, ARM64]
|
||||
|
||||
upload-release-files-ubuntu-22-04:
|
||||
name: Build and upload Ubuntu 22.04 Release Files
|
||||
runs-on: ubuntu-22.04
|
||||
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"
|
||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
image: ubuntu:22.04
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
@@ -144,16 +108,16 @@ jobs:
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
run: bash ./scripts/ubuntu-22.04/1.5-git-safe.sh
|
||||
|
||||
- name: Install Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
|
||||
|
||||
- name: Create Build Environment
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
|
||||
- name: Build Server
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
run: bash ./scripts/ubuntu-22.04/3-build.sh
|
||||
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
@@ -161,20 +125,9 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||
asset_path: ./bin/BeamMP-Server
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
- name: Upload Debug Info
|
||||
id: upload-debug-info
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||
asset_path: ./bin/BeamMP-Server.debug
|
||||
asset_name: BeamMP-Server-ubuntu
|
||||
asset_content_type: application/x-elf
|
||||
|
||||
upload-release-files-windows:
|
||||
@@ -210,6 +163,6 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.create-release.outputs.upload_url }}
|
||||
asset_path: ./bin/Release/BeamMP-Server.exe
|
||||
asset_path: ./bin/BeamMP-Server.exe
|
||||
asset_name: BeamMP-Server.exe
|
||||
asset_content_type: application/vnd.microsoft.portable-executable
|
||||
asset_content_type: application/vnd.microsoft.portable-executable
|
||||
@@ -5,7 +5,6 @@ on: [push]
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
|
||||
jobs:
|
||||
windows-build:
|
||||
@@ -39,5 +38,5 @@ jobs:
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server-windows
|
||||
path: ./bin/Release/BeamMP-Server.exe
|
||||
path: ./bin/BeamMP-Server.exe
|
||||
|
||||
|
||||
@@ -4,6 +4,3 @@
|
||||
[submodule "vcpkg"]
|
||||
path = vcpkg
|
||||
url = https://github.com/Microsoft/vcpkg.git
|
||||
[submodule "deps/BeamMP-Protocol"]
|
||||
path = deps/BeamMP-Protocol
|
||||
url = https://github.com/BeamMP/BeamMP-Protocol
|
||||
|
||||
+21
-27
@@ -15,59 +15,61 @@ include(cmake/StandardSettings.cmake)
|
||||
include(cmake/StaticAnalyzers.cmake)
|
||||
include(cmake/Git.cmake)
|
||||
|
||||
add_subdirectory(deps/BeamMP-Protocol)
|
||||
|
||||
# below are options which should be changed
|
||||
|
||||
### SETTINGS ###
|
||||
|
||||
# add all headers (.h, .hpp) to this
|
||||
set(PRJ_HEADERS
|
||||
set(PRJ_HEADERS
|
||||
include/ArgsParser.h
|
||||
include/BoostAliases.h
|
||||
include/Client.h
|
||||
include/Common.h
|
||||
include/Compat.h
|
||||
include/Cryptography.h
|
||||
include/CustomAssert.h
|
||||
include/Defer.h
|
||||
include/Environment.h
|
||||
include/FileWatcher.h
|
||||
include/Http.h
|
||||
include/IThreaded.h
|
||||
include/Json.h
|
||||
include/LuaAPI.h
|
||||
include/LuaPlugin.h
|
||||
include/Plugin.h
|
||||
include/PluginManager.h
|
||||
include/RWMutex.h
|
||||
include/SignalHandling.h
|
||||
include/TConfig.h
|
||||
include/TConsole.h
|
||||
include/THeartbeatThread.h
|
||||
include/TLuaEngine.h
|
||||
include/TLuaPlugin.h
|
||||
include/TNetwork.h
|
||||
include/TPluginMonitor.h
|
||||
include/TPPSMonitor.h
|
||||
include/TResourceManager.h
|
||||
include/TScopedTimer.h
|
||||
include/Value.h
|
||||
include/TServer.h
|
||||
include/VehicleData.h
|
||||
include/Network.h
|
||||
include/Env.h
|
||||
)
|
||||
# add all source files (.cpp) to this, except the one with main()
|
||||
set(PRJ_SOURCES
|
||||
src/ArgsParser.cpp
|
||||
src/Client.cpp
|
||||
src/Common.cpp
|
||||
src/Compat.cpp
|
||||
src/FileWatcher.cpp
|
||||
src/Http.cpp
|
||||
src/LuaAPI.cpp
|
||||
src/LuaPlugin.cpp
|
||||
src/SignalHandling.cpp
|
||||
src/TConfig.cpp
|
||||
src/TConsole.cpp
|
||||
src/THeartbeatThread.cpp
|
||||
src/TLuaEngine.cpp
|
||||
src/TLuaPlugin.cpp
|
||||
src/TNetwork.cpp
|
||||
src/TPluginMonitor.cpp
|
||||
src/TPPSMonitor.cpp
|
||||
src/TResourceManager.cpp
|
||||
src/TScopedTimer.cpp
|
||||
src/Value.cpp
|
||||
src/TServer.cpp
|
||||
src/VehicleData.cpp
|
||||
src/Network.cpp
|
||||
src/Env.cpp
|
||||
)
|
||||
|
||||
find_package(Lua REQUIRED)
|
||||
@@ -94,26 +96,19 @@ set(PRJ_LIBRARIES
|
||||
httplib::httplib
|
||||
libzip::zip
|
||||
OpenSSL::SSL OpenSSL::Crypto
|
||||
protocol
|
||||
${LUA_LIBRARIES}
|
||||
zstd::libzstd_static
|
||||
Boost::thread
|
||||
Boost::json
|
||||
glm::glm
|
||||
)
|
||||
|
||||
# add dependency find_package calls and similar here
|
||||
find_package(fmt CONFIG REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(doctest CONFIG REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS thread json)
|
||||
find_package(Boost REQUIRED)
|
||||
find_package(httplib CONFIG REQUIRED)
|
||||
find_package(libzip CONFIG REQUIRED)
|
||||
find_package(RapidJSON CONFIG REQUIRED)
|
||||
find_package(sol2 CONFIG REQUIRED)
|
||||
find_package(toml11 CONFIG REQUIRED)
|
||||
find_package(zstd CONFIG REQUIRED)
|
||||
find_package(glm CONFIG REQUIRED)
|
||||
|
||||
include_directories(include)
|
||||
|
||||
@@ -131,10 +126,9 @@ include(FindThreads)
|
||||
# enables compile_commands.json for clang-related tools (such as the clang LS)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# build release builds by default (if not specified otherwise)
|
||||
if(NOT DEFINED CMAKE_BUILD_TYPE)
|
||||
message(NOTICE "No build type specified, defaulting to 'Release'")
|
||||
set(CMAKE_BUILD_TYPE "Release")
|
||||
# build debug builds by default (if not specified otherwise)
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE "Debug")
|
||||
endif()
|
||||
|
||||
if(UNIX)
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
# 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
|
||||
|
||||
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
|
||||
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
|
||||
- ADDED Util.JsonEncode() and Util.JsonDecode(), which turn lua tables into json and vice-versa
|
||||
- ADDED FS.ListFiles and FS.ListDirectories
|
||||
- ADDED onFileChanged event, triggered when a server plugin file changes
|
||||
- ADDED MP.GetPositionRaw(), which can be used to retrieve the latest position packet per player, per vehicle
|
||||
- ADDED error messages to some lua functions
|
||||
- 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 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 issue with client->server events which contain `:`
|
||||
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||
- FIXED onInit not being called on hot-reload
|
||||
- FIXED incorrect timing calculation of Lua EventTimer loop
|
||||
- FIXED bug which caused hot-reload not to report syntax errors
|
||||
- FIXED missing error messages on some event handler calls
|
||||
- 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
|
||||
|
||||
- ADDED Periodic update message if a new server is released
|
||||
- ADDED Config setting for the IP the http server listens on
|
||||
- CHANGED Default MaxPlayers to 8
|
||||
- CHANGED Default http server listen IP to localhost
|
||||
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
|
||||
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
|
||||
- FIXED Lua result queue handling not checking all results
|
||||
- FIXED bug which caused ServerConfig.toml to generate incorrectly
|
||||
|
||||
# v3.0.1
|
||||
|
||||
- ADDED Backup URLs to UpdateCheck (will fail less often now)
|
||||
- ADDED console cursor left and right movement (with arrow keys) and working HOME and END key (via github.com/lionkor/commandline)
|
||||
- FIXED infinite snowmen / infinite unicycle spawning bug
|
||||
- FIXED a bug where, when run with --working-directory, the Server.log would still be in the original directory
|
||||
- FIXED a bug which could cause the plugin reload thread to spin at 100% if the reloaded plugin's didn't terminate
|
||||
- FIXED an issue which would cause servers to crash on mod download via SIGPIPE on POSIX
|
||||
- FIXED an issue which would cause servers to crash when checking if a vehicle is a unicycle
|
||||
|
||||
# v3.0.0
|
||||
|
||||
- CHANGED entire plugin Lua implementation (rewrite)
|
||||
- CHANGED moved *almost all* Lua functions into MP.\*
|
||||
- CHANGED console to use a custom language (type `help`, `list`, or `status`!)
|
||||
- CHANGED all files of a Lua plugin to share a Lua state (no more state-per-file)
|
||||
- ADDED many new Lua API functions, which can be found at <https://wiki.beammp.com/en/Scripting/functions>
|
||||
- ADDED Commandline options. Run with `--help` to see all options.
|
||||
- ADDED HTTP(S) Server (OpenAPI spec coming soon!)
|
||||
- ADDED plugin directories to `package.path` and `package.cpath` before `onInit`
|
||||
- ADDED ability to add `PluginConfig.toml` to your plugin folder to change some settings
|
||||
- ADDED ability to share a lua state with other plugins via `StateId` setting in `PluginConfig.toml`
|
||||
- ADDED ability to see name-to-thread-ID association in debug mode
|
||||
- ADDED dumping tables with `print()` (try it with `print(MP)`)
|
||||
- ADDED `MP.GetOSName()`, `MP.CreateTimer()`, `MP.GetLuaMemoryUsage()` and many more (see <https://wiki.beammp.com/en/Scripting/functions>)
|
||||
- ADDED `MP.Settings` table to make usage of `MP.Set()` easier
|
||||
- ADDED `FS.*` table with common filesystem operations (do `print(FS)` to see them!)
|
||||
- FIXED i/o thread spin when stdout is /dev/null on linux
|
||||
- FIXED removed extra whitespace infront of onChatMessage message
|
||||
|
||||
# v2.3.3
|
||||
|
||||
- CHANGED servers to be private by default
|
||||
|
||||
# v2.3.2
|
||||
|
||||
- ADDED Ctrl+C causes a graceful shutdown on windows (did already on linux)
|
||||
- ADDED more meaningful shutdown messages
|
||||
- ADDED even better backend connection error reporting
|
||||
- ADDED `SendErrors` config in `ServerConfig.toml` to opt-out of error reporting
|
||||
- ADDED hard-shutdown if Ctrl+C pressed 3 times
|
||||
- FIXED issue with shells like bash being unusable after server exit
|
||||
|
||||
# v2.3.1
|
||||
|
||||
- CHANGED join/sync timeout to 20 minutes, players wont drop if loading takes >5 mins
|
||||
|
||||
# v2.3.0
|
||||
|
||||
- ADDED version check - the server will now let you know when a new release is out
|
||||
- ADDED logging of various errors, crashes and exceptions to the backend
|
||||
- ADDED chat messages are now logged to the server console as [CHAT]
|
||||
- ADDED debug message telling you when the server heartbeats to the backend
|
||||
- REMOVED various [DEBUG] messages which were confusing (such as "breaking client loop")
|
||||
- FIXED various crashes and issues with handling unexpected backend responses
|
||||
- FIXED minor bugs due to code correctness
|
||||
|
||||
# v2.2.0
|
||||
|
||||
- FIXED major security flaw
|
||||
- FIXED minor bugs
|
||||
|
||||
# v2.1.4
|
||||
|
||||
- ADDED debug heartbeat print
|
||||
- ADDED kicking every player before shutdown
|
||||
- FIXED rare bug which led to violent crash
|
||||
- FIXED minor bugs
|
||||
|
||||
# v2.1.3
|
||||
|
||||
- FIXED Lua events not cancelling properly on Linux
|
||||
|
||||
# v2.1.2
|
||||
|
||||
- CHANGED default map to gridmap v2
|
||||
- FIXED version number display
|
||||
|
||||
# v2.1.1
|
||||
# v2.1.0 (pre-v2.1.1)
|
||||
# v2.0.4 (pre-v2.1.0)
|
||||
|
||||
- REMOVED boost as a runtime dependency
|
||||
- FIXED Lua plugins on Linux
|
||||
- FIXED console history on Windows
|
||||
- CHANGED to new config format TOML
|
||||
|
||||
# v2.0.3
|
||||
|
||||
- WORKAROUND for timeout bug / ghost player bug
|
||||
- FIXED 100% CPU spin when stdin is /dev/null.
|
||||
|
||||
# v2.0.2
|
||||
|
||||
- ADDED fully new commandline
|
||||
- ADDED new backend
|
||||
- ADDED automated build system
|
||||
- ADDED lua GetPlayerIdentifiers
|
||||
- ADDED lots of debug info
|
||||
- ADDED better POSTing and GETing
|
||||
- ADDED a license
|
||||
- FIXED ghost players in player list issue
|
||||
- FIXED ghost vehicle after joining issue
|
||||
- FIXED missing vehicle after joining issue
|
||||
- FIXED a lot of desync issues
|
||||
- FIXED some memory leaks
|
||||
- FIXED various crashes
|
||||
- FIXED various data-races
|
||||
- FIXED some linux-specific crashes
|
||||
- FIXED some linux-specific issues
|
||||
- FIXED bug which caused kicking to be logged as leaving
|
||||
- FIXED various internal developer quality-of-life things
|
||||
@@ -1,661 +1,2 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor). BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
|
||||
The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
||||
|
||||
**For Linux, you __need__ the runtime dependencies, which are listed below under [Runtime Dependencies](#runtime-dependencies)**
|
||||
**For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
|
||||
|
||||
## Support + Contact
|
||||
|
||||
Feel free to ask any questions via the following channels:
|
||||
|
||||
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
|
||||
- **Discord**: [click for invite](https://discord.gg/beammp)
|
||||
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
|
||||
|
||||
@@ -42,7 +43,7 @@ We only allow building unmodified (original) source code for public use. `master
|
||||
|
||||
## Supported Operating Systems
|
||||
|
||||
The code itself supports (latest stable) Linux, Windows and FreeBSD. In terms of actual build support, for now we usually only distribute Windows binaries and Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
|
||||
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute Windows binaries and sometimes Linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
|
||||
|
||||
Recommended compilers: MSVC, GCC, CLANG.
|
||||
|
||||
@@ -50,45 +51,133 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
||||
|
||||
## Build Instructions
|
||||
|
||||
On Linux, you need some dependencies to **build** the server (on Windows, you don't):
|
||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v3.1.0`!__**
|
||||
|
||||
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)).
|
||||
|
||||
### Prerequisites
|
||||
|
||||
#### Windows
|
||||
|
||||
There are **no runtime libraries** needed for Windows.
|
||||
|
||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||
|
||||
Dependencies for **Windows** can be installed with `vcpkg`.
|
||||
These are:
|
||||
```
|
||||
liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||
lua zlib rapidjson openssl websocketpp curl
|
||||
```
|
||||
The triplet we use for releases is `x64-windows-static`.
|
||||
|
||||
You can install these with your distribution's package manager. You will need sudo or need root for ONLY this step.
|
||||
#### Linux
|
||||
|
||||
The names of each package may change depending on your platform.
|
||||
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).
|
||||
|
||||
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:
|
||||
|
||||
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
|
||||
2. Go into the directory `cd BeamMP-Server`.
|
||||
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
|
||||
4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
|
||||
5. Your executable can be found in `bin/`.
|
||||
|
||||
When you make changes to the code, you only have to run step 4 again.
|
||||
### Building for FreeBSD
|
||||
Building is only supported for major release branches of FreeBSD that are currently not EOL. The build process is the same as on Linux, although build dependencies can be universally installed from ports via pkg:
|
||||
```
|
||||
pkg install git cmake-core zip bash devel/ninja devel/pkgconf lua53
|
||||
```
|
||||
After installing the necessary build dependencies, follow the Linux build instructions beginning from step 3. Beware that running the initial cmake command will compile vcpkg from source, as vcpkg has no native FreeBSD port - this may take some time.
|
||||
|
||||
On systems with a single logical CPU core, `make` may fail to build the server when using the `--parallel` option when calling CMake. If you see error messages related to make, simply omit the `--parallel` from the command: `cmake --build bin --config Release -t BeamMP-Server`.
|
||||
|
||||
### Runtime Dependencies
|
||||
##### Runtime Dependencies
|
||||
|
||||
These are needed to *run* the server.
|
||||
|
||||
Debian, Ubuntu and friends: `liblua5.3-0`
|
||||
<details>
|
||||
<summary>
|
||||
Ubuntu 22.04
|
||||
</summary>
|
||||
|
||||
Other Linux distros: `liblua` of *some kind*.
|
||||
`apt-get install` the following libraries:
|
||||
```
|
||||
liblua5.3-0
|
||||
libssl3
|
||||
curl
|
||||
```
|
||||
</details>
|
||||
|
||||
Windows: No libraries.
|
||||
<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
|
||||
libz-dev
|
||||
rapidjson-dev
|
||||
liblua5.3-dev
|
||||
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
|
||||
g++
|
||||
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
|
||||
|
||||
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
|
||||
2. Clone the repository in a location of your choice with `git clone https://github.com/BeamMP/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).
|
||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`). This may take some time, and will update all submodules and prepare the build.
|
||||
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.*
|
||||
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.
|
||||
|
||||
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
|
||||
|
||||
## Support
|
||||
The BeamMP project is supported by community donations via our [Patreon](https://www.patreon.com/BeamMP). This brings perks such as Patreon-only channels on our Discord, early access to new updates, and more server keys.
|
||||
|
||||
## Copyright
|
||||
|
||||
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
|
||||
BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
|
||||
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
|
||||
|
||||
@@ -71,8 +71,9 @@ function(set_project_warnings project_name)
|
||||
-Werror=write-strings
|
||||
-Werror=strict-aliasing -fstrict-aliasing
|
||||
-Werror=missing-declarations
|
||||
-Werror=missing-field-initializers
|
||||
-Werror=ctor-dtor-privacy
|
||||
-Wno-missing-field-initializers
|
||||
-Werror=switch-enum
|
||||
-Wswitch-default
|
||||
-Werror=unused-result
|
||||
-Werror=implicit-fallthrough
|
||||
|
||||
Vendored
-1
Submodule deps/BeamMP-Protocol deleted from 8eda5714c0
Vendored
+1
-1
Submodule deps/commandline updated: b2a29733f9...0ff46d25b1
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <initializer_list>
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "BoostAliases.h"
|
||||
#include "Common.h"
|
||||
#include "Compat.h"
|
||||
#include "VehicleData.h"
|
||||
|
||||
class TServer;
|
||||
|
||||
#ifdef BEAMMP_WINDOWS
|
||||
// for socklen_t
|
||||
#include <WS2tcpip.h>
|
||||
#endif // WINDOWS
|
||||
|
||||
struct TConnection final {
|
||||
ip::tcp::socket Socket;
|
||||
ip::tcp::endpoint SockAddr;
|
||||
};
|
||||
|
||||
class TClient final {
|
||||
public:
|
||||
using TSetOfVehicleData = std::vector<TVehicleData>;
|
||||
|
||||
struct TVehicleDataLockPair {
|
||||
TSetOfVehicleData* VehicleData;
|
||||
std::unique_lock<std::mutex> Lock;
|
||||
};
|
||||
|
||||
TClient(TServer& Server, ip::tcp::socket&& Socket);
|
||||
TClient(const TClient&) = delete;
|
||||
~TClient();
|
||||
TClient& operator=(const TClient&) = delete;
|
||||
|
||||
void AddNewCar(int Ident, const std::string& Data);
|
||||
void SetCarData(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 SetRoles(const std::string& Role) { mRole = Role; }
|
||||
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
|
||||
std::string GetCarData(int Ident);
|
||||
std::string GetCarPositionRaw(int Ident);
|
||||
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
|
||||
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
|
||||
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
|
||||
void Disconnect(std::string_view Reason);
|
||||
bool IsDisconnected() const { return !mSocket.is_open(); }
|
||||
// locks
|
||||
void DeleteCar(int Ident);
|
||||
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
|
||||
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
|
||||
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
|
||||
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
|
||||
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
|
||||
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
|
||||
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
|
||||
[[nodiscard]] std::string GetRoles() const { return mRole; }
|
||||
[[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 GetCarCount() const;
|
||||
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);
|
||||
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
|
||||
[[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;
|
||||
void UpdatePingTime();
|
||||
int SecondsSinceLastPing();
|
||||
|
||||
private:
|
||||
void InsertVehicle(int ID, const std::string& Data);
|
||||
|
||||
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);
|
||||
+61
-40
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
@@ -23,11 +5,7 @@
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <filesystem>
|
||||
#include <fmt/chrono.h>
|
||||
#include <fmt/format.h>
|
||||
#include <fmt/ostream.h>
|
||||
#include <fmt/ranges.h>
|
||||
#include <fmt/std.h>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
@@ -65,11 +43,10 @@ public:
|
||||
struct TSettings {
|
||||
std::string ServerName { "BeamMP Server" };
|
||||
std::string ServerDesc { "BeamMP Default Description" };
|
||||
std::string ServerTags { "Freeroam" };
|
||||
std::string Resource { "Resources" };
|
||||
std::string MapName { "/levels/gridmap_v2/info.json" };
|
||||
std::string Key {};
|
||||
std::string Password {};
|
||||
std::string Password{};
|
||||
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
|
||||
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
|
||||
bool HTTPServerEnabled { false };
|
||||
@@ -98,7 +75,7 @@ public:
|
||||
static void RegisterShutdownHandler(const TShutdownHandler& Handler);
|
||||
// Causes all threads to finish up and exit gracefull gracefully
|
||||
static void GracefullyShutdown();
|
||||
static TConsole& Console() { return mConsole; }
|
||||
static TConsole& Console() { return *mConsole; }
|
||||
static std::string ServerVersionString();
|
||||
static const Version& ServerVersion() { return mVersion; }
|
||||
static uint8_t ClientMajorVersion() { return 2; }
|
||||
@@ -124,7 +101,9 @@ public:
|
||||
static void SleepSafeSeconds(size_t Seconds);
|
||||
|
||||
static void InitializeConsole() {
|
||||
mConsole.InitializeCommandline();
|
||||
if (!mConsole) {
|
||||
mConsole = std::make_unique<TConsole>();
|
||||
}
|
||||
}
|
||||
|
||||
enum class Status {
|
||||
@@ -150,17 +129,15 @@ private:
|
||||
static inline SystemStatusMap mSystemStatusMap {};
|
||||
static inline std::mutex mSystemStatusMapMutex {};
|
||||
static inline std::string mPPS;
|
||||
static inline TConsole mConsole;
|
||||
static inline std::unique_ptr<TConsole> mConsole;
|
||||
static inline std::shared_mutex mShutdownMtx {};
|
||||
static inline bool mShutdown { false };
|
||||
static inline std::mutex mShutdownHandlersMutex {};
|
||||
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
|
||||
|
||||
static inline Version mVersion { 3, 2, 2 };
|
||||
static inline Version mVersion { 3, 1, 2 };
|
||||
};
|
||||
|
||||
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
|
||||
|
||||
std::string ThreadName(bool DebugModeOverride = false);
|
||||
void RegisterThread(const std::string& str);
|
||||
#define RegisterThreadAuto() RegisterThread(__func__)
|
||||
@@ -222,16 +199,6 @@ void RegisterThread(const std::string& str);
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
|
||||
} while (false)
|
||||
#define beammp_lua_info(x) \
|
||||
do { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA INFO] ") + (x)); \
|
||||
} while (false)
|
||||
#define beammp_lua_debug(x) \
|
||||
do { \
|
||||
if (Application::Settings.DebugModeEnabled) { \
|
||||
Application::Console().Write(_this_location + std::string("[LUA DEBUG] ") + (x)); \
|
||||
} \
|
||||
} while (false)
|
||||
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
|
||||
#define beammp_debug(x) \
|
||||
do { \
|
||||
@@ -262,6 +229,8 @@ void RegisterThread(const std::string& str);
|
||||
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
|
||||
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
|
||||
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
|
||||
|
||||
#else // DOCTEST_CONFIG_DISABLE
|
||||
|
||||
@@ -295,5 +264,57 @@ void RegisterThread(const std::string& str);
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||
|
||||
#define Biggest 30000
|
||||
|
||||
template <typename T>
|
||||
inline T Comp(const T& Data) {
|
||||
std::array<char, Biggest> C {};
|
||||
// obsolete
|
||||
C.fill(0);
|
||||
z_stream defstream;
|
||||
defstream.zalloc = nullptr;
|
||||
defstream.zfree = nullptr;
|
||||
defstream.opaque = nullptr;
|
||||
defstream.avail_in = uInt(Data.size());
|
||||
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
size_t TotalOut = defstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T DeComp(const T& Compressed) {
|
||||
std::array<char, Biggest> C {};
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = nullptr;
|
||||
infstream.zfree = nullptr;
|
||||
infstream.opaque = nullptr;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
size_t TotalOut = infstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
std::string GetPlatformAgnosticErrorString();
|
||||
#define S_DSN SU_RAW
|
||||
|
||||
+1
-29
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Environment.h"
|
||||
@@ -27,17 +9,7 @@
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
char _getch();
|
||||
#endif // linux
|
||||
|
||||
#ifdef BEAMMP_FREEBSD
|
||||
#include <errno.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
char _getch();
|
||||
// macros 'major' and 'minor' need to be undefined on FreeBSD to avoid naming collision with system headers
|
||||
#undef major
|
||||
#undef minor
|
||||
#endif // freebsd
|
||||
#endif // unix
|
||||
|
||||
// ======================= APPLE ========================
|
||||
|
||||
|
||||
+1
-17
@@ -1,20 +1,4 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
// Copyright Anonymous275 8/11/2020
|
||||
|
||||
#pragma once
|
||||
#include <array>
|
||||
|
||||
+1
-17
@@ -1,20 +1,4 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
// Author: lionkor
|
||||
|
||||
/*
|
||||
* Asserts are to be used anywhere where assumptions about state are made
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <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);
|
||||
|
||||
}
|
||||
+2
-22
@@ -1,33 +1,13 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
|
||||
|
||||
// clang-format off
|
||||
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE) && !defined(BEAMMP_FREEBSD)
|
||||
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE)
|
||||
#if defined(_WIN32) || defined(__CYGWIN__)
|
||||
#define BEAMMP_WINDOWS
|
||||
#elif defined(__linux__) || defined(__linux) || defined(linux)
|
||||
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__unix__) || defined(__unix) || defined(unix)
|
||||
#define BEAMMP_LINUX
|
||||
#elif defined(__FreeBSD__)
|
||||
#define BEAMMP_FREEBSD
|
||||
#elif defined(__APPLE__) || defined(__MACH__)
|
||||
#define BEAMMP_APPLE
|
||||
#else
|
||||
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <fmt/core.h>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
/// The Error class represents an error or the absence of an
|
||||
/// error. It behaves like a bool, depending on context.
|
||||
///
|
||||
/// The idea is to use this class to pass around errors, together with
|
||||
/// [[nodiscard]], in order to make errors displayable for the users and
|
||||
/// to give errors some context. The only way to construct an error is to come
|
||||
/// up with an error message with this class, so this is an attempt to enforce
|
||||
/// this.
|
||||
///
|
||||
/// A default constructed Error means "no error" / "success", while
|
||||
/// the only available non-default constructor is one which takes any format.
|
||||
/// For example:
|
||||
///
|
||||
/// \code{.cpp}
|
||||
/// Error myfunc() {
|
||||
/// if (ok) {
|
||||
/// return {}; // no error
|
||||
/// } else {
|
||||
/// return Error("Something went wrong: {}", 42); // error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // ... handling:
|
||||
///
|
||||
/// Error err = myfunc();
|
||||
/// if (err) {
|
||||
/// // error occurred
|
||||
/// l::error("Error running myfunc: {}", err.error);
|
||||
/// } else {
|
||||
/// // ok
|
||||
/// }
|
||||
/// \endcode
|
||||
struct Error {
|
||||
/// Constructs a "non-error" / empty error, which is not considered
|
||||
/// to be an error. Use this as the "no error occurred" return value.
|
||||
Error() = default;
|
||||
/// Constructs an error with a message. Accepts fmt::format() arguments.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// \code{.cpp}
|
||||
/// // format with fmt (automatically), all arguments are forwarded to fmt::format
|
||||
/// return Error("failed to open '{}': {}", file, error);
|
||||
/// // or just as a constexpr string
|
||||
/// return Error("failed to open file");
|
||||
/// \endcode
|
||||
template<typename... Args>
|
||||
Error(fmt::format_string<Args...> s, Args&&... args)
|
||||
: is_error(true)
|
||||
, error(fmt::format(s, std::forward<Args>(args)...)) { }
|
||||
|
||||
/// Whether this error represents an error (true) or success (false).
|
||||
/// Use operator bool() instead of reading this if possible.
|
||||
bool is_error { false };
|
||||
/// The error message. Is a valid string even if is_error is false, but will
|
||||
/// be "Success".
|
||||
std::string error { "Success" };
|
||||
|
||||
/// Implicit conversion to boolean.
|
||||
/// True if this Error contains an error, false if not.
|
||||
operator bool() const { return is_error; }
|
||||
};
|
||||
|
||||
// TODO: Add docs
|
||||
|
||||
template<typename T>
|
||||
struct Result {
|
||||
/// Constructs an error-value result.
|
||||
/// Currently, you may have to force this by passing a second
|
||||
/// empty string argument.
|
||||
template<typename... Args>
|
||||
Result(fmt::format_string<Args...> s, Args&&... args)
|
||||
: is_error(true)
|
||||
, error(fmt::format(s, std::forward<Args>(args)...)) { }
|
||||
|
||||
/// Constructs a value-result via an explicit type.
|
||||
template<typename S>
|
||||
Result(S&& value)
|
||||
: result(std::move(value)) {
|
||||
}
|
||||
|
||||
/// Constructs a value-result via an explicit type.
|
||||
template<typename S>
|
||||
explicit Result(const S& value)
|
||||
: result(value) {
|
||||
}
|
||||
|
||||
/// Constructs a value-result via an implicit conversion.
|
||||
Result(T&& value)
|
||||
: result(std::move(value)) {
|
||||
}
|
||||
|
||||
/// Constructs a value-result via an implicit conversion.
|
||||
explicit Result(const T& value)
|
||||
: result(value) {
|
||||
}
|
||||
|
||||
/// Converts to bool in context. If it has an error, its considered "not a result",
|
||||
/// so it returns true only if a value is contained.
|
||||
operator bool() const { return !is_error; }
|
||||
|
||||
/// Accesses the value contained by moving it out.
|
||||
T&& move() { return std::move(result.value()); }
|
||||
/// Accesses the value contained by const reference.
|
||||
const T& value() const { return result.value(); }
|
||||
|
||||
/// Holds the optional result value. On error, is nullopt.
|
||||
std::optional<T> result;
|
||||
/// Whether this result holds an error.
|
||||
bool is_error { false };
|
||||
/// Error message.
|
||||
std::string error { "Success" };
|
||||
};
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/// @file
|
||||
/// This file holds the FileWatcher interface.
|
||||
|
||||
#include <boost/asio/deadline_timer.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_duration.hpp>
|
||||
#include <boost/signals2.hpp>
|
||||
#include <boost/system/detail/error_code.hpp>
|
||||
#include <boost/thread/scoped_thread.hpp>
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
/// The FileWatcher class watches a directory or a file for changes,
|
||||
/// and then notifies the caller through a signal.
|
||||
///
|
||||
/// This is a pretty convoluted implementation, and you may find it difficult
|
||||
/// to read. This is not intentional, but simplifying this would
|
||||
/// cost more time than to write this excuse.
|
||||
///
|
||||
/// It operates as follows:
|
||||
///
|
||||
/// A boost::asio::deadline_timer is waited on asynchronously.
|
||||
/// Once expired, this timer calls FileWatcher::on_tick.
|
||||
/// That function then loops through all registered files and directories,
|
||||
/// taking great care to follow symlinks, and tries to find a file which has changed.
|
||||
/// It determines this by storing the last known modification time.
|
||||
/// Once a file is found which has a new modification time, the FileWatcher::sig_file_changed
|
||||
/// signal is fired, and all connected slots must take care to handle the signal.
|
||||
class FileWatcher {
|
||||
public:
|
||||
/// Constructs the FileWatcher to watch the given files every few seconds, as
|
||||
/// specified by the seconds argument.
|
||||
FileWatcher(unsigned seconds);
|
||||
/// Stops the thread via m_shutdown.
|
||||
~FileWatcher();
|
||||
|
||||
/// Add a file to watch. If this file changes, FileWatcher::sig_file_changed is triggered
|
||||
/// with the path to the file.
|
||||
void watch_file(const std::filesystem::path& path);
|
||||
/// Add a directory to watch. If any file in the directory, or any subdirectories, change,
|
||||
/// FileWatcher::sig_file_changed is triggered.
|
||||
void watch_files_in(const std::filesystem::path& dir);
|
||||
|
||||
boost::signals2::signal<void(const std::filesystem::path&)> sig_file_changed {};
|
||||
|
||||
private:
|
||||
/// Entry point for the timer thread.
|
||||
void thread_main();
|
||||
|
||||
/// Called every time the timer runs out, watches for file changes, then starts
|
||||
/// a new timer.
|
||||
void on_tick(const boost::system::error_code&);
|
||||
|
||||
/// Checks files for changes, calls FileWatcher::sig_file_changed on change.
|
||||
void check_files();
|
||||
/// Checks directories for files which changed, calls FileWatcher::sig_file_changed on change.
|
||||
void check_directories();
|
||||
/// Checks a single file for change.
|
||||
void check_file(const std::filesystem::path& file);
|
||||
|
||||
/// Interval in seconds for the timer. Needed to be able to restart the timer over and over.
|
||||
boost::synchronized_value<boost::posix_time::seconds> m_seconds;
|
||||
/// If set, the thread handling the file watching will shut down. Set in the destructor.
|
||||
boost::synchronized_value<bool> m_shutdown { false };
|
||||
/// Io context handles the scheduling of timers on the thread.
|
||||
boost::asio::io_context m_io {};
|
||||
/// Holds all files that are to be checked.
|
||||
///
|
||||
/// It uses a boost::hash<> because in the original C++17
|
||||
/// standard, std::hash of a filesystem path was not defined, and as such
|
||||
/// some implementations still don't have it.
|
||||
/// See https://cplusplus.github.io/LWG/issue3657
|
||||
boost::synchronized_value<std::unordered_set<std::filesystem::path, boost::hash<std::filesystem::path>>> m_files {};
|
||||
/// Holds all the directories that are to be searched for files to be checked.
|
||||
///
|
||||
/// See FileWatcher::m_files for an explanation for the boost::hash.
|
||||
boost::synchronized_value<std::unordered_set<std::filesystem::path, boost::hash<std::filesystem::path>>> m_dirs {};
|
||||
/// Holds the last known modification times of all found files.
|
||||
std::unordered_map<std::filesystem::path, std::filesystem::file_time_type, boost::hash<std::filesystem::path>> m_file_mod_times {};
|
||||
/// Timer used to time the checks. Restarted every FileWatcher::m_seconds seconds.
|
||||
boost::synchronized_value<boost::asio::deadline_timer> m_timer;
|
||||
/// Work guard helps the io_context "sleep" while there is no work to be done - must be reset in the
|
||||
/// destructor in order to not cause work to be thrown away (though in this case we probably don't care).
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> m_work_guard = boost::asio::make_work_guard(m_io);
|
||||
/// Thread on which all watching and timing work runs.
|
||||
boost::scoped_thread<> m_thread;
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/// @file
|
||||
/// HashMap holds hash map implementations and typedefs.
|
||||
///
|
||||
/// The idea is that we can easily swap out the implementation
|
||||
/// in case there is a performance or memory usage concern.
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
|
||||
/// A hash map to be used for any kind of small number of key-value pairs.
|
||||
/// Iterators and pointers may be invalidated on modification.
|
||||
template<typename K, typename V>
|
||||
using HashMap = boost::container::flat_map<K, V>;
|
||||
|
||||
/// A synchronized hash map is a hash map in which each
|
||||
/// access is thread-safe. In this case, this is achieved by locking
|
||||
/// each access with a mutex (which often ends up being a futex in the implementation).
|
||||
template<typename K, typename V>
|
||||
using SynchronizedHashMap = boost::synchronized_value<boost::container::flat_map<K, V>>;
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Common.h>
|
||||
|
||||
+5
-22
@@ -1,24 +1,5 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <boost/thread/scoped_thread.hpp>
|
||||
#include <thread>
|
||||
|
||||
// pure virtual class to be inherited from by classes which intend to be threaded
|
||||
@@ -28,14 +9,16 @@ public:
|
||||
// invokes operator() on this object
|
||||
: mThread() { }
|
||||
virtual ~IThreaded() noexcept {
|
||||
mThread.interrupt();
|
||||
if (mThread.joinable()) {
|
||||
mThread.join();
|
||||
}
|
||||
}
|
||||
|
||||
virtual void Start() final {
|
||||
mThread = boost::scoped_thread<>([this] { (*this)(); });
|
||||
mThread = std::thread([this] { (*this)(); });
|
||||
}
|
||||
virtual void operator()() = 0;
|
||||
|
||||
protected:
|
||||
boost::scoped_thread<> mThread {};
|
||||
std::thread mThread;
|
||||
};
|
||||
|
||||
+1
-15
@@ -1,20 +1,6 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
// Created by anon on 4/21/21.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
|
||||
+10
-33
@@ -1,50 +1,29 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <sol/sol.hpp>
|
||||
#include <string>
|
||||
#include "TLuaEngine.h"
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
namespace LuaAPI {
|
||||
int PanicHandler(lua_State* State);
|
||||
std::string LuaToString(const sol::object Value, size_t Indent = 1, bool QuoteStrings = false);
|
||||
void Print(sol::variadic_args);
|
||||
namespace MP {
|
||||
extern TLuaEngine* Engine;
|
||||
|
||||
std::string GetOSName();
|
||||
std::tuple<int, int, int> GetServerVersion();
|
||||
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||
size_t GetPlayerCount();
|
||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
|
||||
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
|
||||
void Set(int ConfigID, sol::object NewValue);
|
||||
bool IsPlayerGuest(int ID);
|
||||
bool IsPlayerConnected(int ID);
|
||||
/// Returns the current time in millisecond accuracy.
|
||||
size_t GetTimeMS();
|
||||
/// Returns the current time in seconds, with millisecond accuracy (w/ decimal point).
|
||||
double GetTimeS();
|
||||
}
|
||||
|
||||
namespace Util {
|
||||
std::string JsonEncode(const sol::object& object);
|
||||
sol::table JsonDecode(sol::this_state s, const std::string& string);
|
||||
void Sleep(size_t Ms);
|
||||
void PrintRaw(sol::variadic_args);
|
||||
std::string JsonEncode(const sol::table& object);
|
||||
std::string JsonDiff(const std::string& a, const std::string& b);
|
||||
std::string JsonDiffApply(const std::string& data, const std::string& patch);
|
||||
std::string JsonPrettify(const std::string& json);
|
||||
@@ -65,7 +44,5 @@ namespace FS {
|
||||
bool IsDirectory(const std::string& Path);
|
||||
bool IsFile(const std::string& Path);
|
||||
std::string ConcatPaths(sol::variadic_args Args);
|
||||
sol::table ListFiles(sol::this_state s, const std::string& path);
|
||||
sol::table ListDirectories(sol::this_state s, const std::string& path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "FileWatcher.h"
|
||||
#include "HashMap.h"
|
||||
#include "Plugin.h"
|
||||
#include <boost/asio/deadline_timer.hpp>
|
||||
#include <boost/asio/io_service.hpp>
|
||||
#include <boost/asio/post.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_duration.hpp>
|
||||
#include <boost/signals2.hpp>
|
||||
#include <boost/thread/scoped_thread.hpp>
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <sol/forward.hpp>
|
||||
#include <sol/variadic_args.hpp>
|
||||
#include <spdlog/logger.h>
|
||||
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
struct Timer {
|
||||
Timer(boost::asio::deadline_timer&& timer_, long interval_)
|
||||
: timer(std::move(timer_))
|
||||
, interval(interval_) { }
|
||||
boost::asio::deadline_timer timer;
|
||||
boost::posix_time::milliseconds interval;
|
||||
};
|
||||
|
||||
static constexpr const char* BEAMMP_MEMORY_STATE = ":console:";
|
||||
|
||||
class LuaPlugin : public Plugin {
|
||||
public:
|
||||
/// Declare a new plugin with the path.
|
||||
/// Loading of any files only happens on LuaPlugin::initialize().
|
||||
LuaPlugin(const std::string& path);
|
||||
/// Shuts down lua thread, may hang if there is still work to be done.
|
||||
~LuaPlugin();
|
||||
|
||||
template <typename FnT>
|
||||
void register_function(const std::string& table, const std::string& identifier, const FnT& func) {
|
||||
boost::asio::post(m_io, [this, table, identifier, func] {
|
||||
if (!m_state.globals()[table].valid()) {
|
||||
m_state.globals().create_named(table);
|
||||
}
|
||||
if (m_state.globals()[table][identifier].valid()) {
|
||||
beammp_errorf("Global '{}.{}' already exists and could not be injected as function.", table, identifier);
|
||||
} else {
|
||||
m_state.globals()[table][identifier] = func;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Dangerous: Only use this on a special memory state.
|
||||
/// Results are *printed to stdout*.
|
||||
void run_raw_lua(const std::string& raw);
|
||||
|
||||
private:
|
||||
/// Initializes the error handlers for panic and exceptions.
|
||||
Error initialize_error_handlers();
|
||||
/// Initializes / loads base packages and libraries.
|
||||
Error initialize_libraries();
|
||||
/// Loads main file of the plugin.
|
||||
Error load_files();
|
||||
/// Overrides functions such as `print()`
|
||||
Error initialize_overrides();
|
||||
/// Fixes lua's package.path and package.cpath to understand our own file structure better.
|
||||
Error fix_lua_paths();
|
||||
|
||||
/// Loads an extension. Call this from the lua thread.
|
||||
/// This function cannot fail, as it reports errors to the user.
|
||||
void load_extension(const std::filesystem::path& file, const std::string& ext_name);
|
||||
/// Loads all extension from the folder, using the base as a prefix.
|
||||
/// This function is recursive.
|
||||
/// Returns the amount of extensions found. This function cannot fail.
|
||||
size_t load_extensions(const std::filesystem::path& extensions_folder, const std::string& base = "");
|
||||
|
||||
/// Entry point for the lua plugin's thread.
|
||||
void thread_main();
|
||||
|
||||
// Plugin interface
|
||||
public:
|
||||
/// Initializes the Lua Plugin, loads file(s), starts executing code.
|
||||
virtual Error initialize() override;
|
||||
// TODO cleanup
|
||||
virtual Error cleanup() override;
|
||||
// TODO reload
|
||||
virtual Error reload() override;
|
||||
/// Name of this lua plugin (the base name of the folder).
|
||||
virtual std::string name() const override;
|
||||
/// Path to the folder containing this lua plugin.
|
||||
virtual std::filesystem::path path() const override;
|
||||
/// Dispatches the event to the thread which runs all lua.
|
||||
virtual std::shared_future<std::vector<Value>> handle_event(const std::string& event_name, const std::shared_ptr<Value>& args) override;
|
||||
/// Returns the memory usage of this thread, updated at the slowest every 5 seconds.
|
||||
virtual size_t memory_usage() const override;
|
||||
|
||||
private:
|
||||
/// Path to the plugin's root folder.
|
||||
std::filesystem::path m_path;
|
||||
/// Thread where all lua work must happen. Started within the constructor but is blocked until LuaPlugin::initialize is called
|
||||
boost::scoped_thread<> m_thread;
|
||||
/// This asio context schedules all tasks. It's run in the m_thread thread.
|
||||
boost::asio::io_context m_io;
|
||||
|
||||
/// Event handlers which are legacy-style (by name)
|
||||
HashMap<std::string, std::vector<std::string>> m_event_handlers_named {};
|
||||
/// Event handlers which are functions (v4 style)
|
||||
HashMap<std::string, std::vector<sol::protected_function>> m_event_handlers {};
|
||||
|
||||
/// Main (and usually only) lua state of this plugin.
|
||||
/// ONLY access this from the m_thread thread.
|
||||
sol::state m_state;
|
||||
/// Whether the lua thread should shutdown. Triggered by the LuaPlugin::~LuaPlugin dtor.
|
||||
boost::synchronized_value<bool> m_shutdown { false };
|
||||
/// Current memory usage. Cached to avoid having to synchronize access to the lua state.
|
||||
boost::synchronized_value<size_t> m_memory { 0 };
|
||||
/// Hash map of all event handlers in this state.
|
||||
// HashMap<std::string, sol::protected_function> m_event_handlers {};
|
||||
SynchronizedHashMap<std::string, std::filesystem::path> m_known_extensions {};
|
||||
|
||||
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> m_work_guard = boost::asio::make_work_guard(m_io);
|
||||
|
||||
/// Iteration options to be used whenever iterating over a directory in this class.
|
||||
static inline auto s_directory_iteration_options = std::filesystem::directory_options::follow_directory_symlink | std::filesystem::directory_options::skip_permission_denied;
|
||||
|
||||
FileWatcher m_extensions_watcher { 2 };
|
||||
|
||||
boost::signals2::connection m_extensions_watch_conn;
|
||||
|
||||
std::vector<std::shared_ptr<Timer>> m_timers {};
|
||||
|
||||
std::shared_ptr<Timer> make_timer(size_t ms);
|
||||
void cancel_timer(const std::shared_ptr<Timer>& timer);
|
||||
|
||||
// Lua API
|
||||
/// Override for lua's base.print().
|
||||
/// Dumps tables, arrays, etc. properly.
|
||||
void l_print(const sol::variadic_args&);
|
||||
|
||||
std::shared_ptr<Timer> l_mp_schedule_call_repeat(size_t ms, const sol::function& fn, sol::variadic_args args);
|
||||
void l_mp_schedule_call_helper(const boost::system::error_code& err, std::shared_ptr<Timer> timer, const sol::function& fn, std::shared_ptr<ValueTuple> args);
|
||||
void l_mp_schedule_call_once(size_t ms, const sol::function& fn, sol::variadic_args args);
|
||||
|
||||
std::string print_impl(const std::vector<sol::object>&);
|
||||
};
|
||||
@@ -1,250 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "Packet.h"
|
||||
#include "State.h"
|
||||
#include "Sync.h"
|
||||
#include "Transport.h"
|
||||
#include "Util.h"
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/asio/execution_context.hpp>
|
||||
#include <boost/asio/thread_pool.hpp>
|
||||
#include <boost/thread/scoped_thread.hpp>
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <glm/detail/qualifier.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
using ClientID = uint32_t;
|
||||
using VehicleID = uint16_t;
|
||||
|
||||
using namespace boost::asio;
|
||||
|
||||
struct Client : std::enable_shared_from_this<Client> {
|
||||
using StrandPtr = std::shared_ptr<boost::asio::strand<ip::tcp::socket::executor_type>>;
|
||||
using Ptr = std::shared_ptr<Client>;
|
||||
|
||||
ClientID id;
|
||||
Sync<bmp::State> state { bmp::State::None };
|
||||
|
||||
Sync<std::string> name;
|
||||
Sync<std::string> role;
|
||||
Sync<bool> is_guest;
|
||||
Sync<std::unordered_map<std::string /* identifier */, std::string /* value */>> identifiers;
|
||||
/// Writes the packet to the TCP stream. Blocks all other writes.
|
||||
void tcp_write(bmp::Packet& packet);
|
||||
/// Writes the specified to the TCP stream without a header or any metadata - use in
|
||||
/// conjunction with something else. Blocks other writes.
|
||||
void tcp_write_file_raw(const std::filesystem::path& path);
|
||||
|
||||
/// Ensures no client is ever created as a non-shared-ptr, so that enable_shared_from_this works.
|
||||
static Client::Ptr make_ptr(ClientID new_id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||
~Client();
|
||||
|
||||
ip::tcp::socket& tcp_socket() { return m_tcp_socket; }
|
||||
|
||||
void start_tcp();
|
||||
|
||||
/// Used to associate the udp socket with this client.
|
||||
/// This isn't very secure and still allows spoofing of the UDP connection (technically),
|
||||
/// but better than simply using the ID like the old protocol.
|
||||
const uint64_t udp_magic;
|
||||
|
||||
const ip::udp::endpoint& udp_endpoint() const { return m_udp_endpoint; }
|
||||
void set_udp_endpoint(const ip::udp::endpoint& ep) { m_udp_endpoint = ep; }
|
||||
|
||||
private:
|
||||
/// Ctor must be private to ensure all clients are constructed as shared_ptr to enable_shared_from_this.
|
||||
Client(ClientID id, class Network& network, ip::tcp::socket&& tcp_socket);
|
||||
/// Call this when the client seems to have timed out. Will send a ping and set a flag.
|
||||
/// Returns true if try-again, false if the connection was closed.
|
||||
[[nodiscard]] bool handle_timeout();
|
||||
bool m_timed_out { false };
|
||||
|
||||
/// Timeout used for typical tcp reads.
|
||||
boost::posix_time::milliseconds m_read_timeout { 5000 };
|
||||
/// Timeout used for typical tcp writes. Specified in milliseconds per byte.
|
||||
/// For example, 10 mbit/s works out to 1250 B/ms, so a value of 1250 here would
|
||||
/// cause clients with >10 mbit/s download speed to usually not time out.
|
||||
/// This is done because a write is considered completed when all data is written,
|
||||
/// and worst-case this could mean that we're limited by their download speed.
|
||||
/// We're setting it to 50, which will drop clients who are below a download speed + ping
|
||||
/// combination of 0.4 mbit/s.
|
||||
double m_write_byte_timeout { 0.01 };
|
||||
/// Timeout used for mod download tcp writes.
|
||||
/// This is typically orders of magnitude larger
|
||||
/// to allow for slow downloads.
|
||||
boost::posix_time::milliseconds m_download_write_timeout { 60000 };
|
||||
|
||||
std::mutex m_tcp_read_mtx;
|
||||
std::mutex m_tcp_write_mtx;
|
||||
std::mutex m_udp_read_mtx;
|
||||
|
||||
ip::tcp::socket m_tcp_socket;
|
||||
|
||||
boost::scoped_thread<> m_tcp_thread;
|
||||
|
||||
std::vector<uint8_t> m_header { bmp::Header::SERIALIZED_SIZE };
|
||||
bmp::Packet m_packet {};
|
||||
|
||||
ip::udp::endpoint m_udp_endpoint;
|
||||
|
||||
class Network& m_network;
|
||||
|
||||
StrandPtr m_tcp_strand;
|
||||
};
|
||||
|
||||
struct Vehicle {
|
||||
using Ptr = std::shared_ptr<Vehicle>;
|
||||
Sync<ClientID> owner;
|
||||
Sync<std::vector<uint8_t>> data;
|
||||
|
||||
Vehicle(std::span<uint8_t> raw_data)
|
||||
: data(std::vector<uint8_t>(raw_data.begin(), raw_data.end())) {
|
||||
reset_status(data.get());
|
||||
}
|
||||
|
||||
/// Resets all status fields to zero and reads any statuses present in the data into the fields.
|
||||
void reset_status(std::span<const uint8_t> status_data);
|
||||
|
||||
struct Status {
|
||||
glm::vec3 rvel {};
|
||||
glm::vec4 rot {};
|
||||
glm::vec3 vel {};
|
||||
glm::vec3 pos {};
|
||||
float time {};
|
||||
};
|
||||
|
||||
Status get_status();
|
||||
|
||||
void update_status(std::span<const uint8_t> raw_packet);
|
||||
|
||||
const std::vector<uint8_t>& get_raw_status() const { return m_status_data; }
|
||||
|
||||
private:
|
||||
std::recursive_mutex m_mtx;
|
||||
|
||||
/// Holds pos, rvel, vel, etc. raw, updated every time
|
||||
/// such a packet arrives.
|
||||
std::vector<uint8_t> m_status_data;
|
||||
|
||||
/// Parses the status_data on request sets needs_refresh = false.
|
||||
void refresh_cache(std::unique_lock<std::recursive_mutex>& lock);
|
||||
|
||||
bool m_needs_refresh = false;
|
||||
glm::vec3 m_rvel {};
|
||||
glm::vec4 m_rot {};
|
||||
glm::vec3 m_vel {};
|
||||
glm::vec3 m_pos {};
|
||||
float m_time {};
|
||||
};
|
||||
|
||||
class Network {
|
||||
public:
|
||||
Network();
|
||||
~Network();
|
||||
|
||||
friend Client;
|
||||
|
||||
void disconnect(ClientID id, const std::string& msg);
|
||||
|
||||
void send_to(ClientID id, bmp::Packet& packet);
|
||||
|
||||
/// Returns a map of <id, client> containing only clients which are
|
||||
/// fully connected, i.e. who have mods downloaded and everything spawned in.
|
||||
/// If you're unsure which to use, use this one.
|
||||
std::unordered_map<ClientID, Client::Ptr> playing_clients() const;
|
||||
/// Returns a map of <id, client> containing only clients who are authenticated.
|
||||
std::unordered_map<ClientID, Client::Ptr> authenticated_clients() const;
|
||||
/// Returns all clients, including non-authenticated clients. Use only for debugging,
|
||||
/// information, stats, status.
|
||||
std::unordered_map<ClientID, Client::Ptr> all_clients() const;
|
||||
|
||||
std::optional<Client::Ptr> get_client(ClientID id, bmp::State min_state) const;
|
||||
|
||||
std::unordered_map<VehicleID, Vehicle::Ptr> get_vehicles_owned_by(ClientID id);
|
||||
|
||||
std::optional<Vehicle::Ptr> get_vehicle(VehicleID id);
|
||||
|
||||
/// Builds the SessionSetup.PlayersInfo json which contains all player info and all vehicles.
|
||||
nlohmann::json build_players_info();
|
||||
|
||||
size_t authenticated_client_count() const;
|
||||
|
||||
size_t clients_in_state_count(bmp::State state) const;
|
||||
|
||||
size_t guest_count() const;
|
||||
|
||||
size_t vehicle_count() const;
|
||||
|
||||
/// Creates a Playing state packet from uncompressed data.
|
||||
bmp::Packet make_playing_packet(bmp::Purpose purpose, ClientID from_id, VehicleID veh_id, const std::vector<uint8_t>& data);
|
||||
|
||||
/// Sends a <System> or <Server> chat message to all or only one client(s).
|
||||
void send_system_chat_message(const std::string& msg, ClientID to = 0xffffffff);
|
||||
|
||||
/// To be called by accept() async handler once an accept() is completed.
|
||||
void accept();
|
||||
|
||||
/// Gets the async i/o context of the network - can be used to "schedule" tasks on it.
|
||||
boost::asio::thread_pool& context() {
|
||||
return m_threadpool;
|
||||
}
|
||||
|
||||
private:
|
||||
void handle_packet(ClientID id, const bmp::Packet& packet);
|
||||
|
||||
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
|
||||
bmp::Packet udp_read(ip::udp::endpoint& out_ep);
|
||||
/// Sends a packet to the specified UDP endpoint via the UDP socket.
|
||||
void udp_write(bmp::Packet& packet, const ip::udp::endpoint& ep);
|
||||
|
||||
void udp_read_main();
|
||||
void tcp_listen_main();
|
||||
|
||||
/// Handles all packets which are allowed during the Identification state.
|
||||
void handle_identification(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||
/// Handles all packets which are allowed during the Authentication state.
|
||||
void handle_authentication(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||
/// Handles all packets which are allowed during the ModDownload state.
|
||||
void handle_mod_download(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||
/// Handles all packets which are allowed during the SessionSetup state.
|
||||
void handle_session_setup(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||
/// Handles all packets which are allowed during the Playing state.
|
||||
void handle_playing(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
|
||||
|
||||
/// On failure, throws an exception with the error for the client.
|
||||
static void authenticate_user(const std::string& public_key, std::shared_ptr<Client>& client);
|
||||
|
||||
/// Called by accept() once completed (completion handler).
|
||||
void handle_accept(const boost::system::error_code& ec);
|
||||
|
||||
Sync<std::unordered_map<ClientID, Client::Ptr>> m_clients {};
|
||||
Sync<std::unordered_map<VehicleID, Vehicle::Ptr>> m_vehicles {};
|
||||
Sync<std::unordered_map<uint64_t, ClientID>> m_client_magics {};
|
||||
Sync<std::unordered_map<ip::udp::endpoint, ClientID>> m_udp_endpoints {};
|
||||
|
||||
ClientID new_client_id();
|
||||
VehicleID new_vehicle_id();
|
||||
|
||||
thread_pool m_threadpool { std::thread::hardware_concurrency() };
|
||||
Sync<bool> m_shutdown { false };
|
||||
|
||||
ip::udp::socket m_udp_socket { m_threadpool };
|
||||
|
||||
ip::tcp::socket m_tcp_listener { m_threadpool };
|
||||
ip::tcp::acceptor m_tcp_acceptor { m_threadpool };
|
||||
/// This socket gets accepted into, and is then moved.
|
||||
ip::tcp::socket m_temp_socket { m_threadpool };
|
||||
|
||||
boost::scoped_thread<> m_tcp_listen_thread;
|
||||
boost::scoped_thread<> m_udp_read_thread;
|
||||
};
|
||||
@@ -1,68 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "Error.h"
|
||||
#include "Value.h"
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
/// The Plugin class is an abstract interface for any plugin.
|
||||
///
|
||||
/// A plugin must itself figure out how to deal with events, load itself,
|
||||
/// and must react quickly and appropriately to any incoming events or function calls.
|
||||
/// A plugin may *not* ever block a calling thread unless explicitly marked with
|
||||
/// "this may block the caller" or similar.
|
||||
class Plugin {
|
||||
public:
|
||||
/// Self-managing pointer type of this plugin.
|
||||
using Pointer = std::shared_ptr<Plugin>;
|
||||
/// Allocates a Plugin of the specific derived plugin type.
|
||||
template <typename T, typename... Args>
|
||||
static Pointer make_pointer(Args&&... args) {
|
||||
return std::shared_ptr<Plugin>(new T(std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
/// Default constructor to enable derived classes to default-construct.
|
||||
Plugin() = default;
|
||||
|
||||
/// Plugin is not copyable.
|
||||
Plugin(const Plugin&) = delete;
|
||||
/// Plugin is not copyable.
|
||||
Plugin& operator=(const Plugin&) = delete;
|
||||
/// Plugin is movable.
|
||||
Plugin(Plugin&&) = default;
|
||||
/// Plugin is movable.
|
||||
Plugin& operator=(Plugin&&) = default;
|
||||
|
||||
/// Default destructor but virtual, to make the compiler happy.
|
||||
virtual ~Plugin() = default;
|
||||
|
||||
/// Called when the plugin should initialize its state.
|
||||
/// This may block the caller.
|
||||
virtual Error initialize() = 0;
|
||||
/// Called when the plugin should tear down and clean up its state.
|
||||
/// This may block the caller.
|
||||
virtual Error cleanup() = 0;
|
||||
/// Called when the plugin should be reloaded. Usually it's a good idea
|
||||
/// to notify the plugin's code, call cleanup(), etc. internally.
|
||||
virtual Error reload() = 0;
|
||||
|
||||
/// Returns the name of the plugin.
|
||||
virtual std::string name() const = 0;
|
||||
/// Returns the path to the plugin - this can either be the folder in which
|
||||
/// the plugin's files live, or the plugin itself if it's a single file.
|
||||
/// The exact format of what this returns (directory/file) is implementation defined.
|
||||
virtual std::filesystem::path path() const = 0;
|
||||
|
||||
/// Instructs the plugin to handle the given event, with the given arguments.
|
||||
/// Returns a future with a result if this event will be handled by the plugin, otherwise must return
|
||||
/// std::nullopt.
|
||||
virtual std::shared_future<std::vector<Value>> handle_event(const std::string& event_name, const std::shared_ptr<Value>& args) = 0;
|
||||
|
||||
/// Returns how much memory this state thinks it uses.
|
||||
///
|
||||
/// This value is difficult to calculate for some use-cases, but a rough ballpark
|
||||
/// should be returned regardless.
|
||||
virtual size_t memory_usage() const = 0;
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "HashMap.h"
|
||||
#include "Plugin.h"
|
||||
|
||||
/// The PluginManager class manages all plugins, specifically their lifetime,
|
||||
/// events and memory.
|
||||
class PluginManager {
|
||||
public:
|
||||
/// Iterates through all plugins, ask them for their usage, take the sum.
|
||||
size_t memory_usage() const {
|
||||
size_t total = 0;
|
||||
auto plugins = m_plugins.synchronize();
|
||||
for (const auto& [name, plugin] : *plugins) {
|
||||
(void)name; // name ignored
|
||||
total += plugin->memory_usage();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/// Triggers (sends) the event to all plugins and gathers the results as futures.
|
||||
///
|
||||
/// PLEASE be aware that some plugins' handlers may take a while to handle the event,
|
||||
/// so try not to wait on these futures without a timeout.
|
||||
///
|
||||
/// This function should not block.
|
||||
std::vector<std::shared_future<std::vector<Value>>> trigger_event(const std::string& event_name, const std::shared_ptr<Value>& args) {
|
||||
// results will go in here
|
||||
std::vector<std::shared_future<std::vector<Value>>> results;
|
||||
// synchronize practically grabs a lock to the mutex, this is (as the name suggests)
|
||||
// a synchronization point. technically, it could dead-lock if something that is called
|
||||
// in this locked context tries to lock the m_plugins mutex.
|
||||
// Plugin::handle_event should NEVER do much else than dispatch the event to the
|
||||
// plugin's main thread, so this really cannot happen.
|
||||
// that said, if you end up here with gdb, make sure it doesn't ;)
|
||||
auto plugins = m_plugins.synchronize();
|
||||
// allocate as many as we could possibly have, to avoid realloc()'s
|
||||
results.reserve(plugins->size());
|
||||
for (const auto& [name, plugin] : *plugins) {
|
||||
(void)name; // ignore the name
|
||||
// propagates the event to the plugin, this returns a future
|
||||
// we assume that at this point no plugin-specific code has executed
|
||||
auto result = plugin->handle_event(event_name, args);
|
||||
// if the plugin had no handler, this result has no value, and we can ignore it
|
||||
results.push_back(std::move(result));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/// Adds the plugin, calls Plugin::initialize(), and so on
|
||||
[[nodiscard]] Error add_plugin(Plugin::Pointer plugin) {
|
||||
auto plugins = m_plugins.synchronize();
|
||||
if (plugins->contains(plugin->name())) {
|
||||
return Error("Plugin with the name '{}' already exists, refusing to replace it.", plugin->name());
|
||||
} else {
|
||||
auto [iter, b] = plugins->insert({ plugin->name(), std::move(plugin) });
|
||||
(void)b; // ignore b
|
||||
auto err = iter->second->initialize();
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
HashMap<std::string, Plugin::Pointer> get_plugins() {
|
||||
return *m_plugins;
|
||||
}
|
||||
|
||||
private:
|
||||
/// All plugins as pointers to allow inheritance.
|
||||
SynchronizedHashMap<std::string, Plugin::Pointer> m_plugins;
|
||||
};
|
||||
+1
-18
@@ -1,21 +1,4 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
// Author: lionkor
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
void SetupSignalHandlers();
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <mutex>
|
||||
|
||||
/// This header provides convenience aliases for synchronization primitives.
|
||||
|
||||
template<typename T>
|
||||
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
||||
|
||||
+3
-22
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
@@ -40,12 +22,11 @@ private:
|
||||
void CreateConfigFile();
|
||||
void ParseFromFile(std::string_view name);
|
||||
void PrintDebug();
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue);
|
||||
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue);
|
||||
|
||||
void ParseOldFormat();
|
||||
std::string TagsAsPrettyArray() const;
|
||||
bool IsDefault();
|
||||
bool mFailed { false };
|
||||
std::string mConfigFileName;
|
||||
|
||||
+7
-28
@@ -1,26 +1,6 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Cryptography.h"
|
||||
#include "LuaPlugin.h"
|
||||
#include "TScopedTimer.h"
|
||||
#include "commandline.h"
|
||||
#include <atomic>
|
||||
#include <fstream>
|
||||
@@ -31,19 +11,18 @@
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
class TLuaEngine;
|
||||
|
||||
class TConsole {
|
||||
public:
|
||||
TConsole();
|
||||
|
||||
// Initializes the commandline app to take over I/O
|
||||
void InitializeCommandline();
|
||||
|
||||
void Write(const std::string& str);
|
||||
void WriteRaw(const std::string& str);
|
||||
// void InitializeLuaConsole(TLuaEngine& Engine);
|
||||
void InitializeLuaConsole(TLuaEngine& Engine);
|
||||
void BackupOldLog();
|
||||
void StartLoggingToFile();
|
||||
Commandline& Internal() { return *mCommandline; }
|
||||
Commandline& Internal() { return mCommandline; }
|
||||
|
||||
private:
|
||||
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
|
||||
@@ -77,14 +56,14 @@ private:
|
||||
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
|
||||
};
|
||||
|
||||
std::unique_ptr<Commandline> mCommandline { nullptr };
|
||||
Commandline mCommandline;
|
||||
std::vector<std::string> mCachedLuaHistory;
|
||||
std::vector<std::string> mCachedRegularHistory;
|
||||
TLuaEngine* mLuaEngine { nullptr };
|
||||
bool mIsLuaConsole { false };
|
||||
bool mFirstTime { true };
|
||||
std::string mStateId;
|
||||
const std::string mDefaultStateId = BEAMMP_MEMORY_STATE;
|
||||
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
|
||||
std::ofstream mLogFileStream;
|
||||
std::mutex mLogFileStreamMtx;
|
||||
TScopedTimer mUptimeTimer{};
|
||||
};
|
||||
|
||||
@@ -1,30 +1,13 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "IThreaded.h"
|
||||
#include "Network.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
|
||||
class THeartbeatThread : public IThreaded {
|
||||
public:
|
||||
THeartbeatThread(std::shared_ptr<Network> network);
|
||||
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server);
|
||||
//~THeartbeatThread();
|
||||
void operator()() override;
|
||||
|
||||
@@ -32,5 +15,6 @@ private:
|
||||
std::string GenerateCall();
|
||||
std::string GetPlayers();
|
||||
|
||||
std::shared_ptr<Network> m_network;
|
||||
TResourceManager& mResourceManager;
|
||||
TServer& mServer;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
#pragma once
|
||||
|
||||
#include "TNetwork.h"
|
||||
#include "TServer.h"
|
||||
#include <any>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <initializer_list>
|
||||
#include <list>
|
||||
#include <lua.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <toml.hpp>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#define SOL_ALL_SAFETIES_ON 1
|
||||
#define SOL_USER_C_ASSERT SOL_ON
|
||||
#define SOL_C_ASSERT(...) \
|
||||
beammp_lua_errorf("SOL2 assertion failure: Assertion `{}` failed in {}:{}. This *should* be a fatal error, but BeamMP Server overrides it to not be fatal. This may cause the Lua Engine to crash, or cause other issues.", #__VA_ARGS__, __FILE__, __LINE__)
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
using TLuaStateId = std::string;
|
||||
namespace fs = std::filesystem;
|
||||
/**
|
||||
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
|
||||
*/
|
||||
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
|
||||
static constexpr size_t TLuaArgTypes_String = 0;
|
||||
static constexpr size_t TLuaArgTypes_Int = 1;
|
||||
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
|
||||
static constexpr size_t TLuaArgTypes_Bool = 3;
|
||||
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
|
||||
|
||||
class TLuaPlugin;
|
||||
|
||||
struct TLuaResult {
|
||||
bool Ready;
|
||||
bool Error;
|
||||
std::string ErrorMessage;
|
||||
sol::object Result { sol::lua_nil };
|
||||
TLuaStateId StateId;
|
||||
std::string Function;
|
||||
std::shared_ptr<std::mutex> ReadyMutex {
|
||||
std::make_shared<std::mutex>()
|
||||
};
|
||||
std::shared_ptr<std::condition_variable> ReadyCondition {
|
||||
std::make_shared<std::condition_variable>()
|
||||
};
|
||||
|
||||
void MarkAsReady();
|
||||
void WaitUntilReady();
|
||||
};
|
||||
|
||||
struct TLuaPluginConfig {
|
||||
static inline const std::string FileName = "PluginConfig.toml";
|
||||
TLuaStateId StateId;
|
||||
// TODO: Add execute list
|
||||
// TODO: Build a better toml serializer, or some way to do this in an easier way
|
||||
};
|
||||
|
||||
struct TLuaChunk {
|
||||
TLuaChunk(std::shared_ptr<std::string> Content,
|
||||
std::string FileName,
|
||||
std::string PluginPath);
|
||||
std::shared_ptr<std::string> Content;
|
||||
std::string FileName;
|
||||
std::string PluginPath;
|
||||
};
|
||||
|
||||
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
|
||||
public:
|
||||
enum CallStrategy : int {
|
||||
BestEffort,
|
||||
Precise,
|
||||
};
|
||||
|
||||
struct QueuedFunction {
|
||||
std::string FunctionName;
|
||||
std::shared_ptr<TLuaResult> Result;
|
||||
std::vector<TLuaArgTypes> Args;
|
||||
std::string EventName; // optional, may be empty
|
||||
};
|
||||
|
||||
TLuaEngine();
|
||||
virtual ~TLuaEngine() noexcept {
|
||||
beammp_debug("Lua Engine terminated");
|
||||
}
|
||||
|
||||
void operator()() override;
|
||||
|
||||
TNetwork& Network() { return *mNetwork; }
|
||||
TServer& Server() { return *mServer; }
|
||||
|
||||
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
|
||||
void SetServer(TServer* Server) { mServer = Server; }
|
||||
|
||||
size_t GetResultsToCheckSize() {
|
||||
std::unique_lock Lock(mResultsToCheckMutex);
|
||||
return mResultsToCheck.size();
|
||||
}
|
||||
|
||||
size_t GetLuaStateCount() {
|
||||
std::unique_lock Lock(mLuaStatesMutex);
|
||||
return mLuaStates.size();
|
||||
}
|
||||
std::vector<std::string> GetLuaStateNames() {
|
||||
std::vector<std::string> names {};
|
||||
for (auto const& [stateId, _] : mLuaStates) {
|
||||
names.push_back(stateId);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
size_t GetTimedEventsCount() {
|
||||
std::unique_lock Lock(mTimedEventsMutex);
|
||||
return mTimedEvents.size();
|
||||
}
|
||||
size_t GetRegisteredEventHandlerCount() {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
size_t LuaEventsCount = 0;
|
||||
for (const auto& State : mLuaEvents) {
|
||||
for (const auto& Events : State.second) {
|
||||
LuaEventsCount += Events.second.size();
|
||||
}
|
||||
}
|
||||
return LuaEventsCount - GetLuaStateCount();
|
||||
}
|
||||
|
||||
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
|
||||
const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
|
||||
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
|
||||
bool HasState(TLuaStateId StateId);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
|
||||
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
|
||||
/**
|
||||
*
|
||||
* @tparam ArgsT Template Arguments for the event (Metadata) todo: figure out what this means
|
||||
* @param EventName Name of the event
|
||||
* @param IgnoreId
|
||||
* @param Args
|
||||
* @return
|
||||
*/
|
||||
template <typename... ArgsT>
|
||||
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerEvent(const std::string& EventName, TLuaStateId IgnoreId, ArgsT&&... Args) {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
beammp_event(EventName);
|
||||
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
|
||||
for (const auto& Event : mLuaEvents.at(EventName)) {
|
||||
for (const auto& Function : Event.second) {
|
||||
if (Event.first != IgnoreId) {
|
||||
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Results; //
|
||||
}
|
||||
template <typename... ArgsT>
|
||||
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerLocalEvent(const TLuaStateId& StateId, const std::string& EventName, ArgsT&&... Args) {
|
||||
std::unique_lock Lock(mLuaEventsMutex);
|
||||
beammp_event(EventName + " in '" + StateId + "'");
|
||||
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
|
||||
return {};
|
||||
}
|
||||
std::vector<std::shared_ptr<TLuaResult>> Results;
|
||||
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
|
||||
const auto Handlers = GetEventHandlersForState(EventName, StateId);
|
||||
for (const auto& Handler : Handlers) {
|
||||
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
|
||||
}
|
||||
return Results;
|
||||
}
|
||||
std::set<std::string> GetEventHandlersForState(const std::string& EventName, TLuaStateId StateId);
|
||||
void CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy);
|
||||
void CancelEventTimers(const std::string& EventName, TLuaStateId StateId);
|
||||
sol::state_view GetStateForPlugin(const fs::path& PluginPath);
|
||||
TLuaStateId GetStateIDForPlugin(const fs::path& PluginPath);
|
||||
void AddResultToCheck(const std::shared_ptr<TLuaResult>& Result);
|
||||
|
||||
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
|
||||
|
||||
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
|
||||
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
|
||||
|
||||
// Debugging functions (slow)
|
||||
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
|
||||
std::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
|
||||
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
|
||||
|
||||
private:
|
||||
void CollectAndInitPlugins();
|
||||
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
|
||||
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
|
||||
size_t CalculateMemoryUsage();
|
||||
|
||||
class StateThreadData : IThreaded {
|
||||
public:
|
||||
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
|
||||
StateThreadData(const StateThreadData&) = delete;
|
||||
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
|
||||
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
|
||||
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
|
||||
void AddPath(const fs::path& Path); // to be added to path and cpath
|
||||
void operator()() override;
|
||||
sol::state_view State() { return sol::state_view(mState); }
|
||||
|
||||
std::vector<std::string> GetStateGlobalKeys();
|
||||
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
|
||||
|
||||
// Debug functions, slow
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
|
||||
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
|
||||
|
||||
private:
|
||||
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
|
||||
sol::table Lua_GetPlayerIdentifiers(int ID);
|
||||
sol::table Lua_GetPlayers();
|
||||
std::string Lua_GetPlayerName(int ID);
|
||||
sol::table Lua_GetPlayerVehicles(int ID);
|
||||
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_JsonDecode(const std::string& str);
|
||||
int Lua_GetPlayerIDByName(const std::string& Name);
|
||||
sol::table Lua_FS_ListFiles(const std::string& Path);
|
||||
sol::table Lua_FS_ListDirectories(const std::string& Path);
|
||||
|
||||
std::string mName;
|
||||
TLuaStateId mStateId;
|
||||
lua_State* mState;
|
||||
std::thread mThread;
|
||||
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
|
||||
std::recursive_mutex mStateExecuteQueueMutex;
|
||||
std::vector<QueuedFunction> mStateFunctionQueue;
|
||||
std::mutex mStateFunctionQueueMutex;
|
||||
std::condition_variable mStateFunctionQueueCond;
|
||||
TLuaEngine* mEngine;
|
||||
sol::state_view mStateView { mState };
|
||||
std::queue<fs::path> mPaths;
|
||||
std::recursive_mutex mPathsMutex;
|
||||
std::mt19937 mMersenneTwister;
|
||||
std::uniform_real_distribution<double> mUniformRealDistribution01;
|
||||
};
|
||||
|
||||
struct TimedEvent {
|
||||
std::chrono::high_resolution_clock::duration Duration {};
|
||||
std::chrono::high_resolution_clock::time_point LastCompletion {};
|
||||
std::string EventName;
|
||||
TLuaStateId StateId;
|
||||
CallStrategy Strategy;
|
||||
bool Expired();
|
||||
void Reset();
|
||||
};
|
||||
|
||||
TNetwork* mNetwork;
|
||||
TServer* mServer;
|
||||
const fs::path mResourceServerPath;
|
||||
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
|
||||
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
|
||||
std::recursive_mutex mLuaStatesMutex;
|
||||
std::unordered_map<std::string /* event name */, std::unordered_map<TLuaStateId, std::set<std::string>>> mLuaEvents;
|
||||
std::recursive_mutex mLuaEventsMutex;
|
||||
std::vector<TimedEvent> mTimedEvents;
|
||||
std::recursive_mutex mTimedEventsMutex;
|
||||
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
|
||||
std::mutex mResultsToCheckMutex;
|
||||
std::condition_variable mResultsToCheckCond;
|
||||
};
|
||||
|
||||
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
|
||||
@@ -0,0 +1,19 @@
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
class TLuaPlugin {
|
||||
public:
|
||||
TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder);
|
||||
TLuaPlugin(const TLuaPlugin&) = delete;
|
||||
TLuaPlugin& operator=(const TLuaPlugin&) = delete;
|
||||
~TLuaPlugin() noexcept = default;
|
||||
|
||||
const TLuaPluginConfig& GetConfig() const { return mConfig; }
|
||||
fs::path GetFolder() const { return mFolder; }
|
||||
|
||||
private:
|
||||
TLuaPluginConfig mConfig;
|
||||
TLuaEngine& mEngine;
|
||||
fs::path mFolder;
|
||||
std::string mPluginName;
|
||||
std::unordered_map<std::string, std::shared_ptr<std::string>> mFileContents;
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include "BoostAliases.h"
|
||||
#include "Compat.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/ip/udp.hpp>
|
||||
|
||||
struct TConnection;
|
||||
|
||||
class TNetwork {
|
||||
public:
|
||||
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
|
||||
|
||||
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
|
||||
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
|
||||
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
|
||||
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
|
||||
std::vector<uint8_t> TCPRcv(TClient& c);
|
||||
void ClientKick(TClient& c, const std::string& R);
|
||||
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
|
||||
void Identify(TConnection&& client);
|
||||
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
|
||||
void SyncResources(TClient& c);
|
||||
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
|
||||
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
|
||||
void UpdatePlayer(TClient& Client);
|
||||
|
||||
private:
|
||||
void UDPServerMain();
|
||||
void TCPServerMain();
|
||||
|
||||
TServer& mServer;
|
||||
TPPSMonitor& mPPSMonitor;
|
||||
ip::udp::socket mUDPSock;
|
||||
TResourceManager& mResourceManager;
|
||||
std::thread mUDPThread;
|
||||
std::thread mTCPThread;
|
||||
|
||||
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
|
||||
void HandleDownload(TConnection&& TCPSock);
|
||||
void OnConnect(const std::weak_ptr<TClient>& c);
|
||||
void TCPClient(const std::weak_ptr<TClient>& c);
|
||||
void Looper(const std::weak_ptr<TClient>& c);
|
||||
int OpenID();
|
||||
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
|
||||
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
|
||||
void SendFile(TClient& c, const std::string& Name);
|
||||
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
|
||||
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
|
||||
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
|
||||
};
|
||||
|
||||
std::string HashPassword(const std::string& str);
|
||||
std::vector<uint8_t> StringToVector(const std::string& Str);
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "TServer.h"
|
||||
#include <optional>
|
||||
|
||||
class TNetwork;
|
||||
|
||||
class TPPSMonitor : public IThreaded {
|
||||
public:
|
||||
explicit TPPSMonitor(TServer& Server);
|
||||
virtual ~TPPSMonitor() {}
|
||||
|
||||
void operator()() override;
|
||||
|
||||
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
|
||||
void IncrementInternalPPS() { ++mInternalPPS; }
|
||||
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
|
||||
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
|
||||
|
||||
private:
|
||||
TNetwork& Network() { return mNetwork->get(); }
|
||||
|
||||
TServer& mServer;
|
||||
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
|
||||
int mInternalPPS { 0 };
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
#include "IThreaded.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
class TLuaEngine;
|
||||
|
||||
class TPluginMonitor : IThreaded, public std::enable_shared_from_this<TPluginMonitor> {
|
||||
public:
|
||||
TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine);
|
||||
|
||||
void operator()();
|
||||
|
||||
private:
|
||||
std::shared_ptr<TLuaEngine> mEngine;
|
||||
fs::path mPath;
|
||||
std::unordered_map<std::string, fs::file_time_type> mFileTimes;
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
class TResourceManager {
|
||||
public:
|
||||
TResourceManager();
|
||||
|
||||
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
|
||||
[[nodiscard]] std::string FileList() const { return mFileList; }
|
||||
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
|
||||
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
|
||||
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
|
||||
|
||||
private:
|
||||
size_t mMaxModSize = 0;
|
||||
std::string mFileSizes;
|
||||
std::string mFileList;
|
||||
std::string mTrimmedList;
|
||||
int mModsLoaded = 0;
|
||||
};
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "IThreaded.h"
|
||||
#include "RWMutex.h"
|
||||
#include "TScopedTimer.h"
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "BoostAliases.h"
|
||||
|
||||
class TClient;
|
||||
class TNetwork;
|
||||
class TPPSMonitor;
|
||||
|
||||
class TServer final {
|
||||
public:
|
||||
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
|
||||
|
||||
TServer(const std::vector<std::string_view>& Arguments);
|
||||
|
||||
void InsertClient(const std::shared_ptr<TClient>& Ptr);
|
||||
void RemoveClient(const std::weak_ptr<TClient>&);
|
||||
// in Fn, return true to continue, return false to break
|
||||
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
|
||||
size_t ClientCount() const;
|
||||
|
||||
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
|
||||
static void HandleEvent(TClient& c, const std::string& Data);
|
||||
RWMutex& GetClientMutex() const { return mClientsMutex; }
|
||||
|
||||
const TScopedTimer UptimeTimer;
|
||||
|
||||
// asio io context
|
||||
io_context& IoCtx() { return mIoCtx; }
|
||||
|
||||
private:
|
||||
io_context mIoCtx {};
|
||||
TClientSet mClients;
|
||||
mutable RWMutex mClientsMutex;
|
||||
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
|
||||
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
|
||||
static bool IsUnicycle(TClient& c, const std::string& CarJson);
|
||||
static void Apply(TClient& c, int VID, const std::string& pckt);
|
||||
static void HandlePosition(TClient& c, const std::string& Packet);
|
||||
};
|
||||
|
||||
struct BufferView {
|
||||
uint8_t* Data { nullptr };
|
||||
size_t Size { 0 };
|
||||
const uint8_t* data() const { return Data; }
|
||||
uint8_t* data() { return Data; }
|
||||
size_t size() const { return Size; }
|
||||
};
|
||||
-269
@@ -1,269 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/// @file
|
||||
/// The Value.h file describes a collection of wrapper types for use in
|
||||
/// cross-plugin communication and similar. These wrapper types are
|
||||
/// typically not zero-cost, so be careful and use these sparigly.
|
||||
///
|
||||
/// Base visitors, such as ValueToStringVisitor, should be declared
|
||||
/// here also.
|
||||
|
||||
#include "Error.h"
|
||||
#include "HashMap.h"
|
||||
#include "boost/variant/variant_fwd.hpp"
|
||||
#include <boost/json.hpp>
|
||||
#include <boost/variant.hpp>
|
||||
#include <boost/variant/variant.hpp>
|
||||
#include <ostream>
|
||||
#include <sol/forward.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/// Dynamic array, can resize.
|
||||
template<typename T>
|
||||
using Array = std::vector<T>;
|
||||
|
||||
/// Null value, for use in Value.
|
||||
struct Null {
|
||||
/// Makes a null value. It's an identity value,
|
||||
/// so its existance is the value.
|
||||
explicit Null() { }
|
||||
};
|
||||
|
||||
/// Formats "null".
|
||||
std::ostream& operator<<(std::ostream& os, const Null&);
|
||||
|
||||
/// Contains a boolean value, for use in Value,
|
||||
/// as booleans will be implicitly converted to int.
|
||||
struct Bool {
|
||||
/// Construct a bool from a boolean.
|
||||
explicit Bool(bool b_)
|
||||
: b(b_) { }
|
||||
/// Contained value.
|
||||
bool b;
|
||||
/// Implicit conversion to bool, because it's expected to work this way.
|
||||
operator bool() const { return b; }
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct Tuple final : public Array<T> {
|
||||
using Array<T>::Array;
|
||||
};
|
||||
|
||||
/// Formats to "true" or "false".
|
||||
std::ostream& operator<<(std::ostream& os, const Bool&);
|
||||
|
||||
/// The Value type is a recursively defined variant, which allows
|
||||
/// passing a single value with any of a selection of types, including
|
||||
/// the possibility to pass hashmaps of hashmaps of hashmaps of types (and so on).
|
||||
///
|
||||
/// In common pseudo-C++, this would be written as:
|
||||
///
|
||||
/// \code{.cpp}
|
||||
/// using Value = variant<string, int, double, HashMap<string, Value>;
|
||||
/// // ^^^^^
|
||||
/// \endcode
|
||||
/// Note the `^^^` annotated recursion. This isn't directly possible in C++,
|
||||
/// so we use boost's recursive variants for this. Documentation is here
|
||||
/// https://www.boost.org/doc/libs/1_82_0/doc/html/variant/tutorial.html#variant.tutorial.recursive
|
||||
///
|
||||
/// The use-case of a Value is to represent almost any primitive-ish type we may get from, or
|
||||
/// may want to pass to, a Plugin.
|
||||
///
|
||||
/// For example, a table of key-value pairs, or a table of tables, or just a string, or a float, could all
|
||||
/// be represented by this.
|
||||
///
|
||||
/// See the abstract template class ValueVisitor for how to access this with the
|
||||
/// visitor pattern.
|
||||
using Value = boost::make_recursive_variant<
|
||||
std::string,
|
||||
int64_t,
|
||||
double,
|
||||
Null,
|
||||
Array<boost::recursive_variant_>,
|
||||
HashMap<std::string, boost::recursive_variant_>,
|
||||
Bool,
|
||||
Tuple<boost::recursive_variant_>>::type;
|
||||
|
||||
// the following VALUE_TYPE_* variables are used mostly for
|
||||
// unit-tests and code that can't use visitors.
|
||||
|
||||
/// Index of string in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_STRING = 0;
|
||||
/// Index of int in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_INT = 1;
|
||||
/// Index of double in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_DOUBLE = 2;
|
||||
/// Index of null in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_NULL = 3;
|
||||
/// Index of array in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_ARRAY = 4;
|
||||
/// Index of hashmap in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_HASHMAP = 5;
|
||||
/// Index of bool in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_BOOL = 6;
|
||||
/// Index of tuple in Value
|
||||
[[maybe_unused]] constexpr int VALUE_TYPE_IDX_TUPLE = 7;
|
||||
|
||||
/// A handy typedef for the recursive HashMap type inside a Value.
|
||||
/// You may have to use this in order to make the compiler understand
|
||||
/// what kind of value (a hash map) you are constructing.
|
||||
using ValueHashMap = HashMap<std::string, Value>;
|
||||
/// A handy typedef for the recursive Array type inside a Value.
|
||||
/// You may have to use this in order to make the compiler understand
|
||||
/// what kind of value (an array) you are constructing.
|
||||
using ValueArray = Array<Value>;
|
||||
/// A handy dandy typedef for using a tuple of values.
|
||||
using ValueTuple = Tuple<Value>;
|
||||
|
||||
/// The ValueVisitor class is an abstract interface which allows the implementation
|
||||
/// to easily construct a visitor for a Value object.
|
||||
///
|
||||
/// A Value object is a recursive variant class, and as such it's not simple to access
|
||||
/// (no variants are really trivial to access). The visitor pattern gives us a type-safe
|
||||
/// way to access such a variant, and the boost::static_visitor pattern does so in a
|
||||
/// pretty concise way.
|
||||
///
|
||||
/// An example use is the ValueToStringVisitor.
|
||||
template<typename ResultT>
|
||||
class ValueVisitor : public boost::static_visitor<ResultT> {
|
||||
public:
|
||||
/// Needs to be default-constructible for the standard use case (see example above).
|
||||
ValueVisitor() = default;
|
||||
/// Cannot be copied.
|
||||
ValueVisitor(const ValueVisitor&) = delete;
|
||||
/// Cannot be copied.
|
||||
ValueVisitor& operator=(const ValueVisitor&) = delete;
|
||||
/// Virtual destructor is needed for virtual classes.
|
||||
virtual ~ValueVisitor() = default;
|
||||
|
||||
/// ResultT from string.
|
||||
virtual ResultT operator()(const std::string& str) const = 0;
|
||||
/// ResultT from integer.
|
||||
virtual ResultT operator()(int64_t i) const = 0;
|
||||
/// ResultT from float.
|
||||
virtual ResultT operator()(double d) const = 0;
|
||||
/// ResultT from null.
|
||||
virtual ResultT operator()(Null null) const = 0;
|
||||
/// ResultT from boolean.
|
||||
virtual ResultT operator()(Bool b) const = 0;
|
||||
/// ResultT from array of values (must recursively visit).
|
||||
virtual ResultT operator()(const ValueArray& array) const = 0;
|
||||
/// ResultT from tuple of values (must recursively visit).
|
||||
virtual ResultT operator()(const ValueTuple& array) const = 0;
|
||||
/// ResultT from hashmap of values (must recursively visit).
|
||||
virtual ResultT operator()(const HashMap<std::string, Value>& map) const = 0;
|
||||
};
|
||||
|
||||
/// The ValueToStringVisitor class implements a visitor for a Value which
|
||||
/// turns it into a human-readable string.
|
||||
///
|
||||
/// Example
|
||||
/// \code{.cpp}
|
||||
/// #include <boost/variant.hpp>
|
||||
///
|
||||
/// Value value = ...;
|
||||
///
|
||||
/// std::string str = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
/// // ^--------------------^ ^---^
|
||||
/// // default ctor |
|
||||
/// // value to visit
|
||||
/// \endcode
|
||||
class ValueToStringVisitor : public ValueVisitor<std::string> {
|
||||
public:
|
||||
/// Flag used to specify behavior of ValueToStringVisitor.
|
||||
enum Flag {
|
||||
/// No options
|
||||
NONE = 0,
|
||||
/// Quote strings, `value` becomes `"value"`.
|
||||
QUOTE_STRINGS = 0b1,
|
||||
};
|
||||
|
||||
/// Constructs a ValueToStringVisitor with options.
|
||||
/// With flags you can change, for example, whether strings should be quoted
|
||||
/// when they standalone.
|
||||
/// Depth is used by recursion, ignore it.
|
||||
explicit ValueToStringVisitor(Flag flags = QUOTE_STRINGS, int depth = 1);
|
||||
/// Returns the same string, possibly quoted (depends on flags).
|
||||
std::string operator()(const std::string& str) const;
|
||||
/// Uses fmt::format() to stringify the integer.
|
||||
std::string operator()(int64_t i) const;
|
||||
/// Uses fmt::format() to stringify the double.
|
||||
std::string operator()(double d) const;
|
||||
/// Returns "null".
|
||||
std::string operator()(Null null) const;
|
||||
/// Returns "true" or "false".
|
||||
std::string operator()(Bool b) const;
|
||||
/// Returns an object of format [ value, value, value ].
|
||||
/// Recursively visits the elements of the array.
|
||||
std::string operator()(const ValueArray& array) const;
|
||||
/// Returns a tuple of format ( value, value, value ).
|
||||
/// Recursively visits the elements of the array.
|
||||
std::string operator()(const ValueTuple& array) const;
|
||||
/// Returns an object of format { key: value, key: value }.
|
||||
/// Recursively visits the elements of the map.
|
||||
std::string operator()(const HashMap<std::string, Value>& map) const;
|
||||
|
||||
private:
|
||||
/// Whether to quote strings before output.
|
||||
bool m_quote_strings;
|
||||
/// How many 2-space "tabs" to use - used by recursion.
|
||||
int m_depth;
|
||||
};
|
||||
|
||||
/// The ValueToJsonVisitor class is used to convert a Value into
|
||||
/// a boost::json object.
|
||||
class ValueToJsonVisitor : public ValueVisitor<boost::json::value> {
|
||||
public:
|
||||
/// Converts to json string.
|
||||
boost::json::value operator()(const std::string& str) const;
|
||||
/// Converts to json integer.
|
||||
boost::json::value operator()(int64_t i) const;
|
||||
/// Converts to json float.
|
||||
boost::json::value operator()(double d) const;
|
||||
/// Converts to empty json value.
|
||||
boost::json::value operator()(Null null) const;
|
||||
/// Converts to json boolean.
|
||||
boost::json::value operator()(Bool b) const;
|
||||
/// Converts to json array.
|
||||
boost::json::value operator()(const ValueArray& array) const;
|
||||
/// Converts to json array (because tuples don't exist).
|
||||
boost::json::value operator()(const ValueTuple& array) const;
|
||||
/// Converts to json object.
|
||||
boost::json::value operator()(const HashMap<std::string, Value>& map) const;
|
||||
};
|
||||
|
||||
/// The ValueToLuaVisitor class is used to convert a Value into a
|
||||
/// sol object.
|
||||
class ValueToLuaVisitor : public ValueVisitor<sol::object> {
|
||||
public:
|
||||
/// ValueToLuaVisitor needs a sol state in order to construct objects.
|
||||
ValueToLuaVisitor(sol::state& state);
|
||||
|
||||
sol::object operator()(const std::string& str) const;
|
||||
sol::object operator()(int64_t i) const;
|
||||
sol::object operator()(double d) const;
|
||||
sol::object operator()(Null null) const;
|
||||
sol::object operator()(Bool b) const;
|
||||
sol::object operator()(const ValueArray& array) const;
|
||||
sol::object operator()(const ValueTuple& array) const;
|
||||
sol::object operator()(const HashMap<std::string, Value>& map) const;
|
||||
|
||||
private:
|
||||
sol::state& m_state;
|
||||
};
|
||||
|
||||
/// This function converts from a lua (sol) wrapped value into a beammp value, for use in C++.
|
||||
///
|
||||
/// Value is a type which can be passed around between threads, and has no external dependencies.
|
||||
/// Sol values are not like that, as they are references to stack indices in lua, and similar.
|
||||
///
|
||||
/// This function is also used to print values, by first converting them to a Value, then using a
|
||||
/// ValueToStringVisitor.
|
||||
///
|
||||
/// The second argument is a provider for values which the function can't convert.
|
||||
/// "invalid provider" means "provider of values for invalid sol values". If nullptr, then
|
||||
/// any invalid value (such as a function) will be resolved to an error instead and the function will
|
||||
/// fail.
|
||||
Result<Value> sol_obj_to_value(const sol::object&, const std::function<Result<Value>(const sol::object&)>& invalid_provider = nullptr, size_t max_depth = 50);
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
@@ -4,4 +4,4 @@ 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
|
||||
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||
|
||||
@@ -2,6 +2,4 @@
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -s -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
|
||||
|
||||
@@ -3,8 +3,3 @@
|
||||
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
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y liblua5.3-0 curl
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Server-tests
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y liblua5.3-0 curl
|
||||
|
||||
@@ -4,4 +4,4 @@ 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
|
||||
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++
|
||||
|
||||
@@ -2,6 +2,4 @@
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -s -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
|
||||
|
||||
@@ -3,8 +3,3 @@
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Server
|
||||
|
||||
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
|
||||
|
||||
strip -s bin/BeamMP-Server
|
||||
|
||||
Executable → Regular
-2
@@ -2,6 +2,4 @@
|
||||
|
||||
set -ex
|
||||
|
||||
vcpkg add port lua
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Server --config Release
|
||||
cmake --build bin --parallel -t BeamMP-Server
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "ArgsParser.h"
|
||||
#include "Common.h"
|
||||
#include <algorithm>
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#include "Client.h"
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include "TServer.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
void TClient::DeleteCar(int Ident) {
|
||||
// TODO: Send delete packets
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
|
||||
return Ident == elem.ID();
|
||||
});
|
||||
if (iter != mVehicleData.end()) {
|
||||
mVehicleData.erase(iter);
|
||||
} else {
|
||||
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
|
||||
}
|
||||
}
|
||||
|
||||
void TClient::ClearCars() {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
mVehicleData.clear();
|
||||
}
|
||||
|
||||
int TClient::GetOpenCarID() const {
|
||||
int OpenID = 0;
|
||||
bool found;
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
do {
|
||||
found = true;
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == OpenID) {
|
||||
OpenID++;
|
||||
found = false;
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return OpenID;
|
||||
}
|
||||
|
||||
void TClient::AddNewCar(int Ident, const std::string& Data) {
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
mVehicleData.emplace_back(Ident, Data);
|
||||
}
|
||||
|
||||
TClient::TVehicleDataLockPair TClient::GetAllCars() {
|
||||
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
|
||||
}
|
||||
|
||||
std::string TClient::GetCarPositionRaw(int Ident) {
|
||||
std::unique_lock lock(mVehiclePositionMutex);
|
||||
try {
|
||||
return mVehiclePosition.at(size_t(Ident));
|
||||
} catch (const std::out_of_range& oor) {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
void TClient::Disconnect(std::string_view Reason) {
|
||||
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
|
||||
boost::system::error_code ec;
|
||||
mSocket.shutdown(socket_base::shutdown_both, ec);
|
||||
if (ec) {
|
||||
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
||||
}
|
||||
mSocket.close(ec);
|
||||
if (ec) {
|
||||
beammp_debugf("Failed to close client socket: {}", ec.message());
|
||||
}
|
||||
}
|
||||
|
||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||
std::unique_lock lock(mVehiclePositionMutex);
|
||||
mVehiclePosition[size_t(Ident)] = Data;
|
||||
}
|
||||
|
||||
std::string TClient::GetCarData(int Ident) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == Ident) {
|
||||
return v.Data();
|
||||
}
|
||||
}
|
||||
} // unlock
|
||||
DeleteCar(Ident);
|
||||
return "";
|
||||
}
|
||||
|
||||
void TClient::SetCarData(int Ident, const std::string& Data) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
for (auto& v : mVehicleData) {
|
||||
if (v.ID() == Ident) {
|
||||
v.SetData(Data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} // unlock
|
||||
DeleteCar(Ident);
|
||||
}
|
||||
|
||||
int TClient::GetCarCount() const {
|
||||
return int(mVehicleData.size());
|
||||
}
|
||||
|
||||
TServer& TClient::Server() const {
|
||||
return mServer;
|
||||
}
|
||||
|
||||
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
|
||||
std::unique_lock Lock(mMissedPacketsMutex);
|
||||
mPacketsSync.push(Packet);
|
||||
}
|
||||
|
||||
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
|
||||
: mServer(Server)
|
||||
, mSocket(std::move(Socket))
|
||||
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
|
||||
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
|
||||
}
|
||||
|
||||
TClient::~TClient() {
|
||||
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
|
||||
}
|
||||
|
||||
void TClient::UpdatePingTime() {
|
||||
mLastPingTime = std::chrono::high_resolution_clock::now();
|
||||
}
|
||||
int TClient::SecondsSinceLastPing() {
|
||||
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::high_resolution_clock::now() - mLastPingTime)
|
||||
.count();
|
||||
return int(seconds);
|
||||
}
|
||||
|
||||
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
|
||||
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
|
||||
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
|
||||
ReadLock Lock(Server.GetClientMutex());
|
||||
if (!CPtr.expired()) {
|
||||
auto C = CPtr.lock();
|
||||
if (C->GetID() == ID) {
|
||||
MaybeClient = CPtr;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return MaybeClient;
|
||||
}
|
||||
+2
-38
@@ -1,28 +1,8 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
#include "Env.h"
|
||||
#include "TConsole.h"
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <fmt/core.h>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <regex>
|
||||
@@ -221,11 +201,8 @@ void Application::CheckForUpdates() {
|
||||
auto MyVersion = ServerVersion();
|
||||
auto RemoteVersion = Version(VersionStrToInts(Response));
|
||||
if (IsOutdated(MyVersion, RemoteVersion)) {
|
||||
std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
|
||||
const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
|
||||
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);
|
||||
std::string RealVersionString = RemoteVersion.AsString();
|
||||
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET));
|
||||
} else {
|
||||
if (FirstTime) {
|
||||
beammp_info("Server up-to-date!");
|
||||
@@ -293,8 +270,6 @@ void RegisterThread(const std::string& str) {
|
||||
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
|
||||
#elif defined(BEAMMP_LINUX)
|
||||
ThreadId = std::to_string(gettid());
|
||||
#elif defined(BEAMMP_FREEBSD)
|
||||
ThreadId = std::to_string(getpid());
|
||||
#endif
|
||||
if (Application::Settings.DebugModeEnabled) {
|
||||
std::ofstream ThreadFile(".Threads.log", std::ios::app);
|
||||
@@ -373,14 +348,3 @@ std::string GetPlatformAgnosticErrorString() {
|
||||
return "(no human-readable errors on this platform)";
|
||||
#endif
|
||||
}
|
||||
|
||||
// TODO: add unit tests to SplitString
|
||||
void SplitString(const std::string& str, const char delim, std::vector<std::string>& out) {
|
||||
size_t start;
|
||||
size_t end = 0;
|
||||
|
||||
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
|
||||
end = str.find(delim, start);
|
||||
out.push_back(str.substr(start, end - start));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "Compat.h"
|
||||
|
||||
#include <cstring>
|
||||
@@ -59,9 +41,7 @@ TEST_CASE("init and reset termios") {
|
||||
CHECK_EQ(current.c_iflag, original.c_iflag);
|
||||
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||
#ifndef BEAMMP_FREEBSD // The 'c_line' attribute seems to only exist on Linux, so we need to omit it on other platforms
|
||||
CHECK_EQ(current.c_line, original.c_line);
|
||||
#endif
|
||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||
}
|
||||
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "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 "";
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
#include "FileWatcher.h"
|
||||
#include "Common.h"
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
|
||||
/// @file
|
||||
/// This file holds the FileWatcher implementation.
|
||||
|
||||
FileWatcher::FileWatcher(unsigned int seconds)
|
||||
: m_seconds(boost::posix_time::seconds(seconds))
|
||||
, m_timer(boost::asio::deadline_timer(m_io, *m_seconds)) {
|
||||
m_timer->async_wait([this](const auto& err) { on_tick(err); });
|
||||
|
||||
m_thread = boost::scoped_thread<> { &FileWatcher::thread_main, this };
|
||||
}
|
||||
|
||||
FileWatcher::~FileWatcher() {
|
||||
m_work_guard.reset();
|
||||
*m_shutdown = true;
|
||||
}
|
||||
|
||||
void FileWatcher::watch_file(const std::filesystem::path& path) {
|
||||
m_files->insert(path);
|
||||
}
|
||||
|
||||
void FileWatcher::watch_files_in(const std::filesystem::path& path) {
|
||||
m_dirs->insert(path);
|
||||
}
|
||||
|
||||
void FileWatcher::thread_main() {
|
||||
while (!*m_shutdown) {
|
||||
m_io.run_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
|
||||
void FileWatcher::on_tick(const boost::system::error_code& err) {
|
||||
auto timer = m_timer.synchronize();
|
||||
// set up timer so that the operations after this don't impact the accuracy of the
|
||||
// timing
|
||||
timer->expires_at(timer->expires_at() + *m_seconds);
|
||||
|
||||
if (err) {
|
||||
beammp_errorf("FileWatcher encountered error: {}", err.message());
|
||||
// TODO: Should any further action be taken?
|
||||
} else {
|
||||
try {
|
||||
check_files();
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("FileWatcher exception while checking files: {}", e.what());
|
||||
}
|
||||
try {
|
||||
check_directories();
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("FileWatcher exception while checking directories: {}", e.what());
|
||||
}
|
||||
}
|
||||
// finally start the timer again, deadline has already been set at the beginning
|
||||
// of this function
|
||||
timer->async_wait([this](const auto& err) { on_tick(err); });
|
||||
}
|
||||
|
||||
void FileWatcher::check_files() {
|
||||
auto files = m_files.synchronize();
|
||||
for (const auto& file : *files) {
|
||||
check_file(file);
|
||||
// TODO: add deleted/created watches
|
||||
}
|
||||
}
|
||||
|
||||
void FileWatcher::check_directories() {
|
||||
auto directories = m_dirs.synchronize();
|
||||
for (const auto& dir : *directories) {
|
||||
if (std::filesystem::exists(dir)) {
|
||||
for (const auto& entry : std::filesystem::recursive_directory_iterator(dir, std::filesystem::directory_options::follow_directory_symlink | std::filesystem::directory_options::skip_permission_denied)) {
|
||||
if (entry.is_regular_file() || entry.is_symlink()) {
|
||||
check_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO: add deleted/created watches
|
||||
}
|
||||
}
|
||||
|
||||
void FileWatcher::check_file(const std::filesystem::path& file) {
|
||||
if (std::filesystem::exists(file)) {
|
||||
auto real_file = file;
|
||||
if (std::filesystem::is_symlink(file)) {
|
||||
real_file = std::filesystem::read_symlink(file);
|
||||
}
|
||||
auto time = std::filesystem::last_write_time(real_file);
|
||||
if (!m_file_mod_times.contains(file)) {
|
||||
m_file_mod_times.insert_or_assign(file, time);
|
||||
} else {
|
||||
if (m_file_mod_times.at(file) != time) {
|
||||
beammp_tracef("File changed: {}", file);
|
||||
sig_file_changed(file);;
|
||||
m_file_mod_times.at(file) = time;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-21
@@ -1,23 +1,6 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "Http.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
@@ -32,7 +15,7 @@
|
||||
using json = nlohmann::json;
|
||||
|
||||
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
|
||||
static thread_local httplib::SSLClient client(host, port);
|
||||
httplib::SSLClient client(host, port);
|
||||
client.enable_server_certificate_verification(false);
|
||||
client.set_address_family(AF_INET);
|
||||
auto res = client.Get(target.c_str());
|
||||
@@ -47,7 +30,7 @@ std::string Http::GET(const std::string& host, int port, const std::string& targ
|
||||
}
|
||||
|
||||
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
|
||||
static thread_local httplib::SSLClient client(host, port);
|
||||
httplib::SSLClient client(host, port);
|
||||
client.set_read_timeout(std::chrono::seconds(10));
|
||||
beammp_assert(client.is_valid());
|
||||
client.enable_server_certificate_verification(false);
|
||||
@@ -198,7 +181,7 @@ void Http::Server::THttpServerInstance::operator()() try {
|
||||
}
|
||||
}
|
||||
res.set_content(
|
||||
nlohmann::json {
|
||||
json {
|
||||
{ "ok", SystemsBad == 0 },
|
||||
}
|
||||
.dump(),
|
||||
|
||||
+181
-227
@@ -1,33 +1,87 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "LuaAPI.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Value.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <boost/json/serialize.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <sol/types.hpp>
|
||||
|
||||
#define SOL_ALL_SAFETIES_ON 1
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool QuoteStrings) {
|
||||
if (Indent > 80) {
|
||||
return "[[possible recursion, refusing to keep printing]]";
|
||||
}
|
||||
switch (Value.get_type()) {
|
||||
case sol::type::userdata: {
|
||||
std::stringstream ss;
|
||||
ss << "[[userdata: " << Value.as<sol::userdata>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::thread: {
|
||||
std::stringstream ss;
|
||||
ss << "[[thread: " << Value.as<sol::thread>().pointer() << "]] {"
|
||||
<< "\n";
|
||||
for (size_t i = 0; i < Indent; ++i) {
|
||||
ss << "\t";
|
||||
}
|
||||
ss << "status: " << std::to_string(int(Value.as<sol::thread>().status())) << "\n}";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::lightuserdata: {
|
||||
std::stringstream ss;
|
||||
ss << "[[lightuserdata: " << Value.as<sol::lightuserdata>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::string:
|
||||
if (QuoteStrings) {
|
||||
return "\"" + Value.as<std::string>() + "\"";
|
||||
} else {
|
||||
return Value.as<std::string>();
|
||||
}
|
||||
case sol::type::number: {
|
||||
std::stringstream ss;
|
||||
ss << Value.as<float>();
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::none:
|
||||
return "<nil>";
|
||||
case sol::type::boolean:
|
||||
return Value.as<bool>() ? "true" : "false";
|
||||
case sol::type::table: {
|
||||
std::stringstream Result;
|
||||
auto Table = Value.as<sol::table>();
|
||||
Result << "[[table: " << Table.pointer() << "]]: {";
|
||||
if (!Table.empty()) {
|
||||
for (const auto& Entry : Table) {
|
||||
Result << "\n";
|
||||
for (size_t i = 0; i < Indent; ++i) {
|
||||
Result << "\t";
|
||||
}
|
||||
Result << LuaToString(Entry.first, Indent + 1) << ": " << LuaToString(Entry.second, Indent + 1, true) << ",";
|
||||
}
|
||||
Result << "\n";
|
||||
}
|
||||
for (size_t i = 0; i < Indent - 1; ++i) {
|
||||
Result << "\t";
|
||||
}
|
||||
Result << "}";
|
||||
return Result.str();
|
||||
}
|
||||
case sol::type::function: {
|
||||
std::stringstream ss;
|
||||
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::poly:
|
||||
return "<poly>";
|
||||
default:
|
||||
return "<unprintable type>";
|
||||
}
|
||||
}
|
||||
|
||||
std::string LuaAPI::MP::GetOSName() {
|
||||
#if WIN32
|
||||
return "Windows";
|
||||
@@ -42,6 +96,15 @@ std::tuple<int, int, int> LuaAPI::MP::GetServerVersion() {
|
||||
return { Application::ServerVersion().major, Application::ServerVersion().minor, Application::ServerVersion().patch };
|
||||
}
|
||||
|
||||
void LuaAPI::Print(sol::variadic_args Args) {
|
||||
std::string ToPrint = "";
|
||||
for (const auto& Arg : Args) {
|
||||
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||
ToPrint += "\t";
|
||||
}
|
||||
luaprint(ToPrint);
|
||||
}
|
||||
|
||||
TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
||||
const auto [ma, mi, pa] = LuaAPI::MP::GetServerVersion();
|
||||
const auto real = Application::ServerVersion();
|
||||
@@ -51,26 +114,24 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
||||
}
|
||||
|
||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
std::string Packet = "E:" + EventName + ":" + Data;
|
||||
if (PlayerID == -1) {
|
||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
return { true, "" };
|
||||
} else {
|
||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||
if (!MaybeClient) {
|
||||
beammp_errorff("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||
return { false, "Invalid Player ID" };
|
||||
}
|
||||
auto c = MaybeClient.value();
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_errorff("Respond failed, dropping client {}", PlayerID);
|
||||
LuaAPI::MP::Engine->Network().Disconnect(*c);
|
||||
return { false, "Respond failed, dropping client" };
|
||||
}
|
||||
return { true, "" };
|
||||
}*/
|
||||
std::string Packet = "E:" + EventName + ":" + Data;
|
||||
if (PlayerID == -1) {
|
||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
return { true, "" };
|
||||
} else {
|
||||
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
|
||||
return { false, "Invalid Player ID" };
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||
return { false, "Respond failed, dropping client" };
|
||||
}
|
||||
return { true, "" };
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||
@@ -79,22 +140,17 @@ 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) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (!MaybeClient) {
|
||||
beammp_errorff("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
return { false, "Player does not exist" };
|
||||
}
|
||||
auto c = MaybeClient.value();
|
||||
auto c = MaybeClient.value().lock();
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||
return { true, "" };
|
||||
*/
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
std::pair<bool, std::string> Result;
|
||||
std::string Packet = "C:Server: " + Message;
|
||||
if (ID == -1) {
|
||||
@@ -103,43 +159,39 @@ std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::stri
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient) {
|
||||
auto c = MaybeClient.value();
|
||||
if (!c->IsSynced) {
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player still syncing data";
|
||||
return Result;
|
||||
}
|
||||
LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message);
|
||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
|
||||
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||
beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get());
|
||||
Engine->Network().Disconnect(c);
|
||||
// TODO: should we return an error here?
|
||||
}
|
||||
Result.first = true;
|
||||
} else {
|
||||
beammp_errorf("SendChatMessage invalid argument [1] invalid ID");
|
||||
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
return Result;
|
||||
*/
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
std::pair<bool, std::string> Result;
|
||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||
if (!MaybeClient) {
|
||||
beammp_errorf("RemoveVehicle invalid Player ID");
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
return Result;
|
||||
}
|
||||
auto c = MaybeClient.value();
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||
@@ -150,7 +202,6 @@ std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||
Result.second = "Vehicle does not exist";
|
||||
}
|
||||
return Result;
|
||||
*/
|
||||
}
|
||||
|
||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
@@ -160,7 +211,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected boolean");
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 1: // private
|
||||
@@ -168,7 +219,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.Private = NewValue.as<bool>();
|
||||
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected boolean");
|
||||
beammp_lua_error("set invalid argument [2] expected boolean");
|
||||
}
|
||||
break;
|
||||
case 2: // max cars
|
||||
@@ -176,7 +227,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.MaxCars = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected integer");
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 3: // max players
|
||||
@@ -184,7 +235,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.MaxPlayers = NewValue.as<int>();
|
||||
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected integer");
|
||||
beammp_lua_error("set invalid argument [2] expected integer");
|
||||
}
|
||||
break;
|
||||
case 4: // Map
|
||||
@@ -192,7 +243,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.MapName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected string");
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 5: // Name
|
||||
@@ -200,7 +251,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.ServerName = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected string");
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
case 6: // Desc
|
||||
@@ -208,7 +259,7 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
Application::Settings.ServerDesc = NewValue.as<std::string>();
|
||||
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
|
||||
} else {
|
||||
beammp_errorf("set invalid argument [2] expected string");
|
||||
beammp_lua_error("set invalid argument [2] expected string");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
@@ -217,27 +268,42 @@ void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
}
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient) {
|
||||
return MaybeClient.value()->IsConnected.get();
|
||||
} else {
|
||||
return false;
|
||||
}*/
|
||||
void LuaAPI::MP::Sleep(size_t Ms) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
bool LuaAPI::MP::IsPlayerConnected(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient) {
|
||||
return MaybeClient.value()->IsGuest.get();
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsConnected();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
bool LuaAPI::MP::IsPlayerGuest(int ID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
return MaybeClient.value().lock()->IsGuest();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
|
||||
std::string ToPrint = "";
|
||||
for (const auto& Arg : Args) {
|
||||
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
|
||||
ToPrint += "\t";
|
||||
}
|
||||
#ifdef DOCTEST_CONFIG_DISABLE
|
||||
Application::Console().WriteRaw(ToPrint);
|
||||
#endif
|
||||
}
|
||||
|
||||
int LuaAPI::PanicHandler(lua_State* State) {
|
||||
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <typename FnT, typename... ArgsT>
|
||||
@@ -443,7 +509,7 @@ std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
|
||||
for (size_t i = 0; i < Args.size(); ++i) {
|
||||
auto Obj = Args[i];
|
||||
if (!Obj.is<std::string>()) {
|
||||
beammp_errorf("FS.Concat called with non-string argument");
|
||||
beammp_lua_error("FS.Concat called with non-string argument");
|
||||
return "";
|
||||
}
|
||||
Path += Obj.as<std::string>();
|
||||
@@ -457,7 +523,7 @@ std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
|
||||
|
||||
static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, const sol::object& right, bool is_array, size_t depth = 0) {
|
||||
if (depth > 100) {
|
||||
beammp_errorf("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;
|
||||
}
|
||||
std::string key {};
|
||||
@@ -471,7 +537,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
case sol::type::thread:
|
||||
case sol::type::function:
|
||||
case sol::type::table:
|
||||
beammp_errorf("JsonEncode: left side of table field is unexpected type");
|
||||
beammp_lua_error("JsonEncode: left side of table field is unexpected type");
|
||||
return;
|
||||
case sol::type::string:
|
||||
key = left.as<std::string>();
|
||||
@@ -533,33 +599,28 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
}
|
||||
}
|
||||
|
||||
static std::string lua_to_json_impl(const sol::object& obj) {
|
||||
// used as the invalid value provider in sol_obj_to_value.
|
||||
auto special_stringifier = [](const sol::object& object) -> Result<Value> {
|
||||
beammp_debugf("Cannot convert from type {} to json, ignoring (using null)", int(object.get_type()));
|
||||
return { Null {} };
|
||||
};
|
||||
auto maybe_val = sol_obj_to_value(obj, special_stringifier);
|
||||
if (maybe_val) {
|
||||
auto result = boost::apply_visitor(ValueToJsonVisitor {}, maybe_val.move());
|
||||
return boost::json::serialize(result);
|
||||
} else {
|
||||
beammp_errorf("Failed to convert an argument to json: {}", maybe_val.error);
|
||||
return "";
|
||||
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
|
||||
nlohmann::json json;
|
||||
// table
|
||||
bool is_array = true;
|
||||
for (const auto& pair : object.as<sol::table>()) {
|
||||
if (pair.first.get_type() != sol::type::number) {
|
||||
is_array = false;
|
||||
}
|
||||
}
|
||||
for (const auto& entry : object) {
|
||||
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
|
||||
}
|
||||
return json.dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonEncode(const sol::object& object) {
|
||||
return lua_to_json_impl(object);
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonDiff(const std::string& a, const std::string& b) {
|
||||
std::string LuaAPI::MP::JsonDiff(const std::string& a, const std::string& b) {
|
||||
if (!nlohmann::json::accept(a)) {
|
||||
beammp_error("JsonDiff first argument is not valid json: `" + a + "`");
|
||||
beammp_lua_error("JsonDiff first argument is not valid json: `" + a + "`");
|
||||
return "";
|
||||
}
|
||||
if (!nlohmann::json::accept(b)) {
|
||||
beammp_error("JsonDiff second argument is not valid json: `" + b + "`");
|
||||
beammp_lua_error("JsonDiff second argument is not valid json: `" + b + "`");
|
||||
return "";
|
||||
}
|
||||
auto a_json = nlohmann::json::parse(a);
|
||||
@@ -567,13 +628,13 @@ std::string LuaAPI::Util::JsonDiff(const std::string& a, const std::string& b) {
|
||||
return nlohmann::json::diff(a_json, b_json).dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonDiffApply(const std::string& data, const std::string& patch) {
|
||||
std::string LuaAPI::MP::JsonDiffApply(const std::string& data, const std::string& patch) {
|
||||
if (!nlohmann::json::accept(data)) {
|
||||
beammp_error("JsonDiffApply first argument is not valid json: `" + data + "`");
|
||||
beammp_lua_error("JsonDiffApply first argument is not valid json: `" + data + "`");
|
||||
return "";
|
||||
}
|
||||
if (!nlohmann::json::accept(patch)) {
|
||||
beammp_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
|
||||
beammp_lua_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
|
||||
return "";
|
||||
}
|
||||
auto a_json = nlohmann::json::parse(data);
|
||||
@@ -582,145 +643,38 @@ std::string LuaAPI::Util::JsonDiffApply(const std::string& data, const std::stri
|
||||
return a_json.dump();
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonPrettify(const std::string& json) {
|
||||
std::string LuaAPI::MP::JsonPrettify(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_error("JsonPrettify argument is not valid json: `" + json + "`");
|
||||
beammp_lua_error("JsonPrettify argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).dump(4);
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonMinify(const std::string& json) {
|
||||
std::string LuaAPI::MP::JsonMinify(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_error("JsonMinify argument is not valid json: `" + json + "`");
|
||||
beammp_lua_error("JsonMinify argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).dump(-1);
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonFlatten(const std::string& json) {
|
||||
std::string LuaAPI::MP::JsonFlatten(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_error("JsonFlatten argument is not valid json: `" + json + "`");
|
||||
beammp_lua_error("JsonFlatten argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).flatten().dump(-1);
|
||||
}
|
||||
|
||||
std::string LuaAPI::Util::JsonUnflatten(const std::string& json) {
|
||||
std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
||||
if (!nlohmann::json::accept(json)) {
|
||||
beammp_error("JsonUnflatten argument is not valid json: `" + json + "`");
|
||||
beammp_lua_error("JsonUnflatten argument is not valid json: `" + json + "`");
|
||||
return "";
|
||||
}
|
||||
return nlohmann::json::parse(json).unflatten().dump(-1);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, Util::JsonEncode(Data));
|
||||
}
|
||||
|
||||
size_t LuaAPI::MP::GetPlayerCount() { return 0; }
|
||||
|
||||
template <typename T>
|
||||
static void AddToTable(sol::table& table, const std::string& left, const T& value) {
|
||||
if (left.empty()) {
|
||||
table[table.size() + 1] = value;
|
||||
} else {
|
||||
table[left] = value;
|
||||
}
|
||||
}
|
||||
|
||||
static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, const std::string& left, const nlohmann::json& right) {
|
||||
switch (right.type()) {
|
||||
case nlohmann::detail::value_t::null:
|
||||
return;
|
||||
case nlohmann::detail::value_t::object: {
|
||||
auto value = table.create();
|
||||
value.clear();
|
||||
for (const auto& entry : right.items()) {
|
||||
JsonDecodeRecursive(StateView, value, entry.key(), entry.value());
|
||||
}
|
||||
AddToTable(table, left, value);
|
||||
break;
|
||||
}
|
||||
case nlohmann::detail::value_t::array: {
|
||||
auto value = table.create();
|
||||
value.clear();
|
||||
for (const auto& entry : right.items()) {
|
||||
JsonDecodeRecursive(StateView, value, "", entry.value());
|
||||
}
|
||||
AddToTable(table, left, value);
|
||||
break;
|
||||
}
|
||||
case nlohmann::detail::value_t::string:
|
||||
AddToTable(table, left, right.get<std::string>());
|
||||
break;
|
||||
case nlohmann::detail::value_t::boolean:
|
||||
AddToTable(table, left, right.get<bool>());
|
||||
break;
|
||||
case nlohmann::detail::value_t::number_integer:
|
||||
AddToTable(table, left, right.get<int64_t>());
|
||||
break;
|
||||
case nlohmann::detail::value_t::number_unsigned:
|
||||
AddToTable(table, left, right.get<uint64_t>());
|
||||
break;
|
||||
case nlohmann::detail::value_t::number_float:
|
||||
AddToTable(table, left, right.get<double>());
|
||||
break;
|
||||
case nlohmann::detail::value_t::binary:
|
||||
beammp_errorf("JsonDecode can't handle binary blob in json, ignoring");
|
||||
return;
|
||||
case nlohmann::detail::value_t::discarded:
|
||||
return;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
}
|
||||
|
||||
sol::table LuaAPI::Util::JsonDecode(sol::this_state s, const std::string& str) {
|
||||
sol::state_view StateView(s.lua_state());
|
||||
auto table = StateView.create_table(StateView);
|
||||
if (!nlohmann::json::accept(str)) {
|
||||
beammp_error("string given to JsonDecode is not valid json: `" + str + "`");
|
||||
return sol::lua_nil;
|
||||
}
|
||||
nlohmann::json json = nlohmann::json::parse(str);
|
||||
if (json.is_object()) {
|
||||
for (const auto& entry : json.items()) {
|
||||
JsonDecodeRecursive(StateView, table, entry.key(), entry.value());
|
||||
}
|
||||
} else if (json.is_array()) {
|
||||
for (const auto& entry : json) {
|
||||
JsonDecodeRecursive(StateView, table, "", entry);
|
||||
}
|
||||
} else {
|
||||
beammp_error("JsonDecode expected array or object json, instead got " + std::string(json.type_name()));
|
||||
return sol::lua_nil;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
sol::table LuaAPI::FS::ListDirectories(sol::this_state s, const std::string& Path) {
|
||||
if (!std::filesystem::exists(Path)) {
|
||||
return sol::lua_nil;
|
||||
}
|
||||
auto table = sol::state_view(s.lua_state()).create_table();
|
||||
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
|
||||
if (entry.is_directory()) {
|
||||
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
|
||||
}
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
sol::table LuaAPI::FS::ListFiles(sol::this_state s, const std::string& Path) {
|
||||
if (!std::filesystem::exists(Path)) {
|
||||
return sol::lua_nil;
|
||||
}
|
||||
auto table = sol::state_view(s.lua_state()).create_table();
|
||||
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
|
||||
if (entry.is_regular_file() || entry.is_symlink()) {
|
||||
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
|
||||
}
|
||||
}
|
||||
return table;
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||
}
|
||||
|
||||
@@ -1,703 +0,0 @@
|
||||
#include "LuaPlugin.h"
|
||||
#include "Common.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "Value.h"
|
||||
#include <boost/algorithm/string/replace.hpp>
|
||||
#include <boost/asio/post.hpp>
|
||||
#include <boost/date_time/microsec_time_clock.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_config.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_duration.hpp>
|
||||
#include <boost/thread/exceptions.hpp>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <lauxlib.h>
|
||||
#include <lua.h>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
#include <sol/forward.hpp>
|
||||
#include <sol/sol.hpp>
|
||||
#include <sol/types.hpp>
|
||||
#include <sol/variadic_args.hpp>
|
||||
#include <spdlog/common.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
static int lua_panic_handler(lua_State* state) {
|
||||
sol::state_view view(state);
|
||||
sol::state new_state {};
|
||||
luaL_traceback(state, new_state.lua_state(), nullptr, 1);
|
||||
auto traceback = new_state.get<std::string>(-1);
|
||||
beammp_errorf("Lua panic (unclear in which plugin): {}", traceback);
|
||||
return 1;
|
||||
}
|
||||
|
||||
#define beammp_lua_debugf(...) beammp_debugf("[{}] {}", name(), fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_infof(...) beammp_infof("[{}] {}", name(), fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_warnf(...) beammp_warnf("[{}] {}", name(), fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_errorf(...) beammp_errorf("[{}] {}", name(), fmt::format(__VA_ARGS__))
|
||||
#define beammp_lua_tracef(...) beammp_tracef("[{}] {}", name(), fmt::format(__VA_ARGS__))
|
||||
|
||||
static constexpr const char* ERR_HANDLER = "__beammp_lua_error_handler";
|
||||
|
||||
/// Checks whether the supplied name is a valid lua identifier (mostly).
|
||||
static inline bool check_name_validity(const std::string& name) {
|
||||
if (name.empty()) {
|
||||
return false;
|
||||
}
|
||||
if (std::isdigit(name.at(0))) {
|
||||
return false;
|
||||
}
|
||||
for (const char c : name) {
|
||||
if (!std::isalnum(c) && c != '_') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LuaPlugin::LuaPlugin(const std::string& path)
|
||||
: m_path(path) {
|
||||
m_state = sol::state(lua_panic_handler);
|
||||
m_thread = boost::scoped_thread<> { &LuaPlugin::thread_main, this };
|
||||
}
|
||||
|
||||
LuaPlugin::~LuaPlugin() {
|
||||
for (auto& timer : m_timers) {
|
||||
timer->timer.cancel();
|
||||
}
|
||||
// work guard reset means that we allow all work to be finished before exit
|
||||
m_work_guard.reset();
|
||||
// setting this flag signals the thread to shut down
|
||||
*m_shutdown = true;
|
||||
}
|
||||
|
||||
Error LuaPlugin::initialize_error_handlers() {
|
||||
m_state.set_exception_handler([](lua_State* state, sol::optional<const std::exception&>, auto err) -> int {
|
||||
beammp_errorf("Error (unclear in which plugin): {}", err); // TODO: wtf?
|
||||
return sol::stack::push(state, err);
|
||||
});
|
||||
m_state.globals()[ERR_HANDLER] = [this](const std::string& error) {
|
||||
beammp_lua_errorf("Error: {}", error);
|
||||
return error;
|
||||
};
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::initialize_libraries() {
|
||||
m_state.open_libraries(
|
||||
sol::lib::base,
|
||||
sol::lib::package,
|
||||
sol::lib::coroutine,
|
||||
sol::lib::string,
|
||||
sol::lib::os,
|
||||
sol::lib::math,
|
||||
sol::lib::table,
|
||||
sol::lib::debug,
|
||||
sol::lib::bit32,
|
||||
sol::lib::io);
|
||||
|
||||
auto& glob = m_state.globals();
|
||||
|
||||
glob.create_named("MP");
|
||||
glob["MP"]["GetExtensions"] = [this]() -> sol::table {
|
||||
auto table = m_state.create_table();
|
||||
auto extensions = m_known_extensions.synchronize();
|
||||
for (const auto& [ext, path] : *extensions) {
|
||||
(void)path;
|
||||
table[ext] = m_state.globals()[ext];
|
||||
}
|
||||
return table; };
|
||||
glob["MP"]["GetStateMemoryUsage"] = [this]() { return size_t(m_state.memory_used()); };
|
||||
glob["MP"]["GetPluginMemoryUsage"] = [this] { return memory_usage(); };
|
||||
glob["MP"]["LogError"] = [this](const sol::variadic_args& args) {
|
||||
auto result = print_impl({ args.begin(), args.end() });
|
||||
beammp_lua_errorf("[out] {}", result);
|
||||
};
|
||||
glob["MP"]["LogWarn"] = [this](const sol::variadic_args& args) {
|
||||
auto result = print_impl({ args.begin(), args.end() });
|
||||
beammp_lua_warnf("[out] {}", result);
|
||||
};
|
||||
glob["MP"]["LogInfo"] = [this](const sol::variadic_args& args) {
|
||||
auto result = print_impl({ args.begin(), args.end() });
|
||||
beammp_lua_infof("[out] {}", result);
|
||||
};
|
||||
glob["MP"]["LogDebug"] = [this](const sol::variadic_args& args) {
|
||||
auto result = print_impl({ args.begin(), args.end() });
|
||||
beammp_lua_debugf("[out] {}", result);
|
||||
};
|
||||
glob["MP"]["GetPluginPath"] = [this] {
|
||||
return std::filesystem::absolute(m_path).string();
|
||||
};
|
||||
glob["MP"]["RegisterEvent"] = [this](const std::string& event_name, const sol::object& handler) {
|
||||
if (handler.get_type() == sol::type::string) {
|
||||
m_event_handlers_named[event_name].push_back(handler.as<std::string>());
|
||||
} else if (handler.get_type() == sol::type::function) {
|
||||
auto fn = handler.as<sol::protected_function>();
|
||||
fn.set_error_handler(m_state.globals()[ERR_HANDLER]);
|
||||
m_event_handlers[event_name].push_back(fn);
|
||||
} else {
|
||||
beammp_lua_errorf("Invalid call to MP.RegisterEvent for event '{}': Expected string or function as second argument", event_name);
|
||||
}
|
||||
};
|
||||
glob["MP"]["Post"] = [this](const sol::protected_function& fn) {
|
||||
boost::asio::post(m_io, [fn] {
|
||||
fn();
|
||||
});
|
||||
};
|
||||
glob["MP"]["TriggerLocalEvent"] = [this](const std::string& event_name, sol::variadic_args args) -> sol::table {
|
||||
std::vector<sol::object> args_vec(args.begin(), args.end());
|
||||
ValueTuple values {};
|
||||
values.reserve(args_vec.size());
|
||||
for (const auto& obj : args_vec) {
|
||||
auto res = sol_obj_to_value(obj);
|
||||
if (res) [[likely]] {
|
||||
values.emplace_back(res.move());
|
||||
} else {
|
||||
beammp_lua_errorf("Can't serialize an argument across boundaries (for passing to a MP.TriggerLocalEvent): {}", res.error);
|
||||
values.emplace_back(Null {});
|
||||
}
|
||||
}
|
||||
auto results = handle_event(event_name, std::make_shared<Value>(std::move(values)));
|
||||
auto result = m_state.create_table();
|
||||
result["__INTERNAL"] = results;
|
||||
// waits for a specific number of milliseconds for a result to be available, returns false if timed out, true if ready.
|
||||
result["WaitForMS"] = [](const sol::object& self, int milliseconds) {
|
||||
std::shared_future<std::vector<Value>> future = self.as<sol::table>()["__INTERNAL"];
|
||||
auto status = future.wait_for(std::chrono::milliseconds(milliseconds));
|
||||
return status == std::future_status::ready;
|
||||
};
|
||||
// waits indefinitely for all results to be available
|
||||
result["Wait"] = [](const sol::table& self) {
|
||||
std::shared_future<std::vector<Value>> future = self["__INTERNAL"];
|
||||
future.wait();
|
||||
};
|
||||
// waits indefinitely for all results to be available, then returns them
|
||||
result["Results"] = [this](const sol::table& self) -> sol::table {
|
||||
std::shared_future<std::vector<Value>> future = self["__INTERNAL"];
|
||||
future.wait();
|
||||
Value results = future.get();
|
||||
auto lua_res = boost::apply_visitor(ValueToLuaVisitor(m_state), results);
|
||||
return lua_res;
|
||||
};
|
||||
return result;
|
||||
};
|
||||
glob["MP"]["ScheduleCallRepeat"] = [this](size_t ms, sol::function fn, sol::variadic_args args) {
|
||||
return l_mp_schedule_call_repeat(ms, fn, args);
|
||||
};
|
||||
glob["MP"]["ScheduleCallOnce"] = [this](size_t ms, sol::function fn, sol::variadic_args args) {
|
||||
l_mp_schedule_call_once(ms, fn, args);
|
||||
};
|
||||
glob["MP"]["CancelScheduledCall"] = [this](std::shared_ptr<Timer>& timer) {
|
||||
// this has to be post()-ed, otherwise the call will not cancel (not sure why)
|
||||
boost::asio::post(m_io, [this, timer] {
|
||||
if (!timer) {
|
||||
beammp_lua_errorf("MP.cancel_scheduled_call: timer already cancelled");
|
||||
return;
|
||||
}
|
||||
beammp_lua_debugf("Cancelling timer");
|
||||
cancel_timer(timer);
|
||||
});
|
||||
// release the lua's reference to this timer
|
||||
timer.reset();
|
||||
};
|
||||
|
||||
glob["MP"]["GetOSName"] = &LuaAPI::MP::GetOSName;
|
||||
// glob["MP"]["GetTimeMS"] = &LuaAPI::MP::GetTimeMS;
|
||||
// glob["MP"]["GetTimeS"] = &LuaAPI::MP::GetTimeS;
|
||||
|
||||
glob.create_named("Util");
|
||||
glob["Util"]["JsonEncode"] = &LuaAPI::Util::JsonEncode;
|
||||
glob["Util"]["JsonDiff"] = &LuaAPI::Util::JsonDiff;
|
||||
glob["Util"]["JsonDiffApply"] = &LuaAPI::Util::JsonDiffApply;
|
||||
glob["Util"]["JsonPrettify"] = &LuaAPI::Util::JsonPrettify;
|
||||
glob["Util"]["JsonMinify"] = &LuaAPI::Util::JsonMinify;
|
||||
glob["Util"]["JsonFlatten"] = &LuaAPI::Util::JsonFlatten;
|
||||
glob["Util"]["JsonUnflatten"] = &LuaAPI::Util::JsonUnflatten;
|
||||
glob["Util"]["JsonDecode"] = &LuaAPI::Util::JsonDecode;
|
||||
|
||||
glob.create_named("FS");
|
||||
glob["FS"]["Exists"] = &LuaAPI::FS::Exists;
|
||||
glob["FS"]["CreateDirectory"] = &LuaAPI::FS::CreateDirectory;
|
||||
glob["FS"]["ConcatPaths"] = &LuaAPI::FS::ConcatPaths;
|
||||
glob["FS"]["IsFile"] = &LuaAPI::FS::IsFile;
|
||||
glob["FS"]["Remove"] = &LuaAPI::FS::Remove;
|
||||
glob["FS"]["GetFilename"] = &LuaAPI::FS::GetFilename;
|
||||
glob["FS"]["IsDirectory"] = &LuaAPI::FS::IsDirectory;
|
||||
glob["FS"]["GetExtensinon"] = &LuaAPI::FS::GetExtension;
|
||||
glob["FS"]["GetParentFolder"] = &LuaAPI::FS::GetParentFolder;
|
||||
glob["FS"]["Copy"] = &LuaAPI::FS::Copy;
|
||||
glob["FS"]["Rename"] = &LuaAPI::FS::Rename;
|
||||
glob["FS"]["ListFiles"] = &LuaAPI::FS::ListFiles;
|
||||
|
||||
glob["FS"]["PathSep"] = fmt::format("{}", char(std::filesystem::path::preferred_separator));
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::load_files() {
|
||||
// 1. look for main.lua, run that
|
||||
// 2. look for extensions in extensions/, load those.
|
||||
// make those globals based on the filename
|
||||
// 3. call onInit by name (global)
|
||||
auto extensions_folder = m_path / "extensions";
|
||||
if (std::filesystem::exists(extensions_folder)
|
||||
&& (std::filesystem::is_directory(extensions_folder)
|
||||
|| std::filesystem::is_symlink(extensions_folder))) {
|
||||
// TODO: Check that it points to a directory if its a symlink
|
||||
beammp_lua_debugf("Found extensions/: {}", extensions_folder);
|
||||
// load extensions from the folder, can't fail
|
||||
auto n = load_extensions(extensions_folder);
|
||||
beammp_lua_debugf("Loaded {} extensions.", n);
|
||||
beammp_lua_debugf("Set up file watcher to watch extensions folder for changes");
|
||||
// set up file watcher. this will watch for new extensions or for extensions which have
|
||||
// changed (via modification time).
|
||||
m_extensions_watcher.watch_files_in(extensions_folder);
|
||||
// set up callback for when an extension changes.
|
||||
// we simply reload the extension as if nothing happened :)
|
||||
m_extensions_watch_conn = m_extensions_watcher.sig_file_changed.connect(
|
||||
[this, extensions_folder](const std::filesystem::path& path) {
|
||||
if (path.extension() != ".lua") {
|
||||
return; // ignore
|
||||
}
|
||||
auto rel = std::filesystem::relative(path, extensions_folder).string();
|
||||
rel = boost::algorithm::replace_all_copy(rel, "/", "_");
|
||||
rel = boost::algorithm::replace_all_copy(rel, ".lua", "");
|
||||
if (!check_name_validity(rel)) {
|
||||
beammp_lua_errorf("Can't load/reload extension at path: {}. The resulting extension name would be invalid.", path);
|
||||
} else {
|
||||
load_extension(path, rel);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
beammp_lua_debugf("Plugin '{}' has no extensions.", name());
|
||||
}
|
||||
if (m_path != BEAMMP_MEMORY_STATE) {
|
||||
auto main_lua = m_path / "main.lua";
|
||||
if (std::filesystem::exists(main_lua)) {
|
||||
// TODO: Check that it's a regular file or symlink
|
||||
beammp_lua_debugf("Found main.lua: {}", main_lua.string());
|
||||
boost::asio::post(m_io, [this, main_lua] {
|
||||
try {
|
||||
m_state.safe_script_file(main_lua.string());
|
||||
} catch (const std::exception& e) {
|
||||
beammp_lua_errorf("Error running '{}': {}", main_lua.string(), e.what());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
beammp_lua_warnf("No 'main.lua' found, a plugin should have a 'main.lua'.");
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::initialize_overrides() {
|
||||
boost::asio::post(m_io, [this] {
|
||||
m_state.globals()["print"] = [this](sol::variadic_args args) {
|
||||
l_print(args);
|
||||
};
|
||||
});
|
||||
|
||||
Error err = fix_lua_paths();
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::fix_lua_paths() {
|
||||
std::stringstream lua_paths;
|
||||
std::stringstream lua_c_paths;
|
||||
std::vector<std::filesystem::path> relevant_paths = {
|
||||
m_path,
|
||||
m_path / "extensions",
|
||||
};
|
||||
for (const auto& Path : relevant_paths) {
|
||||
lua_paths << ";" << (Path / "?.lua").string();
|
||||
lua_paths << ";" << (Path / "lua/?.lua").string();
|
||||
#if WIN32
|
||||
lua_c_paths << ";" << (Path / "?.dll").string();
|
||||
lua_c_paths << ";" << (Path / "lib/?.dll").string();
|
||||
#else // unix
|
||||
lua_c_paths << ";" << (Path / "?.so").string();
|
||||
lua_c_paths << ";" << (Path / "lib/?.so").string();
|
||||
#endif
|
||||
}
|
||||
auto package_table = m_state.globals().get<sol::table>("package");
|
||||
package_table["path"] = package_table.get<std::string>("path") + lua_paths.str();
|
||||
package_table["cpath"] = package_table.get<std::string>("cpath") + lua_c_paths.str();
|
||||
m_state.globals()["package"] = package_table;
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void LuaPlugin::load_extension(const std::filesystem::path& file, const std::string& ext_name) {
|
||||
// we have to assume that load_extension may be called at any time, even to reload an existing extension.
|
||||
// thus, it cannot make assumptions about the plugin's status or state.
|
||||
beammp_lua_debugf("Loading extension '{}' from {}", ext_name, file);
|
||||
// save the extension in a list to make it queryable
|
||||
m_known_extensions->insert_or_assign(ext_name, file);
|
||||
// extension names, generated by the caller, must be valid lua identifiers
|
||||
if (!check_name_validity(ext_name)) {
|
||||
beammp_lua_errorf("Extension name '{}' is invalid. Please make sure the extension and it's folder(s) do not contain special characters, spaces, start with a digit, or similar.", ext_name);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto result = m_state.safe_script_file(file.string());
|
||||
if (!result.valid()) {
|
||||
beammp_lua_errorf("Error loading extension '{}' from {}. Running file resulted in invalid state: {}. Please check for errors in the lines before this message", ext_name, file, sol::to_string(result.status()));
|
||||
return;
|
||||
} else if (result.get_type() != sol::type::table) {
|
||||
beammp_lua_errorf("Error loading extension '{}' from {}: Expected extension to return a table, got {} instead.", ext_name, file, sol::type_name(m_state.lua_state(), result.get_type()));
|
||||
return;
|
||||
}
|
||||
auto M = result.get<sol::table>();
|
||||
m_state.globals()[ext_name] = M;
|
||||
} catch (const std::exception& e) {
|
||||
beammp_lua_errorf("Error loading extension '{}' from {}: {}", ext_name, file, e.what());
|
||||
return;
|
||||
}
|
||||
beammp_lua_debugf("Extension '{}' loaded!", ext_name);
|
||||
}
|
||||
|
||||
size_t LuaPlugin::load_extensions(const std::filesystem::path& extensions_folder, const std::string& base) {
|
||||
std::filesystem::directory_iterator iter(extensions_folder, s_directory_iteration_options);
|
||||
std::vector<std::filesystem::directory_entry> files;
|
||||
std::vector<std::filesystem::directory_entry> directories;
|
||||
for (const auto& entry : iter) {
|
||||
if (entry.is_directory()) {
|
||||
directories.push_back(entry);
|
||||
} else if (entry.is_regular_file()) {
|
||||
files.push_back(entry);
|
||||
} else {
|
||||
beammp_lua_tracef("{} is neither a file nor a directory, skipping", entry.path());
|
||||
}
|
||||
}
|
||||
// sort files alphabetically
|
||||
std::sort(files.begin(), files.end(), [&](const auto& a, const auto& b) {
|
||||
auto as = a.path().filename().string();
|
||||
auto bs = b.path().filename().string();
|
||||
return std::lexicographical_compare(as.begin(), as.end(), bs.begin(), bs.end());
|
||||
});
|
||||
for (const auto& file : files) {
|
||||
boost::asio::post(m_io, [this, base, file] {
|
||||
std::string ext_name;
|
||||
if (base.empty()) {
|
||||
ext_name = file.path().stem().string();
|
||||
} else {
|
||||
ext_name = fmt::format("{}_{}", base, file.path().stem().string());
|
||||
}
|
||||
load_extension(file, ext_name);
|
||||
});
|
||||
}
|
||||
std::sort(directories.begin(), directories.end(), [&](const auto& a, const auto& b) {
|
||||
auto as = a.path().filename().string();
|
||||
auto bs = b.path().filename().string();
|
||||
return std::lexicographical_compare(as.begin(), as.end(), bs.begin(), bs.end());
|
||||
});
|
||||
size_t count = 0;
|
||||
for (const auto& dir : directories) {
|
||||
std::string ext_name = dir.path().filename().string();
|
||||
std::filesystem::path path = dir.path();
|
||||
count += load_extensions(path, ext_name);
|
||||
}
|
||||
return count + files.size();
|
||||
}
|
||||
|
||||
void LuaPlugin::thread_main() {
|
||||
RegisterThread(name());
|
||||
beammp_lua_debugf("Waiting for initialization");
|
||||
// wait for interruption
|
||||
// we sleep for some time, which can be interrupted by a thread.interrupt(),
|
||||
// which will cause the sleep to throw a boost::thread_interrupted exception.
|
||||
// we (ab)use this to synchronize.
|
||||
try {
|
||||
boost::this_thread::sleep_for(boost::chrono::seconds(1));
|
||||
} catch (boost::thread_interrupted) {
|
||||
}
|
||||
beammp_lua_debugf("Initialized!");
|
||||
while (!*m_shutdown) {
|
||||
auto ran = m_io.run_for(std::chrono::seconds(5));
|
||||
// update the memory used by the Lua Plugin, then immediately resume execution of handlers
|
||||
if (ran != 0) {
|
||||
*m_memory = m_state.memory_used();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Error LuaPlugin::initialize() {
|
||||
Error err = initialize_error_handlers();
|
||||
if (err) {
|
||||
return { "Failed to initialize error handlers: {}", err };
|
||||
}
|
||||
err = initialize_libraries();
|
||||
if (err) {
|
||||
return { "Failed to initialize libraries: {}", err };
|
||||
}
|
||||
err = initialize_overrides();
|
||||
if (err) {
|
||||
return { "Failed to initialize overrides: {}", err };
|
||||
}
|
||||
err = load_files();
|
||||
if (err) {
|
||||
return { "Failed to load initial files: {}", err };
|
||||
}
|
||||
|
||||
// interrupt the thread, signalling it to start
|
||||
m_thread.interrupt();
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::cleanup() {
|
||||
// TODO
|
||||
return {};
|
||||
}
|
||||
|
||||
Error LuaPlugin::reload() {
|
||||
// TODO
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string LuaPlugin::name() const {
|
||||
return m_path.stem().string();
|
||||
}
|
||||
|
||||
std::filesystem::path LuaPlugin::path() const {
|
||||
return m_path;
|
||||
}
|
||||
|
||||
std::shared_future<std::vector<Value>> LuaPlugin::handle_event(const std::string& event_name, const std::shared_ptr<Value>& args) {
|
||||
std::shared_ptr<std::promise<std::vector<Value>>> promise = std::make_shared<std::promise<std::vector<Value>>>();
|
||||
std::shared_future<std::vector<Value>> futures { promise->get_future() };
|
||||
boost::asio::post(m_io, [this, event_name, args, promise, futures] {
|
||||
std::vector<Value> results {};
|
||||
if (m_event_handlers_named.contains(event_name)) {
|
||||
auto handler_names = m_event_handlers_named.at(event_name);
|
||||
for (const auto& handler_name : handler_names) {
|
||||
try {
|
||||
if (m_state.globals()[handler_name].valid() && m_state.globals()[handler_name].get_type() == sol::type::function) {
|
||||
auto fn = m_state.globals().get<sol::protected_function>(handler_name);
|
||||
fn.set_error_handler(m_state.globals()[ERR_HANDLER]);
|
||||
auto lua_args = boost::apply_visitor(ValueToLuaVisitor(m_state), *args);
|
||||
sol::protected_function_result res;
|
||||
|
||||
if (args->which() == VALUE_TYPE_IDX_TUPLE) {
|
||||
res = fn(sol::as_args(lua_args.as<std::vector<sol::object>>()));
|
||||
} else {
|
||||
res = fn(lua_args);
|
||||
}
|
||||
if (res.valid()) {
|
||||
auto maybe_res = sol_obj_to_value(res.get<sol::object>());
|
||||
if (maybe_res) {
|
||||
results.emplace_back(maybe_res.move());
|
||||
} else {
|
||||
beammp_lua_errorf("Error using return value from event handler '{}' for event '{}': {}", handler_name, event_name, maybe_res.error);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
beammp_lua_errorf("Invalid event handler '{}' for event '{}': Handler either doesn't exist or isn't a global function", handler_name, event_name);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_lua_errorf("Error finding and running event handler for event '{}': {}. It was called with argument(s): {}", event_name, e.what(), boost::apply_visitor(ValueToStringVisitor(), *args));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (m_event_handlers.contains(event_name)) {
|
||||
auto handlers = m_event_handlers.at(event_name);
|
||||
for (const auto& fn : handlers) {
|
||||
try {
|
||||
auto lua_args = boost::apply_visitor(ValueToLuaVisitor(m_state), *args);
|
||||
sol::protected_function_result res;
|
||||
|
||||
if (args->which() == VALUE_TYPE_IDX_TUPLE) {
|
||||
res = fn(sol::as_args(lua_args.as<std::vector<sol::object>>()));
|
||||
} else {
|
||||
res = fn(lua_args);
|
||||
}
|
||||
if (res.valid()) {
|
||||
auto maybe_res = sol_obj_to_value(res.get<sol::object>());
|
||||
if (maybe_res) {
|
||||
results.emplace_back(maybe_res.move());
|
||||
} else {
|
||||
beammp_lua_errorf("Error using return value from event handler '<<lua function {:p}>>' for event '{}': {}", fn.pointer(), event_name, maybe_res.error);
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_lua_errorf("Error finding and running event handler for event '{}': {}. It was called with argument(s): {}", event_name, e.what(), boost::apply_visitor(ValueToStringVisitor(), *args));
|
||||
}
|
||||
}
|
||||
}
|
||||
promise->set_value(std::move(results));
|
||||
});
|
||||
return futures;
|
||||
}
|
||||
|
||||
size_t LuaPlugin::memory_usage() const {
|
||||
return *m_memory;
|
||||
}
|
||||
|
||||
std::shared_ptr<Timer> LuaPlugin::make_timer(size_t ms) {
|
||||
m_timers.push_back(std::make_shared<Timer>(boost::asio::deadline_timer(m_io), ms));
|
||||
auto timer = m_timers.back();
|
||||
timer->timer.expires_from_now(timer->interval);
|
||||
std::sort(m_timers.begin(), m_timers.end());
|
||||
return timer;
|
||||
}
|
||||
|
||||
void LuaPlugin::cancel_timer(const std::shared_ptr<Timer>& timer) {
|
||||
auto iter = std::find(m_timers.begin(), m_timers.end(), timer);
|
||||
if (iter != m_timers.end()) {
|
||||
m_timers.erase(iter);
|
||||
timer->timer.cancel();
|
||||
} else {
|
||||
timer->timer.cancel();
|
||||
beammp_lua_debugf("Failed to remove timer (already removed)");
|
||||
}
|
||||
}
|
||||
|
||||
void LuaPlugin::l_print(const sol::variadic_args& args) {
|
||||
auto result = print_impl({ args.begin(), args.end() });
|
||||
beammp_lua_infof("{}", result);
|
||||
}
|
||||
|
||||
void LuaPlugin::l_mp_schedule_call_helper(const boost::system::error_code& err, std::shared_ptr<Timer> timer, const sol::function& fn, std::shared_ptr<ValueTuple> args) {
|
||||
if (err) {
|
||||
beammp_lua_debugf("MP.schedule_call_repeat: {}", err.what());
|
||||
return;
|
||||
}
|
||||
timer->timer.expires_from_now(timer->interval);
|
||||
sol::protected_function prot(fn);
|
||||
prot.set_error_handler(m_state.globals()[ERR_HANDLER]);
|
||||
std::vector<sol::object> objs;
|
||||
objs.reserve(args->size());
|
||||
for (const auto& val : *args) {
|
||||
objs.push_back(boost::apply_visitor(ValueToLuaVisitor(m_state), val));
|
||||
}
|
||||
prot(sol::as_args(objs));
|
||||
timer->timer.async_wait([this, timer, fn, args](const auto& err) {
|
||||
l_mp_schedule_call_helper(err, timer, fn, args);
|
||||
});
|
||||
}
|
||||
|
||||
void LuaPlugin::l_mp_schedule_call_once(size_t ms, const sol::function& fn, sol::variadic_args args) {
|
||||
auto timer = make_timer(ms);
|
||||
std::vector<sol::object> args_vec(args.begin(), args.end());
|
||||
std::shared_ptr<ValueTuple> tuple = std::make_shared<ValueTuple>();
|
||||
tuple->reserve(args_vec.size());
|
||||
for (const auto& obj : args_vec) {
|
||||
auto res = sol_obj_to_value(obj);
|
||||
if (res) [[likely]] {
|
||||
tuple->emplace_back(res.move());
|
||||
} else {
|
||||
beammp_lua_errorf("Can't serialize an argument across boundaries (for passing to a MP.schedule_call_* later): ", res.error);
|
||||
tuple->emplace_back(Null {});
|
||||
}
|
||||
}
|
||||
timer->timer.async_wait([this, timer, fn, tuple](const auto& err) {
|
||||
if (err) {
|
||||
beammp_lua_debugf("MP.schedule_call_once: {}", err.what());
|
||||
return;
|
||||
}
|
||||
sol::protected_function prot(fn);
|
||||
prot.set_error_handler(m_state.globals()[ERR_HANDLER]);
|
||||
std::vector<sol::object> objs;
|
||||
objs.reserve(tuple->size());
|
||||
for (const auto& val : *tuple) {
|
||||
objs.push_back(boost::apply_visitor(ValueToLuaVisitor(m_state), val));
|
||||
}
|
||||
beammp_lua_debugf("Calling with {} args", objs.size());
|
||||
prot(sol::as_args(objs));
|
||||
cancel_timer(timer);
|
||||
});
|
||||
}
|
||||
|
||||
std::shared_ptr<Timer> LuaPlugin::l_mp_schedule_call_repeat(size_t ms, const sol::function& fn, sol::variadic_args args) {
|
||||
auto timer = make_timer(ms);
|
||||
// TODO: Cleanly transfer invalid objects
|
||||
std::vector<sol::object> args_vec(args.begin(), args.end());
|
||||
std::shared_ptr<ValueTuple> tuple = std::make_shared<ValueTuple>();
|
||||
tuple->reserve(args_vec.size());
|
||||
for (const auto& obj : args_vec) {
|
||||
auto res = sol_obj_to_value(obj);
|
||||
if (res) [[likely]] {
|
||||
tuple->emplace_back(res.move());
|
||||
} else {
|
||||
beammp_lua_errorf("Can't serialize an argument across boundaries (for passing to a MP.schedule_call_* later): ", res.error);
|
||||
tuple->emplace_back(Null {});
|
||||
}
|
||||
}
|
||||
timer->timer.async_wait([this, timer, fn, tuple](const auto& err) {
|
||||
l_mp_schedule_call_helper(err, timer, fn, tuple);
|
||||
});
|
||||
return timer;
|
||||
}
|
||||
|
||||
std::string LuaPlugin::print_impl(const std::vector<sol::object>& obj_args) {
|
||||
std::string result {};
|
||||
result.reserve(500);
|
||||
|
||||
// used as the invalid value provider in sol_obj_to_value.
|
||||
auto special_stringifier = [](const sol::object& object) -> Result<Value> {
|
||||
switch (object.get_type()) {
|
||||
case sol::type::none:
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::string:
|
||||
case sol::type::number:
|
||||
case sol::type::boolean:
|
||||
case sol::type::table:
|
||||
// covered by value to string visitor
|
||||
break;
|
||||
case sol::type::thread:
|
||||
return { fmt::format("<<lua thread: {:p}>>", object.pointer()) };
|
||||
case sol::type::function:
|
||||
return { fmt::format("<<lua function: {:p}>>", object.pointer()) };
|
||||
case sol::type::userdata:
|
||||
return { fmt::format("<<lua userdata: {:p}>>", object.pointer()) };
|
||||
case sol::type::lightuserdata:
|
||||
return { fmt::format("<<lua lightuserdata: {:p}>>", object.pointer()) };
|
||||
case sol::type::poly:
|
||||
return { fmt::format("<<lua poly: {:p}>>", object.pointer()) };
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return { fmt::format("<<lua unknown type: {:p}>>", object.pointer()) };
|
||||
};
|
||||
|
||||
for (const auto& obj : obj_args) {
|
||||
auto maybe_val = sol_obj_to_value(obj, special_stringifier);
|
||||
if (maybe_val) {
|
||||
result += boost::apply_visitor(ValueToStringVisitor(ValueToStringVisitor::Flag::NONE), maybe_val.move());
|
||||
result += " ";
|
||||
} else {
|
||||
beammp_lua_errorf("Failed to print() an argument: {}", maybe_val.error);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void LuaPlugin::run_raw_lua(const std::string& raw) {
|
||||
if (raw.empty()) {
|
||||
return;
|
||||
}
|
||||
std::string id = "";
|
||||
if (raw.size() < 5) {
|
||||
id = raw;
|
||||
} else {
|
||||
id = raw.substr(0, 5) + "...";
|
||||
}
|
||||
boost::asio::post(m_io, [this, raw, id] {
|
||||
try {
|
||||
beammp_debugf("Running '{}'", raw);
|
||||
auto res = m_state.safe_script(raw, id);
|
||||
if (res.valid()) {
|
||||
std::vector<sol::object> args;
|
||||
args.push_back(res.get<sol::object>());
|
||||
auto str = print_impl(args);
|
||||
Application::Console().WriteRaw(fmt::format("=> {}", str));
|
||||
}
|
||||
} catch (const sol::error& err) {
|
||||
beammp_lua_errorf("Error: {}", err.what());
|
||||
}
|
||||
});
|
||||
}
|
||||
-1254
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "SignalHandling.h"
|
||||
#include "Common.h"
|
||||
|
||||
|
||||
+53
-88
@@ -1,25 +1,6 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
#include "TConfig.h"
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
@@ -27,29 +8,16 @@
|
||||
|
||||
// General
|
||||
static constexpr std::string_view StrDebug = "Debug";
|
||||
static constexpr std::string_view EnvStrDebug = "BEAMMP_DEBUG";
|
||||
static constexpr std::string_view StrPrivate = "Private";
|
||||
static constexpr std::string_view EnvStrPrivate = "BEAMMP_PRIVATE";
|
||||
static constexpr std::string_view StrPort = "Port";
|
||||
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
|
||||
static constexpr std::string_view StrMaxCars = "MaxCars";
|
||||
static constexpr std::string_view EnvStrMaxCars = "BEAMMP_MAX_CARS";
|
||||
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
|
||||
static constexpr std::string_view EnvStrMaxPlayers = "BEAMMP_MAX_PLAYERS";
|
||||
static constexpr std::string_view StrMap = "Map";
|
||||
static constexpr std::string_view EnvStrMap = "BEAMMP_MAP";
|
||||
static constexpr std::string_view StrName = "Name";
|
||||
static constexpr std::string_view EnvStrName = "BEAMMP_NAME";
|
||||
static constexpr std::string_view StrDescription = "Description";
|
||||
static constexpr std::string_view EnvStrDescription = "BEAMMP_DESCRIPTION";
|
||||
static constexpr std::string_view StrTags = "Tags";
|
||||
static constexpr std::string_view EnvStrTags = "BEAMMP_TAGS";
|
||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||
static constexpr std::string_view EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
|
||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
|
||||
static constexpr std::string_view StrLogChat = "LogChat";
|
||||
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
|
||||
static constexpr std::string_view StrPassword = "Password";
|
||||
|
||||
// Misc
|
||||
@@ -57,6 +25,14 @@ static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
|
||||
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
|
||||
|
||||
// HTTP
|
||||
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
|
||||
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
|
||||
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
|
||||
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
|
||||
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
|
||||
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
|
||||
|
||||
TEST_CASE("TConfig::TConfig") {
|
||||
const std::string CfgFile = "beammp_server_testconfig.toml";
|
||||
fs::remove(CfgFile);
|
||||
@@ -80,6 +56,7 @@ TEST_CASE("TConfig::TConfig") {
|
||||
const auto table = toml::parse(CfgFile);
|
||||
CHECK(table.at("General").is_table());
|
||||
CHECK(table.at("Misc").is_table());
|
||||
CHECK(table.at("HTTP").is_table());
|
||||
|
||||
fs::remove(CfgFile);
|
||||
}
|
||||
@@ -125,26 +102,34 @@ void TConfig::FlushToFile() {
|
||||
data["General"][StrPrivate.data()] = Application::Settings.Private;
|
||||
data["General"][StrPort.data()] = Application::Settings.Port;
|
||||
data["General"][StrName.data()] = Application::Settings.ServerName;
|
||||
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
|
||||
data["General"][StrTags.data()] = Application::Settings.ServerTags;
|
||||
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
|
||||
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
|
||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||
// data["General"][StrPassword.data()] = Application::Settings.Password;
|
||||
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
|
||||
data["General"][StrPassword.data()] = Application::Settings.Password;
|
||||
SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
|
||||
// Misc
|
||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
|
||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
|
||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
|
||||
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
|
||||
// HTTP
|
||||
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
|
||||
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
|
||||
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
|
||||
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
|
||||
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
|
||||
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
|
||||
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
|
||||
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
|
||||
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
|
||||
std::stringstream Ss;
|
||||
Ss << "# This is the BeamMP-Server config file.\n"
|
||||
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
|
||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
|
||||
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n"
|
||||
<< data;
|
||||
auto File = std::fopen(mConfigFileName.c_str(), "w+");
|
||||
if (!File) {
|
||||
@@ -174,38 +159,19 @@ void TConfig::CreateConfigFile() {
|
||||
FlushToFile();
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) {
|
||||
if (!Env.empty()) {
|
||||
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||
OutValue = std::string(envp);
|
||||
return;
|
||||
}
|
||||
}
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_string()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_string();
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
|
||||
if (!Env.empty()) {
|
||||
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||
auto Str = std::string(envp);
|
||||
OutValue = Str == "1" || Str == "true";
|
||||
return;
|
||||
}
|
||||
}
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_boolean()) {
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
|
||||
}
|
||||
}
|
||||
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
|
||||
if (!Env.empty()) {
|
||||
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
|
||||
OutValue = int(std::strtol(envp, nullptr, 10));
|
||||
return;
|
||||
}
|
||||
}
|
||||
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) {
|
||||
if (Table[Category.c_str()][Key.data()].is_integer()) {
|
||||
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
|
||||
}
|
||||
@@ -215,23 +181,29 @@ void TConfig::ParseFromFile(std::string_view name) {
|
||||
try {
|
||||
toml::value data = toml::parse<toml::preserve_comments>(name.data());
|
||||
// GENERAL
|
||||
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
|
||||
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
|
||||
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
|
||||
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
|
||||
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
|
||||
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
|
||||
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
|
||||
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
|
||||
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
|
||||
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
|
||||
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
|
||||
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
|
||||
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
|
||||
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled);
|
||||
TryReadValue(data, "General", StrPrivate, Application::Settings.Private);
|
||||
TryReadValue(data, "General", StrPort, Application::Settings.Port);
|
||||
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars);
|
||||
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||
TryReadValue(data, "General", StrMap, Application::Settings.MapName);
|
||||
TryReadValue(data, "General", StrName, Application::Settings.ServerName);
|
||||
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc);
|
||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||
TryReadValue(data, "General", StrPassword, Application::Settings.Password);
|
||||
// Misc
|
||||
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
|
||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
|
||||
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled);
|
||||
// HTTP
|
||||
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
|
||||
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
|
||||
} catch (const std::exception& err) {
|
||||
beammp_error("Error parsing config file value: " + std::string(err.what()));
|
||||
mFailed = true;
|
||||
@@ -264,9 +236,12 @@ void TConfig::PrintDebug() {
|
||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
|
||||
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
|
||||
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
|
||||
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
|
||||
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
|
||||
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
|
||||
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
|
||||
// special!
|
||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
|
||||
@@ -324,13 +299,3 @@ void TConfig::ParseOldFormat() {
|
||||
Str >> std::ws;
|
||||
}
|
||||
}
|
||||
std::string TConfig::TagsAsPrettyArray() const {
|
||||
std::vector<std::string> TagsArray = {};
|
||||
SplitString(Application::Settings.ServerTags, ',', TagsArray);
|
||||
std::string Pretty = {};
|
||||
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
|
||||
Pretty += '\"' + TagsArray[i] + "\", ";
|
||||
}
|
||||
Pretty += '\"' + TagsArray.at(TagsArray.size() - 1) + "\"";
|
||||
return Pretty;
|
||||
}
|
||||
|
||||
+78
-95
@@ -1,27 +1,11 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TConsole.h"
|
||||
#include "Common.h"
|
||||
#include "Compat.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <ctime>
|
||||
#include <mutex>
|
||||
@@ -68,6 +52,17 @@ TEST_CASE("TrimString") {
|
||||
CHECK(TrimString("") == "");
|
||||
}
|
||||
|
||||
// TODO: add unit tests to SplitString
|
||||
static inline void SplitString(std::string const& str, const char delim, std::vector<std::string>& out) {
|
||||
size_t start;
|
||||
size_t end = 0;
|
||||
|
||||
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
|
||||
end = str.find(delim, start);
|
||||
out.push_back(str.substr(start, end - start));
|
||||
}
|
||||
}
|
||||
|
||||
static std::string GetDate() {
|
||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||
@@ -153,7 +148,6 @@ void TConsole::StartLoggingToFile() {
|
||||
|
||||
void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
||||
if (!mIsLuaConsole) {
|
||||
/*
|
||||
if (!mLuaEngine) {
|
||||
beammp_error("Lua engine not initialized yet, please wait and try again");
|
||||
return;
|
||||
@@ -163,13 +157,13 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
||||
mIsLuaConsole = true;
|
||||
if (mStateId != mDefaultStateId) {
|
||||
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`");
|
||||
mCommandline->set_prompt("lua @" + LuaStateId + "> ");
|
||||
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
||||
} else {
|
||||
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
|
||||
mCommandline->set_prompt("lua> ");
|
||||
mCommandline.set_prompt("lua> ");
|
||||
}
|
||||
mCachedRegularHistory = mCommandline->history();
|
||||
mCommandline->set_history(mCachedLuaHistory);*/
|
||||
mCachedRegularHistory = mCommandline.history();
|
||||
mCommandline.set_history(mCachedLuaHistory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,9 +175,9 @@ void TConsole::ChangeToRegularConsole() {
|
||||
} else {
|
||||
Application::Console().WriteRaw("Detached from Lua.");
|
||||
}
|
||||
mCachedLuaHistory = mCommandline->history();
|
||||
mCommandline->set_history(mCachedRegularHistory);
|
||||
mCommandline->set_prompt("> ");
|
||||
mCachedLuaHistory = mCommandline.history();
|
||||
mCommandline.set_history(mCachedRegularHistory);
|
||||
mCommandline.set_prompt("> ");
|
||||
mStateId = mDefaultStateId;
|
||||
}
|
||||
}
|
||||
@@ -222,17 +216,13 @@ void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& a
|
||||
if (args.size() == 1) {
|
||||
auto NewStateId = args.at(0);
|
||||
beammp_assert(!NewStateId.empty());
|
||||
// TODO: This must be implemented
|
||||
/*
|
||||
if (mLuaEngine->HasState(NewStateId)) {
|
||||
ChangeToLuaConsole(NewStateId);
|
||||
} else {
|
||||
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
|
||||
}
|
||||
*/
|
||||
} else if (args.size() == 0) {
|
||||
ChangeToLuaConsole(mDefaultStateId);
|
||||
// CONTINUE HERE
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,7 +257,7 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
|
||||
if (!EnsureArgsCount(args, 0, size_t(-1))) {
|
||||
return;
|
||||
}
|
||||
mCommandline->write("\x1b[;H\x1b[2J");
|
||||
mCommandline.write("\x1b[;H\x1b[2J");
|
||||
}
|
||||
|
||||
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
|
||||
@@ -287,15 +277,17 @@ 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))); });
|
||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||
};
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||
if (NameCompare(Client->Name.get(), Name)) {
|
||||
mLuaEngine->Network().ClientKick(*Client, Reason);
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
if (NameCompare(locked->GetName(), Name)) {
|
||||
mLuaEngine->Network().ClientKick(*locked, Reason);
|
||||
Kicked = true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});*/
|
||||
});
|
||||
if (!Kicked) {
|
||||
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
|
||||
} else {
|
||||
@@ -378,24 +370,23 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
|
||||
if (!EnsureArgsCount(args, 0)) {
|
||||
return;
|
||||
}
|
||||
// Implement once running
|
||||
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
|
||||
/*
|
||||
if (mLuaEngine->Server().ClientCount() == 0) {
|
||||
Application::Console().WriteRaw("No players online.");
|
||||
} else {
|
||||
std::stringstream ss;
|
||||
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
|
||||
mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
|
||||
ss << std::left << std::setw(25) << Client->Name.get()
|
||||
<< std::setw(6) << Client->ID.get()
|
||||
<< std::setw(6) << Client->GetCarCount() << "\n";
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto locked = Client.lock();
|
||||
ss << std::left << std::setw(25) << locked->GetName()
|
||||
<< std::setw(6) << locked->GetID()
|
||||
<< std::setw(6) << locked->GetCarCount() << "\n";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
auto Str = ss.str();
|
||||
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
|
||||
@@ -404,6 +395,29 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
}
|
||||
std::stringstream Status;
|
||||
|
||||
size_t CarCount = 0;
|
||||
size_t ConnectedCount = 0;
|
||||
size_t GuestCount = 0;
|
||||
size_t SyncedCount = 0;
|
||||
size_t SyncingCount = 0;
|
||||
size_t MissedPacketQueueSum = 0;
|
||||
int LargestSecondsSinceLastPing = 0;
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
if (!Client.expired()) {
|
||||
auto Locked = Client.lock();
|
||||
CarCount += Locked->GetCarCount();
|
||||
ConnectedCount += Locked->IsConnected() ? 1 : 0;
|
||||
GuestCount += Locked->IsGuest() ? 1 : 0;
|
||||
SyncedCount += Locked->IsSynced() ? 1 : 0;
|
||||
SyncingCount += Locked->IsSyncing() ? 1 : 0;
|
||||
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
|
||||
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
|
||||
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
size_t SystemsStarting = 0;
|
||||
size_t SystemsGood = 0;
|
||||
size_t SystemsBad = 0;
|
||||
@@ -448,22 +462,15 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
|
||||
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
|
||||
|
||||
auto ElapsedTime = mUptimeTimer.GetElapsedTime();
|
||||
|
||||
/*
|
||||
auto network = mLuaEngine->Network();
|
||||
auto clients = network->all_clients();
|
||||
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
|
||||
|
||||
Status << "BeamMP-Server Status:\n"
|
||||
<< "\tTotal Players: " << clients.size() << "\n"
|
||||
<< "\tPlayers identifying: " << network->clients_in_state_count(bmp::State::Identification) << "\n"
|
||||
<< "\tPlayers authenticating: " << network->clients_in_state_count(bmp::State::Authentication) << "\n"
|
||||
<< "\tPlayers downloading mods: " << network->clients_in_state_count(bmp::State::ModDownload) << "\n"
|
||||
<< "\tPlayers spawning in: " << network->clients_in_state_count(bmp::State::SessionSetup) << "\n"
|
||||
<< "\tPlayers playing: " << network->clients_in_state_count(bmp::State::Playing) << "\n"
|
||||
<< "\tPlayers leaving: " << network->clients_in_state_count(bmp::State::Leaving) << "\n"
|
||||
<< "\tGuests: " << network->guest_count() << "\n"
|
||||
<< "\tVehicles: " << network->vehicle_count() << "\n"
|
||||
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
|
||||
<< "\tSyncing Players: " << SyncingCount << "\n"
|
||||
<< "\tSynced Players: " << SyncedCount << "\n"
|
||||
<< "\tConnected Players: " << ConnectedCount << "\n"
|
||||
<< "\tGuests: " << GuestCount << "\n"
|
||||
<< "\tCars: " << CarCount << "\n"
|
||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||
<< "\tLua:\n"
|
||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||
@@ -478,13 +485,12 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
|
||||
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
|
||||
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
|
||||
<< "";*/
|
||||
<< "";
|
||||
|
||||
Application::Console().WriteRaw(Status.str());
|
||||
}
|
||||
|
||||
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
/*
|
||||
auto FutureIsNonNil =
|
||||
[](const std::shared_ptr<TLuaResult>& Future) {
|
||||
if (!Future->Error && Future->Result.valid()) {
|
||||
@@ -528,11 +534,9 @@ void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
|
||||
}
|
||||
Application::Console().WriteRaw(Reply.str());
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
void TConsole::HandleLuaInternalCommand(const std::string& cmd) {
|
||||
/*
|
||||
if (cmd == "exit") {
|
||||
ChangeToRegularConsole();
|
||||
} else if (cmd == "queued") {
|
||||
@@ -582,26 +586,20 @@ Commands
|
||||
} else {
|
||||
beammp_error("internal command '" + cmd + "' is not known");
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
TConsole::TConsole() {
|
||||
}
|
||||
|
||||
void TConsole::InitializeCommandline() {
|
||||
mCommandline = std::make_unique<Commandline>();
|
||||
mCommandline->enable_history();
|
||||
mCommandline->set_history_limit(20);
|
||||
mCommandline->set_prompt("> ");
|
||||
mCommandline.enable_history();
|
||||
mCommandline.set_history_limit(20);
|
||||
mCommandline.set_prompt("> ");
|
||||
BackupOldLog();
|
||||
mCommandline->on_command = [this](Commandline& c) {
|
||||
mCommandline.on_command = [this](Commandline& c) {
|
||||
try {
|
||||
auto TrimmedCmd = c.get_command();
|
||||
TrimmedCmd = TrimString(TrimmedCmd);
|
||||
auto [cmd, args] = ParseCommand(TrimmedCmd);
|
||||
mCommandline->write(mCommandline->prompt() + TrimmedCmd);
|
||||
mCommandline.write(mCommandline.prompt() + TrimmedCmd);
|
||||
if (mIsLuaConsole) {
|
||||
/*
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else if (!cmd.empty() && cmd.at(0) == ':') {
|
||||
@@ -613,9 +611,7 @@ void TConsole::InitializeCommandline() {
|
||||
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
|
||||
}
|
||||
}
|
||||
*/
|
||||
} else {
|
||||
/*
|
||||
if (!mLuaEngine) {
|
||||
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
|
||||
} else if (cmd == "exit") {
|
||||
@@ -631,17 +627,16 @@ void TConsole::InitializeCommandline() {
|
||||
} else {
|
||||
RunAsCommand(TrimmedCmd);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||
}
|
||||
};
|
||||
mCommandline->on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||
std::vector<std::string> suggestions;
|
||||
try {
|
||||
if (mIsLuaConsole) { // if lua
|
||||
/*
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else {
|
||||
@@ -663,6 +658,7 @@ void TConsole::InitializeCommandline() {
|
||||
if (stub.rfind('.') != stub.size() - 1 && !tablekeys.empty()) {
|
||||
tablekeys.pop_back();
|
||||
}
|
||||
|
||||
auto keys = mLuaEngine->GetStateTableKeysForState(mStateId, tablekeys);
|
||||
|
||||
for (const auto& key : keys) { // go through each bottom-level key
|
||||
@@ -678,18 +674,17 @@ void TConsole::InitializeCommandline() {
|
||||
suggestions.push_back(prefix + before_last_atom + key);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
}
|
||||
} else { // if not lua
|
||||
if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
|
||||
std::string after_prefix = TrimString(stub.substr(3));
|
||||
/*auto stateNames = mLuaEngine->GetLuaStateNames();
|
||||
auto stateNames = mLuaEngine->GetLuaStateNames();
|
||||
|
||||
for (const auto& name : stateNames) {
|
||||
if (name.find(after_prefix) == 0) {
|
||||
suggestions.push_back("lua " + name);
|
||||
}
|
||||
}
|
||||
*/
|
||||
} else {
|
||||
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||
if (cmd_name.find(stub) == 0) {
|
||||
@@ -708,25 +703,13 @@ void TConsole::InitializeCommandline() {
|
||||
|
||||
void TConsole::Write(const std::string& str) {
|
||||
auto ToWrite = GetDate() + str;
|
||||
// allows writing to stdout without an initialized console
|
||||
if (mCommandline) {
|
||||
mCommandline->write(ToWrite);
|
||||
} else {
|
||||
std::cout << ToWrite << std::endl;
|
||||
}
|
||||
mCommandline.write(ToWrite);
|
||||
}
|
||||
|
||||
void TConsole::WriteRaw(const std::string& str) {
|
||||
// allows writing to stdout without an initialized console
|
||||
if (mCommandline) {
|
||||
mCommandline->write(str);
|
||||
} else {
|
||||
std::cout << str << std::endl;
|
||||
}
|
||||
mCommandline.write(str);
|
||||
}
|
||||
|
||||
/*
|
||||
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
|
||||
mLuaEngine = &Engine;
|
||||
}
|
||||
*/
|
||||
|
||||
+20
-32
@@ -1,25 +1,8 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "THeartbeatThread.h"
|
||||
|
||||
#include "Client.h"
|
||||
#include "Http.h"
|
||||
// #include "SocketIO.h"
|
||||
//#include "SocketIO.h"
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/rapidjson.h>
|
||||
#include <sstream>
|
||||
@@ -138,7 +121,7 @@ std::string THeartbeatThread::GenerateCall() {
|
||||
std::stringstream Ret;
|
||||
|
||||
Ret << "uuid=" << Application::Settings.Key
|
||||
<< "&players=" << m_network->authenticated_client_count()
|
||||
<< "&players=" << mServer.ClientCount()
|
||||
<< "&maxplayers=" << Application::Settings.MaxPlayers
|
||||
<< "&port=" << Application::Settings.Port
|
||||
<< "&map=" << Application::Settings.MapName
|
||||
@@ -146,17 +129,17 @@ std::string THeartbeatThread::GenerateCall() {
|
||||
<< "&version=" << Application::ServerVersionString()
|
||||
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
|
||||
<< "&name=" << Application::Settings.ServerName
|
||||
<< "&tags=" << Application::Settings.ServerTags
|
||||
<< "&modlist=" << "-"//mResourceManager.TrimmedList()
|
||||
<< "&modstotalsize=" << 0 //mResourceManager.MaxModSize()
|
||||
<< "&modstotal=" << 0 // mResourceManager.ModsLoaded()
|
||||
<< "&modlist=" << mResourceManager.TrimmedList()
|
||||
<< "&modstotalsize=" << mResourceManager.MaxModSize()
|
||||
<< "&modstotal=" << mResourceManager.ModsLoaded()
|
||||
<< "&playerslist=" << GetPlayers()
|
||||
<< "&desc=" << Application::Settings.ServerDesc
|
||||
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
|
||||
return Ret.str();
|
||||
}
|
||||
THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
|
||||
: m_network(std::move(network)) {
|
||||
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
|
||||
: mResourceManager(ResourceManager)
|
||||
, mServer(Server) {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
|
||||
@@ -168,10 +151,15 @@ THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
|
||||
Start();
|
||||
}
|
||||
std::string THeartbeatThread::GetPlayers() {
|
||||
std::string players;
|
||||
for (const auto& [id, client] : m_network->authenticated_clients()) {
|
||||
players += client->name.get() + ";";
|
||||
}
|
||||
return players;
|
||||
std::string Return;
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
Return += ClientPtr.lock()->GetName() + ";";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return Return;
|
||||
}
|
||||
|
||||
/*THeartbeatThread::~THeartbeatThread() {
|
||||
}*/
|
||||
|
||||
+1103
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
#include "TLuaPlugin.h"
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
#include <utility>
|
||||
|
||||
TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder)
|
||||
: mConfig(Config)
|
||||
, mEngine(Engine)
|
||||
, mFolder(MainFolder)
|
||||
, mPluginName(MainFolder.stem().string())
|
||||
, mFileContents(0) {
|
||||
beammp_debug("Lua plugin \"" + mPluginName + "\" starting in \"" + mFolder.string() + "\"");
|
||||
std::vector<fs::path> Entries;
|
||||
for (const auto& Entry : fs::directory_iterator(mFolder)) {
|
||||
if (Entry.is_regular_file() && Entry.path().extension() == ".lua") {
|
||||
Entries.push_back(Entry);
|
||||
}
|
||||
}
|
||||
// sort alphabetically (not needed if config is used to determine call order)
|
||||
// TODO: Use config to figure out what to run in which order
|
||||
std::sort(Entries.begin(), Entries.end(), [](const fs::path& first, const fs::path& second) {
|
||||
auto firstStr = first.string();
|
||||
auto secondStr = second.string();
|
||||
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
|
||||
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
|
||||
return firstStr < secondStr;
|
||||
});
|
||||
std::vector<std::pair<fs::path, std::shared_ptr<TLuaResult>>> ResultsToCheck;
|
||||
for (const auto& Entry : Entries) {
|
||||
// read in entire file
|
||||
try {
|
||||
std::ifstream FileStream(Entry.string(), std::ios::in | std::ios::binary);
|
||||
auto Size = std::filesystem::file_size(Entry);
|
||||
auto Contents = std::make_shared<std::string>();
|
||||
Contents->resize(Size);
|
||||
FileStream.read(Contents->data(), Contents->size());
|
||||
mFileContents[fs::relative(Entry).string()] = Contents;
|
||||
// Execute first time
|
||||
auto Result = mEngine.EnqueueScript(mConfig.StateId, TLuaChunk(Contents, Entry.string(), MainFolder.string()));
|
||||
ResultsToCheck.emplace_back(Entry.string(), std::move(Result));
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Error loading file \"" + Entry.string() + "\": " + e.what());
|
||||
}
|
||||
}
|
||||
for (auto& Result : ResultsToCheck) {
|
||||
Result.second->WaitUntilReady();
|
||||
if (Result.second->Error) {
|
||||
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Result.second->ErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,999 @@
|
||||
#include "TNetwork.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "TLuaEngine.h"
|
||||
#include "nlohmann/json.hpp"
|
||||
#include <CustomAssert.h>
|
||||
#include <Http.h>
|
||||
#include <array>
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
#include <boost/asio/ip/address_v4.hpp>
|
||||
#include <cstring>
|
||||
|
||||
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option;
|
||||
|
||||
std::vector<uint8_t> StringToVector(const std::string& Str) {
|
||||
return std::vector<uint8_t>(Str.data(), Str.data() + Str.size());
|
||||
}
|
||||
|
||||
static void CompressProperly(std::vector<uint8_t>& Data) {
|
||||
constexpr std::string_view ABG = "ABG:";
|
||||
auto CombinedData = std::vector<uint8_t>(ABG.begin(), ABG.end());
|
||||
auto CompData = Comp(Data);
|
||||
CombinedData.resize(ABG.size() + CompData.size());
|
||||
std::copy(CompData.begin(), CompData.end(), CombinedData.begin() + ABG.size());
|
||||
Data = CombinedData;
|
||||
}
|
||||
|
||||
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
|
||||
: mServer(Server)
|
||||
, mPPSMonitor(PPSMonitor)
|
||||
, mUDPSock(Server.IoCtx())
|
||||
, mResourceManager(ResourceManager) {
|
||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting);
|
||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
beammp_debug("Kicking all players due to shutdown");
|
||||
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
|
||||
if (!client.expired()) {
|
||||
ClientKick(*client.lock(), "Server shutdown");
|
||||
}
|
||||
return true;
|
||||
});
|
||||
});
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown);
|
||||
if (mUDPThread.joinable()) {
|
||||
mUDPThread.detach();
|
||||
}
|
||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Shutdown);
|
||||
});
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::ShuttingDown);
|
||||
if (mTCPThread.joinable()) {
|
||||
mTCPThread.detach();
|
||||
}
|
||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Shutdown);
|
||||
});
|
||||
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
|
||||
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
|
||||
}
|
||||
|
||||
void TNetwork::UDPServerMain() {
|
||||
RegisterThread("UDPServer");
|
||||
ip::udp::endpoint UdpListenEndpoint(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
|
||||
boost::system::error_code ec;
|
||||
mUDPSock.open(UdpListenEndpoint.protocol(), ec);
|
||||
if (ec) {
|
||||
beammp_error("open() failed: " + ec.message());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
Application::GracefullyShutdown();
|
||||
}
|
||||
mUDPSock.bind(UdpListenEndpoint, ec);
|
||||
if (ec) {
|
||||
beammp_error("bind() failed: " + ec.message());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
Application::GracefullyShutdown();
|
||||
}
|
||||
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good);
|
||||
beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
|
||||
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
|
||||
while (!Application::IsShuttingDown()) {
|
||||
try {
|
||||
ip::udp::endpoint client {};
|
||||
std::vector<uint8_t> Data = UDPRcvFromClient(client); // Receives any data from Socket
|
||||
auto Pos = std::find(Data.begin(), Data.end(), ':');
|
||||
if (Data.empty() || Pos > Data.begin() + 2)
|
||||
continue;
|
||||
uint8_t ID = uint8_t(Data.at(0)) - 1;
|
||||
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
|
||||
std::shared_ptr<TClient> Client;
|
||||
{
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
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);
|
||||
TServer::GlobalParser(ClientPtr, std::move(Data), mPPSMonitor, *this);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error(("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::TCPServerMain() {
|
||||
RegisterThread("TCPServer");
|
||||
|
||||
ip::tcp::endpoint ListenEp(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
|
||||
ip::tcp::socket Listener(mServer.IoCtx());
|
||||
boost::system::error_code ec;
|
||||
Listener.open(ListenEp.protocol(), ec);
|
||||
if (ec) {
|
||||
beammp_errorf("Failed to open socket: {}", ec.message());
|
||||
return;
|
||||
}
|
||||
socket_base::linger LingerOpt {};
|
||||
LingerOpt.enabled(false);
|
||||
Listener.set_option(LingerOpt, ec);
|
||||
if (ec) {
|
||||
beammp_errorf("Failed to set up listening socket to not linger / reuse address. "
|
||||
"This may cause the socket to refuse to bind(). Error: {}",
|
||||
ec.message());
|
||||
}
|
||||
|
||||
ip::tcp::acceptor Acceptor(mServer.IoCtx(), ListenEp);
|
||||
Acceptor.listen(socket_base::max_listen_connections, ec);
|
||||
if (ec) {
|
||||
beammp_errorf("listen() failed, which is needed for the server to operate. "
|
||||
"Shutting down. Error: {}",
|
||||
ec.message());
|
||||
Application::GracefullyShutdown();
|
||||
}
|
||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
||||
beammp_info("Vehicle event network online");
|
||||
do {
|
||||
try {
|
||||
if (Application::IsShuttingDown()) {
|
||||
beammp_debug("shutdown during TCP wait for accept loop");
|
||||
break;
|
||||
}
|
||||
ip::tcp::endpoint ClientEp;
|
||||
ip::tcp::socket ClientSocket = Acceptor.accept(ClientEp, ec);
|
||||
if (ec) {
|
||||
beammp_errorf("failed to accept: {}", ec.message());
|
||||
}
|
||||
TConnection Conn { std::move(ClientSocket), ClientEp };
|
||||
std::thread ID(&TNetwork::Identify, this, std::move(Conn));
|
||||
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("fatal: " + std::string(e.what()));
|
||||
}
|
||||
} while (!Application::IsShuttingDown());
|
||||
}
|
||||
|
||||
#undef GetObject // Fixes Windows
|
||||
|
||||
#include "Json.h"
|
||||
namespace json = rapidjson;
|
||||
|
||||
void TNetwork::Identify(TConnection&& RawConnection) {
|
||||
RegisterThreadAuto();
|
||||
char Code;
|
||||
|
||||
boost::system::error_code ec;
|
||||
read(RawConnection.Socket, buffer(&Code, 1), ec);
|
||||
if (ec) {
|
||||
// TODO: is this right?!
|
||||
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
|
||||
return;
|
||||
}
|
||||
std::shared_ptr<TClient> Client { nullptr };
|
||||
try {
|
||||
if (Code == 'C') {
|
||||
Client = Authentication(std::move(RawConnection));
|
||||
} else if (Code == 'D') {
|
||||
HandleDownload(std::move(RawConnection));
|
||||
} else if (Code == 'P') {
|
||||
boost::system::error_code ec;
|
||||
write(RawConnection.Socket, buffer("P"), ec);
|
||||
return;
|
||||
} else {
|
||||
beammp_errorf("Invalid code got in Identify: '{}'", Code);
|
||||
}
|
||||
} catch(const std::exception& e) {
|
||||
beammp_errorf("Error during handling of code {} - client left in invalid state, closing socket", Code);
|
||||
boost::system::error_code ec;
|
||||
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
|
||||
if (ec) {
|
||||
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
|
||||
}
|
||||
RawConnection.Socket.close(ec);
|
||||
if (ec) {
|
||||
beammp_debugf("Failed to close client socket: {}", ec.message());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::HandleDownload(TConnection&& Conn) {
|
||||
char D;
|
||||
boost::system::error_code ec;
|
||||
read(Conn.Socket, buffer(&D, 1), ec);
|
||||
if (ec) {
|
||||
Conn.Socket.shutdown(socket_base::shutdown_both, ec);
|
||||
// ignore ec
|
||||
return;
|
||||
}
|
||||
auto ID = uint8_t(D);
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
auto c = ClientPtr.lock();
|
||||
if (c->GetID() == ID) {
|
||||
c->SetDownSock(std::move(Conn.Socket));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
std::string HashPassword(const std::string& str) {
|
||||
std::stringstream ret;
|
||||
unsigned char* hash = SHA256(reinterpret_cast<const unsigned char*>(str.c_str()), str.length(), nullptr);
|
||||
for (int i = 0; i < 32; i++) {
|
||||
ret << std::hex << static_cast<int>(hash[i]);
|
||||
}
|
||||
return ret.str();
|
||||
}
|
||||
|
||||
std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
|
||||
auto Client = CreateClient(std::move(RawConnection.Socket));
|
||||
Client->SetIdentifier("ip", RawConnection.SockAddr.address().to_string());
|
||||
beammp_tracef("This thread is ip {}", RawConnection.SockAddr.address().to_string());
|
||||
|
||||
beammp_info("Identifying new ClientConnection...");
|
||||
|
||||
auto Data = TCPRcv(*Client);
|
||||
|
||||
constexpr std::string_view VC = "VC";
|
||||
if (Data.size() > 3 && std::equal(Data.begin(), Data.begin() + VC.size(), VC.begin(), VC.end())) {
|
||||
std::string ClientVersionStr(reinterpret_cast<const char*>(Data.data() + 2), Data.size() - 2);
|
||||
Version ClientVersion = Application::VersionStrToInts(ClientVersionStr + ".0");
|
||||
if (ClientVersion.major != Application::ClientMajorVersion()) {
|
||||
beammp_errorf("Client tried to connect with version '{}', but only versions '{}.x.x' is allowed",
|
||||
ClientVersion.AsString(), Application::ClientMajorVersion());
|
||||
ClientKick(*Client, "Outdated Version!");
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
ClientKick(*Client, fmt::format("Invalid version header: '{}' ({})", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()), Data.size()));
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (!TCPSend(*Client, StringToVector("A"))) { //changed to A for Accepted version
|
||||
// TODO: handle
|
||||
}
|
||||
|
||||
Data = TCPRcv(*Client);
|
||||
|
||||
if (Data.size() > 50) {
|
||||
ClientKick(*Client, "Invalid Key (too long)!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string key(reinterpret_cast<const char*>(Data.data()), Data.size());
|
||||
|
||||
nlohmann::json AuthReq{};
|
||||
std::string AuthResStr{};
|
||||
try {
|
||||
AuthReq = nlohmann::json {
|
||||
{ "key", key }
|
||||
};
|
||||
|
||||
auto Target = "/pkToUser";
|
||||
unsigned int ResponseCode = 0;
|
||||
AuthResStr = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, AuthReq.dump(), "application/json", &ResponseCode);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
beammp_debugf("Invalid json sent by client, kicking: {}", e.what());
|
||||
ClientKick(*Client, "Invalid Key (invalid UTF8 string)!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
try {
|
||||
nlohmann::json AuthRes = nlohmann::json::parse(AuthResStr);
|
||||
|
||||
if (AuthRes["username"].is_string() && AuthRes["roles"].is_string()
|
||||
&& AuthRes["guest"].is_boolean() && AuthRes["identifiers"].is_array()) {
|
||||
|
||||
Client->SetName(AuthRes["username"]);
|
||||
Client->SetRoles(AuthRes["roles"]);
|
||||
Client->SetIsGuest(AuthRes["guest"]);
|
||||
for (const auto& ID : AuthRes["identifiers"]) {
|
||||
auto Raw = std::string(ID);
|
||||
auto SepIndex = Raw.find(':');
|
||||
Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
|
||||
}
|
||||
} else {
|
||||
beammp_error("Invalid authentication data received from authentication backend");
|
||||
ClientKick(*Client, "Invalid authentication data!");
|
||||
return nullptr;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_errorf("Client sent invalid key. Error was: {}", e.what());
|
||||
// TODO: we should really clarify that this was a backend response or parsing error
|
||||
ClientKick(*Client, "Invalid key! Please restart your game.");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if(!Application::Settings.Password.empty()) { // ask password
|
||||
if(!TCPSend(*Client, StringToVector("S"))) {
|
||||
// TODO: handle
|
||||
}
|
||||
beammp_info("Waiting for password");
|
||||
Data = TCPRcv(*Client);
|
||||
std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size());
|
||||
if(Pass != HashPassword(Application::Settings.Password)) {
|
||||
beammp_debug(Client->GetName() + " attempted to connect with a wrong password");
|
||||
ClientKick(*Client, "Wrong password!");
|
||||
return {};
|
||||
} else {
|
||||
beammp_debug(Client->GetName() + " used the correct password");
|
||||
}
|
||||
}
|
||||
|
||||
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
std::shared_ptr<TClient> 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 true;
|
||||
});
|
||||
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers());
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||
return !Result->Error && Result->Result.is<int>() && bool(Result->Result.as<int>());
|
||||
});
|
||||
std::string Reason;
|
||||
bool NotAllowedWithReason = std::any_of(Futures.begin(), Futures.end(),
|
||||
[&Reason](const std::shared_ptr<TLuaResult>& Result) -> bool {
|
||||
if (!Result->Error && Result->Result.is<std::string>()) {
|
||||
Reason = Result->Result.as<std::string>();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (NotAllowed) {
|
||||
ClientKick(*Client, "you are not allowed on the server!");
|
||||
return {};
|
||||
} else if (NotAllowedWithReason) {
|
||||
ClientKick(*Client, Reason);
|
||||
return {};
|
||||
}
|
||||
|
||||
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
|
||||
beammp_info("Identification success");
|
||||
mServer.InsertClient(Client);
|
||||
TCPClient(Client);
|
||||
} else {
|
||||
ClientKick(*Client, "Server full!");
|
||||
}
|
||||
|
||||
return Client;
|
||||
}
|
||||
|
||||
std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
|
||||
auto c = std::make_shared<TClient>(mServer, std::move(TCPSock));
|
||||
return c;
|
||||
}
|
||||
|
||||
bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) {
|
||||
if (!IsSync) {
|
||||
if (c.IsSyncing()) {
|
||||
if (!Data.empty()) {
|
||||
if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') {
|
||||
c.EnqueuePacket(Data);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
auto& Sock = c.GetTCPSock();
|
||||
|
||||
/*
|
||||
* our TCP protocol sends a header of 4 bytes, followed by the data.
|
||||
*
|
||||
* [][][][][][]...[]
|
||||
* ^------^^---...-^
|
||||
* size data
|
||||
*/
|
||||
|
||||
const auto Size = int32_t(Data.size());
|
||||
std::vector<uint8_t> ToSend;
|
||||
ToSend.resize(Data.size() + sizeof(Size));
|
||||
std::memcpy(ToSend.data(), &Size, sizeof(Size));
|
||||
std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size());
|
||||
boost::system::error_code ec;
|
||||
write(Sock, buffer(ToSend), ec);
|
||||
if (ec) {
|
||||
beammp_debugf("write(): {}", ec.message());
|
||||
c.Disconnect("write() failed");
|
||||
return false;
|
||||
}
|
||||
c.UpdatePingTime();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
|
||||
if (c.IsDisconnected()) {
|
||||
beammp_error("Client disconnected, cancelling TCPRcv");
|
||||
return {};
|
||||
}
|
||||
|
||||
int32_t Header {};
|
||||
auto& Sock = c.GetTCPSock();
|
||||
|
||||
boost::system::error_code ec;
|
||||
std::array<uint8_t, sizeof(Header)> HeaderData;
|
||||
read(Sock, buffer(HeaderData), ec);
|
||||
if (ec) {
|
||||
// TODO: handle this case (read failed)
|
||||
beammp_debugf("TCPRcv: Reading header failed: {}", ec.message());
|
||||
return {};
|
||||
}
|
||||
Header = *reinterpret_cast<int32_t*>(HeaderData.data());
|
||||
|
||||
if (Header < 0) {
|
||||
ClientKick(c, "Invalid packet - header negative");
|
||||
beammp_errorf("Client {} send negative TCP header, ignoring packet", c.GetID());
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<uint8_t> Data;
|
||||
// TODO: This is arbitrary, this needs to be handled another way
|
||||
if (Header < int32_t(100 * MB)) {
|
||||
Data.resize(Header);
|
||||
} else {
|
||||
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.");
|
||||
return {};
|
||||
}
|
||||
auto N = read(Sock, buffer(Data), ec);
|
||||
if (ec) {
|
||||
// TODO: handle this case properly
|
||||
beammp_debugf("TCPRcv: Reading data failed: {}", ec.message());
|
||||
return {};
|
||||
}
|
||||
|
||||
if (N != Header) {
|
||||
beammp_errorf("Expected to read {} bytes, instead got {}", Header, N);
|
||||
}
|
||||
|
||||
constexpr std::string_view ABG = "ABG:";
|
||||
if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
||||
Data.erase(Data.begin(), Data.begin() + ABG.size());
|
||||
return DeComp(Data);
|
||||
} else {
|
||||
return Data;
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::ClientKick(TClient& c, const std::string& R) {
|
||||
beammp_info("Client kicked: " + R);
|
||||
if (!TCPSend(c, StringToVector("K" + R))) {
|
||||
beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.GetName(), c.GetID());
|
||||
}
|
||||
c.Disconnect("Kicked");
|
||||
}
|
||||
|
||||
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
|
||||
RegisterThreadAuto();
|
||||
while (!c.expired()) {
|
||||
auto Client = c.lock();
|
||||
if (Client->IsDisconnected()) {
|
||||
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 {};
|
||||
{ // locked context
|
||||
std::unique_lock lock(Client->MissedPacketQueueMutex());
|
||||
if (Client->MissedPacketQueueSize() <= 0) {
|
||||
break;
|
||||
}
|
||||
QData = Client->MissedPacketQueue().front();
|
||||
Client->MissedPacketQueue().pop();
|
||||
} // end locked context
|
||||
// beammp_debug("sending a missed packet: " + QData);
|
||||
if (!TCPSend(*Client, QData, true)) {
|
||||
Client->Disconnect("Failed to TCPSend while clearing the missed packet queue");
|
||||
std::unique_lock lock(Client->MissedPacketQueueMutex());
|
||||
while (!Client->MissedPacketQueue().empty()) {
|
||||
Client->MissedPacketQueue().pop();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
|
||||
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
|
||||
if (c.expired() || !c.lock()->GetTCPSock().is_open()) {
|
||||
mServer.RemoveClient(c);
|
||||
return;
|
||||
}
|
||||
OnConnect(c);
|
||||
RegisterThread("(" + std::to_string(c.lock()->GetID()) + ") \"" + c.lock()->GetName() + "\"");
|
||||
|
||||
std::thread QueueSync(&TNetwork::Looper, this, c);
|
||||
|
||||
while (true) {
|
||||
if (c.expired())
|
||||
break;
|
||||
auto Client = c.lock();
|
||||
if (Client->IsDisconnected()) {
|
||||
beammp_debug("client status < 0, breaking client loop");
|
||||
break;
|
||||
}
|
||||
|
||||
auto res = TCPRcv(*Client);
|
||||
if (res.empty()) {
|
||||
beammp_debug("TCPRcv empty");
|
||||
Client->Disconnect("TCPRcv failed");
|
||||
break;
|
||||
}
|
||||
TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this);
|
||||
}
|
||||
|
||||
if (QueueSync.joinable())
|
||||
QueueSync.join();
|
||||
|
||||
if (!c.expired()) {
|
||||
auto Client = c.lock();
|
||||
OnDisconnect(c);
|
||||
} else {
|
||||
beammp_warn("client expired in TCPClient, should never happen");
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::UpdatePlayer(TClient& Client) {
|
||||
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
auto c = ClientPtr.lock();
|
||||
Packet += c->GetName() + ",";
|
||||
}
|
||||
return true;
|
||||
});
|
||||
Packet = Packet.substr(0, Packet.length() - 1);
|
||||
Client.EnqueuePacket(StringToVector(Packet));
|
||||
//(void)Respond(Client, Packet, true);
|
||||
}
|
||||
|
||||
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) {
|
||||
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
||||
try {
|
||||
LockedClientPtr = ClientPtr.lock();
|
||||
} catch (const std::exception&) {
|
||||
beammp_warn("Client expired in OnDisconnect, this is unexpected");
|
||||
return;
|
||||
}
|
||||
beammp_assert(LockedClientPtr != nullptr);
|
||||
TClient& c = *LockedClientPtr;
|
||||
beammp_info(c.GetName() + (" Connection Terminated"));
|
||||
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);
|
||||
}
|
||||
|
||||
int TNetwork::OpenID() {
|
||||
int ID = 0;
|
||||
bool found;
|
||||
do {
|
||||
found = true;
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
auto c = ClientPtr.lock();
|
||||
if (c->GetID() == ID) {
|
||||
found = false;
|
||||
ID++;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
} while (!found);
|
||||
return ID;
|
||||
}
|
||||
|
||||
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
|
||||
beammp_assert(!c.expired());
|
||||
beammp_info("Client connected");
|
||||
auto LockedClient = c.lock();
|
||||
LockedClient->SetID(OpenID());
|
||||
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID()));
|
||||
SyncResources(*LockedClient);
|
||||
if (LockedClient->IsDisconnected())
|
||||
return;
|
||||
(void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
|
||||
beammp_info(LockedClient->GetName() + " : Connected");
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
|
||||
}
|
||||
|
||||
void TNetwork::SyncResources(TClient& c) {
|
||||
if (!TCPSend(c, StringToVector("P" + std::to_string(c.GetID())))) {
|
||||
// TODO handle
|
||||
}
|
||||
std::vector<uint8_t> Data;
|
||||
while (!c.IsDisconnected()) {
|
||||
Data = TCPRcv(c);
|
||||
if (Data.empty()) {
|
||||
break;
|
||||
}
|
||||
constexpr std::string_view Done = "Done";
|
||||
if (std::equal(Data.begin(), Data.end(), Done.begin(), Done.end()))
|
||||
break;
|
||||
Parse(c, Data);
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
|
||||
if (Packet.empty())
|
||||
return;
|
||||
char Code = Packet.at(0), SubCode = 0;
|
||||
if (Packet.size() > 1)
|
||||
SubCode = Packet.at(1);
|
||||
switch (Code) {
|
||||
case 'f':
|
||||
SendFile(c, std::string(reinterpret_cast<const char*>(Packet.data() + 1), Packet.size() - 1));
|
||||
return;
|
||||
case 'S':
|
||||
if (SubCode == 'R') {
|
||||
beammp_debug("Sending Mod Info");
|
||||
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
|
||||
if (ToSend.empty())
|
||||
ToSend = "-";
|
||||
if (!TCPSend(c, StringToVector(ToSend))) {
|
||||
// TODO: error
|
||||
}
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
|
||||
beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
|
||||
|
||||
if (!fs::path(UnsafeName).has_filename()) {
|
||||
if (!TCPSend(c, StringToVector("CO"))) {
|
||||
// TODO: handle
|
||||
}
|
||||
beammp_warn("File " + UnsafeName + " is not a file!");
|
||||
return;
|
||||
}
|
||||
auto FileName = fs::path(UnsafeName).filename().string();
|
||||
FileName = Application::Settings.Resource + "/Client/" + FileName;
|
||||
|
||||
if (!std::filesystem::exists(FileName)) {
|
||||
if (!TCPSend(c, StringToVector("CO"))) {
|
||||
// TODO: handle
|
||||
}
|
||||
beammp_warn("File " + UnsafeName + " could not be accessed!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TCPSend(c, StringToVector("AG"))) {
|
||||
// TODO: handle
|
||||
}
|
||||
|
||||
/// Wait for connections
|
||||
int T = 0;
|
||||
while (!c.GetDownSock().is_open() && T < 50) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
T++;
|
||||
}
|
||||
|
||||
if (!c.GetDownSock().is_open()) {
|
||||
beammp_error("Client doesn't have a download socket!");
|
||||
if (!c.IsDisconnected())
|
||||
c.Disconnect("Missing download socket");
|
||||
return;
|
||||
}
|
||||
|
||||
size_t Size = size_t(std::filesystem::file_size(FileName)), MSize = Size / 2;
|
||||
|
||||
std::thread SplitThreads[2] {
|
||||
std::thread([&] {
|
||||
RegisterThread("SplitLoad_0");
|
||||
SplitLoad(c, 0, MSize, false, FileName);
|
||||
}),
|
||||
std::thread([&] {
|
||||
RegisterThread("SplitLoad_1");
|
||||
SplitLoad(c, MSize, Size, true, FileName);
|
||||
})
|
||||
};
|
||||
|
||||
for (auto& SplitThread : SplitThreads) {
|
||||
if (SplitThread.joinable()) {
|
||||
SplitThread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static std::pair<size_t /* count */, size_t /* last chunk */> SplitIntoChunks(size_t FullSize, size_t ChunkSize) {
|
||||
if (FullSize < ChunkSize) {
|
||||
return { 0, FullSize };
|
||||
}
|
||||
size_t Count = FullSize / (FullSize / ChunkSize);
|
||||
size_t LastChunkSize = FullSize - (Count * ChunkSize);
|
||||
return { Count, LastChunkSize };
|
||||
}
|
||||
|
||||
TEST_CASE("SplitIntoChunks") {
|
||||
size_t FullSize;
|
||||
size_t ChunkSize;
|
||||
SUBCASE("Normal case") {
|
||||
FullSize = 1234567;
|
||||
ChunkSize = 1234;
|
||||
}
|
||||
SUBCASE("Zero original size") {
|
||||
FullSize = 0;
|
||||
ChunkSize = 100;
|
||||
}
|
||||
SUBCASE("Equal full size and chunk size") {
|
||||
FullSize = 125;
|
||||
ChunkSize = 125;
|
||||
}
|
||||
SUBCASE("Even split") {
|
||||
FullSize = 10000;
|
||||
ChunkSize = 100;
|
||||
}
|
||||
SUBCASE("Odd split") {
|
||||
FullSize = 13;
|
||||
ChunkSize = 2;
|
||||
}
|
||||
SUBCASE("Large sizes") {
|
||||
FullSize = 10 * GB;
|
||||
ChunkSize = 125 * MB;
|
||||
}
|
||||
auto [Count, LastSize] = SplitIntoChunks(FullSize, ChunkSize);
|
||||
CHECK((Count * ChunkSize) + LastSize == FullSize);
|
||||
}
|
||||
|
||||
const uint8_t* /* end ptr */ TNetwork::SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size) {
|
||||
if (TCPSendRaw(c, Socket, DataPtr, Size)) {
|
||||
return DataPtr + Size;
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
|
||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
||||
uint32_t Split = 125 * MB;
|
||||
std::vector<uint8_t> Data;
|
||||
if (Size > Split)
|
||||
Data.resize(Split);
|
||||
else
|
||||
Data.resize(Size);
|
||||
ip::tcp::socket* TCPSock { nullptr };
|
||||
if (D)
|
||||
TCPSock = &c.GetDownSock();
|
||||
else
|
||||
TCPSock = &c.GetTCPSock();
|
||||
while (!c.IsDisconnected() && Sent < Size) {
|
||||
size_t Diff = Size - Sent;
|
||||
if (Diff > Split) {
|
||||
f.seekg(Sent, std::ios_base::beg);
|
||||
f.read(reinterpret_cast<char*>(Data.data()), Split);
|
||||
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
|
||||
if (!c.IsDisconnected())
|
||||
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())
|
||||
c.Disconnect("TCPSendRaw failed in mod download (2)");
|
||||
break;
|
||||
}
|
||||
Sent += Diff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool TNetwork::TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size) {
|
||||
boost::system::error_code ec;
|
||||
write(socket, buffer(Data, Size), ec);
|
||||
if (ec) {
|
||||
beammp_errorf("Failed to send raw data to client: {}", ec.message());
|
||||
return false;
|
||||
}
|
||||
C.UpdatePingTime();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TNetwork::SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync) {
|
||||
if (Data.size() > 400) {
|
||||
CompressProperly(Data);
|
||||
}
|
||||
return TCPSend(c, Data, isSync);
|
||||
}
|
||||
|
||||
bool TNetwork::Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync) {
|
||||
char C = MSG.at(0);
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || MSG.size() > 1000) {
|
||||
return SendLarge(c, MSG, isSync);
|
||||
} else {
|
||||
return TCPSend(c, MSG, isSync);
|
||||
}
|
||||
} else {
|
||||
return UDPSend(c, MSG);
|
||||
}
|
||||
}
|
||||
|
||||
bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
|
||||
if (c.expired()) {
|
||||
return false;
|
||||
}
|
||||
auto LockedClient = c.lock();
|
||||
if (LockedClient->IsSynced())
|
||||
return true;
|
||||
// Syncing, later set isSynced
|
||||
// after syncing is done, we apply all packets they missed
|
||||
if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->GetName()), true)) {
|
||||
return false;
|
||||
}
|
||||
// ignore error
|
||||
(void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->GetName() + "!"), false, true);
|
||||
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID()));
|
||||
LockedClient->SetIsSyncing(true);
|
||||
bool Return = false;
|
||||
bool res = true;
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
std::shared_ptr<TClient> client;
|
||||
{
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
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()) {
|
||||
Return = true;
|
||||
res = false;
|
||||
return false;
|
||||
}
|
||||
res = Respond(*LockedClient, StringToVector(v.Data()), true, true);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
LockedClient->SetIsSyncing(false);
|
||||
if (Return) {
|
||||
return res;
|
||||
}
|
||||
LockedClient->SetIsSynced(true);
|
||||
beammp_info(LockedClient->GetName() + (" is now synced!"));
|
||||
return true;
|
||||
}
|
||||
|
||||
void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) {
|
||||
if (!Self)
|
||||
beammp_assert(c);
|
||||
char C = Data.at(0);
|
||||
bool ret = true;
|
||||
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 (Client->IsSynced() || Client->IsSyncing()) {
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || Data.size() > 1000) {
|
||||
if (Data.size() > 400) {
|
||||
auto CompressedData = Data;
|
||||
CompressProperly(CompressedData);
|
||||
Client->EnqueuePacket(CompressedData);
|
||||
} else {
|
||||
Client->EnqueuePacket(Data);
|
||||
}
|
||||
// ret = SendLarge(*Client, Data);
|
||||
} else {
|
||||
Client->EnqueuePacket(Data);
|
||||
// ret = TCPSend(*Client, Data);
|
||||
}
|
||||
} else {
|
||||
ret = UDPSend(*Client, Data);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!ret) {
|
||||
// TODO: handle
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
|
||||
if (!Client.IsConnected() || Client.IsDisconnected()) {
|
||||
// this can happen if we try to send a packet to a client that is either
|
||||
// 1. not yet fully connected, or
|
||||
// 2. disconnected and not yet fully removed
|
||||
// this is fine can can be ignored :^)
|
||||
return true;
|
||||
}
|
||||
const auto Addr = Client.GetUDPAddr();
|
||||
if (Data.size() > 400) {
|
||||
CompressProperly(Data);
|
||||
}
|
||||
boost::system::error_code ec;
|
||||
mUDPSock.send_to(buffer(Data), Addr, 0, ec);
|
||||
if (ec) {
|
||||
beammp_debugf("UDP sendto() failed: {}", ec.message());
|
||||
if (!Client.IsDisconnected())
|
||||
Client.Disconnect("UDP send failed");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> TNetwork::UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint) {
|
||||
std::array<char, 1024> Ret {};
|
||||
boost::system::error_code ec;
|
||||
const auto Rcv = mUDPSock.receive_from(mutable_buffer(Ret.data(), Ret.size()), ClientEndpoint, 0, ec);
|
||||
if (ec) {
|
||||
beammp_errorf("UDP recvfrom() failed: {}", ec.message());
|
||||
return {};
|
||||
}
|
||||
beammp_assert(Rcv <= Ret.size());
|
||||
return std::vector<uint8_t>(Ret.begin(), Ret.begin() + Rcv);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "TPPSMonitor.h"
|
||||
#include "Client.h"
|
||||
#include "TNetwork.h"
|
||||
|
||||
TPPSMonitor::TPPSMonitor(TServer& Server)
|
||||
: mServer(Server) {
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
|
||||
Application::SetPPS("-");
|
||||
Application::RegisterShutdownHandler([&] {
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
|
||||
if (mThread.joinable()) {
|
||||
beammp_debug("shutting down PPSMonitor");
|
||||
mThread.join();
|
||||
beammp_debug("shut down PPSMonitor");
|
||||
}
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
|
||||
});
|
||||
Start();
|
||||
}
|
||||
void TPPSMonitor::operator()() {
|
||||
RegisterThread("PPSMonitor");
|
||||
while (!mNetwork) {
|
||||
// hard(-ish) spin
|
||||
std::this_thread::yield();
|
||||
}
|
||||
beammp_debug("PPSMonitor starting");
|
||||
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
|
||||
std::vector<std::shared_ptr<TClient>> TimedOutClients;
|
||||
while (!Application::IsShuttingDown()) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
int C = 0, V = 0;
|
||||
if (mServer.ClientCount() == 0) {
|
||||
Application::SetPPS("-");
|
||||
continue;
|
||||
}
|
||||
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
|
||||
std::shared_ptr<TClient> c;
|
||||
{
|
||||
ReadLock Lock(mServer.GetClientMutex());
|
||||
if (!ClientPtr.expired()) {
|
||||
c = ClientPtr.lock();
|
||||
} else
|
||||
return true;
|
||||
}
|
||||
if (c->GetCarCount() > 0) {
|
||||
C++;
|
||||
V += c->GetCarCount();
|
||||
}
|
||||
// kick on "no ping"
|
||||
if (c->SecondsSinceLastPing() > (20 * 60)) {
|
||||
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
|
||||
TimedOutClients.push_back(c);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
for (auto& ClientToKick : TimedOutClients) {
|
||||
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
|
||||
}
|
||||
TimedOutClients.clear();
|
||||
if (C == 0 || mInternalPPS == 0) {
|
||||
Application::SetPPS("-");
|
||||
} else {
|
||||
int R = (mInternalPPS / C) / V;
|
||||
Application::SetPPS(std::to_string(R));
|
||||
}
|
||||
mInternalPPS = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "TPluginMonitor.h"
|
||||
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
|
||||
: mEngine(Engine)
|
||||
, mPath(Path) {
|
||||
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Starting);
|
||||
if (!fs::exists(mPath)) {
|
||||
fs::create_directories(mPath);
|
||||
}
|
||||
for (const auto& Entry : fs::recursive_directory_iterator(mPath)) {
|
||||
// TODO: trigger an event when a subfolder file changes
|
||||
if (Entry.is_regular_file()) {
|
||||
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
Application::RegisterShutdownHandler([this] {
|
||||
if (mThread.joinable()) {
|
||||
mThread.join();
|
||||
}
|
||||
});
|
||||
|
||||
Start();
|
||||
}
|
||||
|
||||
void TPluginMonitor::operator()() {
|
||||
RegisterThread("PluginMonitor");
|
||||
beammp_info("PluginMonitor started");
|
||||
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Good);
|
||||
while (!Application::IsShuttingDown()) {
|
||||
std::vector<std::string> ToRemove;
|
||||
for (const auto& Pair : mFileTimes) {
|
||||
try {
|
||||
auto CurrentTime = fs::last_write_time(Pair.first);
|
||||
if (CurrentTime > Pair.second) {
|
||||
mFileTimes[Pair.first] = CurrentTime;
|
||||
// grandparent of the path should be Resources/Server
|
||||
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
|
||||
beammp_infof("File \"{}\" changed, reloading", Pair.first);
|
||||
// is in root folder, so reload
|
||||
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
|
||||
auto Size = std::filesystem::file_size(Pair.first);
|
||||
auto Contents = std::make_shared<std::string>();
|
||||
Contents->resize(Size);
|
||||
FileStream.read(Contents->data(), Contents->size());
|
||||
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
|
||||
auto StateID = mEngine->GetStateIDForPlugin(fs::path(Pair.first).parent_path());
|
||||
auto Res = mEngine->EnqueueScript(StateID, Chunk);
|
||||
Res->WaitUntilReady();
|
||||
if (Res->Error) {
|
||||
beammp_lua_errorf("Error while hot-reloading \"{}\": {}", Pair.first, Res->ErrorMessage);
|
||||
} else {
|
||||
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
|
||||
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||
}
|
||||
} else {
|
||||
// is in subfolder, dont reload, just trigger an event
|
||||
beammp_debugf("File \"{}\" changed, not reloading because it's in a subdirectory. Triggering 'onFileChanged' event instead", Pair.first);
|
||||
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ToRemove.push_back(Pair.first);
|
||||
}
|
||||
}
|
||||
Application::SleepSafeSeconds(3);
|
||||
for (const auto& File : ToRemove) {
|
||||
mFileTimes.erase(File);
|
||||
beammp_warnf("File \"{}\" couldn't be accessed, so it was removed from plugin hot reload monitor (probably got deleted)", File);
|
||||
}
|
||||
}
|
||||
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Shutdown);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#include "TResourceManager.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
TResourceManager::TResourceManager() {
|
||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
|
||||
std::string Path = Application::Settings.Resource + "/Client";
|
||||
if (!fs::exists(Path))
|
||||
fs::create_directories(Path);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
std::string File(entry.path().string());
|
||||
if (auto pos = File.find(".zip"); pos != std::string::npos) {
|
||||
if (File.length() - pos == 4) {
|
||||
std::replace(File.begin(), File.end(), '\\', '/');
|
||||
mFileList += File + ';';
|
||||
if (auto i = File.find_last_of('/'); i != std::string::npos) {
|
||||
++i;
|
||||
File = File.substr(i, pos - i);
|
||||
}
|
||||
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
|
||||
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
|
||||
mMaxModSize += size_t(fs::file_size(entry.path()));
|
||||
mModsLoaded++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mModsLoaded) {
|
||||
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
|
||||
}
|
||||
|
||||
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
|
||||
}
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "TScopedTimer.h"
|
||||
#include "Common.h"
|
||||
|
||||
|
||||
+456
@@ -0,0 +1,456 @@
|
||||
#include "TServer.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "TNetwork.h"
|
||||
#include "TPPSMonitor.h"
|
||||
#include <TLuaPlugin.h>
|
||||
#include <algorithm>
|
||||
#include <any>
|
||||
#include <sstream>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include "LuaAPI.h"
|
||||
|
||||
#undef GetObject // Fixes Windows
|
||||
|
||||
#include "Json.h"
|
||||
|
||||
static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
|
||||
auto IDSep = str.find('-');
|
||||
std::string pid = str.substr(0, IDSep);
|
||||
std::string vid = str.substr(IDSep + 1);
|
||||
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
try {
|
||||
int PID = stoi(pid);
|
||||
int VID = stoi(vid);
|
||||
return { { PID, VID } };
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
TEST_CASE("GetPidVid") {
|
||||
SUBCASE("Valid singledigit") {
|
||||
const auto MaybePidVid = GetPidVid("0-1");
|
||||
CHECK(MaybePidVid);
|
||||
auto [pid, vid] = MaybePidVid.value();
|
||||
|
||||
CHECK_EQ(pid, 0);
|
||||
CHECK_EQ(vid, 1);
|
||||
}
|
||||
SUBCASE("Valid doubledigit") {
|
||||
const auto MaybePidVid = GetPidVid("10-12");
|
||||
CHECK(MaybePidVid);
|
||||
auto [pid, vid] = MaybePidVid.value();
|
||||
|
||||
CHECK_EQ(pid, 10);
|
||||
CHECK_EQ(vid, 12);
|
||||
}
|
||||
SUBCASE("Empty string") {
|
||||
const auto MaybePidVid = GetPidVid("");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
SUBCASE("Invalid separator") {
|
||||
const auto MaybePidVid = GetPidVid("0x0");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
SUBCASE("Missing pid") {
|
||||
const auto MaybePidVid = GetPidVid("-0");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
SUBCASE("Missing vid") {
|
||||
const auto MaybePidVid = GetPidVid("0-");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
SUBCASE("Invalid pid") {
|
||||
const auto MaybePidVid = GetPidVid("x-0");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
SUBCASE("Invalid vid") {
|
||||
const auto MaybePidVid = GetPidVid("0-x");
|
||||
CHECK(!MaybePidVid);
|
||||
}
|
||||
}
|
||||
|
||||
TServer::TServer(const std::vector<std::string_view>& Arguments) {
|
||||
beammp_info("BeamMP Server v" + Application::ServerVersionString());
|
||||
Application::SetSubsystemStatus("Server", Application::Status::Starting);
|
||||
if (Arguments.size() > 1) {
|
||||
Application::Settings.CustomIP = Arguments[0];
|
||||
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
|
||||
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
|
||||
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
|
||||
Application::Settings.CustomIP.clear();
|
||||
beammp_warn("IP Specified is invalid! Ignoring");
|
||||
} else {
|
||||
beammp_info("server started with custom IP");
|
||||
}
|
||||
}
|
||||
Application::SetSubsystemStatus("Server", Application::Status::Good);
|
||||
}
|
||||
|
||||
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
|
||||
std::shared_ptr<TClient> LockedClientPtr { nullptr };
|
||||
try {
|
||||
LockedClientPtr = WeakClientPtr.lock();
|
||||
} catch (const std::exception&) {
|
||||
// silently fail, as there's nothing to do
|
||||
return;
|
||||
}
|
||||
beammp_assert(LockedClientPtr != nullptr);
|
||||
TClient& Client = *LockedClientPtr;
|
||||
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
|
||||
// TODO: Send delete packets for all cars
|
||||
Client.ClearCars();
|
||||
WriteLock Lock(mClientsMutex);
|
||||
mClients.erase(WeakClientPtr.lock());
|
||||
}
|
||||
|
||||
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
|
||||
decltype(mClients) Clients;
|
||||
{
|
||||
ReadLock lock(mClientsMutex);
|
||||
Clients = mClients;
|
||||
}
|
||||
for (auto& Client : Clients) {
|
||||
if (!Fn(Client)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t TServer::ClientCount() const {
|
||||
ReadLock Lock(mClientsMutex);
|
||||
return mClients.size();
|
||||
}
|
||||
|
||||
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
|
||||
constexpr std::string_view ABG = "ABG:";
|
||||
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
|
||||
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
|
||||
Packet = DeComp(Packet);
|
||||
}
|
||||
if (Packet.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Client.expired()) {
|
||||
return;
|
||||
}
|
||||
auto LockedClient = Client.lock();
|
||||
|
||||
std::any Res;
|
||||
char Code = Packet.at(0);
|
||||
|
||||
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||
|
||||
// V to Y
|
||||
if (Code <= 89 && Code >= 86) {
|
||||
PPSMonitor.IncrementInternalPPS();
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||
return;
|
||||
}
|
||||
switch (Code) {
|
||||
case 'H': // initial connection
|
||||
if (!Network.SyncClient(Client)) {
|
||||
// TODO handle
|
||||
}
|
||||
return;
|
||||
case 'p':
|
||||
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
|
||||
// failed to send
|
||||
LockedClient->Disconnect("Failed to send ping");
|
||||
} else {
|
||||
Network.UpdatePlayer(*LockedClient);
|
||||
}
|
||||
return;
|
||||
case 'O':
|
||||
if (Packet.size() > 1000) {
|
||||
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
|
||||
}
|
||||
ParseVehicle(*LockedClient, StringPacket, Network);
|
||||
return;
|
||||
case 'C': {
|
||||
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
|
||||
break;
|
||||
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
|
||||
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);
|
||||
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
|
||||
if (std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Elem) {
|
||||
return !Elem->Error
|
||||
&& Elem->Result.is<int>()
|
||||
&& bool(Elem->Result.as<int>());
|
||||
})) {
|
||||
break;
|
||||
}
|
||||
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
|
||||
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
|
||||
return;
|
||||
}
|
||||
case 'E':
|
||||
HandleEvent(*LockedClient, StringPacket);
|
||||
return;
|
||||
case 'N':
|
||||
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, true);
|
||||
return;
|
||||
case 'Z': // position packet
|
||||
PPSMonitor.IncrementInternalPPS();
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||
HandlePosition(*LockedClient, StringPacket);
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
|
||||
// E:Name:Data
|
||||
// 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);
|
||||
if (NameDataSep == std::string::npos) {
|
||||
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
|
||||
}
|
||||
std::string Name = RawData.substr(2, NameDataSep - 2);
|
||||
std::string Data = RawData.substr(NameDataSep + 1);
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
|
||||
}
|
||||
|
||||
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
|
||||
try {
|
||||
auto Car = nlohmann::json::parse(CarJson);
|
||||
const std::string jbm = "jbm";
|
||||
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
|
||||
return true;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
|
||||
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
|
||||
c.SetUnicycleID(ID);
|
||||
return true;
|
||||
} else {
|
||||
return c.GetCarCount() < Application::Settings.MaxCars;
|
||||
}
|
||||
}
|
||||
|
||||
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
|
||||
if (Pckt.length() < 6)
|
||||
return;
|
||||
std::string Packet = Pckt;
|
||||
char Code = Packet.at(1);
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
std::string Data = Packet.substr(3), pid, vid;
|
||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||
case 's':
|
||||
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
|
||||
if (Data.at(0) == '0') {
|
||||
int CarID = c.GetOpenCarID();
|
||||
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
|
||||
|
||||
std::string CarJson = Packet.substr(5);
|
||||
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||
});
|
||||
|
||||
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
|
||||
c.AddNewCar(CarID, Packet);
|
||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
} else {
|
||||
if (!Network.Respond(c, StringToVector(Packet), true)) {
|
||||
// TODO: handle
|
||||
}
|
||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
|
||||
if (!Network.Respond(c, StringToVector(Destroy), true)) {
|
||||
// TODO: handle
|
||||
}
|
||||
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'c': {
|
||||
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||
TLuaEngine::WaitForAll(Futures);
|
||||
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
|
||||
[](const std::shared_ptr<TLuaResult>& Result) {
|
||||
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
|
||||
});
|
||||
|
||||
auto FoundPos = Packet.find('{');
|
||||
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
|
||||
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
|
||||
&& !ShouldntAllow) {
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
Apply(c, VID, Packet);
|
||||
} else {
|
||||
if (c.GetUnicycleID() == VID) {
|
||||
c.SetUnicycleID(-1);
|
||||
}
|
||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
|
||||
c.DeleteCar(VID);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'd': {
|
||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
if (c.GetUnicycleID() == VID) {
|
||||
c.SetUnicycleID(-1);
|
||||
}
|
||||
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
|
||||
// TODO: should this trigger on all vehicle deletions?
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
|
||||
c.DeleteCar(VID);
|
||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'r': {
|
||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
}
|
||||
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
Data = Data.substr(Data.find('{'));
|
||||
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 't':
|
||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
Network.SendToAll(&c, StringToVector(Packet), false, true);
|
||||
return;
|
||||
case 'm':
|
||||
Network.SendToAll(&c, StringToVector(Packet), true, true);
|
||||
return;
|
||||
default:
|
||||
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
|
||||
auto FoundPos = pckt.find('{');
|
||||
if (FoundPos == std::string::npos) {
|
||||
beammp_error("Malformed packet received, no '{' found");
|
||||
return;
|
||||
}
|
||||
std::string Packet = pckt.substr(FoundPos);
|
||||
std::string VD = c.GetCarData(VID);
|
||||
if (VD.empty()) {
|
||||
beammp_error("Tried to apply change to vehicle that does not exist");
|
||||
return;
|
||||
}
|
||||
std::string Header = VD.substr(0, VD.find('{'));
|
||||
|
||||
FoundPos = VD.find('{');
|
||||
if (FoundPos == std::string::npos) {
|
||||
return;
|
||||
}
|
||||
VD = VD.substr(FoundPos);
|
||||
rapidjson::Document Veh, Pack;
|
||||
Veh.Parse(VD.c_str());
|
||||
if (Veh.HasParseError()) {
|
||||
beammp_error("Could not get vehicle config!");
|
||||
return;
|
||||
}
|
||||
Pack.Parse(Packet.c_str());
|
||||
if (Pack.HasParseError() || Pack.IsNull()) {
|
||||
beammp_error("Could not get active vehicle config!");
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto& M : Pack.GetObject()) {
|
||||
if (Veh[M.name].IsNull()) {
|
||||
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
|
||||
} else {
|
||||
Veh[M.name] = Pack[M.name];
|
||||
}
|
||||
}
|
||||
rapidjson::StringBuffer Buffer;
|
||||
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
|
||||
Veh.Accept(writer);
|
||||
c.SetCarData(VID, Header + Buffer.GetString());
|
||||
}
|
||||
|
||||
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
||||
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
|
||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||
(void)mClients.insert(NewClient);
|
||||
}
|
||||
|
||||
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
||||
if (Packet.size() < 3) {
|
||||
// invalid packet
|
||||
return;
|
||||
}
|
||||
// Zp:serverVehicleID:data
|
||||
// Zp:0:data
|
||||
std::string withoutCode = Packet.substr(3);
|
||||
auto NameDataSep = withoutCode.find(':', 2);
|
||||
if (NameDataSep == std::string::npos || NameDataSep < 2) {
|
||||
// invalid packet
|
||||
return;
|
||||
}
|
||||
// FIXME: ensure that -2 does what it should... it seems weird.
|
||||
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
||||
if (NameDataSep + 1 > withoutCode.size()) {
|
||||
// invalid packet
|
||||
return;
|
||||
}
|
||||
std::string Data = withoutCode.substr(NameDataSep + 1);
|
||||
|
||||
// parse veh ID
|
||||
auto MaybePidVid = GetPidVid(ServerVehicleID);
|
||||
if (MaybePidVid) {
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
// FIXME: check that the VID and PID are valid, so that we don't waste memory
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
|
||||
c.SetCarPosition(VID, Data);
|
||||
}
|
||||
}
|
||||
-478
@@ -1,478 +0,0 @@
|
||||
#include "Value.h"
|
||||
#include "Common.h"
|
||||
#include "boost/json/value_from.hpp"
|
||||
#include "sol/as_args.hpp"
|
||||
#include "sol/types.hpp"
|
||||
#include <doctest/doctest.h>
|
||||
#include <fmt/format.h>
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
ValueToStringVisitor::ValueToStringVisitor(Flag flags, int depth)
|
||||
: m_quote_strings(flags & QUOTE_STRINGS)
|
||||
, m_depth(depth) {
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(const std::string& str) const {
|
||||
if (m_quote_strings) {
|
||||
return fmt::format("\"{}\"", str);
|
||||
} else {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(int64_t i) const {
|
||||
return fmt::format("{}", i);
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(double d) const {
|
||||
return fmt::format("{}", d);
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(Null) const {
|
||||
return "null";
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(Bool b) const {
|
||||
return b ? "true" : "false";
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(const ValueArray& array) const {
|
||||
std::string res = "[ ";
|
||||
size_t i = 0;
|
||||
for (const auto& elem : array) {
|
||||
res += fmt::format("\n{:>{}}{}", "", m_depth * 2, boost::apply_visitor(ValueToStringVisitor(QUOTE_STRINGS, m_depth + 1), elem));
|
||||
if (i + 2 <= array.size()) {
|
||||
res += ",";
|
||||
} else {
|
||||
res += "\n";
|
||||
}
|
||||
++i;
|
||||
}
|
||||
return res += fmt::format("{:>{}}]", "", (m_depth == 0 ? 0 : (m_depth - 1) * 2));
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(const ValueTuple& array) const {
|
||||
std::string res = "( ";
|
||||
size_t i = 0;
|
||||
for (const auto& elem : array) {
|
||||
res += fmt::format("\n{:>{}}{}", "", m_depth * 2, boost::apply_visitor(ValueToStringVisitor(QUOTE_STRINGS, m_depth + 1), elem));
|
||||
if (i + 2 <= array.size()) {
|
||||
res += ",";
|
||||
} else {
|
||||
res += "\n";
|
||||
}
|
||||
++i;
|
||||
}
|
||||
return res += fmt::format("{:>{}})", "", (m_depth == 0 ? 0 : (m_depth - 1) * 2));
|
||||
}
|
||||
|
||||
std::string ValueToStringVisitor::operator()(const HashMap<std::string, Value>& map) const {
|
||||
std::string res = "{ ";
|
||||
size_t i = 0;
|
||||
for (const auto& [key, value] : map) {
|
||||
res += fmt::format("\n{:>{}}{}: {}", "", m_depth * 2, key, boost::apply_visitor(ValueToStringVisitor(QUOTE_STRINGS, m_depth + 1), value));
|
||||
if (i + 2 <= map.size()) {
|
||||
res += ",";
|
||||
} else {
|
||||
res += "\n";
|
||||
}
|
||||
++i;
|
||||
}
|
||||
return res += fmt::format("{:>{}}}}", "", (m_depth == 0 ? 0 : (m_depth - 1) * 2));
|
||||
}
|
||||
|
||||
TEST_CASE("Value constructors") {
|
||||
SUBCASE("string via const char*") {
|
||||
Value value = "hello, world";
|
||||
CHECK_EQ(value.which(), VALUE_TYPE_IDX_STRING);
|
||||
}
|
||||
SUBCASE("int via long literal") {
|
||||
Value value = int64_t(1l);
|
||||
CHECK_EQ(value.which(), VALUE_TYPE_IDX_INT);
|
||||
}
|
||||
SUBCASE("double via double literal") {
|
||||
Value value = 5.432;
|
||||
CHECK_EQ(value.which(), VALUE_TYPE_IDX_DOUBLE);
|
||||
}
|
||||
// other constructors must be explicit as far as we're concerned
|
||||
}
|
||||
|
||||
TEST_CASE("ValueToStringVisitor") {
|
||||
SUBCASE("string quoted") {
|
||||
Value value = "hello, world";
|
||||
// expected to implicitly be "ValueToStringVisitor::Flag::QUOTE_STRINGS"
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "\"hello, world\"");
|
||||
}
|
||||
SUBCASE("string not quoted") {
|
||||
Value value = "hello, world";
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(ValueToStringVisitor::Flag::NONE), value);
|
||||
CHECK_EQ(res, "hello, world");
|
||||
}
|
||||
SUBCASE("int") {
|
||||
Value value = int64_t(123456789l);
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "123456789");
|
||||
}
|
||||
SUBCASE("negative int") {
|
||||
Value value = int64_t(-123456789l);
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "-123456789");
|
||||
}
|
||||
SUBCASE("whole integer double") {
|
||||
Value value = 123456789.0;
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "123456789");
|
||||
}
|
||||
SUBCASE("double") {
|
||||
Value value = 1234.56789;
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "1234.56789");
|
||||
}
|
||||
SUBCASE("null") {
|
||||
Value value = Null {};
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "null");
|
||||
} /*
|
||||
SUBCASE("array") {
|
||||
Value value = ValueArray { 1l, 2l, "hello", 5.4 };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "[ 1, 2, \"hello\", 5.4 ]");
|
||||
}
|
||||
SUBCASE("tuple") {
|
||||
Value value = ValueArray { 1l, 2l, "hello" };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "( 1, 2, \"hello\" )");
|
||||
}
|
||||
SUBCASE("array with array inside") {
|
||||
Value value = ValueArray { 1l, 2l, "hello", ValueArray { -1l, -2l }, 5.4 };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "[ 1, 2, \"hello\", [ -1, -2 ], 5.4 ]");
|
||||
}
|
||||
SUBCASE("map") {
|
||||
Value value = ValueHashMap { { "hello", "world" }, { "x", 53.5 } };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, R"({ hello="world", x=53.5 })");
|
||||
}
|
||||
SUBCASE("map with map inside") {
|
||||
Value value = ValueHashMap { { "hello", "world" }, { "my map", ValueHashMap { { "value", 1l } } }, { "x", 53.5 } };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, R"({ hello="world", my map={ value=1 }, x=53.5 })");
|
||||
}
|
||||
*/
|
||||
SUBCASE("empty array") {
|
||||
Value value = ValueArray {};
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "[ ]");
|
||||
}
|
||||
SUBCASE("empty tuple") {
|
||||
Value value = ValueTuple {};
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "( )");
|
||||
}
|
||||
SUBCASE("empty map") {
|
||||
Value value = ValueHashMap {};
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "{ }");
|
||||
}
|
||||
SUBCASE("bool") {
|
||||
Value value = Bool { false };
|
||||
std::string res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "false");
|
||||
|
||||
value = Bool { true };
|
||||
res = boost::apply_visitor(ValueToStringVisitor(), value);
|
||||
CHECK_EQ(res, "true");
|
||||
}
|
||||
}
|
||||
|
||||
static Result<Value> sol_obj_to_value_impl(const sol::object& obj, const std::function<Result<Value>(const sol::object&)>& invalid_provider, size_t max_depth, size_t depth) {
|
||||
if (depth == max_depth) {
|
||||
return { Null {} };
|
||||
}
|
||||
++depth;
|
||||
switch (obj.get_type()) {
|
||||
case sol::type::none:
|
||||
case sol::type::lua_nil:
|
||||
return { Null {} };
|
||||
case sol::type::string:
|
||||
return { obj.as<std::string>() };
|
||||
case sol::type::number:
|
||||
if (obj.is<int64_t>()) {
|
||||
return { obj.as<int64_t>() };
|
||||
} else {
|
||||
return { obj.as<double>() };
|
||||
}
|
||||
case sol::type::thread: {
|
||||
if (invalid_provider) {
|
||||
return invalid_provider(obj);
|
||||
} else {
|
||||
return Result<Value>("Can't convert {} to Value", "lua thread");
|
||||
}
|
||||
}
|
||||
case sol::type::boolean:
|
||||
return { Bool { obj.as<bool>() } };
|
||||
case sol::type::function:
|
||||
if (invalid_provider) {
|
||||
return invalid_provider(obj);
|
||||
} else {
|
||||
return Result<Value>("Can't convert {} to Value", "lua function");
|
||||
}
|
||||
case sol::type::userdata:
|
||||
if (invalid_provider) {
|
||||
return invalid_provider(obj);
|
||||
} else {
|
||||
return Result<Value>("Can't convert {} to Value", "lua userdata");
|
||||
}
|
||||
case sol::type::lightuserdata:
|
||||
if (invalid_provider) {
|
||||
return invalid_provider(obj);
|
||||
} else {
|
||||
return Result<Value>("Can't convert {} to Value", "lua lightuserdata");
|
||||
}
|
||||
case sol::type::table: {
|
||||
bool is_map = false;
|
||||
// look through all keys, if all are numbers, its not a map
|
||||
for (const auto& [k, v] : obj.as<sol::table>()) {
|
||||
// due to a quirk in lua+sol (sol issue #247), you have to
|
||||
// both check that it's a number, but also that its an integer number.
|
||||
// technically, lua allows float keys in an array (i guess?)
|
||||
// but for us that counts as a type we need to use a hashmap for.
|
||||
// k.is<double>() would be true for any number type, but
|
||||
// k.is<int>() is only true for such numbers that are non-float.
|
||||
if (k.get_type() == sol::type::number) {
|
||||
if (!k.is<int64_t>()) {
|
||||
is_map = true;
|
||||
break;
|
||||
}
|
||||
} else if (k.get_type() == sol::type::string) {
|
||||
is_map = true;
|
||||
break;
|
||||
} else {
|
||||
return Result<Value>("Can't use non-string and non-number object as key for table (type id is {})", int(k.get_type())); // TODO: make a fucntion to fix htis messy way to enfore sending an error
|
||||
}
|
||||
}
|
||||
if (is_map) {
|
||||
ValueHashMap map;
|
||||
for (const auto& [k, v] : obj.as<sol::table>()) {
|
||||
std::string key;
|
||||
if (k.get_type() == sol::type::number) {
|
||||
if (k.is<int64_t>()) {
|
||||
key = fmt::format("{}", k.as<int64_t>());
|
||||
} else {
|
||||
key = fmt::format("{:F}", k.as<double>());
|
||||
}
|
||||
} else if (k.get_type() == sol::type::string) {
|
||||
key = k.as<std::string>();
|
||||
} else {
|
||||
return Result<Value>("Failed to construct hash-map: Can't use non-string and non-number object as key for table{}", "");
|
||||
}
|
||||
auto maybe_val = sol_obj_to_value_impl(v, invalid_provider, max_depth, depth);
|
||||
if (maybe_val) [[likely]] {
|
||||
map.emplace(key, maybe_val.move());
|
||||
} else {
|
||||
return maybe_val; // error
|
||||
}
|
||||
}
|
||||
return { std::move(map) };
|
||||
} else {
|
||||
ValueArray array;
|
||||
for (const auto& [k, v] : obj.as<sol::table>()) {
|
||||
auto i = k.as<int64_t>() - 1; // -1 due to lua arrays starting at 1
|
||||
if (size_t(i) >= array.size()) {
|
||||
array.resize(size_t(i) + 1, Null {});
|
||||
}
|
||||
auto maybe_val = sol_obj_to_value_impl(v, invalid_provider, max_depth, depth);
|
||||
if (maybe_val) [[likely]] {
|
||||
array[size_t(i)] = maybe_val.move();
|
||||
} else {
|
||||
return maybe_val; // error
|
||||
}
|
||||
}
|
||||
return { std::move(array) };
|
||||
}
|
||||
}
|
||||
case sol::type::poly:
|
||||
if (invalid_provider) {
|
||||
return invalid_provider(obj);
|
||||
} else {
|
||||
return Result<Value>("Can't convert {} to Value", "lua poly");
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return Result<Value>("Unknown type, can't convert to value.{}", "");
|
||||
}
|
||||
|
||||
Result<Value> sol_obj_to_value(const sol::object& obj, const std::function<Result<Value>(const sol::object&)>& invalid_provider, size_t max_depth) {
|
||||
return sol_obj_to_value_impl(obj, invalid_provider, max_depth, 0);
|
||||
}
|
||||
|
||||
TEST_CASE("sol_obj_to_value") {
|
||||
sol::state state {};
|
||||
SUBCASE("nil") {
|
||||
sol::table obj = state.create_table();
|
||||
sol::object o = obj.get<sol::object>(0);
|
||||
CHECK_EQ(sol_obj_to_value(o).value().which(), VALUE_TYPE_IDX_NULL);
|
||||
}
|
||||
SUBCASE("string") {
|
||||
auto res = sol::make_object(state.lua_state(), "hello");
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_STRING);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto str = boost::get<std::string>(val);
|
||||
CHECK_EQ(str, "hello");
|
||||
}
|
||||
SUBCASE("int") {
|
||||
auto res = sol::make_object(state.lua_state(), 1234l);
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_INT);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto i = boost::get<int64_t>(val);
|
||||
CHECK_EQ(i, 1234l);
|
||||
}
|
||||
SUBCASE("double") {
|
||||
auto res = sol::make_object(state.lua_state(), 53.3);
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_DOUBLE);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto d = boost::get<double>(val);
|
||||
CHECK_EQ(d, 53.3);
|
||||
}
|
||||
SUBCASE("bool") {
|
||||
auto res = sol::make_object(state.lua_state(), true);
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_BOOL);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto d = boost::get<Bool>(val);
|
||||
CHECK_EQ(bool(d), true);
|
||||
}
|
||||
SUBCASE("table (map)") {
|
||||
auto res = state.create_table_with(
|
||||
"hello", "world",
|
||||
"x", 35l);
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_HASHMAP);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto m = boost::get<ValueHashMap>(val);
|
||||
CHECK(m.contains("hello"));
|
||||
CHECK(m.contains("x"));
|
||||
CHECK_EQ(boost::get<std::string>(m["hello"]), "world");
|
||||
CHECK_EQ(boost::get<int64_t>(m["x"]), 35l);
|
||||
}
|
||||
SUBCASE("table (array)") {
|
||||
auto res = state.create_table_with(
|
||||
1, 1,
|
||||
2, 2,
|
||||
3, 3,
|
||||
6, 6);
|
||||
CHECK_EQ(sol_obj_to_value(res).value().which(), VALUE_TYPE_IDX_ARRAY);
|
||||
auto val = sol_obj_to_value(res).value();
|
||||
auto m = boost::get<ValueArray>(val);
|
||||
CHECK_EQ(boost::get<int64_t>(m[0]), 1);
|
||||
CHECK_EQ(boost::get<int64_t>(m[1]), 2);
|
||||
CHECK_EQ(boost::get<int64_t>(m[2]), 3);
|
||||
CHECK_EQ(m[3].which(), VALUE_TYPE_IDX_NULL);
|
||||
CHECK_EQ(m[4].which(), VALUE_TYPE_IDX_NULL);
|
||||
CHECK_EQ(boost::get<int64_t>(m[5]), 6);
|
||||
}
|
||||
// TODO: add test for all the invalid types
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const Null&) {
|
||||
return os << "null";
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const Bool& b) {
|
||||
return os << (b ? "true" : "false");
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(const std::string& str) const {
|
||||
return boost::json::value_from(str);
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(int64_t i) const {
|
||||
return boost::json::value_from(i);
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(double d) const {
|
||||
return boost::json::value_from(d);
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(Null) const {
|
||||
return boost::json::value_from(nullptr);
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(Bool b) const {
|
||||
return boost::json::value_from(b.b);
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(const ValueArray& array) const {
|
||||
auto ja = boost::json::array();
|
||||
for (const auto& val : array) {
|
||||
auto obj = boost::apply_visitor(ValueToJsonVisitor(), val);
|
||||
ja.push_back(obj);
|
||||
}
|
||||
return ja;
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(const ValueTuple& tuple) const {
|
||||
auto ja = boost::json::array();
|
||||
for (const auto& val : tuple) {
|
||||
auto obj = boost::apply_visitor(ValueToJsonVisitor(), val);
|
||||
ja.push_back(obj);
|
||||
}
|
||||
return ja;
|
||||
}
|
||||
|
||||
boost::json::value ValueToJsonVisitor::operator()(const HashMap<std::string, Value>& map) const {
|
||||
auto jo = boost::json::object();
|
||||
for (const auto& [key, val] : map) {
|
||||
auto json_val = boost::apply_visitor(ValueToJsonVisitor(), val);
|
||||
jo.emplace(std::string(key), json_val);
|
||||
}
|
||||
return jo;
|
||||
}
|
||||
|
||||
ValueToLuaVisitor::ValueToLuaVisitor(sol::state& state)
|
||||
: m_state(state) {
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(const std::string& str) const {
|
||||
return sol::make_object(m_state.lua_state(), str);
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(int64_t i) const {
|
||||
return sol::make_object(m_state.lua_state(), i);
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(double d) const {
|
||||
return sol::make_object(m_state.lua_state(), d);
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(Null) const {
|
||||
return sol::lua_nil_t();
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(Bool b) const {
|
||||
return sol::make_object(m_state.lua_state(), b.b);
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(const ValueArray& array) const {
|
||||
auto table = m_state.create_table();
|
||||
for (const auto& val : array) {
|
||||
table.add(boost::apply_visitor(*this, val));
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(const ValueTuple& tuple) const {
|
||||
auto table = m_state.create_table();
|
||||
for (const auto& val : tuple) {
|
||||
table.add(boost::apply_visitor(*this, val));
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
sol::object ValueToLuaVisitor::operator()(const HashMap<std::string, Value>& map) const {
|
||||
auto table = m_state.create_table();
|
||||
for (const auto& [key, val] : map) {
|
||||
table.set(key, boost::apply_visitor(*this, val));
|
||||
}
|
||||
return table;
|
||||
}
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "VehicleData.h"
|
||||
|
||||
#include "Common.h"
|
||||
|
||||
+31
-55
@@ -1,32 +1,17 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#include "ArgsParser.h"
|
||||
#include "Common.h"
|
||||
#include "Http.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "LuaPlugin.h"
|
||||
#include "Plugin.h"
|
||||
#include "PluginManager.h"
|
||||
#include "SignalHandling.h"
|
||||
#include "TConfig.h"
|
||||
#include "THeartbeatThread.h"
|
||||
#include <cstdlib>
|
||||
#include "TLuaEngine.h"
|
||||
#include "TNetwork.h"
|
||||
#include "TPPSMonitor.h"
|
||||
#include "TPluginMonitor.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TServer.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
@@ -84,6 +69,7 @@ int main(int argc, char** argv) {
|
||||
|
||||
int BeamMPServerMain(MainArguments Arguments) {
|
||||
setlocale(LC_ALL, "C");
|
||||
Application::InitializeConsole();
|
||||
ArgsParser Parser;
|
||||
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
|
||||
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
|
||||
@@ -94,17 +80,16 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
return 1;
|
||||
}
|
||||
if (Parser.FoundArgument({ "help" })) {
|
||||
Application::Console().Internal().set_prompt("");
|
||||
Application::Console().WriteRaw(sCommandlineArguments);
|
||||
return 0;
|
||||
}
|
||||
if (Parser.FoundArgument({ "version" })) {
|
||||
Application::Console().Internal().set_prompt("");
|
||||
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
|
||||
return 0;
|
||||
}
|
||||
|
||||
// badly seed C's rng - this is only because rand() is used here and there for unimportant stuff
|
||||
std::srand(std::time(0));
|
||||
|
||||
std::string ConfigPath = "ServerConfig.toml";
|
||||
if (Parser.FoundArgument({ "config" })) {
|
||||
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
|
||||
@@ -125,21 +110,10 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
}
|
||||
}
|
||||
|
||||
TConfig Config(ConfigPath);
|
||||
|
||||
if (Config.Failed()) {
|
||||
beammp_info("Closing in 10 seconds");
|
||||
// loop to make it possible to ctrl+c instead
|
||||
for (size_t i = 0; i < 20; ++i) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
Application::InitializeConsole();
|
||||
Application::Console().StartLoggingToFile();
|
||||
|
||||
Application::SetSubsystemStatus("Main", Application::Status::Starting);
|
||||
|
||||
Application::Console().StartLoggingToFile();
|
||||
|
||||
SetupSignalHandlers();
|
||||
|
||||
bool Shutdown = false;
|
||||
@@ -148,36 +122,38 @@ int BeamMPServerMain(MainArguments Arguments) {
|
||||
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
|
||||
Shutdown = true;
|
||||
});
|
||||
/*
|
||||
Application::RegisterShutdownHandler([] {
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
|
||||
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
|
||||
});
|
||||
|
||||
TServer Server(Arguments.List);
|
||||
TConfig Config(ConfigPath);
|
||||
auto LuaEngine = std::make_shared<TLuaEngine>();
|
||||
LuaEngine->SetServer(&Server);
|
||||
Application::Console().InitializeLuaConsole(*LuaEngine);
|
||||
|
||||
*/
|
||||
if (Config.Failed()) {
|
||||
beammp_info("Closing in 10 seconds");
|
||||
// loop to make it possible to ctrl+c instead
|
||||
for (size_t i = 0; i < 20; ++i) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
RegisterThread("Main");
|
||||
|
||||
beammp_trace("Running in debug mode on a debug build");
|
||||
std::shared_ptr<Network> network = std::make_shared<Network>();
|
||||
THeartbeatThread Heartbeat(network);
|
||||
// LuaEngine->SetNetwork(network);
|
||||
TResourceManager ResourceManager;
|
||||
TPPSMonitor PPSMonitor(Server);
|
||||
THeartbeatThread Heartbeat(ResourceManager, Server);
|
||||
TNetwork Network(Server, PPSMonitor, ResourceManager);
|
||||
LuaEngine->SetNetwork(&Network);
|
||||
PPSMonitor.SetNetwork(Network);
|
||||
Application::CheckForUpdates();
|
||||
|
||||
// TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||
PluginManager PluginManager;
|
||||
(void)PluginManager.add_plugin(Plugin::make_pointer<LuaPlugin>("Resources/Server/Test"));
|
||||
auto console = Plugin::make_pointer<LuaPlugin>(BEAMMP_MEMORY_STATE);
|
||||
(void)PluginManager.add_plugin(console);
|
||||
|
||||
dynamic_cast<LuaPlugin&>(*console).run_raw_lua(R"(local n = 12; return n)");
|
||||
|
||||
PluginManager.trigger_event("onInit", std::make_shared<Value>(HashMap<std::string, Value> {
|
||||
{ "big", "balls" },
|
||||
{ "longer", "falls" },
|
||||
}));
|
||||
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
|
||||
|
||||
if (Application::Settings.HTTPServerEnabled) {
|
||||
Http::Server::THttpServerInstance HttpServerInstance {};
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
// BeamMP, the BeamNG.drive multiplayer mod.
|
||||
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
|
||||
//
|
||||
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published
|
||||
// by the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
#define DOCTEST_CONFIG_IMPLEMENT
|
||||
#include <doctest/doctest.h>
|
||||
|
||||
|
||||
+1
-1
Submodule vcpkg updated: 8397227251...72010900b7
+8
-11
@@ -2,21 +2,18 @@
|
||||
"name": "server",
|
||||
"version-string": "0.1.0",
|
||||
"dependencies": [
|
||||
"fmt",
|
||||
"doctest",
|
||||
"boost-asio",
|
||||
"boost-variant",
|
||||
"boost-spirit",
|
||||
"boost-uuid",
|
||||
"boost-variant",
|
||||
"boost-iostreams",
|
||||
"boost-json",
|
||||
"cpp-httplib",
|
||||
"doctest",
|
||||
"fmt",
|
||||
"toml11",
|
||||
"libzip",
|
||||
"rapidjson",
|
||||
"nlohmann-json",
|
||||
"openssl",
|
||||
"rapidjson",
|
||||
"sol2",
|
||||
"toml11",
|
||||
"zstd",
|
||||
"glm"
|
||||
"sol2"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user