Compare commits

...

55 Commits

Author SHA1 Message Date
Lion Kortlepel 5f456584a8 use lua 5.3.6 for static build 2022-09-29 11:19:20 +02:00
Lion Kortlepel b88b64cd0e update docker-build.sh to add an option to run-only 2022-09-28 00:01:09 +02:00
Lion Kortlepel dccdd3f5f2 add ability to change openssl and zlib 2022-09-27 23:46:19 +02:00
Lion Kortlepel ae38f01fdc add initial docker static build container 2022-09-27 23:41:47 +02:00
Lion Kortlepel a1d99c0203 update commandline library
includes a fix for alpine
2022-09-27 23:07:30 +02:00
Lion Kortlepel 10dff185e0 change changelog to correctly say "Util.Json*", not MP 2022-09-27 17:25:18 +02:00
Lion Kortlepel dd17b95427 add changelog message about MP.TriggerClientEventJson 2022-09-27 17:02:25 +02:00
Lion Kortlepel 1a9872db00 fix unhandled return value of fread in TConfig::TConfig unit test 2022-09-27 15:49:55 +02:00
Lion Kortlepel dbb01998ea fix ignored return value in getch_ 2022-09-26 12:24:44 +02:00
Lion 3c4737a145 fix colon in changelog once more, thanks to github's editor being bad 2022-09-26 12:23:30 +02:00
Lion 36e8ba1614 fix colon in changelog to be in proper code quotes 2022-09-26 12:22:22 +02:00
Lion Kortlepel 988f19fd00 fix getch_ to explicitly ignore read() return value 2022-09-26 12:20:07 +02:00
Lion Kortlepel b145c8159e update changelog to add HOME and END button, fix ip comment 2022-09-26 12:12:16 +02:00
Lion Kortlepel ae517b30c0 fix bug which caused updates to only check the first URL 2022-09-26 12:04:42 +02:00
Lion Kortlepel e638c25f70 change assertions to print the error in release builds
this should make it easier to debug crashes in the server remotely in
release builds when sentry is down.
2022-09-26 12:03:57 +02:00
Lion Kortlepel 24c98eb2b2 add more compile-time diagnostics, implement fixes for them
Before, a lot of common errors went unnoticed, due to insufficient
compiler diagnostics. This commit fixes this by adding a lot of new
diagnostics, and fixing the issues found by this.
2022-09-26 12:02:05 +02:00
Lion 501fddadc6 Merge pull request #127 from BeamMP/feature-betterautocomplete
Feature: Better autocomplete
2022-09-26 10:44:15 +02:00
Lion Kortlepel 6da9a921d0 fix "init and reset termios" unit test
it was testing via memory-equality, which is not valid.
2022-09-26 01:14:08 +02:00
Lion Kortlepel a8333359ce update commandline to work with new autocomplete 2022-09-26 00:17:23 +02:00
20dka b71aa2db04 advanced autocomplete for lua 2022-09-26 00:13:16 +02:00
Lion 78f7cdc17a Merge branch 'master' into rc-v3.1.0 2022-09-25 19:50:12 +02:00
Lion Kortlepel 36a1da3218 fix TServer::HandlePosition declaration
it was different from the implementation
2022-09-14 20:59:07 +02:00
Lion Kortlepel 23e9941704 update linux and windows workflows to run on pr open, reopen, review submit 2022-09-14 20:42:25 +02:00
Lion 469eb78c80 Merge pull request #123 from 20dka/rc-v3.1.0
Add MP.GetPositionRaw() with lua fixes and features
2022-09-14 20:41:33 +02:00
Lion Kortlepel af5658d0e1 update toml11 2022-09-14 20:41:00 +02:00
Lion Kortlepel 1062e29582 update sentry-native 2022-09-14 20:41:00 +02:00
Lion Kortlepel ec9a280d30 update libzip 2022-09-14 20:41:00 +02:00
Lion Kortlepel 784bbd4f6b update fmt 2022-09-14 20:41:00 +02:00
Lion Kortlepel bc6b4e40e1 update httplib 2022-09-14 20:41:00 +02:00
Lion Kortlepel 071ba08dfe update sol2 2022-09-14 20:41:00 +02:00
Lion Kortlepel 023738c41b update json 2022-09-14 20:41:00 +02:00
Lion Kortlepel 6a166110f6 update doctest 2022-09-14 20:41:00 +02:00
Lion Kortlepel 71fbf7b7cc update commandline 2022-09-14 20:41:00 +02:00
20dka 4b242c26fc optimize function argument passing in GetPidVid, TServer::HandlePosition 2022-09-14 18:53:44 +02:00
20dka a84d042a8a add error messages to some lua events 2022-09-14 12:45:40 +02:00
20dka 44b94c9e58 add MP.GetPositionRaw(pid, vid)
fix vehicles sometimes not deleting for all players
2022-09-14 01:54:49 +02:00
Lion 660f94b691 Merge pull request #110 from tsao-chi-forks/patch-2
Support build on apple silicon
2022-09-13 16:15:34 +02:00
Lion a7c4103f7c add section about adding features 2022-08-08 20:10:50 +03:00
Lion Kortlepel 0932078e4b add CONTRIBUTING.md 2022-08-08 20:10:50 +03:00
Lion Kortlepel 54e02abad1 update toml11 2022-08-03 18:16:56 +02:00
Lion Kortlepel e4cbba59ef update sentry-native 2022-08-03 18:14:19 +02:00
Lion Kortlepel e4db66782e update libzip 2022-08-03 18:13:49 +02:00
Lion Kortlepel b443bec72e update fmt 2022-08-03 18:13:25 +02:00
Lion Kortlepel 76a8f231ac update httplib 2022-08-03 14:02:11 +02:00
Lion Kortlepel 398f8d3fa4 update sol2 2022-08-03 14:01:40 +02:00
Lion Kortlepel 60dd1e2472 update json 2022-08-03 14:01:04 +02:00
Lion Kortlepel e634b4b6b7 update doctest 2022-08-03 14:00:26 +02:00
Lion Kortlepel 1caa5e3517 update commandline 2022-08-03 13:59:54 +02:00
Lion Kortlepel b009a37f35 update asio to 1-23-0 2022-08-03 13:59:11 +02:00
Lion a28b3e1532 Merge pull request #113 from Mack29446/master
Update README.md
2022-07-10 12:55:23 +02:00
Mackenzie b01bed2996 change dependency section 2022-07-10 11:51:19 +01:00
Mackenzie 7bdc2b304b refactor: master is considered unstable 2022-07-10 11:47:55 +01:00
Mackenzie b19bca4c82 fix numbering 2022-07-10 11:38:51 +01:00
Mackenzie 708848f275 Update README.md 2022-07-10 11:35:44 +01:00
ㄗㄠˋ ㄑㄧˊ d6625187d1 Support build on apple silicon 2022-06-29 13:43:36 +08:00
38 changed files with 724 additions and 217 deletions
+8 -3
View File
@@ -1,6 +1,11 @@
name: CMake Linux Build name: CMake Linux Build
on: [push] on:
push:
pull_request:
types: [opened, reopened]
pull_request_review:
types: [submitted]
env: env:
BUILD_TYPE: Release BUILD_TYPE: Release
@@ -74,5 +79,5 @@ jobs:
working-directory: ${{github.workspace}} working-directory: ${{github.workspace}}
shell: bash shell: bash
run: | run: |
chmod +x ./BeamMP-Server-tests chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests ./BeamMP-Server-tests
+11 -7
View File
@@ -1,6 +1,11 @@
name: CMake Windows Build name: CMake Windows Build
on: [push] on:
push:
pull_request:
types: [opened, reopened]
pull_request_review:
types: [submitted]
env: env:
BUILD_TYPE: Release BUILD_TYPE: Release
@@ -12,16 +17,16 @@ jobs:
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
with: with:
submodules: 'recursive' submodules: "recursive"
- name: Restore artifacts, or run vcpkg, build and cache artifacts - name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@v7 uses: lukka/run-vcpkg@v7
id: runvcpkg id: runvcpkg
with: with:
vcpkgArguments: 'lua zlib rapidjson openssl websocketpp curl' vcpkgArguments: "lua zlib rapidjson openssl websocketpp curl"
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg' vcpkgDirectory: "${{ runner.workspace }}/b/vcpkg"
vcpkgGitCommitId: 'a106de33bbee694e3be6243718aa2a549a692832' vcpkgGitCommitId: "a106de33bbee694e3be6243718aa2a549a692832"
vcpkgTriplet: 'x64-windows-static' vcpkgTriplet: "x64-windows-static"
- name: Create Build Environment - name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows run: cmake -E make_directory ${{github.workspace}}/build-windows
@@ -55,4 +60,3 @@ jobs:
with: with:
name: BeamMP-Server-debug.exe name: BeamMP-Server-debug.exe
path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe path: ${{github.workspace}}/build-windows/Debug/BeamMP-Server.exe
+95 -27
View File
@@ -26,24 +26,25 @@ endif()
set(HTTPLIB_REQUIRE_OPENSSL ON) set(HTTPLIB_REQUIRE_OPENSSL ON)
set(SENTRY_BUILD_SHARED_LIBS OFF) 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) add_compile_definitions(CPPHTTPLIB_OPENSSL_SUPPORT=1)
# ------------------------ APPLE --------------------------------- # ------------------------ APPLE ---------------------------------
if(APPLE) if(APPLE)
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3) 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_LIBRARIES lua) set(LUA_LIBRARIES lua)
include_directories(/usr/local/opt/openssl@1.1/include) if(IS_DIRECTORY /opt/homebrew/opt/openssl@1.1)
link_directories(/usr/local/Cellar/lua@5.3/5.3.6/lib) include_directories(/opt/homebrew/opt/openssl@1.1/include)
link_directories(/usr/local/opt/openssl@1.1/lib) 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()
# ------------------------ WINDOWS --------------------------------- # ------------------------ WINDOWS ---------------------------------
elseif (WIN32) elseif (WIN32)
# this has to happen before sentry, so that crashpad on windows links with these settings. # this has to happen before sentry, so that crashpad on windows links with these settings.
@@ -52,17 +53,15 @@ elseif (WIN32)
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
# ------------------------ LINUX --------------------------------- # ------------------------ LINUX ---------------------------------
elseif (UNIX) elseif (UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++ -static-libgcc")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -fno-builtin")
option(SANITIZE "Turns on thread and UB sanitizers" OFF) option(SANITIZE "Turns on thread and UB sanitizers" OFF)
if (SANITIZE) if (SANITIZE)
message(STATUS "sanitize is ON") message(STATUS "sanitize is ON")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize={address,thread,undefined}")
endif (SANITIZE) endif (SANITIZE)
endif () endif ()
include_directories("include/sentry-native/include")
set(BUILD_SHARED_LIBS OFF) set(BUILD_SHARED_LIBS OFF)
# ------------------------ SENTRY --------------------------------- # ------------------------ SENTRY ---------------------------------
message(STATUS "Checking for Sentry URL") message(STATUS "Checking for Sentry URL")
@@ -91,11 +90,28 @@ add_subdirectory(deps)
# ------------------------ VARIABLES --------------------------------- # ------------------------ VARIABLES ---------------------------------
include(FindLua) option(FIND_OPENSSL "Whether or not to find openssl automatically (keep on unless you know what you're doing)" ON)
option(FIND_ZLIB "Whether or not to find zlib automatically (keep on unless you know what you're doing)" ON)
include(FindOpenSSL) include(FindOpenSSL)
if (${FIND_OPENSSL})
set(OPENSSL_CRYPTO OpenSSL::Crypto)
set(OPENSSL_SSL OpenSSL::SSL)
else()
message(STATUS "Using custom openssl libs: ${OPENSSL_CRYPTO} ${OPENSSL_SSL}")
endif()
include(FindLua)
include(FindThreads) include(FindThreads)
include(FindZLIB) include(FindZLIB)
if (${FIND_ZLIB})
set(ZLIB_ZLIB ZLIB::ZLIB)
else()
message(STATUS "Using custom zlib: ${ZLIB_ZLIB}")
endif()
set(BeamMP_Sources set(BeamMP_Sources
include/TConsole.h src/TConsole.cpp include/TConsole.h src/TConsole.cpp
include/TServer.h src/TServer.cpp include/TServer.h src/TServer.cpp
@@ -121,27 +137,63 @@ set(BeamMP_Sources
) )
set(BeamMP_Includes set(BeamMP_Includes
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
${LUA_INCLUDE_DIR} ${LUA_INCLUDE_DIR}
${CURL_INCLUDE_DIRS} ${CURL_INCLUDE_DIRS}
"include/tomlplusplus" "${CMAKE_CURRENT_SOURCE_DIR}/deps/cpp-httplib"
"include/sentry-native/include" "${CMAKE_CURRENT_SOURCE_DIR}/deps/commandline"
"include/curl/include" "${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"
) )
set(BeamMP_Definitions set(BeamMP_Definitions
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}" 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 set(BeamMP_Libraries
doctest::doctest doctest::doctest
OpenSSL::SSL ${OPENSSL_SSL}
OpenSSL::Crypto ${OPENSSL_CRYPTO}
sol2::sol2 sol2::sol2
fmt::fmt fmt::fmt
Threads::Threads Threads::Threads
ZLIB::ZLIB ${ZLIB_ZLIB}
${LUA_LIBRARIES} ${LUA_LIBRARIES}
commandline commandline
sentry sentry
@@ -163,7 +215,15 @@ target_compile_definitions(BeamMP-Server PRIVATE
DOCTEST_CONFIG_DISABLE DOCTEST_CONFIG_DISABLE
) )
target_include_directories(BeamMP-Server PUBLIC 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
${BeamMP_Includes} ${BeamMP_Includes}
) )
@@ -186,7 +246,15 @@ if(BUILD_TESTS)
${BeamMP_Definitions} ${BeamMP_Definitions}
) )
target_include_directories(BeamMP-Server-tests PUBLIC 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
${BeamMP_Includes} ${BeamMP_Includes}
) )
+111
View File
@@ -0,0 +1,111 @@
# 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.
+8 -3
View File
@@ -3,16 +3,21 @@
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console - 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 lua debug facilities (type `:help` when attached to lua via `lua`)
- ADDED MP.JsonEncode() and MP.JsonDecode(), which turn lua tables into json and vice-versa - ADDED Util.JsonEncode() and Util.JsonDecode(), which turn lua tables into json and vice-versa
- ADDED FS.ListFiles and FS.ListDirectories - ADDED FS.ListFiles and FS.ListDirectories
- ADDED onFileChanged event, triggered when a server plugin file changes - ADDED onFileChanged event, triggered when a server plugin file changes
- FIXED `ip` in MP.GetIdentifiers - ADDED MP.GetPositionRaw(), which can be used to retrieve the latest position packet per player, per vehicle
- FIXED issue with client->server events which contain ':' - 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
- 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 a fatal exception on LuaEngine startup if Resources/Server is a symlink
- FIXED onInit not being called on hot-reload - FIXED onInit not being called on hot-reload
- FIXED incorrect timing calculation of Lua EventTimer loop - FIXED incorrect timing calculation of Lua EventTimer loop
- FIXED bug which caused hot-reload not to report syntax errors - FIXED bug which caused hot-reload not to report syntax errors
- FIXED missing error messages on some event handler calls - FIXED missing error messages on some event handler calls
- FIXED vehicles not deleting for all players if an edit was cancelled by Lua
# v3.0.2 # v3.0.2
+11
View File
@@ -0,0 +1,11 @@
FROM lionkor/alpine-static-cpp:latest
ARG LUA_V=5.3.6
RUN apk update && apk --no-cache add python3 git lua zlib-static openssl curl rapidjson curl-dev wget readline-static
RUN apk --no-cache add openssl-libs-static curl-static readline-dev
RUN wget "https://www.lua.org/ftp/lua-${LUA_V}.tar.gz"; tar xzvf lua-${LUA_V}.tar.gz; mv "lua-${LUA_V}" /lua; rm lua-${LUA_V}.tar.gz
RUN cd /lua; make all -j linux; cd ..
+27 -35
View File
@@ -4,9 +4,9 @@
[![CMake Linux Build](https://github.com/BeamMP/BeamMP-Server/workflows/CMake%20Linux%20Build/badge.svg?branch=master)](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Linux+Build%22) [![CMake Linux Build](https://github.com/BeamMP/BeamMP-Server/workflows/CMake%20Linux%20Build/badge.svg?branch=master)](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/). This is the server for the multiplayer mod **[BeamMP](https://beammp.com/)** for the game [BeamNG.drive](https://www.beamng.com/).
The server is the point throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com). The server is the point 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, listed below under "prerequisites".** **For Linux, you __need__ the runtime dependencies, listed below under "[prerequisites](#prerequisites)".**
## Support + Contact ## Support + Contact
@@ -14,6 +14,7 @@ Feel free to ask any questions via the following channels:
- **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/) - **IRC**: `#beammp` on [irc.libera.chat](https://web.libera.chat/)
- **Discord**: [click for invite](https://discord.gg/beammp) - **Discord**: [click for invite](https://discord.gg/beammp)
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
## Minimum Requirements ## Minimum Requirements
@@ -28,13 +29,13 @@ These values are guesstimated and are subject to change with each release.
## Contributing ## Contributing
TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column. TLDR; [Issues](https://github.com/BeamMP/BeamMP-Server/issues) with the "help wanted" label or with nobody assigned.
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) 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. 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.
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. 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 ## About Building from Source
@@ -42,7 +43,7 @@ We only allow building unmodified (original) source code for public use. `master
## Supported Operating Systems ## 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. Recommended compilers: MSVC, GCC, CLANG.
@@ -52,7 +53,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`!__** **__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 ### Prerequisites
@@ -60,7 +61,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/). Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
Dependencies for **windows** can be installed with `vcpkg`. Dependencies for **Windows** can be installed with `vcpkg`.
These are: These are:
``` ```
lua lua
@@ -73,19 +74,15 @@ curl
#### Linux #### Linux
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro. Runtime dependencies - you want to find packages for:
- libz
- rapidjson
- lua5.3
- ssl / openssl
- websocketpp
- curl (with ssl support)
Runtime dependencies for **linux** are (debian/ubuntu): Build-time dependencies are:
```
libz-dev
rapidjson-dev
liblua5.3
libssl-dev
libwebsocketpp-dev
libcurl4-openssl-dev
```
Build-time dependencies for **linux** are:
``` ```
git git
make make
@@ -93,29 +90,24 @@ cmake
g++ g++
``` ```
For other distributions (e.g. Arch) you want to find packages for:
- libz
- rapidjson
- lua5.3
- ssl / openssl
- websocketpp
- curl (with ssl support)
- \+ the build time dependencies from above
### How to build ### How to build
On windows, use git-bash for these commands. On Linux, these should work in your shell. On Windows, use git-bash for these commands. On Linux, these should work in your shell.
1. Make sure you have all [prerequisites](#prerequisites) installed 1. Make sure you have all [prerequisites](#prerequisites) installed
2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`. 2. Clone the repository in a location of your choice with `git clone --recurse-submodules https://github.com/BeamMP/BeamMP-Server`.
3. Ensure that all submodules are initialized by running `git submodule update --init --recursive`. Then change into the cloned directory by running `cd BeamMP-Server`. 3. Change into the BeamMP-Server 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). 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. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`) 5. Ensure that all submodules are initialized by running `git submodule update --init --recursive`
6. Run `make` 6. Run `cmake . -DCMAKE_BUILD_TYPE=Release` (with `.`)
7. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server. 7. Run `make`
8. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (Windows or Linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/server-installation) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.* *tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
## 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
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor). Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
-1
View File
@@ -1,5 +1,4 @@
include_directories("${PROJECT_SOURCE_DIR}/deps") 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/commandline")
add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt") add_subdirectory("${PROJECT_SOURCE_DIR}/deps/fmt")
Vendored
+1 -1
Submodule deps/asio updated: d038fb3c2f...4915cfd8a1
+1 -1
Vendored
+1 -1
Submodule deps/fmt updated: ce246aaf74...c4ee726532
Vendored
+1 -1
Submodule deps/json updated: ede6667858...69d744867f
Vendored
+1 -1
Vendored
+1 -1
Submodule deps/sol2 updated: c068aefbed...eba86625b7
Vendored
+1 -1
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# usage:
# ./docker-build.sh
# builds the image, and then runs it
# ./docker-build.sh run
# only runs it
set -e
if [ "$1" != "run" ]
then
git submodule update --init --recursive
docker build . --tag beammp-static
fi
docker run -v $(pwd):/root -it --rm beammp-static sh -c "cd root; cmake . -B build -DGIT_SUBMODULE=OFF -DLUA_INCLUDE_DIR=/lua/src -DSOL2_SINGLE=ON -DFIND_OPENSSL=OFF -DOPENSSL_CRYPTO=\"/usr/lib/libcrypto.a\" -DOPENSSL_SSL=\"/usr/lib/libssl.a\" -DFIND_ZLIB=OFF -DZLIB_ZLIB=/lib/libz.a -DCURL_FOUND=ON -DCURL_LIBRARIES=\"/usr/lib/libcurl.a\" -DLUA_LIBRARIES=\"/lua/src/liblua.a\" -DSENTRY_BACKEND=none -DSENTRY_TRANSPORT=none; make -C build -j BeamMP-Server"
# try to chown the build directory afterwards
sudo chown -R "$USER":"$USER" build
+4
View File
@@ -39,11 +39,13 @@ public:
void AddNewCar(int Ident, const std::string& Data); void AddNewCar(int Ident, const std::string& Data);
void SetCarData(int Ident, const std::string& Data); void SetCarData(int Ident, const std::string& Data);
void SetCarPosition(int Ident, const std::string& Data);
TVehicleDataLockPair GetAllCars(); TVehicleDataLockPair GetAllCars();
void SetName(const std::string& Name) { mName = Name; } void SetName(const std::string& Name) { mName = Name; }
void SetRoles(const std::string& Role) { mRole = Role; } void SetRoles(const std::string& Role) { mRole = Role; }
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; } void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
std::string GetCarData(int Ident); std::string GetCarData(int Ident);
std::string GetCarPositionRaw(int Ident);
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; } void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; } void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; } void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
@@ -93,7 +95,9 @@ private:
std::unordered_map<std::string, std::string> mIdentifiers; std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false; bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex; mutable std::mutex mVehicleDataMutex;
mutable std::mutex mVehiclePositionMutex;
TSetOfVehicleData mVehicleData; TSetOfVehicleData mVehicleData;
SparseArray<std::string> mVehiclePosition;
std::string mName = "Unknown Client"; std::string mName = "Unknown Client";
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) }; SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
+14 -14
View File
@@ -14,14 +14,13 @@ extern TSentry Sentry;
#include <mutex> #include <mutex>
#include <shared_mutex> #include <shared_mutex>
#include <sstream> #include <sstream>
#include <unordered_map>
#include <zlib.h> #include <zlib.h>
#include <doctest/doctest.h> #include <doctest/doctest.h>
#include <filesystem> #include <filesystem>
namespace fs = std::filesystem; namespace fs = std::filesystem;
#include "Compat.h"
#include "TConsole.h" #include "TConsole.h"
struct Version { struct Version {
@@ -33,6 +32,9 @@ struct Version {
std::string AsString(); std::string AsString();
}; };
template <typename T>
using SparseArray = std::unordered_map<size_t, T>;
// static class handling application start, shutdown, etc. // static class handling application start, shutdown, etc.
// yes, static classes, singletons, globals are all pretty // yes, static classes, singletons, globals are all pretty
// bad idioms. In this case we need a central way to access // bad idioms. In this case we need a central way to access
@@ -273,11 +275,11 @@ inline T Comp(const T& Data) {
// obsolete // obsolete
C.fill(0); C.fill(0);
z_stream defstream; z_stream defstream;
defstream.zalloc = Z_NULL; defstream.zalloc = nullptr;
defstream.zfree = Z_NULL; defstream.zfree = nullptr;
defstream.opaque = Z_NULL; defstream.opaque = nullptr;
defstream.avail_in = (uInt)Data.size(); defstream.avail_in = uInt(Data.size());
defstream.next_in = (Bytef*)&Data[0]; defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
defstream.avail_out = Biggest; defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(C.data()); defstream.next_out = reinterpret_cast<Bytef*>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION); deflateInit(&defstream, Z_BEST_COMPRESSION);
@@ -298,13 +300,13 @@ inline T DeComp(const T& Compressed) {
// not needed // not needed
C.fill(0); C.fill(0);
z_stream infstream; z_stream infstream;
infstream.zalloc = Z_NULL; infstream.zalloc = nullptr;
infstream.zfree = Z_NULL; infstream.zfree = nullptr;
infstream.opaque = Z_NULL; infstream.opaque = nullptr;
infstream.avail_in = Biggest; infstream.avail_in = Biggest;
infstream.next_in = (Bytef*)(&Compressed[0]); infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
infstream.avail_out = Biggest; infstream.avail_out = Biggest;
infstream.next_out = (Bytef*)(C.data()); infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
inflateInit(&infstream); inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH); inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH); inflate(&infstream, Z_FINISH);
@@ -319,5 +321,3 @@ inline T DeComp(const T& Compressed) {
std::string GetPlatformAgnosticErrorString(); std::string GetPlatformAgnosticErrorString();
#define S_DSN SU_RAW #define S_DSN SU_RAW
void LogChatMessage(const std::string& name, int id, const std::string& msg);
+11 -10
View File
@@ -58,16 +58,17 @@ 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(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false) #define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
#else #else
// In release build, these macros turn into NOPs. The compiler will optimize these out. #define beammp_assert(cond) \
#define beammp_assert(cond) \ do { \
do { \ bool result = (cond); \
bool result = (cond); \ if (!result) { \
if (!result) { \ beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
Sentry.LogAssert(#cond, _file_basename, _line, __func__); \ Sentry.LogAssert(#cond, _file_basename, _line, __func__); \
} \ } \
} while (false) } while (false)
#define beammp_assert_not_reachable() \ #define beammp_assert_not_reachable() \
do { \ do { \
Sentry.LogAssert("code is unreachable", _file_basename, _line, __func__); \ 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__); \
} while (false) } while (false)
#endif // DEBUG #endif // DEBUG
+2
View File
@@ -9,6 +9,8 @@
#if defined(BEAMMP_LINUX) #if defined(BEAMMP_LINUX)
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif #endif
#include <httplib.h> #include <httplib.h>
#if defined(BEAMMP_LINUX) #if defined(BEAMMP_LINUX)
+5 -5
View File
@@ -12,12 +12,12 @@ namespace MP {
std::string GetOSName(); std::string GetOSName();
std::tuple<int, int, int> GetServerVersion(); std::tuple<int, int, int> GetServerVersion();
bool TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data); std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
bool TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data); std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); } inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
void DropPlayer(int ID, std::optional<std::string> MaybeReason); std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
void SendChatMessage(int ID, const std::string& Message); std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
void RemoveVehicle(int PlayerID, int VehicleID); std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
void Set(int ConfigID, sol::object NewValue); void Set(int ConfigID, sol::object NewValue);
bool IsPlayerGuest(int ID); bool IsPlayerGuest(int ID);
bool IsPlayerConnected(int ID); bool IsPlayerConnected(int ID);
+10
View File
@@ -96,6 +96,13 @@ public:
std::unique_lock Lock(mLuaStatesMutex); std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.size(); 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() { size_t GetTimedEventsCount() {
std::unique_lock Lock(mTimedEventsMutex); std::unique_lock Lock(mTimedEventsMutex);
return mTimedEvents.size(); return mTimedEvents.size();
@@ -172,6 +179,7 @@ public:
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND"; static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId); std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
// Debugging functions (slow) // Debugging functions (slow)
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId); std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
@@ -199,6 +207,7 @@ private:
sol::state_view State() { return sol::state_view(mState); } sol::state_view State() { return sol::state_view(mState); }
std::vector<std::string> GetStateGlobalKeys(); std::vector<std::string> GetStateGlobalKeys();
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
// Debug functions, slow // Debug functions, slow
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue(); std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
@@ -211,6 +220,7 @@ private:
sol::table Lua_GetPlayers(); sol::table Lua_GetPlayers();
std::string Lua_GetPlayerName(int ID); std::string Lua_GetPlayerName(int ID);
sol::table Lua_GetPlayerVehicles(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_HttpCreateConnection(const std::string& host, uint16_t port);
sol::table Lua_JsonDecode(const std::string& str); sol::table Lua_JsonDecode(const std::string& str);
int Lua_GetPlayerIDByName(const std::string& Name); int Lua_GetPlayerIDByName(const std::string& Name);
+1
View File
@@ -38,4 +38,5 @@ private:
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID); static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson); static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt); static void Apply(TClient& c, int VID, const std::string& pckt);
static void HandlePosition(TClient& c, const std::string& Packet);
}; };
+17
View File
@@ -47,6 +47,23 @@ TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) }; 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) { std::string TClient::GetCarData(int Ident) {
{ // lock { // lock
std::unique_lock lock(mVehicleDataMutex); std::unique_lock lock(mVehicleDataMutex);
+6 -1
View File
@@ -9,6 +9,7 @@
#include <sstream> #include <sstream>
#include <thread> #include <thread>
#include "Compat.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Http.h" #include "Http.h"
@@ -170,6 +171,8 @@ void Application::SetSubsystemStatus(const std::string& Subsystem, Status status
case Status::Shutdown: case Status::Shutdown:
beammp_trace("Subsystem '" + Subsystem + "': Shutdown"); beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
break; break;
default:
beammp_assert_not_reachable();
} }
std::unique_lock Lock(mSystemStatusMapMutex); std::unique_lock Lock(mSystemStatusMapMutex);
mSystemStatusMap[Subsystem] = status; mSystemStatusMap[Subsystem] = status;
@@ -195,7 +198,7 @@ void Application::CheckForUpdates() {
// checks current version against latest version // checks current version against latest version
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" }; std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
for (const auto& url : GetBackendUrlsInOrder()) { for (const auto& url : GetBackendUrlsInOrder()) {
auto Response = Http::GET(GetBackendUrlsInOrder().at(0), 443, "/v/s"); auto Response = Http::GET(url, 443, "/v/s");
bool Matches = std::regex_match(Response, VersionRegex); bool Matches = std::regex_match(Response, VersionRegex);
if (Matches) { if (Matches) {
auto MyVersion = ServerVersion(); auto MyVersion = ServerVersion();
@@ -347,5 +350,7 @@ std::string GetPlatformAgnosticErrorString() {
} }
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE) #elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
return std::strerror(errno); return std::strerror(errno);
#else
return "(no human-readable errors on this platform)";
#endif #endif
} }
+14 -5
View File
@@ -7,7 +7,7 @@
static struct termios old, current; static struct termios old, current;
void initTermios(int echo) { static void initTermios(int echo) {
tcgetattr(0, &old); /* grab old terminal i/o settings */ tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */ current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */ current.c_lflag &= ~ICANON; /* disable buffered i/o */
@@ -19,7 +19,7 @@ void initTermios(int echo) {
tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */ tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
} }
void resetTermios(void) { static void resetTermios(void) {
tcsetattr(0, TCSANOW, &old); tcsetattr(0, TCSANOW, &old);
} }
@@ -36,14 +36,23 @@ TEST_CASE("init and reset termios") {
resetTermios(); resetTermios();
struct termios current; struct termios current;
tcgetattr(0, &current); tcgetattr(0, &current);
CHECK(std::memcmp(&original, &current, sizeof(struct termios)) == 0); CHECK_EQ(std::memcmp(&current.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);
} }
} }
char getch_(int echo) { static char getch_(int echo) {
char ch; char ch;
initTermios(echo); initTermios(echo);
read(STDIN_FILENO, &ch, 1); if (read(STDIN_FILENO, &ch, 1) < 0) {
// ignore, not much we can do
}
resetTermios(); resetTermios();
return ch; return ch;
} }
+2 -1
View File
@@ -4,7 +4,6 @@
#include "Common.h" #include "Common.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "httplib.h"
#include <map> #include <map>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -177,6 +176,8 @@ void Http::Server::THttpServerInstance::operator()() try {
case Application::Status::Bad: case Application::Status::Bad:
SystemsBad++; SystemsBad++;
break; break;
default:
beammp_assert_not_reachable();
} }
} }
res.set_content( res.set_content(
+51 -21
View File
@@ -1,6 +1,7 @@
#include "LuaAPI.h" #include "LuaAPI.h"
#include "Client.h" #include "Client.h"
#include "Common.h" #include "Common.h"
#include "CustomAssert.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -74,8 +75,10 @@ std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool Quo
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]"; ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
return ss.str(); return ss.str();
} }
case sol::type::poly:
return "<poly>";
default: default:
return "((unprintable type))"; return "<unprintable type>";
} }
} }
@@ -110,72 +113,95 @@ TEST_CASE("LuaAPI::MP::GetServerVersion") {
CHECK(pa == real.patch); CHECK(pa == real.patch);
} }
static inline bool InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) { static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
std::string Packet = "E:" + EventName + ":" + Data; std::string Packet = "E:" + EventName + ":" + Data;
if (PlayerID == -1) if (PlayerID == -1) {
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true); LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true);
else { return { true, "" };
} else {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_error("TriggerClientEvent invalid Player ID"); beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
return false; return { false, "Invalid Player ID" };
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) { if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) {
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID)); beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets"); LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
return false; return { false, "Respond failed, dropping client" };
} }
return { true, "" };
} }
return true;
} }
bool LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) { std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
std::string Data = DataObj.as<std::string>(); std::string Data = DataObj.as<std::string>();
return InternalTriggerClientEvent(PlayerID, EventName, Data); return InternalTriggerClientEvent(PlayerID, EventName, Data);
} }
void LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) { std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_error("Tried to drop client with id " + std::to_string(ID) + ", who doesn't exist"); beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
return; return { false, "Player does not exist" };
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason")); LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" };
} }
void LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) { std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
std::pair<bool, std::string> Result;
std::string Packet = "C:Server: " + Message; std::string Packet = "C:Server: " + Message;
if (ID == -1) { if (ID == -1) {
LogChatMessage("<Server> (to everyone) ", -1, Message); LogChatMessage("<Server> (to everyone) ", -1, Message);
Engine->Network().SendToAll(nullptr, Packet, true, true); Engine->Network().SendToAll(nullptr, Packet, true, true);
Result.first = true;
} else { } else {
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient && !MaybeClient.value().expired()) {
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!c->IsSynced()) if (!c->IsSynced()) {
return; Result.first = false;
Result.second = "Player still syncing data";
return Result;
}
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message); LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
Engine->Network().Respond(*c, Packet, true); if (!Engine->Network().Respond(*c, Packet, true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
// TODO: should we return an error here?
}
Result.first = true;
} else { } else {
beammp_lua_error("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;
} }
void LuaAPI::MP::RemoveVehicle(int PID, int VID) { std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
std::pair<bool, std::string> Result;
auto MaybeClient = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_error("RemoveVehicle invalid Player ID"); beammp_lua_error("RemoveVehicle invalid Player ID");
return; Result.first = false;
Result.second = "Invalid Player ID";
return Result;
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) { if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, Destroy, true, true); Engine->Network().SendToAll(nullptr, Destroy, true, true);
c->DeleteCar(VID); 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) { void LuaAPI::MP::Set(int ConfigID, sol::object NewValue) {
@@ -500,7 +526,7 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path"); beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
return; return;
} }
std::string key; std::string key{};
switch (left.get_type()) { switch (left.get_type()) {
case sol::type::lua_nil: case sol::type::lua_nil:
case sol::type::none: case sol::type::none:
@@ -519,6 +545,8 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
case sol::type::number: case sol::type::number:
key = std::to_string(left.as<double>()); key = std::to_string(left.as<double>());
break; break;
default:
beammp_assert_not_reachable();
} }
nlohmann::json value; nlohmann::json value;
switch (right.get_type()) { switch (right.get_type()) {
@@ -561,6 +589,8 @@ static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, c
} }
break; break;
} }
default:
beammp_assert_not_reachable();
} }
if (is_array) { if (is_array) {
json.push_back(value); json.push_back(value);
@@ -645,6 +675,6 @@ std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
return nlohmann::json::parse(json).unflatten().dump(-1); return nlohmann::json::parse(json).unflatten().dump(-1);
} }
bool LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) { std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data)); return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
} }
+5 -2
View File
@@ -44,7 +44,10 @@ TEST_CASE("TConfig::TConfig") {
{ {
buf.resize(fs::file_size(CfgFile)); buf.resize(fs::file_size(CfgFile));
auto fp = std::fopen(CfgFile.c_str(), "r"); auto fp = std::fopen(CfgFile.c_str(), "r");
std::fread(buf.data(), 1, buf.size(), fp); auto res = std::fread(buf.data(), 1, buf.size(), fp);
if (res != buf.size()) {
// IGNORE?
}
std::fclose(fp); std::fclose(fp);
} }
INFO("file contents are:", buf); INFO("file contents are:", buf);
@@ -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) { 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()) { if (Table[Category.c_str()][Key.data()].is_integer()) {
OutValue = Table[Category.c_str()][Key.data()].as_integer(); OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
} }
} }
+64 -23
View File
@@ -51,7 +51,18 @@ TEST_CASE("TrimString") {
CHECK(TrimString("") == ""); CHECK(TrimString("") == "");
} }
std::string GetDate() { // 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(); std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t(now); time_t tt = std::chrono::system_clock::to_time_t(now);
auto local_tm = std::localtime(&tt); auto local_tm = std::localtime(&tt);
@@ -144,10 +155,10 @@ void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
mStateId = LuaStateId; mStateId = LuaStateId;
mIsLuaConsole = true; mIsLuaConsole = true;
if (mStateId != mDefaultStateId) { if (mStateId != mDefaultStateId) {
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:detach`"); 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 { } else {
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:detach`"); 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(); mCachedRegularHistory = mCommandline.history();
@@ -259,9 +270,10 @@ void TConsole::Command_Kick(const std::string&, const std::vector<std::string>&
} }
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'"); beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
bool Kicked = false; bool Kicked = false;
// TODO: this sucks, tolower is locale-dependent.
auto NameCompare = [](std::string Name1, std::string Name2) -> bool { auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = tolower(c); }); 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 = tolower(c); }); std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1); return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
}; };
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
@@ -320,7 +332,9 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
} }
++Ptr; ++Ptr;
} }
Arg = std::string(PrevPtr, Ptr - PrevPtr); // 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));
// remove quotes if enclosed in quotes // remove quotes if enclosed in quotes
for (char Quote : { '"', '\'', '`' }) { for (char Quote : { '"', '\'', '`' }) {
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) { if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
@@ -436,6 +450,8 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
SystemsShutdown++; SystemsShutdown++;
SystemsShutdownList += NameStatusPair.first + ", "; SystemsShutdownList += NameStatusPair.first + ", ";
break; break;
default:
beammp_assert_not_reachable();
} }
} }
// remove ", " at the end // remove ", " at the end
@@ -454,7 +470,7 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
<< "\tConnected Players: " << ConnectedCount << "\n" << "\tConnected Players: " << ConnectedCount << "\n"
<< "\tGuests: " << GuestCount << "\n" << "\tGuests: " << GuestCount << "\n"
<< "\tCars: " << CarCount << "\n" << "\tCars: " << CarCount << "\n"
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n" << "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
<< "\tLua:\n" << "\tLua:\n"
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n" << "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n" << "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
@@ -621,42 +637,67 @@ TConsole::TConsole() {
mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) { mCommandline.on_autocomplete = [this](Commandline&, std::string stub, int) {
std::vector<std::string> suggestions; std::vector<std::string> suggestions;
try { try {
auto cmd = TrimString(stub);
// beammp_error("yes 1");
// beammp_error(stub);
if (mIsLuaConsole) { // if lua if (mIsLuaConsole) { // if lua
if (!mLuaEngine) { if (!mLuaEngine) {
beammp_info("Lua not started yet, please try again in a second"); beammp_info("Lua not started yet, please try again in a second");
} else { } else {
std::string prefix {}; std::string prefix {}; // stores non-table part of input
for (size_t i = stub.length(); i > 0; i--) { for (size_t i = stub.length(); i > 0; i--) { // separate table from input
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_') { if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
prefix = stub.substr(0, i); prefix = stub.substr(0, i);
stub = stub.substr(i); stub = stub.substr(i);
break; break;
} }
} }
auto keys = mLuaEngine->GetStateGlobalKeysForState(mStateId);
for (const auto& key : keys) { // turn string into vector of keys
std::string::size_type n = key.find(stub); 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);
if (n == 0) { if (n == 0) {
suggestions.push_back(prefix + key); suggestions.push_back(prefix + before_last_atom + key);
// beammp_warn(cmd_name);
} }
} }
} }
} else { // if not lua } else { // if not lua
for (const auto& [cmd_name, cmd_fn] : mCommandMap) { if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
std::string::size_type n = cmd_name.find(stub); std::string after_prefix = TrimString(stub.substr(3));
if (n == 0) { auto stateNames = mLuaEngine->GetLuaStateNames();
suggestions.push_back(cmd_name);
// beammp_warn(cmd_name); 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);
}
} }
} }
} }
} catch (const std::exception& e) { } 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."); 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; return suggestions;
}; };
} }
+94 -1
View File
@@ -7,7 +7,6 @@
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
#include <httplib.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <random> #include <random>
#include <thread> #include <thread>
@@ -221,6 +220,66 @@ std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
return Result; 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) { 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) { for (const auto& Result : Results) {
bool Cancelled = false; bool Cancelled = false;
@@ -517,6 +576,35 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
return sol::lua_nil; 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) { sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
auto table = mStateView.create_table(); auto table = mStateView.create_table();
constexpr const char* InternalClient = "__InternalClient"; constexpr const char* InternalClient = "__InternalClient";
@@ -590,6 +678,8 @@ static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, c
return; return;
case nlohmann::detail::value_t::discarded: case nlohmann::detail::value_t::discarded:
return; return;
default:
beammp_assert_not_reachable();
} }
} }
@@ -673,6 +763,9 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table { MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
return Lua_GetPlayerVehicles(ID); 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("SendChatMessage", &LuaAPI::MP::SendChatMessage);
MPTable.set_function("GetPlayers", [&]() -> sol::table { MPTable.set_function("GetPlayers", [&]() -> sol::table {
return Lua_GetPlayers(); return Lua_GetPlayers();
+10 -11
View File
@@ -57,7 +57,7 @@ void TNetwork::UDPServerMain() {
serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian
// Try and bind the socket to the IP and port // Try and bind the socket to the IP and port
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) { if (bind(mUDPSock, reinterpret_cast<struct sockaddr*>(&serverAddr), sizeof(serverAddr)) != 0) {
beammp_error("bind() failed: " + GetPlatformAgnosticErrorString()); beammp_error("bind() failed: " + GetPlatformAgnosticErrorString());
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1); // TODO: Wtf. exit(-1); // TODO: Wtf.
@@ -134,7 +134,7 @@ void TNetwork::TCPServerMain() {
addr.sin_addr.s_addr = INADDR_ANY; addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_port = htons(uint16_t(Application::Settings.Port)); addr.sin_port = htons(uint16_t(Application::Settings.Port));
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) < 0) { if (bind(Listener, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) < 0) {
beammp_error("bind() failed, the server cannot operate and will shut down now. " beammp_error("bind() failed, the server cannot operate and will shut down now. "
"Error: " "Error: "
+ GetPlatformAgnosticErrorString()); + GetPlatformAgnosticErrorString());
@@ -166,7 +166,7 @@ void TNetwork::TCPServerMain() {
int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS)); int ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&SendTimeoutMS), sizeof(SendTimeoutMS));
#else // POSIX #else // POSIX
struct timeval optval; struct timeval optval;
optval.tv_sec = (int)(SendTimeoutMS / 1000); optval.tv_sec = int(SendTimeoutMS / 1000);
optval.tv_usec = (SendTimeoutMS % 1000) * 1000; optval.tv_usec = (SendTimeoutMS % 1000) * 1000;
ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval)); ret = ::setsockopt(client.Socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<void*>(&optval), sizeof(optval));
#endif #endif
@@ -237,13 +237,13 @@ void TNetwork::HandleDownload(SOCKET TCPSock) {
}); });
} }
static int get_ip_str(const struct sockaddr* sa, char* strBuf, size_t strBufSize) { static int get_ip_str(const struct sockaddr* sa, char* strBuf, socklen_t strBufSize) {
switch (sa->sa_family) { switch (sa->sa_family) {
case AF_INET: case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in*)sa)->sin_addr), strBuf, strBufSize); inet_ntop(AF_INET, &reinterpret_cast<const struct sockaddr_in*>(sa)->sin_addr, strBuf, strBufSize);
break; break;
case AF_INET6: case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6*)sa)->sin6_addr), strBuf, strBufSize); inet_ntop(AF_INET6, &reinterpret_cast<const struct sockaddr_in6*>(sa)->sin6_addr, strBuf, strBufSize);
break; break;
default: default:
return 1; return 1;
@@ -453,7 +453,7 @@ bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
} }
std::string TNetwork::TCPRcv(TClient& c) { std::string TNetwork::TCPRcv(TClient& c) {
int32_t Header, BytesRcv = 0, Temp; int32_t Header {}, BytesRcv = 0, Temp {};
if (c.GetStatus() < 0) if (c.GetStatus() < 0)
return ""; return "";
@@ -470,7 +470,7 @@ std::string TNetwork::TCPRcv(TClient& c) {
if (!CheckBytes(c, BytesRcv)) { if (!CheckBytes(c, BytesRcv)) {
return ""; return "";
} }
if (Header < 100 * MB) { if (Header < int32_t(100 * MB)) {
Data.resize(Header); Data.resize(Header);
} else { } else {
ClientKick(c, "Header size limit exceeded"); ClientKick(c, "Header size limit exceeded");
@@ -822,7 +822,6 @@ 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) { void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
std::ifstream f(Name.c_str(), std::ios::binary); std::ifstream f(Name.c_str(), std::ios::binary);
auto Buf = f.rdbuf();
uint32_t Split = 125 * MB; uint32_t Split = 125 * MB;
std::vector<uint8_t> Data; std::vector<uint8_t> Data;
if (Size > Split) if (Size > Split)
@@ -1018,7 +1017,7 @@ bool TNetwork::UDPSend(TClient& Client, std::string Data) const {
size_t len = Data.size(); size_t len = Data.size();
#endif // WIN32 #endif // WIN32
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize)); sendOk = sendto(mUDPSock, Data.c_str(), len, 0, reinterpret_cast<struct sockaddr*>(&Addr), int(AddrSize));
if (sendOk == -1) { if (sendOk == -1) {
beammp_debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString()); beammp_debug("(UDP) sendto() failed: " + GetPlatformAgnosticErrorString());
if (Client.GetStatus() > -1) if (Client.GetStatus() > -1)
@@ -1039,7 +1038,7 @@ std::string TNetwork::UDPRcvFromClient(sockaddr_in& client) const {
#ifdef WIN32 #ifdef WIN32
auto Rcv = recvfrom(mUDPSock, Ret.data(), int(Ret.size()), 0, (sockaddr*)&client, (int*)&clientLength); auto Rcv = recvfrom(mUDPSock, Ret.data(), int(Ret.size()), 0, (sockaddr*)&client, (int*)&clientLength);
#else // unix #else // unix
int64_t Rcv = recvfrom(mUDPSock, Ret.data(), Ret.size(), 0, (sockaddr*)&client, (socklen_t*)&clientLength); int64_t Rcv = recvfrom(mUDPSock, Ret.data(), Ret.size(), 0, reinterpret_cast<struct sockaddr*>(&client), reinterpret_cast<socklen_t*>(&clientLength));
#endif // WIN32 #endif // WIN32
if (Rcv == -1) { if (Rcv == -1) {
+1 -1
View File
@@ -6,7 +6,7 @@
#include <sstream> #include <sstream>
TSentry::TSentry() { TSentry::TSentry() {
if (std::strlen(S_DSN) == 0) { if (std::strlen(S_DSN) == /* DISABLES CODE */ (0)) {
mValid = false; mValid = false;
} else { } else {
mValid = true; mValid = true;
+102 -26
View File
@@ -15,6 +15,66 @@
#include "Json.h" #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) { TServer::TServer(const std::vector<std::string_view>& Arguments) {
beammp_info("BeamMP Server v" + Application::ServerVersionString()); beammp_info("BeamMP Server v" + Application::ServerVersionString());
Application::SetSubsystemStatus("Server", Application::Status::Starting); Application::SetSubsystemStatus("Server", Application::Status::Starting);
@@ -86,8 +146,8 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
std::any Res; std::any Res;
char Code = Packet.at(0); char Code = Packet.at(0);
// V to Z // V to Y
if (Code <= 90 && Code >= 86) { if (Code <= 89 && Code >= 86) {
PPSMonitor.IncrementInternalPPS(); PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false); Network.SendToAll(LockedClient.get(), Packet, false, false);
return; return;
@@ -145,6 +205,11 @@ void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Pac
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")"); beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true); Network.SendToAll(LockedClient.get(), Packet, false, true);
return; return;
case 'Z': // position packet
PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false);
HandlePosition(*LockedClient, Packet);
default: default:
return; return;
} }
@@ -190,7 +255,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
std::string Packet = Pckt; std::string Packet = Pckt;
char Code = Packet.at(1); char Code = Packet.at(1);
int PID = -1; int PID = -1;
int VID = -1, Pos; int VID = -1;
std::string Data = Packet.substr(3), pid, vid; std::string Data = Packet.substr(3), pid, vid;
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
case 's': case 's':
@@ -223,13 +288,11 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
} }
} }
return; return;
case 'c': case 'c': {
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
pid = Data.substr(0, Data.find('-')); auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1); if (MaybePidVid) {
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) { std::tie(PID, VID) = MaybePidVid.value();
PID = stoi(pid);
VID = stoi(vid);
} }
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3)); auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
@@ -250,20 +313,17 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
c.SetUnicycleID(-1); c.SetUnicycleID(-1);
} }
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
if (!Network.Respond(c, Destroy, true)) { Network.SendToAll(nullptr, Destroy, true, true);
// TODO: handle
}
c.DeleteCar(VID); c.DeleteCar(VID);
} }
} }
return; return;
case 'd': }
case 'd': {
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
pid = Data.substr(0, Data.find('-')); auto MaybePidVid = GetPidVid(Data);
vid = Data.substr(Data.find('-') + 1); if (MaybePidVid) {
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) { std::tie(PID, VID) = MaybePidVid.value();
PID = stoi(pid);
VID = stoi(vid);
} }
if (PID != -1 && VID != -1 && PID == c.GetID()) { if (PID != -1 && VID != -1 && PID == c.GetID()) {
if (c.GetUnicycleID() == VID) { if (c.GetUnicycleID() == VID) {
@@ -276,15 +336,12 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID)); beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
} }
return; return;
case 'r': }
case 'r': {
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Pos = int(Data.find('-')); auto MaybePidVid = GetPidVid(Data);
pid = Data.substr(0, Pos++); if (MaybePidVid) {
vid = Data.substr(Pos, Data.find(':') - Pos); std::tie(PID, VID) = MaybePidVid.value();
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 (PID != -1 && VID != -1 && PID == c.GetID()) {
@@ -293,6 +350,7 @@ void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Networ
Network.SendToAll(&c, Packet, false, true); Network.SendToAll(&c, Packet, false, true);
} }
return; return;
}
case 't': case 't':
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")")); beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(&c, Packet, false, true); Network.SendToAll(&c, Packet, false, true);
@@ -365,3 +423,21 @@ void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
(void)mClients.insert(NewClient); (void)mClients.insert(NewClient);
} }
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);
}
}
+1 -3
View File
@@ -2,7 +2,6 @@
#include "ArgsParser.h" #include "ArgsParser.h"
#include "Common.h" #include "Common.h"
#include "CustomAssert.h"
#include "Http.h" #include "Http.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "SignalHandling.h" #include "SignalHandling.h"
@@ -13,7 +12,6 @@
#include "TPPSMonitor.h" #include "TPPSMonitor.h"
#include "TPluginMonitor.h" #include "TPluginMonitor.h"
#include "TResourceManager.h" #include "TResourceManager.h"
#include "TScopedTimer.h"
#include "TServer.h" #include "TServer.h"
#include <iostream> #include <iostream>
@@ -56,7 +54,7 @@ int BeamMPServerMain(MainArguments Arguments);
int main(int argc, char** argv) { int main(int argc, char** argv) {
MainArguments Args { argc, argv, {}, argv[0] }; MainArguments Args { argc, argv, {}, argv[0] };
Args.List.reserve(argc); Args.List.reserve(size_t(argc));
for (int i = 1; i < argc; ++i) { for (int i = 1; i < argc; ++i) {
Args.List.push_back(argv[i]); Args.List.push_back(argv[i]);
} }