mirror of
https://github.com/SantaSpeen/BeamMP-Server.git
synced 2026-02-16 16:20:41 +00:00
Compare commits
4 Commits
rc-v3.1.0
...
feature-dl
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b209e70d62 | ||
|
|
5394122d77 | ||
|
|
f48b8ff1a1 | ||
|
|
de2a3795cc |
15
.github/workflows/cmake-linux.yml
vendored
15
.github/workflows/cmake-linux.yml
vendored
@@ -1,11 +1,6 @@
|
||||
name: CMake Linux Build
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
@@ -68,16 +63,16 @@ jobs:
|
||||
with:
|
||||
name: BeamMP-Server-linux-tests
|
||||
path: ${{github.workspace}}
|
||||
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y liblua5.3 openssl
|
||||
sudo apt-get install -y liblua5.3 openssl
|
||||
|
||||
- name: Test
|
||||
working-directory: ${{github.workspace}}
|
||||
shell: bash
|
||||
run: |
|
||||
chmod +x ./BeamMP-Server-tests
|
||||
./BeamMP-Server-tests
|
||||
chmod +x ./BeamMP-Server-tests
|
||||
./BeamMP-Server-tests
|
||||
|
||||
24
.github/workflows/cmake-windows.yml
vendored
24
.github/workflows/cmake-windows.yml
vendored
@@ -1,11 +1,6 @@
|
||||
name: CMake Windows Build
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
types: [opened, reopened]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
BUILD_TYPE: Release
|
||||
@@ -13,20 +8,20 @@ env:
|
||||
jobs:
|
||||
windows-build:
|
||||
runs-on: windows-latest
|
||||
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: "recursive"
|
||||
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Restore artifacts, or run vcpkg, build and cache artifacts
|
||||
uses: lukka/run-vcpkg@v7
|
||||
id: runvcpkg
|
||||
with:
|
||||
vcpkgArguments: "lua zlib rapidjson openssl websocketpp curl"
|
||||
vcpkgDirectory: "${{ runner.workspace }}/b/vcpkg"
|
||||
vcpkgGitCommitId: "a106de33bbee694e3be6243718aa2a549a692832"
|
||||
vcpkgTriplet: "x64-windows-static"
|
||||
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl'
|
||||
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
|
||||
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832'
|
||||
vcpkgTriplet: 'x64-windows-static'
|
||||
|
||||
- name: Create Build Environment
|
||||
run: cmake -E make_directory ${{github.workspace}}/build-windows
|
||||
@@ -54,9 +49,10 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
cmake --build . --config Debug
|
||||
|
||||
|
||||
- name: Archive debug artifacts
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Server-debug.exe
|
||||
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
|
||||
|
||||
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -31,3 +31,6 @@
|
||||
[submodule "deps/doctest"]
|
||||
path = deps/doctest
|
||||
url = https://github.com/doctest/doctest
|
||||
[submodule "deps/dlhttp"]
|
||||
path = deps/dlhttp
|
||||
url = https://github.com/lionkor/dlhttp
|
||||
|
||||
124
CMakeLists.txt
124
CMakeLists.txt
@@ -9,16 +9,20 @@ project(BeamMP-Server
|
||||
HOMEPAGE_URL https://beammp.com
|
||||
LANGUAGES CXX C)
|
||||
|
||||
find_package(Git REQUIRED)
|
||||
# Update submodules as needed
|
||||
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||
if(GIT_SUBMODULE)
|
||||
message(STATUS "Submodule update")
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
||||
option(BEAMMP_RUN_GIT "Run git to make sure submodules are updated (leave this on unless you know what you're doing)" ON)
|
||||
|
||||
if (BEAMMP_RUN_GIT)
|
||||
find_package(Git REQUIRED)
|
||||
# Update submodules as needed
|
||||
option(GIT_SUBMODULE "Check submodules during build" ON)
|
||||
if(GIT_SUBMODULE)
|
||||
message(STATUS "Submodule update")
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
message(FATAL_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
@@ -26,25 +30,24 @@ endif()
|
||||
set(HTTPLIB_REQUIRE_OPENSSL ON)
|
||||
set(SENTRY_BUILD_SHARED_LIBS OFF)
|
||||
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/websocketpp")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include")
|
||||
include_directories("${CMAKE_CURRENT_SOURCE_DIR}/deps")
|
||||
|
||||
add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
|
||||
|
||||
# ------------------------ APPLE ---------------------------------
|
||||
if(APPLE)
|
||||
if(IS_DIRECTORY /opt/homebrew/Cellar/lua@5.3/5.3.6)
|
||||
set(LUA_INCLUDE_DIR /opt/homebrew/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||
link_directories(/opt/homebrew/Cellar/lua@5.3/5.3.6/lib)
|
||||
else()
|
||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||
endif()
|
||||
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
|
||||
set(LUA_LIBRARIES lua)
|
||||
if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
|
||||
include_directories(/opt/homebrew/opt/openssl@1.1/include)
|
||||
link_directories(/opt/homebrew/opt/openssl@1.1/lib)
|
||||
else()
|
||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||
endif()
|
||||
include_directories(/usr/local/opt/openssl@1.1/include)
|
||||
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib)
|
||||
link_directories(/usr/local/opt/openssl@1.1/lib)
|
||||
# ------------------------ WINDOWS ---------------------------------
|
||||
elseif (WIN32)
|
||||
# this has to happen before sentry, so that crashpad on windows links with these settings.
|
||||
@@ -53,15 +56,17 @@ elseif (WIN32)
|
||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||
# ------------------------ LINUX ---------------------------------
|
||||
elseif (UNIX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
|
||||
option(SANITIZE "Turns on thread and UB sanitizers" OFF)
|
||||
if (SANITIZE)
|
||||
message(STATUS "sanitize is ON")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize={address,thread,undefined}")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
|
||||
endif (SANITIZE)
|
||||
endif ()
|
||||
|
||||
include_directories("include/sentry-native/include")
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
# ------------------------ SENTRY ---------------------------------
|
||||
message(STATUS "Checking for Sentry URL")
|
||||
@@ -120,55 +125,19 @@ set(BeamMP_Sources
|
||||
)
|
||||
|
||||
set(BeamMP_Includes
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
|
||||
${LUA_INCLUDE_DIR}
|
||||
${CURL_INCLUDE_DIRS}
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/json/single_include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/sol2/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/rapidjson/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps/asio/asio/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/deps"
|
||||
"include/tomlplusplus"
|
||||
"include/sentry-native/include"
|
||||
"include/curl/include"
|
||||
)
|
||||
|
||||
set(BeamMP_Definitions
|
||||
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
|
||||
)
|
||||
|
||||
if (UNIX)
|
||||
set(BeamMP_CompileOptions
|
||||
-Wall
|
||||
-Wextra
|
||||
-Wpedantic
|
||||
|
||||
-Werror=uninitialized
|
||||
-Werror=float-equal
|
||||
-Werror=pointer-arith
|
||||
-Werror=double-promotion
|
||||
-Werror=write-strings
|
||||
-Werror=cast-qual
|
||||
-Werror=init-self
|
||||
-Werror=cast-align
|
||||
-Werror=unreachable-code
|
||||
-Werror=strict-aliasing -fstrict-aliasing
|
||||
-Werror=redundant-decls
|
||||
-Werror=missing-declarations
|
||||
-Werror=missing-field-initializers
|
||||
-Werror=write-strings
|
||||
-Werror=ctor-dtor-privacy
|
||||
-Werror=switch-enum
|
||||
-Werror=switch-default
|
||||
-Werror=old-style-cast
|
||||
-Werror=overloaded-virtual
|
||||
-Werror=zero-as-null-pointer-constant
|
||||
-Werror=overloaded-virtual
|
||||
-Werror=missing-include-dirs
|
||||
-Werror=unused-result
|
||||
|
||||
-fstack-protector
|
||||
)
|
||||
endif()
|
||||
|
||||
set(BeamMP_Libraries
|
||||
doctest::doctest
|
||||
OpenSSL::SSL
|
||||
@@ -180,6 +149,7 @@ set(BeamMP_Libraries
|
||||
${LUA_LIBRARIES}
|
||||
commandline
|
||||
sentry
|
||||
dlhttp
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
@@ -198,15 +168,7 @@ target_compile_definitions(BeamMP-Server PRIVATE
|
||||
DOCTEST_CONFIG_DISABLE
|
||||
)
|
||||
|
||||
target_compile_options(BeamMP-Server PRIVATE
|
||||
${BeamMP_CompileOptions}
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server SYSTEM PRIVATE
|
||||
target_include_directories(BeamMP-Server PUBLIC
|
||||
${BeamMP_Includes}
|
||||
)
|
||||
|
||||
@@ -228,19 +190,11 @@ if(BUILD_TESTS)
|
||||
target_compile_definitions(BeamMP-Server-tests PRIVATE
|
||||
${BeamMP_Definitions}
|
||||
)
|
||||
|
||||
target_compile_options(BeamMP-Server-tests PRIVATE
|
||||
${BeamMP_CompileOptions}
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server-tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
|
||||
target_include_directories(BeamMP-Server-tests SYSTEM PRIVATE
|
||||
target_include_directories(BeamMP-Server-tests PUBLIC
|
||||
${BeamMP_Includes}
|
||||
)
|
||||
|
||||
|
||||
target_link_libraries(BeamMP-Server-tests
|
||||
${BeamMP_Libraries}
|
||||
${BeamMP_PlatformLibs}
|
||||
|
||||
111
CONTRIBUTING.md
111
CONTRIBUTING.md
@@ -1,111 +0,0 @@
|
||||
# Contributing to BeamMP-Server
|
||||
|
||||
Unlike other parts of BeamMP, the BeamMP-Server does not have any dependency to the BeamNG.drive game.
|
||||
|
||||
To contribute *C++ code*, you'll need a MacOS, Linux or Windows PC, and intermediate to advanced knowledge of C++.
|
||||
For reference, you should know be reasonably comfortable with the STL, the concept of RAII, templates, and generally know how to read & write post-C++17 code. To contribute anything else, you won't need most of this (though it'd be helpful to have some vocabulary about computers).
|
||||
|
||||
# Ways to Contribute
|
||||
|
||||
## Bug Reports
|
||||
|
||||
If you work with BeamMP-Server, either by simply using it, or even writing plugins for it, and you run into any issues, we definitely want to know about it. Please use [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues) and select the "Bug" template, read it, and fill it out accordingly.
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
If you are interested in fixing bugs, check out the [GitHub issues](https://github.com/BeamMP/BeamMP-Server/issues). There, you can pick any issue that has nobody assigned to it. For example, some bugs which we definitely need some help with are marked with the "help wanted" tag.
|
||||
|
||||
Once you picked a bug, you need to reproduce it. Start by following the instructions in the bug report, and don't be afraid to ask for more information or clarification on the issue itself.
|
||||
|
||||
Refer to [getting started with the codebase](#getting-started-with-the-codebase) for more information on how to build the server. You can also ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||
|
||||
## Features
|
||||
|
||||
If you want to add new features, please make an issue for it first or ask on our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`).
|
||||
|
||||
You need to make sure the feature isn't being worked on by someone else, and aligns with the vision we have for the server.
|
||||
|
||||
# Git Guidelines
|
||||
|
||||
**Read this carefully. Failing to follow these rules results in your changes not being accepted**. This applies for outside contributors, members of the BeamMP development team ("BeamMP Developers"), project owners, maintainers, frequent contributors, and literally everyone else. **It applies to everyone**.
|
||||
|
||||
## How to Commit
|
||||
|
||||
Commit messages **MUST** (mandatory):
|
||||
|
||||
- start with a **lower case action verb in present tense**, for example `add`, `fix`, `implement`, `refactor`, `remove`, `rename`. *Counter examples (these are bad): ~~`Fixed`, `fixing`, `added`, `removing`~~*.
|
||||
- not have a first line much longer than 70 characters.
|
||||
- explain briefly the changes made.
|
||||
- reference the issue by number, if there is an issue the commit addresses, like so: `#<number>`. Example: `#123`.
|
||||
|
||||
If any of these are not followed, **your changes will not be accepted.**
|
||||
|
||||
Commit messages **SHOULD** (optional, "nice to have"):
|
||||
|
||||
- only address one "atomic" change.
|
||||
- have an empty second line, and the subsequent lines explaining the changes in more detail (if more detail is available).
|
||||
|
||||
Commits may be squashed (via a Git "interactive rebase") in order to satisfy these rules, but history that is >1h old should not be rewritten if possible. Force pushes are ugly ;)
|
||||
|
||||
## Pulling, Merging
|
||||
|
||||
Do **NOT** pull with merge. This is the default git behavior for `git pull`, but creates ugly and unnecessary commit messages like `"merge origin/master into master"`. Instead, pull with rebase, for example via `git pull -r`. If you get conflicts, resolve them properly.
|
||||
|
||||
The only acceptable merge commits are those which actually merge functionally different branches into each other, for example for merging one feature branch into another.
|
||||
|
||||
## Branches
|
||||
|
||||
### Which branch should I base my work on?
|
||||
|
||||
Each *feature* or *bug-fix* is implemented on a new Git branch, branched off of the branch it should be based on. The `master` branch is usually stable, so we don't do development on it. It is always a safe bet to branch off of `master`, but it may be more work to merge later. Branches to base your work on are usually branches like `rc-v3.3.0`, when the latest public version is `3.2.0`, for example. These can often be found in Pull-Requests on GitHub which are tagged `Release Candidate`.
|
||||
|
||||
## Unit tests & CI/CD
|
||||
|
||||
We use GitHub Actions, which runs our unit-tests. PR's which fail these tests, or even fail any of our actions (which run automatically), will not be merged and require further changes until they compile, link, and all tests pass properly. If you have issues with this, feel free to ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`)
|
||||
|
||||
### What should I call by branch?
|
||||
|
||||
Keep branch names **unique**, **descriptive**, and **shorter than 30 characters**. Names must be in present-tense, such as `fix-xyz`, **not** ~~`fixing-xyz`~~.
|
||||
|
||||
We generally use *feature branches*, so we keep one branch per feature or fix.
|
||||
|
||||
For example:
|
||||
- You want to fix issue number #123? You could call the branch `fix-123`.
|
||||
- You want to add a feature described in issue #456? You could call the branch `implement-456`.
|
||||
- You want to add a feature or fix a bug that has no issue? You should probably make an issue for it first! Or, if you're not ready for that yet, you could call it by the feature name or bug description, for example for a bug that makes cars disappear: `fix-disappearing-cars`.
|
||||
|
||||
## Pull Requests, Code Review
|
||||
|
||||
Once you are ready to show what you did, and get feedback on it, you open a Pull-Request on GitHub. Please make sure to pick the right branches, and a descriptive title. Mention any related issues with `#<issue number>`, for example `#123`.
|
||||
|
||||
Make sure to explain what the PR does, what it fixes, and what needs to still be done (if anything).
|
||||
|
||||
A BeamMP-Developer must review your code in detail, and leave a review. If this takes too long, feel free to @ a maintainer/developer, or leave another comment on the PR. It helps to say something like "Ready for review", for example.
|
||||
|
||||
# Getting Started with the Codebase
|
||||
|
||||
1. Look at current Pull-Requests, look at the git branches, or ask in our [Discord server](https://discord.gg/beammp), or on IRC ([irc.libera.chat](https://web.libera.chat/), join `#beammp`), in order to find out which branch you should work on to minimize conflict. See [this section on branches](#branches) for more info.
|
||||
2. Fork the repository (with that branch) on GitHub. GitHub, by default, gives you only the `master` branch when forking, so make sure you fork with other branches enabled when you want to work on a branch that isn't master (it's a checkbox when you fork).
|
||||
3. Clone the fork to your local machine.
|
||||
4. Check out the branch you want to work on (see 1.).
|
||||
5. Run `git submodule update --init --recursive`.
|
||||
6. Make a new branch for your feature or fix from the branch you are on. You can do this via `git checkout -b <branch name>`. See [this section on branches](#branches) for more info on branch naming.
|
||||
7. Install all dependencies. Those are usually listed in the `README.md` in the branch you're in, or, more reliably, in one of the files in `.github/workflows` (if you can read `yaml`).
|
||||
8. Run CMake to configure the project. You can find tutorials on this online. You will want to tell CMake to build with `CMAKE_BUILD_TYPE=Debug`, for example by passing it to CMake via the commandline switch `-DCMAKE_BUILD_TYPE=Debug`. You may also want to turn off sentry by setting `SENTRY_BACKEND=none` (for example via commandline switch `-DSENTRY_BACKEND=none`). An example invocation on Linux with GNU make would be
|
||||
`cmake . -DCMAKE_BUILD_TYPE=Debug -DSENTRY_BACKEND=none` .
|
||||
9. Build the `BeamMP-Server` target to build the BeamMP-Server, or the `BeamMP-Server-tests` target to build the unit-tests (does not include a working server). In the example from 8. (on Linux), you could build with `make BeamMP-Server`, `make -j BeamMP-Server` or `cmake --build . --parallel --target BeamMP-Server` . Or, on Windows, (in Visual Studio), you would just press some big green "run" or "debug" button.
|
||||
10. When making changes, refer to [this section on how to commit properly](#how-to-commit). Not following those guidelines will result in your changes being rejected, so please take a look.
|
||||
11. Make sure to add Unit-tests with `doctest` if you build new stuff. You can find examples all over the latest version of the codebase (search for `TEST_CASE`).
|
||||
|
||||
# Code Guidelines
|
||||
|
||||
## Formatting
|
||||
|
||||
1. Use `clang-format` to format your code before committig. A `.clang-format` file is provided in the root of the repository.
|
||||
2. All identifiers, type names, function names, etc. should be `PascalCase`. Type names may also have the `T` prefix, although this is not enforced (for example `TNetwork`).
|
||||
|
||||
## Modular code
|
||||
|
||||
Write code that is modular and testable. Generally, if you can write a good unit-test for it, it's modular. If you can't, it's not.
|
||||
|
||||
Don't overdo it though - sometimes its okay to just write code, do the job, be done with it. You'll get feedback on this in the code review for your PR.
|
||||
@@ -6,17 +6,13 @@
|
||||
- ADDED MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa
|
||||
- ADDED FS.ListFiles and FS.ListDirectories
|
||||
- ADDED onFileChanged event, triggered when a server plugin file changes
|
||||
- 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
|
||||
- FIXED `ip` in MP.GetPlayerIdentifiers
|
||||
- FIXED issue with client->server events which contain `:`
|
||||
- FIXED `ip` in MP.GetIdentifiers
|
||||
- FIXED issue with client->server events which contain ':'
|
||||
- FIXED a fatal exception on LuaEngine startup if Resources/Server is a symlink
|
||||
- FIXED onInit not being called on hot-reload
|
||||
- FIXED incorrect timing calculation of Lua EventTimer loop
|
||||
- FIXED bug which caused hot-reload not to report syntax errors
|
||||
- FIXED missing error messages on some event handler calls
|
||||
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
|
||||
|
||||
# v3.0.2
|
||||
|
||||
|
||||
62
README.md
62
README.md
@@ -4,9 +4,9 @@
|
||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22)
|
||||
|
||||
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).
|
||||
The server is the point throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
|
||||
|
||||
**For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
|
||||
**For Linux, you __need__ the runtime dependencies, listed below under "prerequisites".**
|
||||
|
||||
## Support + Contact
|
||||
|
||||
@@ -14,7 +14,6 @@ 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)
|
||||
|
||||
## Minimum Requirements
|
||||
|
||||
@@ -29,13 +28,13 @@ These values are guesstimated and are subject to change with each release.
|
||||
|
||||
## Contributing
|
||||
|
||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned.
|
||||
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column.
|
||||
|
||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues). Any issues that have the "help wanted" label or don't have anyone assigned are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) and at the [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer). Any issues that have the "help wanted" label or don't have anyone assigned and any trello cards that aren't assigned or in the "In-Progress" section are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
|
||||
|
||||
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
|
||||
|
||||
If you need support with understanding the codebase, please write us in the Discord. You'll need to be proficient in modern C++.
|
||||
If you need support with understanding the codebase, please write us in the discord. You'll need to be proficient in modern C++.
|
||||
|
||||
## About Building from Source
|
||||
|
||||
@@ -43,7 +42,7 @@ We only allow building unmodified (original) source code for public use. `master
|
||||
|
||||
## Supported Operating Systems
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
@@ -53,7 +52,7 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
|
||||
|
||||
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__**
|
||||
|
||||
Currently only Linux and Windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
|
||||
|
||||
### Prerequisites
|
||||
|
||||
@@ -61,7 +60,7 @@ Currently only Linux and Windows are supported (generally). See [Releases](https
|
||||
|
||||
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
|
||||
|
||||
Dependencies for **Windows** can be installed with `vcpkg`.
|
||||
Dependencies for **windows** can be installed with `vcpkg`.
|
||||
These are:
|
||||
```
|
||||
lua
|
||||
@@ -74,15 +73,19 @@ curl
|
||||
|
||||
#### Linux
|
||||
|
||||
Runtime dependencies - you want to find packages for:
|
||||
- libz
|
||||
- rapidjson
|
||||
- lua5.3
|
||||
- ssl / openssl
|
||||
- websocketpp
|
||||
- curl (with ssl support)
|
||||
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
|
||||
|
||||
Build-time dependencies are:
|
||||
Runtime dependencies for **linux** are (debian/ubuntu):
|
||||
```
|
||||
libz-dev
|
||||
rapidjson-dev
|
||||
liblua5.3
|
||||
libssl-dev
|
||||
libwebsocketpp-dev
|
||||
libcurl4-openssl-dev
|
||||
```
|
||||
|
||||
Build-time dependencies for **linux** are:
|
||||
```
|
||||
git
|
||||
make
|
||||
@@ -90,24 +93,29 @@ cmake
|
||||
g++
|
||||
```
|
||||
|
||||
For other distributions (e.g. Arch) you want to find packages for:
|
||||
- libz
|
||||
- rapidjson
|
||||
- lua5.3
|
||||
- ssl / openssl
|
||||
- websocketpp
|
||||
- curl (with ssl support)
|
||||
- \+ the build time dependencies from above
|
||||
|
||||
### How to build
|
||||
|
||||
On Windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||
On windows, use git-bash for these commands. On Linux, these should work in your shell.
|
||||
|
||||
1. Make sure you have all [prerequisites](#prerequisites) installed
|
||||
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
|
||||
3. Change into the BeamMP-Server directory by running `cd BeamMP-Server`.
|
||||
4. Checkout the branch of the release you want to compile, for example `git checkout tags/v3.0.2` for version 3.0.2. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||
5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
|
||||
6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||
7. Run `make`
|
||||
8. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`.
|
||||
4. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v3.0.1` for version 3.0.1. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
|
||||
5. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
|
||||
6. Run `make`
|
||||
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
|
||||
|
||||
*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).
|
||||
|
||||
14
deps/CMakeLists.txt
vendored
14
deps/CMakeLists.txt
vendored
@@ -1,6 +1,14 @@
|
||||
include_directories("${PROJECT_SOURCE_DIR}/deps")
|
||||
include_directories("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/commandline")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
|
||||
if (NOT TARGET fmt)
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
|
||||
endif()
|
||||
if (NOT TARGET sol2)
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/sol2")
|
||||
endif()
|
||||
if (NOT TARGET doctest)
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/doctest")
|
||||
endif()
|
||||
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/dlhttp")
|
||||
|
||||
2
deps/asio
vendored
2
deps/asio
vendored
Submodule deps/asio updated: 4915cfd8a1...d038fb3c2f
2
deps/commandline
vendored
2
deps/commandline
vendored
Submodule deps/commandline updated: 7b9f51d6a0...d6b1c32c8a
2
deps/cpp-httplib
vendored
2
deps/cpp-httplib
vendored
Submodule deps/cpp-httplib updated: d92c314466...47044c05a8
1
deps/dlhttp
vendored
Submodule
1
deps/dlhttp
vendored
Submodule
Submodule deps/dlhttp added at f507c6c4e6
2
deps/doctest
vendored
2
deps/doctest
vendored
Submodule deps/doctest updated: b7c21ec5ce...7b98851331
2
deps/fmt
vendored
2
deps/fmt
vendored
Submodule deps/fmt updated: c4ee726532...ce246aaf74
2
deps/json
vendored
2
deps/json
vendored
Submodule deps/json updated: 69d744867f...ede6667858
2
deps/libzip
vendored
2
deps/libzip
vendored
Submodule deps/libzip updated: 5532f9baa0...76df02f86b
2
deps/sentry-native
vendored
2
deps/sentry-native
vendored
Submodule deps/sentry-native updated: 87e67ad783...90966cc102
2
deps/sol2
vendored
2
deps/sol2
vendored
Submodule deps/sol2 updated: eba86625b7...c068aefbed
2
deps/toml11
vendored
2
deps/toml11
vendored
Submodule deps/toml11 updated: c7627ff6a1...1400dd223f
@@ -39,13 +39,11 @@ public:
|
||||
|
||||
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(sockaddr_in Addr) { mUDPAddress = Addr; }
|
||||
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
|
||||
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
|
||||
@@ -95,9 +93,7 @@ private:
|
||||
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";
|
||||
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
|
||||
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
|
||||
|
||||
@@ -14,13 +14,14 @@ extern TSentry Sentry;
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <zlib.h>
|
||||
|
||||
#include <doctest/doctest.h>
|
||||
#include <filesystem>
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
#include "Compat.h"
|
||||
|
||||
#include "TConsole.h"
|
||||
|
||||
struct Version {
|
||||
@@ -32,9 +33,6 @@ struct Version {
|
||||
std::string AsString();
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
using SparseArray = std::unordered_map<size_t, T>;
|
||||
|
||||
// static class handling application start, shutdown, etc.
|
||||
// yes, static classes, singletons, globals are all pretty
|
||||
// bad idioms. In this case we need a central way to access
|
||||
@@ -57,6 +55,7 @@ public:
|
||||
int MaxCars { 1 };
|
||||
bool DebugModeEnabled { false };
|
||||
int Port { 30814 };
|
||||
int DownloadThreads { 4 };
|
||||
std::string CustomIP {};
|
||||
bool LogChat { true };
|
||||
bool SendErrors { true };
|
||||
@@ -275,11 +274,11 @@ inline T Comp(const T& Data) {
|
||||
// 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.zalloc = Z_NULL;
|
||||
defstream.zfree = Z_NULL;
|
||||
defstream.opaque = Z_NULL;
|
||||
defstream.avail_in = (uInt)Data.size();
|
||||
defstream.next_in = (Bytef*)&Data[0];
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
@@ -300,13 +299,13 @@ inline T DeComp(const T& Compressed) {
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = nullptr;
|
||||
infstream.zfree = nullptr;
|
||||
infstream.opaque = nullptr;
|
||||
infstream.zalloc = Z_NULL;
|
||||
infstream.zfree = Z_NULL;
|
||||
infstream.opaque = Z_NULL;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||
infstream.next_in = (Bytef*)(&Compressed[0]);
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
||||
infstream.next_out = (Bytef*)(C.data());
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
@@ -321,3 +320,5 @@ inline T DeComp(const T& Compressed) {
|
||||
|
||||
std::string GetPlatformAgnosticErrorString();
|
||||
#define S_DSN SU_RAW
|
||||
|
||||
void LogChatMessage(const std::string& name, int id, const std::string& msg);
|
||||
|
||||
@@ -58,17 +58,16 @@ inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const ch
|
||||
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
|
||||
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
|
||||
#else
|
||||
#define beammp_assert(cond) \
|
||||
do { \
|
||||
bool result = (cond); \
|
||||
if (!result) { \
|
||||
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
|
||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
||||
} \
|
||||
// In release build, these macros turn into NOPs. The compiler will optimize these out.
|
||||
#define beammp_assert(cond) \
|
||||
do { \
|
||||
bool result = (cond); \
|
||||
if (!result) { \
|
||||
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
|
||||
} \
|
||||
} while (false)
|
||||
#define beammp_assert_not_reachable() \
|
||||
do { \
|
||||
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
|
||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
||||
#define beammp_assert_not_reachable() \
|
||||
do { \
|
||||
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \
|
||||
} while (false)
|
||||
#endif // DEBUG
|
||||
|
||||
@@ -9,8 +9,6 @@
|
||||
#if defined(BEAMMP_LINUX)
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
|
||||
#pragma GCC diagnostic ignored "-Wcast-qual"
|
||||
#pragma GCC diagnostic ignored "-Wold-style-cast"
|
||||
#endif
|
||||
#include <httplib.h>
|
||||
#if defined(BEAMMP_LINUX)
|
||||
|
||||
@@ -12,12 +12,12 @@ namespace MP {
|
||||
|
||||
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);
|
||||
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
|
||||
bool TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
|
||||
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
|
||||
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 DropPlayer(int ID, std::optional<std::string> MaybeReason);
|
||||
void SendChatMessage(int ID, const std::string& Message);
|
||||
void RemoveVehicle(int PlayerID, int VehicleID);
|
||||
void Set(int ConfigID, sol::object NewValue);
|
||||
bool IsPlayerGuest(int ID);
|
||||
bool IsPlayerConnected(int ID);
|
||||
|
||||
@@ -96,13 +96,6 @@ public:
|
||||
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();
|
||||
@@ -179,7 +172,6 @@ public:
|
||||
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);
|
||||
@@ -207,7 +199,6 @@ private:
|
||||
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();
|
||||
@@ -220,7 +211,6 @@ private:
|
||||
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);
|
||||
|
||||
@@ -38,5 +38,4 @@ private:
|
||||
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);
|
||||
};
|
||||
|
||||
@@ -47,23 +47,6 @@ 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(Ident);
|
||||
}
|
||||
catch (const std::out_of_range& oor) {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
void TClient::SetCarPosition(int Ident, const std::string& Data) {
|
||||
std::unique_lock lock(mVehiclePositionMutex);
|
||||
mVehiclePosition[Ident] = Data;
|
||||
}
|
||||
|
||||
std::string TClient::GetCarData(int Ident) {
|
||||
{ // lock
|
||||
std::unique_lock lock(mVehicleDataMutex);
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#include "Compat.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Http.h"
|
||||
|
||||
@@ -171,8 +170,6 @@ void Application::SetSubsystemStatus(const std::string& Subsystem, Status status
|
||||
case Status::Shutdown:
|
||||
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
|
||||
break;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
std::unique_lock Lock(mSystemStatusMapMutex);
|
||||
mSystemStatusMap[Subsystem] = status;
|
||||
@@ -198,7 +195,7 @@ void Application::CheckForUpdates() {
|
||||
// checks current version against latest version
|
||||
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
|
||||
for (const auto& url : GetBackendUrlsInOrder()) {
|
||||
auto Response = Http::GET(url, 443, "/v/s");
|
||||
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/v/s");
|
||||
bool Matches = std::regex_match(Response, VersionRegex);
|
||||
if (Matches) {
|
||||
auto MyVersion = ServerVersion();
|
||||
@@ -350,7 +347,5 @@ std::string GetPlatformAgnosticErrorString() {
|
||||
}
|
||||
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
|
||||
return std::strerror(errno);
|
||||
#else
|
||||
return "(no human-readable errors on this platform)";
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
static struct termios old, current;
|
||||
|
||||
static void initTermios(int echo) {
|
||||
void initTermios(int echo) {
|
||||
tcgetattr(0, &old); /* grab old terminal i/o settings */
|
||||
current = old; /* make new settings same as old settings */
|
||||
current.c_lflag &= ~ICANON; /* disable buffered i/o */
|
||||
@@ -19,7 +19,7 @@ static void initTermios(int echo) {
|
||||
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
|
||||
}
|
||||
|
||||
static void resetTermios(void) {
|
||||
void resetTermios(void) {
|
||||
tcsetattr(0, TCSANOW, &old);
|
||||
}
|
||||
|
||||
@@ -36,23 +36,14 @@ TEST_CASE("init and reset termios") {
|
||||
resetTermios();
|
||||
struct termios current;
|
||||
tcgetattr(0, ¤t);
|
||||
CHECK_EQ(std::memcmp(¤t.c_cc, &original.c_cc, sizeof(current.c_cc)), 0);
|
||||
CHECK_EQ(current.c_cflag, original.c_cflag);
|
||||
CHECK_EQ(current.c_iflag, original.c_iflag);
|
||||
CHECK_EQ(current.c_ispeed, original.c_ispeed);
|
||||
CHECK_EQ(current.c_lflag, original.c_lflag);
|
||||
CHECK_EQ(current.c_line, original.c_line);
|
||||
CHECK_EQ(current.c_oflag, original.c_oflag);
|
||||
CHECK_EQ(current.c_ospeed, original.c_ospeed);
|
||||
CHECK(std::memcmp(&original, ¤t, sizeof(struct termios)) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
static char getch_(int echo) {
|
||||
char getch_(int echo) {
|
||||
char ch;
|
||||
initTermios(echo);
|
||||
if (read(STDIN_FILENO, &ch, 1) < 0) {
|
||||
// ignore, not much we can do
|
||||
}
|
||||
read(STDIN_FILENO, &ch, 1);
|
||||
resetTermios();
|
||||
return ch;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "httplib.h"
|
||||
|
||||
#include <map>
|
||||
#include <nlohmann/json.hpp>
|
||||
@@ -176,8 +177,6 @@ void Http::Server::THttpServerInstance::operator()() try {
|
||||
case Application::Status::Bad:
|
||||
SystemsBad++;
|
||||
break;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
}
|
||||
res.set_content(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
#include "LuaAPI.h"
|
||||
#include "Client.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "TLuaEngine.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
@@ -75,10 +74,8 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
|
||||
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
|
||||
return ss.str();
|
||||
}
|
||||
case sol::type::poly:
|
||||
return "<poly>";
|
||||
default:
|
||||
return "<unprintable type>";
|
||||
return "((unprintable type))";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,95 +110,72 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
|
||||
CHECK(pa == real.patch);
|
||||
}
|
||||
|
||||
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||
static inline bool InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
|
||||
std::string Packet = "E:" + EventName + ":" + Data;
|
||||
if (PlayerID == -1) {
|
||||
if (PlayerID == -1)
|
||||
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||
return { true, "" };
|
||||
} else {
|
||||
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" };
|
||||
beammp_lua_error("TriggerClientEvent invalid Player ID");
|
||||
return false;
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
|
||||
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
|
||||
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID));
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
|
||||
return { false, "Respond failed, dropping client" };
|
||||
return false;
|
||||
}
|
||||
return { true, "" };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||
bool LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
|
||||
std::string Data = DataObj.as<std::string>();
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, Data);
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
|
||||
return { false, "Player does not exist" };
|
||||
beammp_lua_error("Tried to drop client with id " + std::to_string(ID) + ", who doesn't exist");
|
||||
return;
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
|
||||
return { true, "" };
|
||||
}
|
||||
|
||||
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||
std::pair<bool, std::string> Result;
|
||||
void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
|
||||
std::string Packet = "C:Server: " + Message;
|
||||
if (ID == -1) {
|
||||
LogChatMessage("<Server> (to everyone) ", -1, Message);
|
||||
Engine->Network().SendToAll(nullptr, Packet, true, true);
|
||||
Result.first = true;
|
||||
} else {
|
||||
auto MaybeClient = GetClient(Engine->Server(), ID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->IsSynced()) {
|
||||
Result.first = false;
|
||||
Result.second = "Player still syncing data";
|
||||
return Result;
|
||||
}
|
||||
if (!c->IsSynced())
|
||||
return;
|
||||
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
|
||||
if (!Engine->Network().Respond(*c, Packet, true)) {
|
||||
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
|
||||
// TODO: should we return an error here?
|
||||
}
|
||||
Result.first = true;
|
||||
Engine->Network().Respond(*c, Packet, true);
|
||||
} else {
|
||||
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) {
|
||||
std::pair<bool, std::string> Result;
|
||||
void LuaAPI::MP::RemoveVehicle(int PID, int VID) {
|
||||
auto MaybeClient = GetClient(Engine->Server(), PID);
|
||||
if (!MaybeClient || MaybeClient.value().expired()) {
|
||||
beammp_lua_error("RemoveVehicle invalid Player ID");
|
||||
Result.first = false;
|
||||
Result.second = "Invalid Player ID";
|
||||
return Result;
|
||||
return;
|
||||
}
|
||||
auto c = MaybeClient.value().lock();
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
Engine->Network().SendToAll(nullptr, Destroy, true, true);
|
||||
c->DeleteCar(VID);
|
||||
Result.first = true;
|
||||
} else {
|
||||
Result.first = false;
|
||||
Result.second = "Vehicle does not exist";
|
||||
}
|
||||
return Result;
|
||||
}
|
||||
|
||||
void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
|
||||
@@ -526,7 +500,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
|
||||
return;
|
||||
}
|
||||
std::string key{};
|
||||
std::string key;
|
||||
switch (left.get_type()) {
|
||||
case sol::type::lua_nil:
|
||||
case sol::type::none:
|
||||
@@ -545,8 +519,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
case sol::type::number:
|
||||
key = std::to_string(left.as<double>());
|
||||
break;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
nlohmann::json value;
|
||||
switch (right.get_type()) {
|
||||
@@ -589,8 +561,6 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
if (is_array) {
|
||||
json.push_back(value);
|
||||
@@ -675,6 +645,6 @@ std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
|
||||
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) {
|
||||
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
|
||||
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ static constexpr std::string_view StrDescription = "Description";
|
||||
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
|
||||
static constexpr std::string_view StrAuthKey = "AuthKey";
|
||||
static constexpr std::string_view StrLogChat = "LogChat";
|
||||
static constexpr std::string_view StrDownloadThreads = "DownloadThreads";
|
||||
|
||||
// Misc
|
||||
static constexpr std::string_view StrSendErrors = "SendErrors";
|
||||
@@ -103,6 +104,8 @@ void TConfig::FlushToFile() {
|
||||
data["General"][StrMap.data()] = Application::Settings.MapName;
|
||||
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
|
||||
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
|
||||
data["General"][StrDownloadThreads.data()] = Application::Settings.DownloadThreads;
|
||||
SetComment(data["General"][StrDownloadThreads.data()].comments(), " How many simultaneous downloads may run at the same time");
|
||||
// Misc
|
||||
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
|
||||
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
|
||||
@@ -167,7 +170,7 @@ void TConfig::TryReadValue(toml::value& Table, const std::string& Category, cons
|
||||
|
||||
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());
|
||||
OutValue = Table[Category.c_str()][Key.data()].as_integer();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,6 +189,7 @@ void TConfig::ParseFromFile(std::string_view name) {
|
||||
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource);
|
||||
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key);
|
||||
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat);
|
||||
TryReadValue(data, "General", StrDownloadThreads, Application::Settings.DownloadThreads);
|
||||
// Misc
|
||||
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors);
|
||||
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages);
|
||||
@@ -221,22 +225,26 @@ void TConfig::ParseFromFile(std::string_view name) {
|
||||
}
|
||||
|
||||
void TConfig::PrintDebug() {
|
||||
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
|
||||
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
|
||||
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
|
||||
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
|
||||
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
|
||||
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
|
||||
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
|
||||
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 + "\"");
|
||||
beammp_debugf("{}: {}", StrDebug, Application::Settings.DebugModeEnabled ? "true" : "false");
|
||||
beammp_debugf("{}: {}", StrPrivate, Application::Settings.Private ? "true" : "false");
|
||||
beammp_debugf("{}: {}", StrPort, Application::Settings.Port);
|
||||
beammp_debugf("{}: {}", StrMaxCars, Application::Settings.MaxCars);
|
||||
beammp_debugf("{}: {}", StrMaxPlayers, Application::Settings.MaxPlayers);
|
||||
beammp_debugf("{}: '{}'", StrMap, Application::Settings.MapName);
|
||||
beammp_debugf("{}: '{}'", StrName, Application::Settings.ServerName);
|
||||
beammp_debugf("{}: '{}'", StrDescription, Application::Settings.ServerDesc);
|
||||
beammp_debugf("{}: {}", StrLogChat, Application::Settings.LogChat ? "true" : "false");
|
||||
beammp_debugf("{}: '{}'", StrResourceFolder, Application::Settings.Resource);
|
||||
beammp_debugf("{}: '{}'", StrSSLKeyPath, Application::Settings.SSLKeyPath);
|
||||
beammp_debugf("{}: '{}'", StrSSLCertPath, Application::Settings.SSLCertPath);
|
||||
beammp_debugf("{}: {}", StrHTTPServerPort, Application::Settings.HTTPServerPort);
|
||||
beammp_debugf("{}: '{}'", StrHTTPServerIP, Application::Settings.HTTPServerIP);
|
||||
beammp_debugf("{}: {}", StrDownloadThreads, Application::Settings.DownloadThreads);
|
||||
if (Application::Settings.DownloadThreads < 1) {
|
||||
beammp_warnf("'{}' of <1 is not allowed, will use 1", StrDownloadThreads);
|
||||
}
|
||||
// special!
|
||||
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
|
||||
beammp_debugf("Key Length: {}", Application::Settings.Key.length());
|
||||
}
|
||||
|
||||
void TConfig::ParseOldFormat() {
|
||||
|
||||
@@ -51,18 +51,7 @@ 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::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);
|
||||
auto local_tm = std::localtime(&tt);
|
||||
@@ -155,10 +144,10 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
|
||||
mStateId = LuaStateId;
|
||||
mIsLuaConsole = true;
|
||||
if (mStateId != mDefaultStateId) {
|
||||
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`");
|
||||
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:detach`");
|
||||
mCommandline.set_prompt("lua @" + LuaStateId + "> ");
|
||||
} else {
|
||||
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
|
||||
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:detach`");
|
||||
mCommandline.set_prompt("lua> ");
|
||||
}
|
||||
mCachedRegularHistory = mCommandline.history();
|
||||
@@ -270,10 +259,9 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
|
||||
}
|
||||
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
|
||||
bool Kicked = false;
|
||||
// TODO: this sucks, tolower is locale-dependent.
|
||||
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
|
||||
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
|
||||
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); });
|
||||
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = tolower(c); });
|
||||
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
|
||||
};
|
||||
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
|
||||
@@ -332,9 +320,7 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
|
||||
}
|
||||
++Ptr;
|
||||
}
|
||||
// this is required, otherwise we get negative int to unsigned cast in the next operations
|
||||
beammp_assert(PrevPtr <= Ptr);
|
||||
Arg = std::string(PrevPtr, std::string::size_type(Ptr - PrevPtr));
|
||||
Arg = std::string(PrevPtr, Ptr - PrevPtr);
|
||||
// remove quotes if enclosed in quotes
|
||||
for (char Quote : { '"', '\'', '`' }) {
|
||||
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
|
||||
@@ -450,8 +436,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
SystemsShutdown++;
|
||||
SystemsShutdownList += NameStatusPair.first + ", ";
|
||||
break;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
}
|
||||
// remove ", " at the end
|
||||
@@ -470,7 +454,7 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
|
||||
<< "\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"
|
||||
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n"
|
||||
<< "\tLua:\n"
|
||||
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
|
||||
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
|
||||
@@ -637,67 +621,42 @@ TConsole::TConsole() {
|
||||
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
|
||||
std::vector<std::string> suggestions;
|
||||
try {
|
||||
auto cmd = TrimString(stub);
|
||||
// beammp_error("yes 1");
|
||||
// beammp_error(stub);
|
||||
if (mIsLuaConsole) { // if lua
|
||||
if (!mLuaEngine) {
|
||||
beammp_info("Lua not started yet, please try again in a second");
|
||||
} else {
|
||||
std::string prefix {}; // stores non-table part of input
|
||||
for (size_t i = stub.length(); i > 0; i--) { // separate table from input
|
||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
|
||||
std::string prefix {};
|
||||
for (size_t i = stub.length(); i > 0; i--) {
|
||||
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') {
|
||||
prefix = stub.substr(0, i);
|
||||
stub = stub.substr(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// turn string into vector of keys
|
||||
std::vector<std::string> tablekeys;
|
||||
|
||||
SplitString(stub, '.', tablekeys);
|
||||
|
||||
// remove last key if incomplete
|
||||
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
|
||||
auto last_dot = stub.rfind('.');
|
||||
std::string last_atom;
|
||||
if (last_dot != std::string::npos) {
|
||||
last_atom = stub.substr(last_dot + 1);
|
||||
}
|
||||
std::string before_last_atom = stub.substr(0, last_dot + 1); // get last confirmed key
|
||||
auto last = stub.substr(stub.rfind('.') + 1);
|
||||
std::string::size_type n = key.find(last);
|
||||
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
|
||||
for (const auto& key : keys) {
|
||||
std::string::size_type n = key.find(stub);
|
||||
if (n == 0) {
|
||||
suggestions.push_back(prefix + before_last_atom + key);
|
||||
suggestions.push_back(prefix + key);
|
||||
// beammp_warn(cmd_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
} 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();
|
||||
|
||||
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) {
|
||||
suggestions.push_back(cmd_name);
|
||||
}
|
||||
for (const auto& [cmd_name, cmd_fn] : mCommandMap) {
|
||||
std::string::size_type n = cmd_name.find(stub);
|
||||
if (n == 0) {
|
||||
suggestions.push_back(cmd_name);
|
||||
// beammp_warn(cmd_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
|
||||
}
|
||||
std::sort(suggestions.begin(), suggestions.end());
|
||||
return suggestions;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <httplib.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <random>
|
||||
#include <thread>
|
||||
@@ -220,66 +221,6 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::vector<std::string> TLuaEngine::GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys) {
|
||||
std::unique_lock Lock(mLuaStatesMutex);
|
||||
auto Result = mLuaStates.at(StateId)->GetStateTableKeys(keys);
|
||||
return Result;
|
||||
}
|
||||
|
||||
std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const std::vector<std::string>& keys) {
|
||||
auto globals = mStateView.globals();
|
||||
|
||||
sol::table current = globals;
|
||||
std::vector<std::string> Result {};
|
||||
|
||||
for (const auto& [key, value] : current) {
|
||||
std::string s = key.as<std::string>();
|
||||
if (value.get_type() == sol::type::function) {
|
||||
s += "(";
|
||||
}
|
||||
Result.push_back(s);
|
||||
}
|
||||
|
||||
if (!keys.empty()) {
|
||||
Result.clear();
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i) {
|
||||
auto obj = current.get<sol::object>(keys.at(i));
|
||||
if (obj.get_type() == sol::type::nil) {
|
||||
// error
|
||||
break;
|
||||
} else if (i == keys.size() - 1) {
|
||||
if (obj.get_type() == sol::type::table) {
|
||||
for (const auto& [key, value] : obj.as<sol::table>()) {
|
||||
std::string s = key.as<std::string>();
|
||||
if (value.get_type() == sol::type::function) {
|
||||
s += "(";
|
||||
}
|
||||
Result.push_back(s);
|
||||
}
|
||||
} else {
|
||||
Result = { obj.as<std::string>() };
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (obj.get_type() == sol::type::table) {
|
||||
current = obj;
|
||||
} else {
|
||||
// error
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return Result;
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
_G.a.b.c.d.
|
||||
|
||||
*/
|
||||
|
||||
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
|
||||
for (const auto& Result : Results) {
|
||||
bool Cancelled = false;
|
||||
@@ -576,35 +517,6 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
|
||||
return sol::lua_nil;
|
||||
}
|
||||
|
||||
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
|
||||
std::pair<sol::table, std::string> Result;
|
||||
auto MaybeClient = GetClient(mEngine->Server(), PID);
|
||||
if (MaybeClient && !MaybeClient.value().expired()) {
|
||||
auto Client = MaybeClient.value().lock();
|
||||
std::string VehiclePos = Client->GetCarPositionRaw(VID);
|
||||
|
||||
if (VehiclePos.empty()) {
|
||||
//return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
|
||||
Result.second = "Vehicle not found";
|
||||
return Result;
|
||||
}
|
||||
|
||||
sol::table t = Lua_JsonDecode(VehiclePos);
|
||||
if (t == sol::lua_nil){
|
||||
Result.second = "Packet decode failed";
|
||||
}
|
||||
//return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
|
||||
Result.first = t;
|
||||
return Result;
|
||||
}
|
||||
else {
|
||||
//return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
|
||||
Result.second = "Client expired";
|
||||
return Result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
|
||||
auto table = mStateView.create_table();
|
||||
constexpr const char* InternalClient = "__InternalClient";
|
||||
@@ -678,8 +590,6 @@ static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, c
|
||||
return;
|
||||
case nlohmann::detail::value_t::discarded:
|
||||
return;
|
||||
default:
|
||||
beammp_assert_not_reachable();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -763,9 +673,6 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
|
||||
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
|
||||
return Lua_GetPlayerVehicles(ID);
|
||||
});
|
||||
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> {
|
||||
return Lua_GetPositionRaw(PID, VID);
|
||||
});
|
||||
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
|
||||
MPTable.set_function("GetPlayers", [&]() -> sol::table {
|
||||
return Lua_GetPlayers();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <Http.h>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <dlhttp/dlhttp.h>
|
||||
|
||||
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
|
||||
: mServer(Server)
|
||||
@@ -57,7 +58,7 @@ void TNetwork::UDPServerMain() {
|
||||
serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian
|
||||
|
||||
// Try and bind the socket to the IP and port
|
||||
if (bind(mUDPSock, reinterpret_cast<struct sockaddr*>(&serverAddr), sizeof(serverAddr)) != 0) {
|
||||
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
|
||||
beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(-1); // TODO: Wtf.
|
||||
@@ -134,7 +135,7 @@ void TNetwork::TCPServerMain() {
|
||||
addr.sin_addr.s_addr = INADDR_ANY;
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(uint16_t(Application::Settings.Port));
|
||||
if (bind(Listener, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
|
||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) < 0) {
|
||||
beammp_error("bind() failed, the server cannot operate and will shut down now. "
|
||||
"Error: "
|
||||
+ GetPlatformAgnosticErrorString());
|
||||
@@ -148,6 +149,12 @@ void TNetwork::TCPServerMain() {
|
||||
}
|
||||
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
|
||||
beammp_info("Vehicle event network online");
|
||||
const auto ThreadCount = std::max(1, Application::Settings.DownloadThreads);
|
||||
beammp_debugf("Using {} download threads", ThreadCount);
|
||||
dlhttp::AsyncContext Ctx(ThreadCount);
|
||||
dlhttp::EndpointHandlerMap Map {
|
||||
{ "/modlist", [this]() -> dlhttp::Response { return { mResourceManager.FileList() }; } },
|
||||
};
|
||||
do {
|
||||
try {
|
||||
if (Application::IsShuttingDown()) {
|
||||
@@ -166,13 +173,22 @@ void TNetwork::TCPServerMain() {
|
||||
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS));
|
||||
#else // POSIX
|
||||
struct timeval optval;
|
||||
optval.tv_sec = int(SendTimeoutMS / 1000);
|
||||
optval.tv_sec = (int)(SendTimeoutMS / 1000);
|
||||
optval.tv_usec = (SendTimeoutMS % 1000) * 1000;
|
||||
ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval));
|
||||
#endif
|
||||
if (ret < 0) {
|
||||
throw std::runtime_error("setsockopt recv timeout: " + GetPlatformAgnosticErrorString());
|
||||
}
|
||||
|
||||
// check for http
|
||||
if (dlhttp::is_http(client.Socket)) {
|
||||
beammp_info("IS HTTP!");
|
||||
dlhttp::handle_http(client.Socket, Ctx, Map);
|
||||
} else {
|
||||
beammp_info("IS NOT HTTP!");
|
||||
}
|
||||
|
||||
std::thread ID(&TNetwork::Identify, this, client);
|
||||
ID.detach(); // TODO: Add to a queue and attempt to join periodically
|
||||
} catch (const std::exception& e) {
|
||||
@@ -237,13 +253,13 @@ void TNetwork::HandleDownload(SOCKET TCPSock) {
|
||||
});
|
||||
}
|
||||
|
||||
static int get_ip_str(const struct sockaddr* sa, char* strBuf, socklen_t strBufSize) {
|
||||
static int get_ip_str(const struct sockaddr* sa, char* strBuf, size_t strBufSize) {
|
||||
switch (sa->sa_family) {
|
||||
case AF_INET:
|
||||
inet_ntop(AF_INET, &reinterpret_cast<const struct sockaddr_in*>(sa)->sin_addr, strBuf, strBufSize);
|
||||
inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), strBuf, strBufSize);
|
||||
break;
|
||||
case AF_INET6:
|
||||
inet_ntop(AF_INET6, &reinterpret_cast<const struct sockaddr_in6*>(sa)->sin6_addr, strBuf, strBufSize);
|
||||
inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), strBuf, strBufSize);
|
||||
break;
|
||||
default:
|
||||
return 1;
|
||||
@@ -453,7 +469,7 @@ bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
|
||||
}
|
||||
|
||||
std::string TNetwork::TCPRcv(TClient& c) {
|
||||
int32_t Header {}, BytesRcv = 0, Temp {};
|
||||
int32_t Header, BytesRcv = 0, Temp;
|
||||
if (c.GetStatus() < 0)
|
||||
return "";
|
||||
|
||||
@@ -470,7 +486,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
|
||||
if (!CheckBytes(c, BytesRcv)) {
|
||||
return "";
|
||||
}
|
||||
if (Header < int32_t(100 * MB)) {
|
||||
if (Header < 100 * MB) {
|
||||
Data.resize(Header);
|
||||
} else {
|
||||
ClientKick(c, "Header size limit exceeded");
|
||||
@@ -822,6 +838,7 @@ uint8_t* /* end ptr */ TNetwork::SendSplit(TClient& c, SOCKET Socket, uint8_t* D
|
||||
|
||||
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);
|
||||
auto Buf = f.rdbuf();
|
||||
uint32_t Split = 125 * MB;
|
||||
std::vector<uint8_t> Data;
|
||||
if (Size > Split)
|
||||
@@ -1017,7 +1034,7 @@ bool TNetwork::UDPSend(TClient& Client, std::string Data) const {
|
||||
size_t len = Data.size();
|
||||
#endif // WIN32
|
||||
|
||||
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, reinterpret_cast<struct sockaddr*>(&Addr), int(AddrSize));
|
||||
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize));
|
||||
if (sendOk == -1) {
|
||||
beammp_debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString());
|
||||
if (Client.GetStatus() > -1)
|
||||
@@ -1038,7 +1055,7 @@ std::string TNetwork::UDPRcvFromClient(sockaddr_in& client) const {
|
||||
#ifdef WIN32
|
||||
auto Rcv = recvfrom(mUDPSock, Ret.data(), int(Ret.size()), 0, (sockaddr*)&client, (int*)&clientLength);
|
||||
#else // unix
|
||||
int64_t Rcv = recvfrom(mUDPSock, Ret.data(), Ret.size(), 0, reinterpret_cast<struct sockaddr*>(&client), reinterpret_cast<socklen_t*>(&clientLength));
|
||||
int64_t Rcv = recvfrom(mUDPSock, Ret.data(), Ret.size(), 0, (sockaddr*)&client, (socklen_t*)&clientLength);
|
||||
#endif // WIN32
|
||||
|
||||
if (Rcv == -1) {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <sstream>
|
||||
|
||||
TSentry::TSentry() {
|
||||
if (std::strlen(S_DSN) == /* DISABLES CODE */ (0)) {
|
||||
if (std::strlen(S_DSN) == 0) {
|
||||
mValid = false;
|
||||
} else {
|
||||
mValid = true;
|
||||
|
||||
128
src/TServer.cpp
128
src/TServer.cpp
@@ -15,66 +15,6 @@
|
||||
|
||||
#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);
|
||||
@@ -146,8 +86,8 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
||||
std::any Res;
|
||||
char Code = Packet.at(0);
|
||||
|
||||
// V to Y
|
||||
if (Code <= 89 && Code >= 86) {
|
||||
// V to Z
|
||||
if (Code <= 90 && Code >= 86) {
|
||||
PPSMonitor.IncrementInternalPPS();
|
||||
Network.SendToAll(LockedClient.get(), Packet, false, false);
|
||||
return;
|
||||
@@ -205,11 +145,6 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
|
||||
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, Packet);
|
||||
default:
|
||||
return;
|
||||
}
|
||||
@@ -255,7 +190,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
std::string Packet = Pckt;
|
||||
char Code = Packet.at(1);
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
int VID = -1, Pos;
|
||||
std::string Data = Packet.substr(3), pid, vid;
|
||||
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
|
||||
case 's':
|
||||
@@ -288,11 +223,13 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'c': {
|
||||
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();
|
||||
pid = Data.substr(0, Data.find('-'));
|
||||
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
PID = stoi(pid);
|
||||
VID = stoi(vid);
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
|
||||
@@ -313,17 +250,20 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
c.SetUnicycleID(-1);
|
||||
}
|
||||
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
|
||||
Network.SendToAll(nullptr, Destroy, true, true);
|
||||
if (!Network.Respond(c, Destroy, true)) {
|
||||
// TODO: handle
|
||||
}
|
||||
c.DeleteCar(VID);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'd': {
|
||||
case 'd':
|
||||
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data);
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
pid = Data.substr(0, Data.find('-'));
|
||||
vid = Data.substr(Data.find('-') + 1);
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
PID = stoi(pid);
|
||||
VID = stoi(vid);
|
||||
}
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
if (c.GetUnicycleID() == VID) {
|
||||
@@ -336,12 +276,15 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 'r': {
|
||||
case 'r':
|
||||
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
auto MaybePidVid = GetPidVid(Data);
|
||||
if (MaybePidVid) {
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
Pos = int(Data.find('-'));
|
||||
pid = Data.substr(0, Pos++);
|
||||
vid = Data.substr(Pos, Data.find(':') - Pos);
|
||||
|
||||
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
|
||||
PID = stoi(pid);
|
||||
VID = stoi(vid);
|
||||
}
|
||||
|
||||
if (PID != -1 && VID != -1 && PID == c.GetID()) {
|
||||
@@ -350,7 +293,6 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
|
||||
Network.SendToAll(&c, Packet, false, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
case 't':
|
||||
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
|
||||
Network.SendToAll(&c, Packet, false, true);
|
||||
@@ -423,21 +365,3 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
|
||||
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
|
||||
(void)mClients.insert(NewClient);
|
||||
}
|
||||
|
||||
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
|
||||
// Zp:serverVehicleID:data
|
||||
std::string withoutCode = Packet.substr(3);
|
||||
auto NameDataSep = withoutCode.find(':', 2);
|
||||
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
|
||||
std::string Data = withoutCode.substr(NameDataSep + 1);
|
||||
|
||||
// parse veh ID
|
||||
auto MaybePidVid = GetPidVid(ServerVehicleID);
|
||||
if (MaybePidVid) {
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
std::tie(PID, VID) = MaybePidVid.value();
|
||||
|
||||
c.SetCarPosition(VID, Data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "ArgsParser.h"
|
||||
#include "Common.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Http.h"
|
||||
#include "LuaAPI.h"
|
||||
#include "SignalHandling.h"
|
||||
@@ -12,6 +13,7 @@
|
||||
#include "TPPSMonitor.h"
|
||||
#include "TPluginMonitor.h"
|
||||
#include "TResourceManager.h"
|
||||
#include "TScopedTimer.h"
|
||||
#include "TServer.h"
|
||||
|
||||
#include <iostream>
|
||||
@@ -54,7 +56,7 @@ int BeamMPServerMain(MainArguments Arguments);
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
MainArguments Args { argc, argv, {}, argv[0] };
|
||||
Args.List.reserve(size_t(argc));
|
||||
Args.List.reserve(argc);
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
Args.List.push_back(argv[i]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user