Compare commits

...

251 Commits

Author SHA1 Message Date
Lion Kortlepel d0d560405c add readline, start working on a new console sink 2024-02-15 17:17:27 +01:00
Lion Kortlepel 98c69561b5 add libzip 2024-02-15 12:42:51 +01:00
Lion Kortlepel d0cc23333c ensure client stays referenced while referenced in thread pool 2024-01-26 10:32:41 +01:00
Lion Kortlepel c173ffdbdc implement state change to playing 2024-01-25 12:12:06 +01:00
Lion Kortlepel 7d813f7562 use a single strand per client to avoid writing to tcp out of order 2024-01-25 08:52:11 +01:00
Lion Kortlepel ee74d6291b update protocol 2024-01-25 08:40:45 +01:00
Lion Kortlepel 8654beb706 implement most of the Playing state, vehicle positions, vehicle data 2024-01-22 18:23:50 +01:00
Lion Kortlepel 630d5f1cfa implement session sync 2024-01-22 16:56:07 +01:00
Lion Kortlepel bde689d31a implement fully async read and write with individual timeouts 2024-01-21 22:54:36 +01:00
Lion Kortlepel 303a619ece implement async accept, async read for tcp 2024-01-20 19:20:33 +01:00
Lion Kortlepel 24723c01da update protocol 2024-01-20 18:18:15 +01:00
Lion Kortlepel b06991aaca migrate codebase to new network
marked non-implemented stuff with an exception
2024-01-19 17:34:36 +01:00
Lion Kortlepel e0fe6693e0 implement vehicle specifics, code needed for the rest of the server 2024-01-19 17:33:53 +01:00
Lion Kortlepel b882174ae7 add boost thread, glm 2024-01-19 17:33:19 +01:00
Lion Kortlepel 3de142a6d0 use boost::scoped_thread in IThreaded 2024-01-19 14:42:21 +01:00
Lion Kortlepel 9502048525 move packet to protocol 2024-01-17 14:59:45 +01:00
Lion Kortlepel 9e99177fcb implement compression and decompression 2024-01-17 14:52:09 +01:00
Lion Kortlepel dbab9eb894 handle udp packets like usual packets 2024-01-16 01:03:03 +01:00
Lion Kortlepel 9ea0931e13 implement udp connection 2024-01-16 00:58:14 +01:00
Lion Kortlepel e9805c3679 refactor identification to its own method 2024-01-15 22:22:27 +01:00
Lion Kortlepel ff33f1d42f update protocol 2024-01-15 22:18:59 +01:00
Lion Kortlepel 65d2ba3556 server-side identification done 2024-01-15 22:18:25 +01:00
Lion Kortlepel 6a411171f9 start implementing parsing of packets server-side 2024-01-15 22:11:44 +01:00
Lion Kortlepel 05dfb4e0c3 fix c header -> c++ header 2024-01-15 20:57:15 +01:00
Lion Kortlepel 4aca87d3e6 fully implement tcp and udp send and recv of packet types 2024-01-15 20:56:44 +01:00
Lion Kortlepel 7e9bb0cbf2 start rewriting networking 2024-01-15 20:39:32 +01:00
Lion Kortlepel 443871ec0f remove usages of weak_ptr 2024-01-11 14:30:25 +01:00
Lion Kortlepel 130e1acdb3 refactor client disconnect, client interation
anywhere a client is disconnected, TNetwork::Disconnect is called now.
Nothing else is valid.
ForEachClientWeak() was fully removed.
2024-01-11 14:14:34 +01:00
Lion Kortlepel aa29d04b60 remove unused TVehicleDataLockPair 2024-01-11 14:14:34 +01:00
Lion Kortlepel b9f73f77c3 major refactor of Client and Server
this refactor includes changes to TClient:

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

changes to TServer and TNetwork:

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

update linux.yml to fix incorrect runs-on tags

add ubuntu 22.04 arm64 build

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update linux.yml

Update 2-configure.sh

Update 2-configure.sh

Update 1-install-deps.sh

Update 1-install-deps.sh

Update 2-configure.sh

Update 2-configure.sh

Update linux.yml

use get-cmake

update vcpkg

force arm64 triplet
2024-01-09 15:35:47 +01:00
Lion Kortlepel 4228e18c90 reset default ID to 0 2024-01-09 15:34:33 +01:00
Lion Kortlepel 023e968302 refactor position packet handling, add regression tests 2024-01-09 15:34:33 +01:00
Lion Kortlepel a4eb10b6a4 fix MP.GetPositionRaw 2024-01-09 15:34:33 +01:00
Lion Kortlepel 0166e488d0 fix calling GlobalParser as static 2024-01-09 15:34:33 +01:00
Lion Kortlepel 0836fd3af8 fix bug in HandlePosition which caused the vehicle position not to be
saved properly
2024-01-09 15:34:33 +01:00
Lion Kortlepel 9791b8875c fix wrong order of SendErrorsShowMessage and SendErrors 2024-01-09 15:34:16 +01:00
Lion 01e8a1644a Bump version to v3.2.2 (#253) 2024-01-08 19:40:00 +01:00
Lion Kortlepel cebb2634a1 bump version 2024-01-08 17:43:54 +01:00
Lion 21a7ca1b64 Update README.md to remove mention of scripts and add ARM instructions (#243) 2023-12-30 15:07:39 +01:00
Lion bd4ab2b10d Update README.md 2023-12-30 10:22:12 +01:00
Lion 1cdc8e8f48 bump version number (#241) 2023-12-29 01:43:40 +01:00
Lion Kortlepel 1f72a45231 bump version number 2023-12-29 01:43:03 +01:00
Lion 002223afda Fix Server.log empty when stdout or stdin redirected (#235) 2023-12-28 21:27:44 +01:00
Lion Kortlepel ecc79b1918 update commandline to fix redirect issue 2023-12-28 21:23:31 +01:00
Lion d5000aea87 Remove changelog (#232)
now fully replaced by github releases due to issue-based workflow
2023-12-28 14:25:42 +01:00
Lion 810788a3e4 Add Tags Feature (#192)
This PR adds a tags functionality to the BeamMP server config and
heartbeat.
The intended purpose of this is to enable better filtering on the server
list based on keywords such as gamemode or roleplay.
2023-12-28 13:58:59 +01:00
Lion Kortlepel e724a2e467 Merge remote-tracking branch 'origin/master' into feature-tags 2023-12-28 13:57:49 +01:00
Lion Kortlepel 54ba295fce remove changelog
now fully replaced by github releases due to issue-based workflow
2023-12-28 13:53:32 +01:00
Lion f419550061 Allow env to override serverconfig (#227) 2023-12-28 13:51:00 +01:00
Lion Kortlepel 8cccbe8542 Merge remote-tracking branch 'origin/master' into 226-allow-env-to-override-serverconfig 2023-12-28 13:49:02 +01:00
Lion Kortlepel 6787843b37 pretty-print tags on startup 2023-12-28 12:58:29 +01:00
Lion Kortlepel 16d3c6f796 Merge remote-tracking branch 'origin/master' into feature-tags 2023-12-28 12:36:22 +01:00
Lion 21e5101560 Make debug symbols available for release builds (#216)
Closes #214
2023-12-28 12:30:40 +01:00
Lion 1adf19d416 Bump version to 3.2.0 (#231)
Due to new features like ENV reading this is now a feature release, so
minor
2023-12-28 12:16:05 +01:00
Lion c7e228fbae bump version to 3.2.0
due to new features like ENV reading this is now a feature release, so minor
2023-12-28 11:56:25 +01:00
Lion 6e04b2d93a Fix GitHub Actions not downloading the latest tests to run them (#220)
Closes #219
2023-12-28 11:55:02 +01:00
Lion 57a4c47cb0 Remove HTTP Server settings from config (#221)
This is not implemented and won't be implemented
2023-12-28 11:50:33 +01:00
Lion 416e0399af Remove [Feature Request] from issue title (#217) 2023-12-28 11:47:51 +01:00
Lion 050b574cc0 Remove [Bug] title from issue template (#218) 2023-12-28 11:47:39 +01:00
Lion d65f3cf75b Fix hot reload not working with symlinked entire plugins (#230) 2023-12-28 11:42:39 +01:00
Lion Kortlepel 329d2eb268 fix hot reload not working with symlinked entire plugins 2023-12-28 11:22:00 +01:00
Lion Kortlepel 221f491019 return early after reading ENV in config 2023-12-25 16:19:53 +01:00
Lion Kortlepel 89db370e12 use env variables by default to override config values 2023-12-25 16:16:01 +01:00
Lion aa84a65546 Update feature_request.md 2023-12-21 13:15:48 +01:00
Lion Kortlepel b28c69a515 remove http settings from config 2023-12-21 13:07:35 +01:00
Lion Kortlepel ac41547123 bump version to 3.1.4 2023-12-21 13:05:33 +01:00
Lion Kortlepel 2fc610f6bc fix tests not downloading artifacts by not using artifacts 2023-12-21 13:01:50 +01:00
Lion Kortlepel ddd3883aa9 fix failing gh actions test run 2023-12-21 13:01:50 +01:00
Lion defadf094f Fix exit after 10 seconds (#215)
Also fixes initializing the console too early by @lionkor
2023-12-21 12:50:19 +01:00
Lion Kortlepel 81299db946 fix console initializing too early
the console was initialized too early, leading to the server waiting for
it to shut down if the authkey is invalid, among other issues.
2023-12-21 12:49:20 +01:00
Lion c3895ec1ca remove [Bug] title from issue template 2023-12-21 12:17:50 +01:00
Lion c741fe5310 remove [Feature Request] from issue title 2023-12-21 12:17:11 +01:00
Lion Kortlepel e1dfb1085e modify release workflows to add debug info artifacts 2023-12-21 11:17:17 +01:00
Lion Kortlepel 142b6fa47a modify build scripts to generate .debug files with debug info 2023-12-21 11:13:51 +01:00
Bennett a6cbffc774 fix exit after 10 seconds 2023-12-21 02:01:21 -08:00
Starystars67 dc4ead532d Changed default tag to Freeroam as that is the majority of servers. 2023-12-18 14:10:07 +00:00
Lion f28d9bc7dc Update README.md 2023-12-16 20:18:40 +00:00
Starystars67 8c73eb8aea Added Tags Feature to the BeamMP Server. This allows better filtering on the server list. 2023-12-10 12:50:24 +01:00
Lion 43b1b050e2 Fix workflows to make release builds (#202)
Currently the Windows workflow doesn't properly create a release binary.
2023-12-09 20:17:10 +01:00
Lion Kortlepel 9f87edc6e9 add msvcp140.dll comment to the release text 2023-12-09 20:09:56 +01:00
Lion Kortlepel c6f78c5522 fix release build path 2023-12-09 20:06:50 +01:00
Lion Kortlepel 9f01268538 update version to 3.1.3 2023-12-09 20:01:53 +01:00
Lion Kortlepel 5523a4fe4b force build release config on windows 2023-12-09 20:00:33 +01:00
Lion Kortlepel 7f11d0f002 make release builds by default 2023-12-09 19:22:50 +01:00
Lion Kortlepel 6b31ba35fd attempt to fix workflows to make release builds 2023-12-09 19:18:33 +01:00
Lion d2329f0723 Remove password setting from config to avoid confusion (#199)
...until implemented.

The client afaik currently doesn't support this setting.
2023-12-09 19:05:54 +01:00
Luuk van Oijen ef45efeb86 Update readme to new build system (#200)
Now building is like 2 steps, so the readme reflects that now.
2023-12-09 18:33:46 +01:00
Lion edcca75637 Update README.md 2023-12-08 17:18:54 +01:00
Lion c1bacf1f3a remove old instructions from readme, cleanup 2023-12-08 17:16:47 +01:00
Lion Kortlepel 795b651744 remove macos section 2023-12-05 18:35:57 +01:00
Lion Kortlepel be108bb8b3 update readme to new build system 2023-12-05 18:34:06 +01:00
Lion Kortlepel d8b8812026 remove password setting from config to avoid confusion
...until implemented
2023-12-05 18:23:23 +01:00
Lion 872c2d410d New buildsystem (#197) 2023-12-05 18:21:20 +01:00
Lion Kortlepel f98704e0f3 fix warnings about implicit conversion 2023-12-05 18:05:35 +01:00
Lion Kortlepel dea203c108 make IThreaded::~IThreaded virtual to make destruction happen 2023-12-05 18:03:13 +01:00
Lion Kortlepel e245c9e9e2 fix pps monitor warning about virtual dtor 2023-12-05 18:02:35 +01:00
Lion Kortlepel 11fe5ad200 fix invalid timeout value 2023-12-05 18:00:34 +01:00
Lion Kortlepel 667da22b0e Merge remote-tracking branch 'origin/master' into new-buildsystem 2023-12-05 17:59:05 +01:00
Lion Kortlepel a6eb2f7bfe switch to vcpkg+cmake, add debian build to workflows
using lionkor's template (MIT licensed)

This is a combination of 64 commits.
2023-12-05 17:57:19 +01:00
Lion Kortlepel 103d2dc030 update vcpkg in workflows 2023-12-03 17:50:45 +01:00
Lion Kortlepel 7f206fd0d4 bump version to 3.1.2 2023-12-03 17:49:12 +01:00
Lion Kortlepel 22805af716 fix crash in authentication 2023-12-03 17:43:41 +01:00
Lion 2c29a195f9 optimize: Add conditional variable to LuaResult (#162)
Implementing TODO for optimization I saw in the code.
2023-03-27 13:31:21 +02:00
rgnter 222d2492ff Merge branch 'master' into optimize/add_cv_to_luaresult 2023-03-21 20:17:17 +01:00
Simon 879b9772f5 Apply suggestions from code review
Co-authored-by: Lion <development@kortlepel.com>
2023-01-15 17:12:35 +00:00
Anonymous275 c51cf090ef fix linux build 2023-01-15 17:12:35 +00:00
Anonymous275 d677d8d58d rename Hash function to HashPassword
move HashPassword to cpp only
move check to line 285
2023-01-15 17:12:35 +00:00
Anonymous275 4b30918659 - add 120 seconds timeout 2023-01-15 17:12:35 +00:00
Anonymous275 688e46f524 - fix linux build 2023-01-15 17:12:35 +00:00
Anonymous275 9f59c27b1f - add hash function
- add password config
- add debug messages for password stages
- add pass boolean for heartbeat
- adjust network codes
2023-01-15 17:12:35 +00:00
Lion 6a11bcd20b fix bad package name for Ubuntu in Readme (#161)
The package name for liblua required to build is not correct. The
correct name is
[`liblua-5.3-dev`](https://packages.ubuntu.com/search?suite=all&searchon=names&keywords=liblua5.3)
2022-12-21 16:29:49 +01:00
rgnter b7b578bf3e add conditional variable to LuaResult 2022-12-18 14:45:33 +01:00
rgnter 6c145a6dbf fix: Bad package name for Ubuntu 2022-12-18 12:32:45 +01:00
Lion 67d792e0e0 remove repeated dependency from README (#155) 2022-11-14 14:32:19 +01:00
Qest333 eaeef0c7d0 Remove double dependency from README 2022-11-14 14:00:21 +01:00
Lion 47e64a7343 merge release candidate v3.1.1 (#142)
patches and hotfixes!
2022-10-31 11:32:16 +01:00
Lion Kortlepel 7f5b3919f4 make destructors of virtual classes virtual
this causes warnings in clang, and rightfully so :^)
2022-10-31 11:31:16 +01:00
Lion Kortlepel 896e777e23 update changelog 2022-10-31 11:31:16 +01:00
Lion Kortlepel aa58c1e211 another potential fix for #141 2022-10-31 11:31:15 +01:00
Lion Kortlepel 49a9226dca update changelog to mention fixes 2022-10-31 11:31:15 +01:00
Lion Kortlepel b10d5d0f4e fix empty events causing issues in the server
an empty event packet, if sent just right, could crash the server
2022-10-31 11:31:15 +01:00
Lion Kortlepel 5581fd1692 fix chat message impersonation issue
instead of using the supplied name, we ignore it entirely and use the
server's internal name for the client
2022-10-31 11:31:15 +01:00
Lion Kortlepel d36bb7962c ignore empty chat messages
this could happen with a malicious client of some kind, we should simply
ignore them
2022-10-31 11:31:15 +01:00
Lion Kortlepel 4e8bd993d5 remove J packet handler
it wasn't used by anything in the launcher, mod, or during the join
sequence, so i removed it for now.
2022-10-31 11:31:15 +01:00
Lion Kortlepel abff9bfbdb fix crash when chat message is malformed 2022-10-31 11:31:15 +01:00
Lion Kortlepel b024533f90 fix crash when the header of a TCP packet is negative 2022-10-31 11:31:15 +01:00
Lion Kortlepel f9251ff92c add more warning prints on unexpected cases 2022-10-31 11:31:15 +01:00
Lion Kortlepel 99f41c28cb fix #135 by making onPlayerDisconnect blocking, and calling it before removing the player
before, the handlers were not waited for, so the client was usually
destructed before lua got to the actual event handler call. Now, the
handler is called and waited on, and once all handlers are done, the
client is properly removed from the players internally, thus making
calls to GetPlayerName, GetPlayerIdentifiers, etc. return nil etc.
2022-10-31 11:31:15 +01:00
Lion Kortlepel bbd27c9cba fix formatting bug in status (closes #143) 2022-10-31 11:31:15 +01:00
Lion Kortlepel 4682922467 add more fixes for msvc static linking 2022-10-31 11:31:15 +01:00
Lion Kortlepel 83fb387dfe potential fix to #141 2022-10-31 11:31:09 +01:00
Lion Kortlepel 2b61f11a86 fix EnsureArgsCount not properly printing min/max 2022-10-31 11:24:13 +01:00
Lion Kortlepel a8b1a205f7 bump version to 3.1.1
I'm expecting to release a 3.1.1 with some fixes
2022-10-31 11:24:13 +01:00
Lion dd9376447a Fix README errors (#138) 2022-10-26 14:34:01 +02:00
Lion aa185afabf Update README.md 2022-10-23 03:35:39 +02:00
Lion e8caeb9126 merge release candidate v3.1.0 (#83)
See https://github.com/BeamMP/BeamMP-Server/blob/rc-v3.1.0/Changelog.md for
a list of changes
2022-10-22 23:24:48 +02:00
Lion Kortlepel fa1944dbef update readme to reflect dependency- and code-changes in 3.1.0 2022-10-22 23:22:42 +02:00
Lion Kortlepel 093f905fd8 remove redundant addition libboost library install in cmake-linux action 2022-10-22 23:06:11 +02:00
Lion Kortlepel 2a45d2282d update rc-v3.1.0 to master 2022-10-22 22:55:12 +02:00
Lion Kortlepel aeb024953a fix sentry line that caused build to fail 2022-10-22 22:48:23 +02:00
ㄗㄠˋ ㄑㄧˊ 12a0ab7fdd document dependencies for macos (#109) 2022-10-22 22:47:53 +02:00
Lion Kortlepel 917c501faf fix typo causing beammp forum id not to show in identifiers (fix #137) 2022-10-22 21:16:31 +02:00
Lion Kortlepel 340933bbb3 fix dependencies for test run (add curl, fix ssl) 2022-10-22 21:01:44 +02:00
Lion Kortlepel a63359479e rename dependencies for test run in github actions 2022-10-22 20:44:47 +02:00
Lion Kortlepel bdf2da758c remove pps from heartbeat
"PPS has no meaning anymore and is completely irrelevant. You should
ignore it, it is not an indicator of ANYTHING. If it’s high, that means
NOTHING. If it’s low, that means NOTHING. If it’s -, that means
NOTHING."

It's packets per second per player per vehicle, but is only sent every
30 seconds, its not averaged, and on the client-side, it shows a ping
icon next to it.

A client can open a new connection to the server and send a `P`, and
measure the time to the `P` response packet. The connection is then
closed. This was added ages ago, please use this instead for ping :)
2022-10-17 14:05:51 +02:00
Lion Kortlepel 88c0ed56e4 add _WIN32_WINNT and move CRT no warnings flag 2022-10-17 12:25:13 +02:00
Lion Kortlepel 4256977400 remove crt's "this function or variable may be unsafe" warnings
they are useless, as they are in dependencies or parts of the code
we don't care about. Also, the "safe" alternatives straightup dont work
on linux.
2022-10-17 12:21:27 +02:00
Lion Kortlepel 309a9d1fa9 fix invalid windows workflows indentation 2022-10-17 12:12:55 +02:00
Lion Kortlepel ad860835ca fix linux tests run not installing openssl properly 2022-10-17 12:10:52 +02:00
Lion Kortlepel c6c2efb0b1 revert "update linux and windows workflows to run on pr open, reopen, review submit"
This reverts commit 23e9941704.
2022-10-17 12:09:36 +02:00
Lion c4c3b03b7a replace networking with boost::asio (synchronous) (#134)
- replaced all networking with boost::asio abstractions
- rewrote the SetStatus(), GetStatus() crap (now IsDisconnected() and
Disconnect() with reason)
- fixed bug related to ghost players / ghost cars
- handles packets as binary for the most part (vector<uint8_t> instead
of string) to fix various issues
2022-10-17 12:03:43 +02:00
Lion Kortlepel fd51336a91 update vcpkg 2022-10-17 12:01:08 +02:00
Lion Kortlepel 466845b314 add udp binary data fix to Changelog 2022-10-16 00:05:02 +02:00
Lion Kortlepel 92632b53b5 fix binary data breaking in UDPRcvFromClient 2022-10-15 23:30:09 +02:00
Lion Kortlepel 331a597ec7 add info about new networking to changelog 2022-10-15 23:19:33 +02:00
Lion Kortlepel 87965433c2 change log levels of common warnings and errors to debug
this hides a lot of the "standard" errors we get behind the debug flag.
for example, disconnecting a disconnected player would be such an error
2022-10-15 23:16:16 +02:00
Lion Kortlepel 75ff9f7571 remove "backend response failed to parse as valid json" 2022-10-15 23:16:16 +02:00
Lion Kortlepel 94c0547a35 fix crash when the client disconnects while sending first identify setting 2022-10-15 23:16:16 +02:00
Lion Kortlepel 98f77e157f add WIN32_STATIC_RUNTIME option to cmake 2022-10-15 23:16:16 +02:00
Lion Kortlepel 54730d2baf remove heartbeat spam logging 2022-10-15 23:16:16 +02:00
Lion Kortlepel 064e71e59f fix client version check 2022-10-15 23:16:16 +02:00
Lion Kortlepel 2678234d67 dont check for -Werror=zero-as-null-pointer-constant 2022-10-15 23:16:16 +02:00
Lion Kortlepel 4320a91e5c use message() instead of what() for ec 2022-10-15 23:16:16 +02:00
Lion Kortlepel 7d1318653c fix boost::system::error_code 2022-10-15 23:16:16 +02:00
Lion Kortlepel 67d02d4cf2 remove unused error check 2022-10-15 23:16:16 +02:00
Lion Kortlepel 93b2559120 switch to boost 1.74 2022-10-15 23:16:05 +02:00
Lion Kortlepel ed872f730d link against boost::system 2022-10-06 00:57:31 +02:00
Lion Kortlepel b25f4a875c run on latest ubuntu 2022-10-06 00:54:57 +02:00
Lion Kortlepel cc6b7846b2 add system include 2022-10-06 00:51:51 +02:00
Lion Kortlepel 88f5db514f remove unused headers 2022-10-06 00:46:35 +02:00
Lion Kortlepel e595192829 rename header to boost errc 2022-10-06 00:43:17 +02:00
Lion Kortlepel c69418ea5e add boost_system dependency for linux gh actions 2022-10-06 00:40:39 +02:00
Lion Kortlepel 917e3f98ab fix github actions dependencies for linux to use proper boost version 2022-10-06 00:36:57 +02:00
Lion Kortlepel c42a523532 remove SO_SNDTIMEO for now 2022-10-06 00:24:13 +02:00
Lion Kortlepel 95ae0f5d03 fix 'Od' and 'Or' packets not being broadcast 2022-10-05 22:17:56 +02:00
Lion Kortlepel fc0a509bd9 fix clientversion parameter in heartbeat 2022-10-05 21:15:11 +02:00
Lion Kortlepel 6249397fb5 add libboost-all-dev to github actions
it's a new dependency
2022-10-05 20:50:28 +02:00
Lion Kortlepel 231b13a0e7 fix a ghost client bug 2022-10-05 18:17:18 +02:00
Lion Kortlepel 7d2e4d4581 replace tcp networking with boost::asio tcp networking 2022-10-05 18:17:04 +02:00
Lion Kortlepel 7446526a19 fix binding of udp server socket
it was not binding properly because it wasn't open()ed, i guess
2022-10-05 13:06:36 +02:00
Lion Kortlepel 6e97a3cd6e switch udp networking to boost implementation 2022-10-05 12:14:25 +02:00
Lion Kortlepel 30482d290a add boost 1.75 dependency
this should be available on most platforms.
boost allows us to simplify a LOT of code.
2022-10-05 11:50:15 +02:00
Lion Kortlepel 5f1d003077 fix various potential crashes in TServer::HandlePosition 2022-10-03 17:06:32 +02:00
Lion Kortlepel 5d3dff3c88 add identifiers (beammp id, ip) as an argument to onPlayerAuth 2022-10-03 15:31:32 +02:00
Lion Kortlepel cb0cb30797 fix windows compiler not understanding a CLEAR AND SIMPLE FUNCTION-STYLE
CONSTRUCTOR CALL

AHHHHHHH
2022-10-03 15:12:59 +02:00
Lion Kortlepel 1f14de2e71 revert 9c6127a105 and apply proper fix 2022-10-03 15:11:26 +02:00
Lion Kortlepel 658b37acac fix error sometimes not displaying when failing inside global event handler 2022-10-03 14:38:19 +02:00
Lion Kortlepel d63c84286e replace logging functions with new fmt versions in ParseVehicle 2022-10-01 22:25:45 +02:00
Lion Kortlepel 9c6127a105 fix bug which may cause a server to crash when a car is spawned
thanks @Anonymous275
2022-10-01 19:10:21 +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
ㄗㄠˋ ㄑㄧˊ fdf24815bb document dependencies for macos (#109) 2022-09-26 12:18:47 +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
98 changed files with 3422 additions and 3259 deletions
-1
View File
@@ -1,7 +1,6 @@
--- ---
name: Bug report name: Bug report
about: Create a report to help us improve about: Create a report to help us improve
title: "[Bug] Enter issue title here"
labels: bug labels: bug
assignees: '' assignees: ''
+1 -2
View File
@@ -1,8 +1,7 @@
--- ---
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: "[Feature Request]" labels: feature
labels: enhancement
assignees: '' assignees: ''
--- ---
-78
View File
@@ -1,78 +0,0 @@
name: CMake Linux Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
linux-build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
with:
submodules: "recursive"
- name: Install Dependencies
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: |
echo ${#beammp_sentry_url}
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev cmake g++-10
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build Server
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server --parallel
- name: Build Tests
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE -t BeamMP-Server-tests --parallel
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-linux
path: ${{github.workspace}}/build-linux/BeamMP-Server
- name: Archive test artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-linux-tests
path: ${{github.workspace}}/build-linux/BeamMP-Server-tests
run-tests:
needs: linux-build
runs-on: ubuntu-20.04
steps:
- uses: actions/download-artifact@master
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
- name: Test
working-directory: ${{github.workspace}}
shell: bash
run: |
chmod +x ./BeamMP-Server-tests
./BeamMP-Server-tests
-58
View File
@@ -1,58 +0,0 @@
name: CMake Windows Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
windows-build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
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'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Archive artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server.exe
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
- name: Build debug
working-directory: ${{github.workspace}}/build-windows
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
+152
View File
@@ -0,0 +1,152 @@
name: Linux
on: [push]
env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_FORCE_SYSTEM_BINARIES: 1
CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs:
x86_64-matrix:
runs-on: ubuntu-22.04
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container:
image: ${{ matrix.distro }}:${{ matrix.version }}
steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
path: ./bin/BeamMP-Server
- name: Archive server debug info artifact
uses: actions/upload-artifact@v2
with:
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
path: ./bin/BeamMP-Server.debug
- name: Build Tests
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
- name: Install Runtime Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
- name: Test
run: ./bin/BeamMP-Server-tests
arm64-matrix:
runs-on: [Linux, ARM64]
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container:
image: ${{ matrix.distro }}:${{ matrix.version }}
steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
path: ./bin/BeamMP-Server
- name: Archive server debug info artifact
uses: actions/upload-artifact@v2
with:
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
path: ./bin/BeamMP-Server.debug
- name: Build Tests
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
- name: Install Runtime Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
- name: Test
run: ./bin/BeamMP-Server-tests
-115
View File
@@ -1,115 +0,0 @@
name: Release Create & Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
BUILD_TYPE: Release
jobs:
create-release:
runs-on: ubuntu-latest
name: Create Release
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: true
body: |
Files included in this release:
- `BeamMP-Server.exe` is the windows build
- `BeamMP-Server-linux` is a ubuntu build, so you need the dependencies listed in README.md to run it. For any other distros please build from source as described in README.md.
upload-release-files-linux:
name: Upload Linux Release Files
runs-on: ubuntu-latest
needs: create-release
steps:
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev libcurl4-openssl-dev
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10 -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-linux/BeamMP-Server
asset_name: BeamMP-Server-linux
asset_content_type: application/x-elf
upload-release-files-windows:
name: Upload Windows Release Files
runs-on: windows-latest
needs: create-release
steps:
- uses: actions/checkout@v2
with:
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'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
env:
beammp_sentry_url: ${{ secrets.BEAMMP_SECRET_SENTRY_URL }}
run: cmake $GITHUB_WORKSPACE -DSENTRY_BACKEND=breakpad -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static -DBEAMMP_SECRET_SENTRY_URL="$beammp_sentry_url"
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable
+214
View File
@@ -0,0 +1,214 @@
name: Release Create & Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release"
DEBIAN_FRONTEND: "noninteractive"
jobs:
create-release:
runs-on: ubuntu-latest
name: Create Release
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: true
body: |
Files included in this release are:
- `BeamMP-Server.$DISTRO.$DISTROVERSION.$ARCH` for linux builds, for example `BeamMP-Server.debian.11.x86_64` for the Debian 11 build for x86_64. All require `liblua5.3` to be installed.
- `BeamMP-Server.exe` for the Windows build (x86_64). You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this.
x86_64-matrix:
runs-on: ubuntu-22.04
needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
container:
image: ${{ matrix.distro }}:${{ matrix.version }}
steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server
asset_content_type: application/x-elf
- name: Upload Debug Info
id: upload-debug-info
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_content_type: application/x-elf
arm64-matrix:
runs-on: [Linux, ARM64]
needs: create-release
strategy:
matrix:
include:
- distro: debian
version: 11
- distro: debian
version: 12
- distro: ubuntu
version: 22.04
- distro: ubuntu
version: 20.04
env:
VCPKG_DEFAULT_TRIPLET: "arm64-linux"
container:
image: ${{ matrix.distro }}:${{ matrix.version }}
steps:
- name: get-cmake
uses: lukka/get-cmake@v3.28.1
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- name: Install git
run: |
apt-get update -y
apt-get install -y git
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Git config safe directory
shell: bash
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: BeamMP-Server.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server
asset_content_type: application/x-elf
- name: Upload Debug Info
id: upload-debug-info
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
asset_name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_content_type: application/x-elf
upload-release-files-windows:
name: Build and upload Windows Release Files
runs-on: windows-latest
needs: create-release
env:
VCPKG_DEFAULT_TRIPLET: x64-windows-static
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Create Build Environment
shell: bash
run: ./scripts/windows/1-configure.sh
- name: Build Server
shell: bash
run: bash ./scripts/windows/2-build.sh
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/Release/BeamMP-Server.exe
asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable
+43
View File
@@ -0,0 +1,43 @@
name: Windows
on: [push]
env:
VCPKG_DEFAULT_TRIPLET: x64-windows-static
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release"
jobs:
windows-build:
runs-on: windows-latest
steps:
- name: Export GitHub Actions cache environment variables
uses: actions/github-script@v6
with:
script: |
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
- uses: actions/checkout@v2
with:
submodules: 'recursive'
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
shell: bash
run: ./scripts/windows/1-configure.sh
- name: Build Server
shell: bash
run: bash ./scripts/windows/2-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-windows
path: ./bin/Release/BeamMP-Server.exe
+6 -30
View File
@@ -1,33 +1,9 @@
[submodule "deps/commandline"] [submodule "deps/commandline"]
path = deps/commandline path = deps/commandline
url = https://github.com/lionkor/commandline url = https://github.com/lionkor/commandline
[submodule "deps/asio"] [submodule "vcpkg"]
path = deps/asio path = vcpkg
url = https://github.com/chriskohlhoff/asio url = https://github.com/Microsoft/vcpkg.git
[submodule "deps/rapidjson"] [submodule "deps/BeamMP-Protocol"]
path = deps/rapidjson path = deps/BeamMP-Protocol
url = https://github.com/Tencent/rapidjson url = https://github.com/BeamMP/BeamMP-Protocol
[submodule "deps/toml11"]
path = deps/toml11
url = https://github.com/ToruNiina/toml11
[submodule "deps/sentry-native"]
path = deps/sentry-native
url = https://github.com/getsentry/sentry-native
[submodule "deps/sol2"]
path = deps/sol2
url = https://github.com/ThePhD/sol2
[submodule "deps/libzip"]
path = deps/libzip
url = https://github.com/nih-at/libzip
[submodule "deps/cpp-httplib"]
path = deps/cpp-httplib
url = https://github.com/yhirose/cpp-httplib
[submodule "deps/json"]
path = deps/json
url = https://github.com/nlohmann/json
[submodule "deps/fmt"]
path = deps/fmt
url = https://github.com/fmtlib/fmt
[submodule "deps/doctest"]
path = deps/doctest
url = https://github.com/doctest/doctest
+211 -194
View File
@@ -1,198 +1,215 @@
# 3.4 is required for imported targets. cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
cmake_minimum_required(VERSION 3.4 FATAL_ERROR)
message(STATUS "You can find build instructions and a list of dependencies in the README at \
https://github.com/BeamMP/BeamMP-Server")
project(BeamMP-Server
DESCRIPTION "Server for BeamMP - The Multiplayer Mod for BeamNG.drive"
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")
endif()
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)
set(LUA_INCLUDE_DIR /usr/local/Cellar/lua@5.3/5.3.6/include/lua5.3)
set(LUA_LIBRARIES lua)
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.
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
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 -static-libstdc++ -static-libgcc")
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=undefined,thread")
endif (SANITIZE)
endif ()
include_directories("include/sentry-native/include")
set(BUILD_SHARED_LIBS OFF)
# ------------------------ SENTRY ---------------------------------
message(STATUS "Checking for Sentry URL")
# this is set by the build system.
# IMPORTANT: if you're building from source, just leave this empty
if (NOT DEFINED BEAMMP_SECRET_SENTRY_URL)
message(WARNING "No sentry URL configured. Sentry logging is disabled for this build. \
This is not an error, and if you're building the BeamMP-Server yourself, this is expected and can be ignored.")
set(BEAMMP_SECRET_SENTRY_URL "")
set(SENTRY_BACKEND none)
else()
set(SENTRY_BACKEND breakpad)
endif()
add_subdirectory("deps/sentry-native")
# ------------------------ C++ SETUP ---------------------------------
set(CMAKE_CXX_STANDARD 17)
if (MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
endif ()
# ------------------------ DEPENDENCIES ------------------------------
message(STATUS "Adding local source dependencies")
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
add_subdirectory(deps)
# ------------------------ VARIABLES ---------------------------------
include(FindLua)
include(FindOpenSSL)
include(FindThreads)
include(FindZLIB)
set(BeamMP_Sources
include/TConsole.h src/TConsole.cpp
include/TServer.h src/TServer.cpp
include/Compat.h src/Compat.cpp
include/Common.h src/Common.cpp
include/Client.h src/Client.cpp
include/VehicleData.h src/VehicleData.cpp
include/TConfig.h src/TConfig.cpp
include/TLuaEngine.h src/TLuaEngine.cpp
include/TLuaPlugin.h src/TLuaPlugin.cpp
include/TResourceManager.h src/TResourceManager.cpp
include/THeartbeatThread.h src/THeartbeatThread.cpp
include/Http.h src/Http.cpp
include/TSentry.h src/TSentry.cpp
include/TPPSMonitor.h src/TPPSMonitor.cpp
include/TNetwork.h src/TNetwork.cpp
include/LuaAPI.h src/LuaAPI.cpp
include/TScopedTimer.h src/TScopedTimer.cpp
include/SignalHandling.h src/SignalHandling.cpp
include/ArgsParser.h src/ArgsParser.cpp
include/TPluginMonitor.h src/TPluginMonitor.cpp
include/Environment.h
)
set(BeamMP_Includes
"${CMAKE_CURRENT_SOURCE_DIR}/include"
"${CMAKE_CURRENT_SOURCE_DIR}/commandline"
${LUA_INCLUDE_DIR}
${CURL_INCLUDE_DIRS}
"include/tomlplusplus"
"include/sentry-native/include"
"include/curl/include"
)
set(BeamMP_Definitions
SECRET_SENTRY_URL="${BEAMMP_SECRET_SENTRY_URL}"
)
set(BeamMP_Libraries
doctest::doctest
OpenSSL::SSL
OpenSSL::Crypto
sol2::sol2
fmt::fmt
Threads::Threads
ZLIB::ZLIB
${LUA_LIBRARIES}
commandline
sentry
)
if (WIN32) if (WIN32)
set(BeamMP_PlatformLibs wsock32 ws2_32) set(VCPKG_TARGET_TRIPLET x64-windows-static)
endif () endif()
# ------------------------ BEAMMP SERVER ----------------------------- include(cmake/Vcpkg.cmake) # needs to happen before project()
add_executable(BeamMP-Server project(
src/main.cpp "BeamMP-Server" # replace this
${BeamMP_Sources} VERSION 3.3.0
) )
target_compile_definitions(BeamMP-Server PRIVATE include(cmake/StandardSettings.cmake)
${BeamMP_Definitions} include(cmake/StaticAnalyzers.cmake)
DOCTEST_CONFIG_DISABLE include(cmake/Git.cmake)
)
add_subdirectory(deps/BeamMP-Protocol)
target_include_directories(BeamMP-Server PUBLIC
${BeamMP_Includes} # below are options which should be changed
)
### SETTINGS ###
target_link_libraries(BeamMP-Server
${BeamMP_Libraries} # add all headers (.h, .hpp) to this
${BeamMP_PlatformLibs} set(PRJ_HEADERS
) include/ArgsParser.h
include/BoostAliases.h
# ------------------------ BEAMMP SERVER TESTS ----------------------- include/Common.h
include/Compat.h
option(BUILD_TESTS "Build BeamMP-Server tests" ON) include/Cryptography.h
include/CustomAssert.h
if(BUILD_TESTS) include/Defer.h
add_executable(BeamMP-Server-tests include/Environment.h
test/test_main.cpp include/Http.h
${BeamMP_Sources} include/IThreaded.h
) include/Json.h
include/LuaAPI.h
target_compile_definitions(BeamMP-Server-tests PRIVATE include/RWMutex.h
${BeamMP_Definitions} include/SignalHandling.h
) include/TConfig.h
include/TConsole.h
target_include_directories(BeamMP-Server-tests PUBLIC include/THeartbeatThread.h
${BeamMP_Includes} include/TLuaEngine.h
) include/TLuaPlugin.h
include/TPluginMonitor.h
target_link_libraries(BeamMP-Server-tests include/TScopedTimer.h
${BeamMP_Libraries} include/VehicleData.h
${BeamMP_PlatformLibs} include/Env.h
) include/Network.h
)
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES
src/ArgsParser.cpp
src/Common.cpp
src/Compat.cpp
src/Http.cpp
src/LuaAPI.cpp
src/SignalHandling.cpp
src/TConfig.cpp
src/TConsole.cpp
src/THeartbeatThread.cpp
src/TLuaEngine.cpp
src/TLuaPlugin.cpp
src/TPluginMonitor.cpp
src/TScopedTimer.cpp
src/VehicleData.cpp
src/Env.cpp
src/Network.cpp
)
find_package(Lua REQUIRED)
# set the source file containing main()
set(PRJ_MAIN src/main.cpp)
# set the source file containing the test's main
set(PRJ_TEST_MAIN test/test_main.cpp)
# set include paths not part of libraries
set(PRJ_INCLUDE_DIRS ${LUA_INCLUDE_DIR})
# set compile features (e.g. standard version)
set(PRJ_COMPILE_FEATURES cxx_std_20)
# set #defines (test enable/disable not included here)
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT)
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
set(PRJ_LIBRARIES
fmt::fmt
doctest::doctest
Threads::Threads
commandline_static
toml11::toml11
rapidjson
sol2
httplib::httplib
libzip::zip
OpenSSL::SSL OpenSSL::Crypto
protocol
${LUA_LIBRARIES}
zstd::libzstd_static
Boost::thread
glm::glm
)
# add dependency find_package calls and similar here
find_package(fmt CONFIG REQUIRED)
find_package(OpenSSL REQUIRED)
find_package(doctest CONFIG REQUIRED)
find_package(Boost REQUIRED COMPONENTS thread)
find_package(httplib CONFIG REQUIRED)
find_package(libzip CONFIG REQUIRED)
find_package(RapidJSON CONFIG REQUIRED)
find_package(sol2 CONFIG REQUIRED)
find_package(toml11 CONFIG REQUIRED)
find_package(zstd CONFIG REQUIRED)
find_package(glm CONFIG REQUIRED)
include_directories(include)
# to enable multithreading and the Threads::Threads dependency
include(FindThreads)
### END SETTINGS ###
# DONT change anything beyond this point unless you've read the cmake bible and
# swore on it not to bonk up the ci/cd pipelines with your changes.
####################
# enables compile_commands.json for clang-related tools (such as the clang LS)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# build release builds by default (if not specified otherwise)
if(NOT DEFINED CMAKE_BUILD_TYPE)
message(NOTICE "No build type specified, defaulting to 'Release'")
set(CMAKE_BUILD_TYPE "Release")
endif()
if(UNIX)
# this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
endif(UNIX)
if (WIN32)
add_compile_options("-D_WIN32_WINNT=0x0601")
endif(WIN32)
include(cmake/CompilerWarnings.cmake)
# set MT library for msvc - this is required (says documentation)
# linux/mac/etc should simply ignore this by default.
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
)
# build commandline manually for funky windows flags to carry over without a custom toolchain file
add_library(commandline_static
deps/commandline/src/impls.h
deps/commandline/src/windows_impl.cpp
deps/commandline/src/linux_impl.cpp
deps/commandline/src/backends/InteractiveBackend.cpp
deps/commandline/src/backends/InteractiveBackend.h
deps/commandline/src/backends/Backend.cpp
deps/commandline/src/backends/Backend.h
deps/commandline/src/commandline.h
deps/commandline/src/commandline.cpp
deps/commandline/src/backends/BufferedBackend.cpp
deps/commandline/src/backends/BufferedBackend.h
)
if (WIN32)
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_WINDOWS=1)
else ()
target_compile_definitions(commandline_static PRIVATE -DPLATFORM_LINUX=1)
endif ()
target_include_directories(commandline_static PUBLIC "deps/commandline/src")
target_link_libraries(commandline_static Threads::Threads)
# end of commandline custom build
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
set_target_properties(${PROJECT_NAME} PROPERTIES
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
)
if(MSVC)
target_link_options(${PROJECT_NAME} PRIVATE "/SUBSYSTEM:CONSOLE")
endif(MSVC)
# setup all warnings (from cmake/CompilerWarnings.cmake)
set_project_warnings(${PROJECT_NAME})
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
set_project_warnings(${PROJECT_NAME}-tests)
if(MSVC)
target_link_options(${PROJECT_NAME}-tests PRIVATE "/SUBSYSTEM:CONSOLE")
endif(MSVC)
endif() endif()
+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.
-139
View File
@@ -1,139 +0,0 @@
# v3.1.0
- ADDED Tab autocomplete in console, smart tab autocomplete (understands lua tables and types) in the lua console
- ADDED lua debug facilities (type `:help` when attached to lua via `lua`)
- ADDED 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
- 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
# v3.0.2
- ADDED Periodic update message if a new server is released
- ADDED Config setting for the IP the http server listens on
- CHANGED Default MaxPlayers to 8
- CHANGED Default http server listen IP to localhost
- FIXED `MP.CreateEventTimer` filling up the queue (see <https://wiki.beammp.com/en/Scripting/new-lua-scripting#mpcreateeventtimerevent_name-string-interval_ms-number-strategy-number-since-v302>)
- FIXED `MP.TriggerClientEvent` not kicking the client if it failed
- FIXED Lua result queue handling not checking all results
- FIXED bug which caused ServerConfig.toml to generate incorrectly
# v3.0.1
- ADDED Backup URLs to UpdateCheck (will fail less often now)
- ADDED console cursor left and right movement (with arrow keys) and working HOME and END key (via github.com/lionkor/commandline)
- FIXED infinite snowmen / infinite unicycle spawning bug
- FIXED a bug where, when run with --working-directory, the Server.log would still be in the original directory
- FIXED a bug which could cause the plugin reload thread to spin at 100% if the reloaded plugin's didn't terminate
- FIXED an issue which would cause servers to crash on mod download via SIGPIPE on POSIX
- FIXED an issue which would cause servers to crash when checking if a vehicle is a unicycle
# v3.0.0
- CHANGED entire plugin Lua implementation (rewrite)
- CHANGED moved *almost all* Lua functions into MP.\*
- CHANGED console to use a custom language (type `help`, `list`, or `status`!)
- CHANGED all files of a Lua plugin to share a Lua state (no more state-per-file)
- ADDED many new Lua API functions, which can be found at <https://wiki.beammp.com/en/Scripting/functions>
- ADDED Commandline options. Run with `--help` to see all options.
- ADDED HTTP(S) Server (OpenAPI spec coming soon!)
- ADDED plugin directories to `package.path` and `package.cpath` before `onInit`
- ADDED ability to add `PluginConfig.toml` to your plugin folder to change some settings
- ADDED ability to share a lua state with other plugins via `StateId` setting in `PluginConfig.toml`
- ADDED ability to see name-to-thread-ID association in debug mode
- ADDED dumping tables with `print()` (try it with `print(MP)`)
- ADDED `MP.GetOSName()`, `MP.CreateTimer()`, `MP.GetLuaMemoryUsage()` and many more (see <https://wiki.beammp.com/en/Scripting/functions>)
- ADDED `MP.Settings` table to make usage of `MP.Set()` easier
- ADDED `FS.*` table with common filesystem operations (do `print(FS)` to see them!)
- FIXED i/o thread spin when stdout is /dev/null on linux
- FIXED removed extra whitespace infront of onChatMessage message
# v2.3.3
- CHANGED servers to be private by default
# v2.3.2
- ADDED Ctrl+C causes a graceful shutdown on windows (did already on linux)
- ADDED more meaningful shutdown messages
- ADDED even better backend connection error reporting
- ADDED `SendErrors` config in `ServerConfig.toml` to opt-out of error reporting
- ADDED hard-shutdown if Ctrl+C pressed 3 times
- FIXED issue with shells like bash being unusable after server exit
# v2.3.1
- CHANGED join/sync timeout to 20 minutes, players wont drop if loading takes >5 mins
# v2.3.0
- ADDED version check - the server will now let you know when a new release is out
- ADDED logging of various errors, crashes and exceptions to the backend
- ADDED chat messages are now logged to the server console as [CHAT]
- ADDED debug message telling you when the server heartbeats to the backend
- REMOVED various [DEBUG] messages which were confusing (such as "breaking client loop")
- FIXED various crashes and issues with handling unexpected backend responses
- FIXED minor bugs due to code correctness
# v2.2.0
- FIXED major security flaw
- FIXED minor bugs
# v2.1.4
- ADDED debug heartbeat print
- ADDED kicking every player before shutdown
- FIXED rare bug which led to violent crash
- FIXED minor bugs
# v2.1.3
- FIXED Lua events not cancelling properly on Linux
# v2.1.2
- CHANGED default map to gridmap v2
- FIXED version number display
# v2.1.1
# v2.1.0 (pre-v2.1.1)
# v2.0.4 (pre-v2.1.0)
- REMOVED boost as a runtime dependency
- FIXED Lua plugins on Linux
- FIXED console history on Windows
- CHANGED to new config format TOML
# v2.0.3
- WORKAROUND for timeout bug / ghost player bug
- FIXED 100% CPU spin when stdin is /dev/null.
# v2.0.2
- ADDED fully new commandline
- ADDED new backend
- ADDED automated build system
- ADDED lua GetPlayerIdentifiers
- ADDED lots of debug info
- ADDED better POSTing and GETing
- ADDED a license
- FIXED ghost players in player list issue
- FIXED ghost vehicle after joining issue
- FIXED missing vehicle after joining issue
- FIXED a lot of desync issues
- FIXED some memory leaks
- FIXED various crashes
- FIXED various data-races
- FIXED some linux-specific crashes
- FIXED some linux-specific issues
- FIXED bug which caused kicking to be logged as leaving
- FIXED various internal developer quality-of-life things
+30 -61
View File
@@ -4,16 +4,16 @@
[![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, which are listed below under [Runtime Dependencies](#runtime-dependencies)**
## Support + Contact ## Support + Contact
Feel free to ask any questions via the following channels: 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) - **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,21 +28,21 @@ 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" or "good first issue" 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
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`. We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v3.1.0`.
## 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 Linux. For any other distro or OS, you just have to find the same libraries listed in [Runtime Dependencies](#runtime-dependencies) further down the page, and it should build fine.
Recommended compilers: MSVC, GCC, CLANG. Recommended compilers: MSVC, GCC, CLANG.
@@ -50,71 +50,40 @@ You can find precompiled binaries under [Releases](https://github.com/BeamMP/Bea
## Build Instructions ## Build Instructions
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.3.3`!__** On Linux, you need some dependencies to **build** the server (on Windows, you don't):
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
### Prerequisites
#### Windows
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
Dependencies for **windows** can be installed with `vcpkg`.
These are:
``` ```
lua liblua5.3-dev curl zip unzip tar cmake make git g++
zlib
rapidjson
openssl
websocketpp
curl
``` ```
#### Linux You can install these with your distribution's package manager. You will need sudo or need root for ONLY this step.
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro. The names of each package may change depending on your platform.
Runtime dependencies for **linux** are (debian/ubuntu): If you are building for ARM (like aarch64), you need to run `export VCPKG_FORCE_SYSTEM_BINARIES=1` before the following commands.
```
libz-dev
rapidjson-dev
liblua5.3
libssl-dev
libwebsocketpp-dev
libcurl4-openssl-dev
```
Build-time dependencies for **linux** are: You can build on **Windows, Linux** or other platforms by following these steps:
```
git
make
cmake
g++
```
For other distributions (e.g. Arch) you want to find packages for: 1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
- libz 2. Go into the directory `cd BeamMP-Server`.
- rapidjson 3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
- lua5.3 4. Build via `cmake --build bin --parallel --config Release -t BeamMP-Server`.
- ssl / openssl 5. Your executable can be found in `bin/`.
- websocketpp
- curl (with ssl support)
- \+ the build time dependencies from above
### How to build When you make changes to the code, you only have to run step 4 again.
On windows, use git-bash for these commands. On Linux, these should work in your shell. ### Runtime Dependencies
1. Make sure you have all [prerequisites](#prerequisites) installed These are needed to *run* the 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`.
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 &`*.* Debian, Ubuntu and friends: `liblua5.3-0`
Other Linux distros: `liblua` of *some kind*.
Windows: No libraries.
## 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
+114
View File
@@ -0,0 +1,114 @@
# from here:
#
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
# Courtesy of Jason Turner
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
#
# This version has been modified by the owners of the current respository.
# Modifications have mostly been marked with "modified" or similar, though this is not
# strictly required.
function(set_project_warnings project_name)
set(MSVC_WARNINGS
/W4 # Baseline reasonable warnings
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
# of data
/w14254 # 'operator': conversion from 'type1:field_bits' to
# 'type2:field_bits', possible loss of data
/w14263 # 'function': member function does not override any base class
# virtual member function
/w14265 # 'classname': class has virtual functions, but destructor is not
# virtual instances of this class may not be destructed correctly
/w14287 # 'operator': unsigned/negative constant mismatch
/we4289 # nonstandard extension used: 'variable': loop control variable
# declared in the for-loop is used outside the for-loop scope
/w14296 # 'operator': expression is always 'boolean_value'
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
/w14545 # expression before comma evaluates to a function which is missing
# an argument list
/w14546 # function call before comma missing argument list
/w14547 # 'operator': operator before comma has no effect; expected
# operator with side-effect
/w14549 # 'operator': operator before comma has no effect; did you intend
# 'operator'?
/w14555 # expression has no effect; expected expression with side- effect
/w14619 # pragma warning: there is no warning number 'number'
/w14640 # Enable warning on thread un-safe static member initialization
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
# cause unexpected runtime behavior.
/w14905 # wide string literal cast to 'LPSTR'
/w14906 # string literal cast to 'LPWSTR'
/w14928 # illegal copy-initialization; more than one user-defined
# conversion has been implicitly applied
/permissive- # standards conformance mode for MSVC compiler.
)
set(CLANG_WARNINGS
-Wall
-Wextra # reasonable and standard
-Wshadow # warn the user if a variable declaration shadows one from a
# parent context
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
# non-virtual destructor. This helps catch hard to
# track down memory errors
-Wold-style-cast # warn for c-style casts
-Wcast-align # warn for potential performance problem casts
-Wunused # warn on anything being unused
-Woverloaded-virtual # warn if you overload (not override) a virtual
# function
-Wpedantic # warn if non-standard C++ is used
-Wconversion # warn on type conversions that may lose data
-Wsign-conversion # warn on sign conversions
-Wnull-dereference # warn if a null dereference is detected
-Wdouble-promotion # warn if float is implicit promoted to double
-Wformat=2 # warn on security issues around functions that format output
# (ie printf)
# modified; added more errors / warnings
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
# (see below) should still be used in strict pipelines.
-Werror=uninitialized
-Werror=float-equal
-Werror=write-strings
-Werror=strict-aliasing -fstrict-aliasing
-Werror=missing-declarations
-Werror=ctor-dtor-privacy
-Wno-missing-field-initializers
-Wswitch-default
-Werror=unused-result
-Werror=implicit-fallthrough
-Werror=return-type
-Wmissing-include-dirs
)
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
endif()
set(GCC_WARNINGS
${CLANG_WARNINGS}
-Wmisleading-indentation # warn if indentation implies blocks where blocks
# do not exist
-Wduplicated-cond # warn if if / else chain has duplicated conditions
-Wduplicated-branches # warn if if / else branches have duplicated code
-Wlogical-op # warn about logical operations being used where bitwise were
# probably wanted
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
)
if(MSVC)
set(PRJ_WARNINGS ${MSVC_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
set(PRJ_WARNINGS ${CLANG_WARNINGS})
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(PRJ_WARNINGS ${GCC_WARNINGS})
else()
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
endif()
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
if(NOT TARGET ${project_name})
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
endif()
endfunction()
+21
View File
@@ -0,0 +1,21 @@
find_package(Git)
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
if(Git_FOUND)
message(STATUS "Git found, submodule update and init")
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(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
endif()
else()
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
endif()
endif()
if(Git_FOUND)
else()
message(STATUS "Git not found - the version will not include a git hash.")
set(PRJ_GIT_HASH "unknown")
endif()
+44
View File
@@ -0,0 +1,44 @@
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
# TODO Implement code coverage
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
# Generate compile_commands.json for clang based tools
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Export all symbols when building a shared library
if(BUILD_SHARED_LIBS)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
endif()
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." OFF)
if(${PROJECT_NAME}_ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT result OUTPUT output)
if(result)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
message(SEND_ERROR "IPO is not supported: ${output}.")
endif()
endif()
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
endif()
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
if(${PROJECT_NAME}_ENABLE_SANITIZER)
add_compile_options(-fsanitize=address,undefined)
add_link_options(-fsanitize=address,undefined)
endif()
+20
View File
@@ -0,0 +1,20 @@
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
find_program(CLANGTIDY clang-tidy)
if(CLANGTIDY)
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
message("Clang-Tidy finished setting up.")
else()
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
endif()
endif()
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
find_program(CPPCHECK cppcheck)
if(CPPCHECK)
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
--inline-suppr --inconclusive)
message("Cppcheck finished setting up.")
else()
message(SEND_ERROR "Cppcheck requested but executable not found.")
endif()
endif()
+17
View File
@@ -0,0 +1,17 @@
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
find_package(Git)
if(Git_FOUND)
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive vcpkg
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
RESULT_VARIABLE GIT_SUBMOD_RESULT)
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
endif()
else()
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
endif()
endif()
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
endif()
Vendored Submodule
+1
Submodule deps/BeamMP-Protocol added at 8eda5714c0
-7
View File
@@ -1,7 +0,0 @@
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")
Vendored
-1
Submodule deps/asio deleted from d038fb3c2f
-1
Submodule deps/cpp-httplib deleted from 47044c05a8
-1
Submodule deps/doctest deleted from 7b98851331
Vendored
-1
Submodule deps/fmt deleted from ce246aaf74
Vendored
-1
Submodule deps/json deleted from ede6667858
Vendored
-1
Submodule deps/libzip deleted from 76df02f86b
-1
Submodule deps/rapidjson deleted from 00dbcf2c6e
Submodule deps/sentry-native deleted from 90966cc102
Vendored
-1
Submodule deps/sol2 deleted from c068aefbed
Vendored
-1
Submodule deps/toml11 deleted from 1400dd223f
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
using namespace boost::asio;
-108
View File
@@ -1,108 +0,0 @@
#pragma once
#include <chrono>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <unordered_set>
#include "Common.h"
#include "Compat.h"
#include "VehicleData.h"
class TServer;
#ifdef BEAMMP_WINDOWS
// for socklen_t
#include <WS2tcpip.h>
#endif // WINDOWS
struct TConnection final {
SOCKET Socket;
struct sockaddr SockAddr;
socklen_t SockAddrLen;
};
class TClient final {
public:
using TSetOfVehicleData = std::vector<TVehicleData>;
struct TVehicleDataLockPair {
TSetOfVehicleData* VehicleData;
std::unique_lock<std::mutex> Lock;
};
explicit TClient(TServer& Server);
TClient(const TClient&) = delete;
TClient& operator=(const TClient&) = delete;
void AddNewCar(int Ident, const std::string& Data);
void SetCarData(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);
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
void SetStatus(int Status) { mStatus = Status; }
// locks
void DeleteCar(int Ident);
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
[[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; }
void SetID(int ID) { mID = ID; }
[[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const;
void ClearCars();
[[nodiscard]] int GetStatus() const { return mStatus; }
[[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::string& Packet);
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
[[nodiscard]] TServer& Server() const;
void UpdatePingTime();
int SecondsSinceLastPing();
private:
void InsertVehicle(int ID, const std::string& Data);
TServer& mServer;
bool mIsConnected = false;
bool mIsSynced = false;
bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex;
std::queue<std::string> mPacketsSync;
std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex;
TSetOfVehicleData mVehicleData;
std::string mName = "Unknown Client";
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
int mUnicycleID = -1;
std::string mRole;
std::string mDID;
int mStatus = 0;
int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
};
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
+13 -67
View File
@@ -1,8 +1,5 @@
#pragma once #pragma once
#include "TSentry.h"
extern TSentry Sentry;
#include <array> #include <array>
#include <atomic> #include <atomic>
#include <cstring> #include <cstring>
@@ -14,14 +11,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 +29,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
@@ -44,9 +43,11 @@ public:
struct TSettings { struct TSettings {
std::string ServerName { "BeamMP Server" }; std::string ServerName { "BeamMP Server" };
std::string ServerDesc { "BeamMP Default Description" }; std::string ServerDesc { "BeamMP Default Description" };
std::string ServerTags { "Freeroam" };
std::string Resource { "Resources" }; std::string Resource { "Resources" };
std::string MapName { "/levels/gridmap_v2/info.json" }; std::string MapName { "/levels/gridmap_v2/info.json" };
std::string Key {}; std::string Key {};
std::string Password{};
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" }; std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" }; std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
bool HTTPServerEnabled { false }; bool HTTPServerEnabled { false };
@@ -75,10 +76,10 @@ public:
static void RegisterShutdownHandler(const TShutdownHandler& Handler); static void RegisterShutdownHandler(const TShutdownHandler& Handler);
// Causes all threads to finish up and exit gracefull gracefully // Causes all threads to finish up and exit gracefull gracefully
static void GracefullyShutdown(); static void GracefullyShutdown();
static TConsole& Console() { return *mConsole; } static TConsole& Console() { return mConsole; }
static std::string ServerVersionString(); static std::string ServerVersionString();
static const Version& ServerVersion() { return mVersion; } static const Version& ServerVersion() { return mVersion; }
static std::string ClientVersionString() { return "2.0"; } static uint8_t ClientMajorVersion() { return 2; }
static std::string PPS() { return mPPS; } static std::string PPS() { return mPPS; }
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; } static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
@@ -101,9 +102,7 @@ public:
static void SleepSafeSeconds(size_t Seconds); static void SleepSafeSeconds(size_t Seconds);
static void InitializeConsole() { static void InitializeConsole() {
if (!mConsole) { mConsole.InitializeCommandline();
mConsole = std::make_unique<TConsole>();
}
} }
enum class Status { enum class Status {
@@ -129,15 +128,17 @@ private:
static inline SystemStatusMap mSystemStatusMap {}; static inline SystemStatusMap mSystemStatusMap {};
static inline std::mutex mSystemStatusMapMutex {}; static inline std::mutex mSystemStatusMapMutex {};
static inline std::string mPPS; static inline std::string mPPS;
static inline std::unique_ptr<TConsole> mConsole; static inline TConsole mConsole;
static inline std::shared_mutex mShutdownMtx {}; static inline std::shared_mutex mShutdownMtx {};
static inline bool mShutdown { false }; static inline bool mShutdown { false };
static inline std::mutex mShutdownHandlersMutex {}; static inline std::mutex mShutdownHandlersMutex {};
static inline std::deque<TShutdownHandler> mShutdownHandlers {}; static inline std::deque<TShutdownHandler> mShutdownHandlers {};
static inline Version mVersion { 3, 1, 0 }; static inline Version mVersion { 3, 2, 2 };
}; };
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
std::string ThreadName(bool DebugModeOverride = false); std::string ThreadName(bool DebugModeOverride = false);
void RegisterThread(const std::string& str); void RegisterThread(const std::string& str);
#define RegisterThreadAuto() RegisterThread(__func__) #define RegisterThreadAuto() RegisterThread(__func__)
@@ -190,7 +191,6 @@ void RegisterThread(const std::string& str);
#define beammp_error(x) \ #define beammp_error(x) \
do { \ do { \
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \ Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
Sentry.AddErrorBreadcrumb((x), _file_basename, _line); \
} while (false) } while (false)
#define beammp_lua_error(x) \ #define beammp_lua_error(x) \
do { \ do { \
@@ -265,59 +265,5 @@ void RegisterThread(const std::string& str);
void LogChatMessage(const std::string& name, int id, const std::string& msg); void LogChatMessage(const std::string& name, int id, const std::string& msg);
#define Biggest 30000
template <typename T>
inline T Comp(const T& Data) {
std::array<char, Biggest> C {};
// obsolete
C.fill(0);
z_stream defstream;
defstream.zalloc = 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);
deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
size_t TotalOut = defstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}
template <typename T>
inline T DeComp(const T& Compressed) {
std::array<char, Biggest> C {};
// not needed
C.fill(0);
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = Biggest;
infstream.next_in = (Bytef*)(&Compressed[0]);
infstream.avail_out = Biggest;
infstream.next_out = (Bytef*)(C.data());
inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH);
inflateEnd(&infstream);
size_t TotalOut = infstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}
std::string GetPlatformAgnosticErrorString(); 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);
-31
View File
@@ -5,54 +5,23 @@
// ======================= UNIX ======================== // ======================= UNIX ========================
#ifdef BEAMMP_LINUX #ifdef BEAMMP_LINUX
#include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/socket.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
using SOCKET = int;
using DWORD = unsigned long;
using PDWORD = unsigned long*;
using LPDWORD = unsigned long*;
char _getch(); char _getch();
inline void CloseSocketProper(int TheSocket) {
shutdown(TheSocket, SHUT_RDWR);
close(TheSocket);
}
#endif // unix #endif // unix
// ======================= APPLE ======================== // ======================= APPLE ========================
#ifdef BEAMMP_APPLE #ifdef BEAMMP_APPLE
#include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <sys/socket.h>
#include <termios.h> #include <termios.h>
#include <unistd.h> #include <unistd.h>
using SOCKET = int;
using DWORD = unsigned long;
using PDWORD = unsigned long*;
using LPDWORD = unsigned long*;
char _getch(); char _getch();
inline void CloseSocketProper(int TheSocket) {
shutdown(TheSocket, SHUT_RDWR);
close(TheSocket);
}
#endif // unix #endif // unix
// ======================= WINDOWS ======================= // ======================= WINDOWS =======================
#ifdef BEAMMP_WINDOWS #ifdef BEAMMP_WINDOWS
#include <conio.h> #include <conio.h>
#include <winsock2.h>
inline void CloseSocketProper(SOCKET TheSocket) {
shutdown(TheSocket, 2); // 2 == SD_BOTH
closesocket(TheSocket);
}
#endif // WIN32 #endif // WIN32
#ifdef INVALID_SOCKET
static inline constexpr int BEAMMP_INVALID_SOCKET = INVALID_SOCKET;
#else
static inline constexpr int BEAMMP_INVALID_SOCKET = -1;
#endif
+9 -10
View File
@@ -58,16 +58,15 @@ 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__); \ } \
} \
} 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); \
} while (false) } while (false)
#endif // DEBUG #endif // DEBUG
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <optional>
#include <string>
namespace Env {
enum class Key {
// provider settings
PROVIDER_UPDATE_MESSAGE,
};
std::optional<std::string> Get(Key key);
std::string_view ToString(Key key);
}
+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 -6
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <boost/thread/scoped_thread.hpp>
#include <thread> #include <thread>
// pure virtual class to be inherited from by classes which intend to be threaded // pure virtual class to be inherited from by classes which intend to be threaded
@@ -8,17 +9,15 @@ public:
IThreaded() IThreaded()
// invokes operator() on this object // invokes operator() on this object
: mThread() { } : mThread() { }
~IThreaded() noexcept { virtual ~IThreaded() noexcept {
if (mThread.joinable()) { mThread.interrupt();
mThread.join();
}
} }
virtual void Start() final { virtual void Start() final {
mThread = std::thread([this] { (*this)(); }); mThread = boost::scoped_thread<>([this] { (*this)(); });
} }
virtual void operator()() = 0; virtual void operator()() = 0;
protected: protected:
std::thread mThread; boost::scoped_thread<> mThread {};
}; };
+6 -6
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->Network()->authenticated_client_count(); }
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);
+250
View File
@@ -0,0 +1,250 @@
#pragma once
#include "Common.h"
#include "Packet.h"
#include "State.h"
#include "Sync.h"
#include "Transport.h"
#include "Util.h"
#include <boost/asio.hpp>
#include <boost/asio/execution_context.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <boost/thread/synchronized_value.hpp>
#include <cstdint>
#include <filesystem>
#include <glm/detail/qualifier.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <memory>
#include <mutex>
#include <nlohmann/json.hpp>
#include <optional>
#include <unordered_map>
#include <vector>
using ClientID = uint32_t;
using VehicleID = uint16_t;
using namespace boost::asio;
struct Client : std::enable_shared_from_this<Client> {
using StrandPtr = std::shared_ptr<boost::asio::strand<ip::tcp::socket::executor_type>>;
using Ptr = std::shared_ptr<Client>;
ClientID id;
Sync<bmp::State> state { bmp::State::None };
Sync<std::string> name;
Sync<std::string> role;
Sync<bool> is_guest;
Sync<std::unordered_map<std::string /* identifier */, std::string /* value */>> identifiers;
/// Writes the packet to the TCP stream. Blocks all other writes.
void tcp_write(bmp::Packet& packet);
/// Writes the specified to the TCP stream without a header or any metadata - use in
/// conjunction with something else. Blocks other writes.
void tcp_write_file_raw(const std::filesystem::path& path);
/// Ensures no client is ever created as a non-shared-ptr, so that enable_shared_from_this works.
static Client::Ptr make_ptr(ClientID new_id, class Network& network, ip::tcp::socket&& tcp_socket);
~Client();
ip::tcp::socket& tcp_socket() { return m_tcp_socket; }
void start_tcp();
/// Used to associate the udp socket with this client.
/// This isn't very secure and still allows spoofing of the UDP connection (technically),
/// but better than simply using the ID like the old protocol.
const uint64_t udp_magic;
const ip::udp::endpoint& udp_endpoint() const { return m_udp_endpoint; }
void set_udp_endpoint(const ip::udp::endpoint& ep) { m_udp_endpoint = ep; }
private:
/// Ctor must be private to ensure all clients are constructed as shared_ptr to enable_shared_from_this.
Client(ClientID id, class Network& network, ip::tcp::socket&& tcp_socket);
/// Call this when the client seems to have timed out. Will send a ping and set a flag.
/// Returns true if try-again, false if the connection was closed.
[[nodiscard]] bool handle_timeout();
bool m_timed_out { false };
/// Timeout used for typical tcp reads.
boost::posix_time::milliseconds m_read_timeout { 5000 };
/// Timeout used for typical tcp writes. Specified in milliseconds per byte.
/// For example, 10 mbit/s works out to 1250 B/ms, so a value of 1250 here would
/// cause clients with >10 mbit/s download speed to usually not time out.
/// This is done because a write is considered completed when all data is written,
/// and worst-case this could mean that we're limited by their download speed.
/// We're setting it to 50, which will drop clients who are below a download speed + ping
/// combination of 0.4 mbit/s.
double m_write_byte_timeout { 0.01 };
/// Timeout used for mod download tcp writes.
/// This is typically orders of magnitude larger
/// to allow for slow downloads.
boost::posix_time::milliseconds m_download_write_timeout { 60000 };
std::mutex m_tcp_read_mtx;
std::mutex m_tcp_write_mtx;
std::mutex m_udp_read_mtx;
ip::tcp::socket m_tcp_socket;
boost::scoped_thread<> m_tcp_thread;
std::vector<uint8_t> m_header { bmp::Header::SERIALIZED_SIZE };
bmp::Packet m_packet {};
ip::udp::endpoint m_udp_endpoint;
class Network& m_network;
StrandPtr m_tcp_strand;
};
struct Vehicle {
using Ptr = std::shared_ptr<Vehicle>;
Sync<ClientID> owner;
Sync<std::vector<uint8_t>> data;
Vehicle(std::span<uint8_t> raw_data)
: data(std::vector<uint8_t>(raw_data.begin(), raw_data.end())) {
reset_status(data.get());
}
/// Resets all status fields to zero and reads any statuses present in the data into the fields.
void reset_status(std::span<const uint8_t> status_data);
struct Status {
glm::vec3 rvel {};
glm::vec4 rot {};
glm::vec3 vel {};
glm::vec3 pos {};
float time {};
};
Status get_status();
void update_status(std::span<const uint8_t> raw_packet);
const std::vector<uint8_t>& get_raw_status() const { return m_status_data; }
private:
std::recursive_mutex m_mtx;
/// Holds pos, rvel, vel, etc. raw, updated every time
/// such a packet arrives.
std::vector<uint8_t> m_status_data;
/// Parses the status_data on request sets needs_refresh = false.
void refresh_cache(std::unique_lock<std::recursive_mutex>& lock);
bool m_needs_refresh = false;
glm::vec3 m_rvel {};
glm::vec4 m_rot {};
glm::vec3 m_vel {};
glm::vec3 m_pos {};
float m_time {};
};
class Network {
public:
Network();
~Network();
friend Client;
void disconnect(ClientID id, const std::string& msg);
void send_to(ClientID id, bmp::Packet& packet);
/// Returns a map of <id, client> containing only clients which are
/// fully connected, i.e. who have mods downloaded and everything spawned in.
/// If you're unsure which to use, use this one.
std::unordered_map<ClientID, Client::Ptr> playing_clients() const;
/// Returns a map of <id, client> containing only clients who are authenticated.
std::unordered_map<ClientID, Client::Ptr> authenticated_clients() const;
/// Returns all clients, including non-authenticated clients. Use only for debugging,
/// information, stats, status.
std::unordered_map<ClientID, Client::Ptr> all_clients() const;
std::optional<Client::Ptr> get_client(ClientID id, bmp::State min_state) const;
std::unordered_map<VehicleID, Vehicle::Ptr> get_vehicles_owned_by(ClientID id);
std::optional<Vehicle::Ptr> get_vehicle(VehicleID id);
/// Builds the SessionSetup.PlayersInfo json which contains all player info and all vehicles.
nlohmann::json build_players_info();
size_t authenticated_client_count() const;
size_t clients_in_state_count(bmp::State state) const;
size_t guest_count() const;
size_t vehicle_count() const;
/// Creates a Playing state packet from uncompressed data.
bmp::Packet make_playing_packet(bmp::Purpose purpose, ClientID from_id, VehicleID veh_id, const std::vector<uint8_t>& data);
/// Sends a <System> or <Server> chat message to all or only one client(s).
void send_system_chat_message(const std::string& msg, ClientID to = 0xffffffff);
/// To be called by accept() async handler once an accept() is completed.
void accept();
/// Gets the async i/o context of the network - can be used to "schedule" tasks on it.
boost::asio::thread_pool& context() {
return m_threadpool;
}
private:
void handle_packet(ClientID id, const bmp::Packet& packet);
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
bmp::Packet udp_read(ip::udp::endpoint& out_ep);
/// Sends a packet to the specified UDP endpoint via the UDP socket.
void udp_write(bmp::Packet& packet, const ip::udp::endpoint& ep);
void udp_read_main();
void tcp_listen_main();
/// Handles all packets which are allowed during the Identification state.
void handle_identification(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
/// Handles all packets which are allowed during the Authentication state.
void handle_authentication(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
/// Handles all packets which are allowed during the ModDownload state.
void handle_mod_download(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
/// Handles all packets which are allowed during the SessionSetup state.
void handle_session_setup(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
/// Handles all packets which are allowed during the Playing state.
void handle_playing(ClientID id, const bmp::Packet& packet, std::shared_ptr<Client>& client);
/// On failure, throws an exception with the error for the client.
static void authenticate_user(const std::string& public_key, std::shared_ptr<Client>& client);
/// Called by accept() once completed (completion handler).
void handle_accept(const boost::system::error_code& ec);
Sync<std::unordered_map<ClientID, Client::Ptr>> m_clients {};
Sync<std::unordered_map<VehicleID, Vehicle::Ptr>> m_vehicles {};
Sync<std::unordered_map<uint64_t, ClientID>> m_client_magics {};
Sync<std::unordered_map<ip::udp::endpoint, ClientID>> m_udp_endpoints {};
ClientID new_client_id();
VehicleID new_vehicle_id();
thread_pool m_threadpool { std::thread::hardware_concurrency() };
Sync<bool> m_shutdown { false };
ip::udp::socket m_udp_socket { m_threadpool };
ip::tcp::socket m_tcp_listener { m_threadpool };
ip::tcp::acceptor m_tcp_acceptor { m_threadpool };
/// This socket gets accepted into, and is then moved.
ip::tcp::socket m_temp_socket { m_threadpool };
boost::scoped_thread<> m_tcp_listen_thread;
boost::scoped_thread<> m_udp_read_thread;
};
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <boost/thread/synchronized_value.hpp>
#include <mutex>
/// This header provides convenience aliases for synchronization primitives.
template<typename T>
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
+5 -4
View File
@@ -6,7 +6,7 @@
#include <filesystem> #include <filesystem>
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT #define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
#include <toml11/toml.hpp> // header-only version of TOML++ #include <toml.hpp> // header-only version of TOML++
namespace fs = std::filesystem; namespace fs = std::filesystem;
@@ -22,11 +22,12 @@ private:
void CreateConfigFile(); void CreateConfigFile();
void ParseFromFile(std::string_view name); void ParseFromFile(std::string_view name);
void PrintDebug(); void PrintDebug();
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue); void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue); void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue); void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
void ParseOldFormat(); void ParseOldFormat();
std::string TagsAsPrettyArray() const;
bool IsDefault(); bool IsDefault();
bool mFailed { false }; bool mFailed { false };
std::string mConfigFileName; std::string mConfigFileName;
+32 -2
View File
@@ -1,14 +1,40 @@
#pragma once #pragma once
#include "Cryptography.h" #include "Cryptography.h"
#include "TScopedTimer.h"
#include "commandline.h" #include "commandline.h"
#include <atomic> #include <atomic>
#include <fstream> #include <fstream>
#include <functional> #include <functional>
#include <mutex>
#include <string> #include <string>
#include <tuple> #include <tuple>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <boost/container/deque.hpp>
#include <boost/thread/scoped_thread.hpp>
#include <boost/thread/synchronized_value.hpp>
#include <memory>
#include <optional>
#include <span>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/sink.h>
#include <string>
#include <string_view>
class TConsole;
class ConsoleSink : public spdlog::sinks::base_sink<spdlog::details::null_mutex> {
public:
ConsoleSink(TConsole& console);
private:
void sink_it_(const spdlog::details::log_msg& msg) override;
void flush_() override;
TConsole* m_console;
};
class TLuaEngine; class TLuaEngine;
@@ -16,12 +42,15 @@ class TConsole {
public: public:
TConsole(); TConsole();
// Initializes the commandline app to take over I/O
void InitializeCommandline();
void Write(const std::string& str); void Write(const std::string& str);
void WriteRaw(const std::string& str); void WriteRaw(const std::string& str);
void InitializeLuaConsole(TLuaEngine& Engine); void InitializeLuaConsole(TLuaEngine& Engine);
void BackupOldLog(); void BackupOldLog();
void StartLoggingToFile(); void StartLoggingToFile();
Commandline& Internal() { return mCommandline; } Commandline& Internal() { return *mCommandline; }
private: private:
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false); void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
@@ -55,7 +84,7 @@ private:
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called { "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
}; };
Commandline mCommandline; std::unique_ptr<Commandline> mCommandline { nullptr };
std::vector<std::string> mCachedLuaHistory; std::vector<std::string> mCachedLuaHistory;
std::vector<std::string> mCachedRegularHistory; std::vector<std::string> mCachedRegularHistory;
TLuaEngine* mLuaEngine { nullptr }; TLuaEngine* mLuaEngine { nullptr };
@@ -65,4 +94,5 @@ private:
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE"; const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
std::ofstream mLogFileStream; std::ofstream mLogFileStream;
std::mutex mLogFileStreamMtx; std::mutex mLogFileStreamMtx;
TScopedTimer mUptimeTimer{};
}; };
+3 -5
View File
@@ -2,12 +2,11 @@
#include "Common.h" #include "Common.h"
#include "IThreaded.h" #include "IThreaded.h"
#include "TResourceManager.h" #include "Network.h"
#include "TServer.h"
class THeartbeatThread : public IThreaded { class THeartbeatThread : public IThreaded {
public: public:
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server); THeartbeatThread(std::shared_ptr<Network> network);
//~THeartbeatThread(); //~THeartbeatThread();
void operator()() override; void operator()() override;
@@ -15,6 +14,5 @@ private:
std::string GenerateCall(); std::string GenerateCall();
std::string GetPlayers(); std::string GetPlayers();
TResourceManager& mResourceManager; std::shared_ptr<Network> m_network;
TServer& mServer;
}; };
+38 -19
View File
@@ -1,8 +1,10 @@
#pragma once #pragma once
#include "TNetwork.h" #include "Common.h"
#include "TServer.h" #include "IThreaded.h"
#include "Network.h"
#include <any> #include <any>
#include <boost/thread/scoped_thread.hpp>
#include <condition_variable> #include <condition_variable>
#include <filesystem> #include <filesystem>
#include <initializer_list> #include <initializer_list>
@@ -13,7 +15,7 @@
#include <queue> #include <queue>
#include <random> #include <random>
#include <set> #include <set>
#include <toml11/toml.hpp> #include <toml.hpp>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
@@ -25,11 +27,12 @@ namespace fs = std::filesystem;
/** /**
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args * std::variant means, that TLuaArgTypes may be one of the Types listed as template args
*/ */
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool>; using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
static constexpr size_t TLuaArgTypes_String = 0; static constexpr size_t TLuaArgTypes_String = 0;
static constexpr size_t TLuaArgTypes_Int = 1; static constexpr size_t TLuaArgTypes_Int = 1;
static constexpr size_t TLuaArgTypes_VariadicArgs = 2; static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
static constexpr size_t TLuaArgTypes_Bool = 3; static constexpr size_t TLuaArgTypes_Bool = 3;
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
class TLuaPlugin; class TLuaPlugin;
@@ -40,7 +43,14 @@ struct TLuaResult {
sol::object Result { sol::lua_nil }; sol::object Result { sol::lua_nil };
TLuaStateId StateId; TLuaStateId StateId;
std::string Function; std::string Function;
// TODO: Add condition_variable std::shared_ptr<std::mutex> ReadyMutex {
std::make_shared<std::mutex>()
};
std::shared_ptr<std::condition_variable> ReadyCondition {
std::make_shared<std::condition_variable>()
};
void MarkAsReady();
void WaitUntilReady(); void WaitUntilReady();
}; };
@@ -60,7 +70,7 @@ struct TLuaChunk {
std::string PluginPath; std::string PluginPath;
}; };
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded { class TLuaEngine : public std::enable_shared_from_this<TLuaEngine> {
public: public:
enum CallStrategy : int { enum CallStrategy : int {
BestEffort, BestEffort,
@@ -75,17 +85,15 @@ public:
}; };
TLuaEngine(); TLuaEngine();
~TLuaEngine() noexcept { virtual ~TLuaEngine() noexcept {
beammp_debug("Lua Engine terminated"); beammp_debug("Lua Engine terminated");
} }
void operator()() override; void Start();
TNetwork& Network() { return *mNetwork; } std::shared_ptr<::Network> Network() { return mNetwork; }
TServer& Server() { return *mServer; }
void SetNetwork(TNetwork* Network) { mNetwork = Network; } void SetNetwork(const std::shared_ptr<::Network>& network) { mNetwork = network; }
void SetServer(TServer* Server) { mServer = Server; }
size_t GetResultsToCheckSize() { size_t GetResultsToCheckSize() {
std::unique_lock Lock(mResultsToCheckMutex); std::unique_lock Lock(mResultsToCheckMutex);
@@ -96,6 +104,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 +187,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);
@@ -185,25 +201,28 @@ private:
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config); void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
size_t CalculateMemoryUsage(); size_t CalculateMemoryUsage();
class StateThreadData : IThreaded { class StateThreadData {
public: public:
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine); StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
StateThreadData(const StateThreadData&) = delete; StateThreadData(const StateThreadData&) = delete;
~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); } virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy); [[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
void RegisterEvent(const std::string& EventName, const std::string& FunctionName); void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
void AddPath(const fs::path& Path); // to be added to path and cpath void AddPath(const fs::path& Path); // to be added to path and cpath
void operator()() override; void Start();
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();
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue(); std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
sol::table Lua_JsonDecode(const std::string& str);
private: private:
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs); sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs); sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
@@ -211,8 +230,8 @@ 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_GetVehicleStatus(int VID);
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port); sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
sol::table Lua_JsonDecode(const std::string& str);
int Lua_GetPlayerIDByName(const std::string& Name); int Lua_GetPlayerIDByName(const std::string& Name);
sol::table Lua_FS_ListFiles(const std::string& Path); sol::table Lua_FS_ListFiles(const std::string& Path);
sol::table Lua_FS_ListDirectories(const std::string& Path); sol::table Lua_FS_ListDirectories(const std::string& Path);
@@ -220,7 +239,6 @@ private:
std::string mName; std::string mName;
TLuaStateId mStateId; TLuaStateId mStateId;
lua_State* mState; lua_State* mState;
std::thread mThread;
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue; std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
std::recursive_mutex mStateExecuteQueueMutex; std::recursive_mutex mStateExecuteQueueMutex;
std::vector<QueuedFunction> mStateFunctionQueue; std::vector<QueuedFunction> mStateFunctionQueue;
@@ -232,6 +250,7 @@ private:
std::recursive_mutex mPathsMutex; std::recursive_mutex mPathsMutex;
std::mt19937 mMersenneTwister; std::mt19937 mMersenneTwister;
std::uniform_real_distribution<double> mUniformRealDistribution01; std::uniform_real_distribution<double> mUniformRealDistribution01;
boost::scoped_thread<> mThread;
}; };
struct TimedEvent { struct TimedEvent {
@@ -244,8 +263,7 @@ private:
void Reset(); void Reset();
}; };
TNetwork* mNetwork; std::shared_ptr<::Network> mNetwork;
TServer* mServer;
const fs::path mResourceServerPath; const fs::path mResourceServerPath;
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins; std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates; std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
@@ -257,6 +275,7 @@ private:
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck; std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
std::mutex mResultsToCheckMutex; std::mutex mResultsToCheckMutex;
std::condition_variable mResultsToCheckCond; std::condition_variable mResultsToCheckCond;
boost::scoped_thread<> mThread;
}; };
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait); // std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
-51
View File
@@ -1,51 +0,0 @@
#pragma once
#include "Compat.h"
#include "TResourceManager.h"
#include "TServer.h"
struct TConnection;
class TNetwork {
public:
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
std::string TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(const TConnection& client);
void Authentication(const TConnection& ClientConnection);
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
void SyncResources(TClient& c);
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
void UpdatePlayer(TClient& Client);
private:
void UDPServerMain();
void TCPServerMain();
TServer& mServer;
TPPSMonitor& mPPSMonitor;
SOCKET mUDPSock {};
TResourceManager& mResourceManager;
std::thread mUDPThread;
std::thread mTCPThread;
std::string UDPRcvFromClient(sockaddr_in& client) const;
void HandleDownload(SOCKET TCPSock);
void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::weak_ptr<TClient>& c);
void Looper(const std::weak_ptr<TClient>& c);
int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
void Parse(TClient& c, const std::string& Packet);
void SendFile(TClient& c, const std::string& Name);
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
static uint8_t* SendSplit(TClient& c, SOCKET Socket, uint8_t* DataPtr, size_t Size);
};
-26
View File
@@ -1,26 +0,0 @@
#pragma once
#include "Common.h"
#include "TServer.h"
#include <optional>
class TNetwork;
class TPPSMonitor : public IThreaded {
public:
explicit TPPSMonitor(TServer& Server);
void operator()() override;
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
void IncrementInternalPPS() { ++mInternalPPS; }
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
private:
TNetwork& Network() { return mNetwork->get(); }
TServer& mServer;
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
int mInternalPPS { 0 };
};
-21
View File
@@ -1,21 +0,0 @@
#pragma once
#include "Common.h"
class TResourceManager {
public:
TResourceManager();
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
[[nodiscard]] std::string FileList() const { return mFileList; }
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
private:
size_t mMaxModSize = 0;
std::string mFileSizes;
std::string mFileList;
std::string mTrimmedList;
int mModsLoaded = 0;
};
-38
View File
@@ -1,38 +0,0 @@
#ifndef SENTRY_H
#define SENTRY_H
#include <mutex>
#include <string>
#include <unordered_map>
enum class SentryLevel {
Debug = -1,
Info = 0,
Warning = 1,
Error = 2,
Fatal = 3,
};
// singleton, dont make this twice
class TSentry final {
public:
TSentry();
~TSentry();
void PrintWelcome();
void SetupUser();
void Log(SentryLevel level, const std::string& logger, const std::string& text);
void LogError(const std::string& text, const std::string& file, const std::string& line);
void SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map);
void LogException(const std::exception& e, const std::string& file, const std::string& line);
void LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function);
void AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line);
// cleared when Logged
void SetTransaction(const std::string& id);
[[nodiscard]] std::unique_lock<std::mutex> CreateExclusiveContext();
private:
bool mValid { true };
std::mutex mMutex;
};
#endif // SENTRY_H
-41
View File
@@ -1,41 +0,0 @@
#pragma once
#include "IThreaded.h"
#include "RWMutex.h"
#include "TScopedTimer.h"
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_set>
class TClient;
class TNetwork;
class TPPSMonitor;
class TServer final {
public:
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
TServer(const std::vector<std::string_view>& Arguments);
void InsertClient(const std::shared_ptr<TClient>& Ptr);
std::weak_ptr<TClient> InsertNewClient();
void RemoveClient(const std::weak_ptr<TClient>&);
// in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; }
const TScopedTimer UptimeTimer;
private:
TClientSet mClients;
mutable RWMutex mClientsMutex;
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt);
};
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 liblua5.3-dev curl zip unzip tar cmake make git g++ ninja-build
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
git config --global --add safe.directory $(pwd)
git config --global --add safe.directory $(pwd)/vcpkg
git config --global --add safe.directory $(pwd)/deps/commandline
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/bootstrap-vcpkg.sh
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Server_ENABLE_LTO=ON
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server
objcopy --only-keep-debug bin/BeamMP-Server bin/BeamMP-Server.debug
objcopy --add-gnu-debuglink bin/BeamMP-Server bin/BeamMP-Server.debug
strip -s bin/BeamMP-Server
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set -ex
apt-get update -y
apt-get install -y liblua5.3-0 curl
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
set -ex
./vcpkg/vcpkg add port lua
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Server_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server-tests
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
cmake --build bin --parallel -t BeamMP-Server --config Release
-118
View File
@@ -1,118 +0,0 @@
#include "Client.h"
#include "CustomAssert.h"
#include "TServer.h"
#include <memory>
#include <optional>
void TClient::DeleteCar(int Ident) {
std::unique_lock lock(mVehicleDataMutex);
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
return Ident == elem.ID();
});
if (iter != mVehicleData.end()) {
mVehicleData.erase(iter);
} else {
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
}
}
void TClient::ClearCars() {
std::unique_lock lock(mVehicleDataMutex);
mVehicleData.clear();
}
int TClient::GetOpenCarID() const {
int OpenID = 0;
bool found;
std::unique_lock lock(mVehicleDataMutex);
do {
found = true;
for (auto& v : mVehicleData) {
if (v.ID() == OpenID) {
OpenID++;
found = false;
}
}
} while (!found);
return OpenID;
}
void TClient::AddNewCar(int Ident, const std::string& Data) {
std::unique_lock lock(mVehicleDataMutex);
mVehicleData.emplace_back(Ident, Data);
}
TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
}
std::string TClient::GetCarData(int Ident) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
return v.Data();
}
}
} // unlock
DeleteCar(Ident);
return "";
}
void TClient::SetCarData(int Ident, const std::string& Data) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
v.SetData(Data);
return;
}
}
} // unlock
DeleteCar(Ident);
}
int TClient::GetCarCount() const {
return int(mVehicleData.size());
}
TServer& TClient::Server() const {
return mServer;
}
void TClient::EnqueuePacket(const std::string& Packet) {
std::unique_lock Lock(mMissedPacketsMutex);
mPacketsSync.push(Packet);
}
TClient::TClient(TServer& Server)
: mServer(Server)
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
}
void TClient::UpdatePingTime() {
mLastPingTime = std::chrono::high_resolution_clock::now();
}
int TClient::SecondsSinceLastPing() {
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - mLastPingTime)
.count();
return int(seconds);
}
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
ReadLock Lock(Server.GetClientMutex());
if (!CPtr.expired()) {
auto C = CPtr.lock();
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
}
return true;
});
return MaybeClient;
}
+24 -9
View File
@@ -1,20 +1,20 @@
#include "Common.h" #include "Common.h"
#include "Env.h"
#include "TConsole.h" #include "TConsole.h"
#include <array> #include <array>
#include <charconv> #include <charconv>
#include <fmt/core.h>
#include <iostream> #include <iostream>
#include <map> #include <map>
#include <regex> #include <regex>
#include <sstream> #include <sstream>
#include <thread> #include <thread>
#include "Compat.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Http.h" #include "Http.h"
// global, yes, this is ugly, no, it cant be done another way
TSentry Sentry {};
Application::TSettings Application::Settings = {}; Application::TSettings Application::Settings = {};
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) { void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
@@ -170,6 +170,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,14 +197,17 @@ 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();
auto RemoteVersion = Version(VersionStrToInts(Response)); auto RemoteVersion = Version(VersionStrToInts(Response));
if (IsOutdated(MyVersion, RemoteVersion)) { if (IsOutdated(MyVersion, RemoteVersion)) {
std::string RealVersionString = RemoteVersion.AsString(); std::string RealVersionString = std::string("v") + RemoteVersion.AsString();
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET)); const std::string DefaultUpdateMsg = "NEW VERSION IS OUT! Please update to the new version ({}) of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server";
auto UpdateMsg = Env::Get(Env::Key::PROVIDER_UPDATE_MESSAGE).value_or(DefaultUpdateMsg);
UpdateMsg = fmt::vformat(std::string_view(UpdateMsg), fmt::make_format_args(RealVersionString));
beammp_warnf("{}{}{}", ANSI_YELLOW_BOLD, UpdateMsg, ANSI_RESET);
} else { } else {
if (FirstTime) { if (FirstTime) {
beammp_info("Server up-to-date!"); beammp_info("Server up-to-date!");
@@ -214,9 +219,6 @@ void Application::CheckForUpdates() {
if (FirstTime) { if (FirstTime) {
beammp_debug("Failed to fetch version from: " + url); beammp_debug("Failed to fetch version from: " + url);
beammp_trace("got " + Response); beammp_trace("got " + Response);
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("get-response", { { "response", Response } });
Sentry.LogError("failed to get server version", _file_basename, _line);
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad); Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
} }
} }
@@ -347,5 +349,18 @@ 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
} }
// TODO: add unit tests to SplitString
void SplitString(const std::string& str, const char delim, std::vector<std::string>& out) {
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
+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;
} }
+20
View File
@@ -0,0 +1,20 @@
#include "Env.h"
#include <optional>
std::optional<std::string> Env::Get(Env::Key key) {
auto StrKey = ToString(key);
auto Value = std::getenv(StrKey.data());
if (!Value || std::string_view(Value).empty()) {
return std::nullopt;
}
return Value;
}
std::string_view Env::ToString(Env::Key key) {
switch (key) {
case Key::PROVIDER_UPDATE_MESSAGE:
return "BEAMMP_PROVIDER_UPDATE_MESSAGE";
break;
}
return "";
}
+5 -5
View File
@@ -1,10 +1,8 @@
#include "Http.h" #include "Http.h"
#include "Client.h"
#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>
@@ -16,7 +14,7 @@
using json = nlohmann::json; using json = nlohmann::json;
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) { std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
httplib::SSLClient client(host, port); static thread_local httplib::SSLClient client(host, port);
client.enable_server_certificate_verification(false); client.enable_server_certificate_verification(false);
client.set_address_family(AF_INET); client.set_address_family(AF_INET);
auto res = client.Get(target.c_str()); auto res = client.Get(target.c_str());
@@ -31,7 +29,7 @@ std::string Http::GET(const std::string& host, int port, const std::string& targ
} }
std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) { std::string Http::POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status, const httplib::Headers& headers) {
httplib::SSLClient client(host, port); static thread_local httplib::SSLClient client(host, port);
client.set_read_timeout(std::chrono::seconds(10)); client.set_read_timeout(std::chrono::seconds(10));
beammp_assert(client.is_valid()); beammp_assert(client.is_valid());
client.enable_server_certificate_verification(false); client.enable_server_certificate_verification(false);
@@ -177,10 +175,12 @@ 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(
json { nlohmann::json {
{ "ok", SystemsBad == 0 }, { "ok", SystemsBad == 0 },
} }
.dump(), .dump(),
+92 -46
View File
@@ -1,6 +1,6 @@
#include "LuaAPI.h" #include "LuaAPI.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 +74,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 +112,107 @@ 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; throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
if (PlayerID == -1) /*
LuaAPI::MP::Engine->Network().SendToAll(nullptr, Packet, true, true); std::string Packet = "E:" + EventName + ":" + Data;
else { if (PlayerID == -1) {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID); LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
if (!MaybeClient || MaybeClient.value().expired()) { return { true, "" };
beammp_lua_error("TriggerClientEvent invalid Player ID"); } else {
return false; auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
} if (!MaybeClient) {
auto c = MaybeClient.value().lock(); beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
if (!LuaAPI::MP::Engine->Network().Respond(*c, Packet, true)) { return { false, "Invalid Player ID" };
beammp_lua_error("Respond failed, dropping client " + std::to_string(PlayerID)); }
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets"); auto c = MaybeClient.value();
return false; if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
} beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
} LuaAPI::MP::Engine->Network().Disconnect(*c);
return true; return { false, "Respond failed, dropping client" };
}
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) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient) {
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();
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) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
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, StringToVector(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) {
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
if (!c->IsSynced()) if (!c->IsSynced) {
return; Result.first = false;
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message); Result.second = "Player still syncing data";
Engine->Network().Respond(*c, Packet, true); return Result;
}
LogChatMessage("<Server> (to \"" + c->Name.get() + "\")", -1, Message);
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
beammp_infof("Disconnecting client {} for failure to receive a chat message (TCP disconnect)", c->Name.get());
Engine->Network().Disconnect(c);
}
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) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
std::pair<bool, std::string> Result;
auto MaybeClient = GetClient(Engine->Server(), PID); auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient || MaybeClient.value().expired()) { if (!MaybeClient) {
beammp_lua_error("RemoveVehicle invalid Player ID"); beammp_lua_error("RemoveVehicle invalid Player ID");
return; Result.first = false;
Result.second = "Invalid Player ID";
return Result;
} }
auto c = MaybeClient.value().lock(); auto c = MaybeClient.value();
if (!c->GetCarData(VID).empty()) { if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID); std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, Destroy, true, true); Engine->Network().SendToAll(nullptr, StringToVector(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) {
@@ -247,21 +284,26 @@ void LuaAPI::MP::Sleep(size_t Ms) {
} }
bool LuaAPI::MP::IsPlayerConnected(int ID) { bool LuaAPI::MP::IsPlayerConnected(int ID) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
return MaybeClient.value().lock()->IsConnected(); return MaybeClient.value()->IsConnected.get();
} else { } else {
return false; return false;
} }*/
} }
bool LuaAPI::MP::IsPlayerGuest(int ID) { bool LuaAPI::MP::IsPlayerGuest(int ID) {
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
auto MaybeClient = GetClient(Engine->Server(), ID); auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
return MaybeClient.value().lock()->IsGuest(); return MaybeClient.value()->IsGuest.get();
} else { } else {
return false; return false;
} }
*/
} }
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) { void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
@@ -500,7 +542,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 +561,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 +605,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 +691,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));
} }
+1251
View File
File diff suppressed because it is too large Load Diff
+77 -52
View File
@@ -1,6 +1,7 @@
#include "Common.h" #include "Common.h"
#include "TConfig.h" #include "TConfig.h"
#include <cstdlib>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <istream> #include <istream>
@@ -8,30 +9,36 @@
// General // General
static constexpr std::string_view StrDebug = "Debug"; static constexpr std::string_view StrDebug = "Debug";
static constexpr std::string_view EnvStrDebug = "BEAMMP_DEBUG";
static constexpr std::string_view StrPrivate = "Private"; static constexpr std::string_view StrPrivate = "Private";
static constexpr std::string_view EnvStrPrivate = "BEAMMP_PRIVATE";
static constexpr std::string_view StrPort = "Port"; static constexpr std::string_view StrPort = "Port";
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
static constexpr std::string_view StrMaxCars = "MaxCars"; static constexpr std::string_view StrMaxCars = "MaxCars";
static constexpr std::string_view EnvStrMaxCars = "BEAMMP_MAX_CARS";
static constexpr std::string_view StrMaxPlayers = "MaxPlayers"; static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
static constexpr std::string_view EnvStrMaxPlayers = "BEAMMP_MAX_PLAYERS";
static constexpr std::string_view StrMap = "Map"; static constexpr std::string_view StrMap = "Map";
static constexpr std::string_view EnvStrMap = "BEAMMP_MAP";
static constexpr std::string_view StrName = "Name"; static constexpr std::string_view StrName = "Name";
static constexpr std::string_view EnvStrName = "BEAMMP_NAME";
static constexpr std::string_view StrDescription = "Description"; static constexpr std::string_view StrDescription = "Description";
static constexpr std::string_view EnvStrDescription = "BEAMMP_DESCRIPTION";
static constexpr std::string_view StrTags = "Tags";
static constexpr std::string_view EnvStrTags = "BEAMMP_TAGS";
static constexpr std::string_view StrResourceFolder = "ResourceFolder"; static constexpr std::string_view StrResourceFolder = "ResourceFolder";
static constexpr std::string_view EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
static constexpr std::string_view StrAuthKey = "AuthKey"; static constexpr std::string_view StrAuthKey = "AuthKey";
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
static constexpr std::string_view StrLogChat = "LogChat"; static constexpr std::string_view StrLogChat = "LogChat";
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
static constexpr std::string_view StrPassword = "Password";
// Misc // Misc
static constexpr std::string_view StrSendErrors = "SendErrors"; static constexpr std::string_view StrSendErrors = "SendErrors";
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage"; static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates"; static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
// HTTP
static constexpr std::string_view StrHTTPServerEnabled = "HTTPServerEnabled";
static constexpr std::string_view StrHTTPServerUseSSL = "UseSSL";
static constexpr std::string_view StrSSLKeyPath = "SSLKeyPath";
static constexpr std::string_view StrSSLCertPath = "SSLCertPath";
static constexpr std::string_view StrHTTPServerPort = "HTTPServerPort";
static constexpr std::string_view StrHTTPServerIP = "HTTPServerIP";
TEST_CASE("TConfig::TConfig") { TEST_CASE("TConfig::TConfig") {
const std::string CfgFile = "beammp_server_testconfig.toml"; const std::string CfgFile = "beammp_server_testconfig.toml";
fs::remove(CfgFile); fs::remove(CfgFile);
@@ -44,7 +51,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);
@@ -52,7 +62,6 @@ TEST_CASE("TConfig::TConfig") {
const auto table = toml::parse(CfgFile); const auto table = toml::parse(CfgFile);
CHECK(table.at("General").is_table()); CHECK(table.at("General").is_table());
CHECK(table.at("Misc").is_table()); CHECK(table.at("Misc").is_table());
CHECK(table.at("HTTP").is_table());
fs::remove(CfgFile); fs::remove(CfgFile);
} }
@@ -98,32 +107,26 @@ void TConfig::FlushToFile() {
data["General"][StrPrivate.data()] = Application::Settings.Private; data["General"][StrPrivate.data()] = Application::Settings.Private;
data["General"][StrPort.data()] = Application::Settings.Port; data["General"][StrPort.data()] = Application::Settings.Port;
data["General"][StrName.data()] = Application::Settings.ServerName; data["General"][StrName.data()] = Application::Settings.ServerName;
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
data["General"][StrTags.data()] = Application::Settings.ServerTags;
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars; data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers; data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
data["General"][StrMap.data()] = Application::Settings.MapName; data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::Settings.ServerDesc; data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::Settings.Resource; data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
// data["General"][StrPassword.data()] = Application::Settings.Password;
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
// Misc // Misc
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages; data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless."); SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors; data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here"); SetComment(data["Misc"][StrSendErrors.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`");
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled; data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`"); SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
// HTTP
data["HTTP"][StrSSLKeyPath.data()] = Application::Settings.SSLKeyPath;
data["HTTP"][StrSSLCertPath.data()] = Application::Settings.SSLCertPath;
data["HTTP"][StrHTTPServerPort.data()] = Application::Settings.HTTPServerPort;
SetComment(data["HTTP"][StrHTTPServerIP.data()].comments(), " Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.");
data["HTTP"][StrHTTPServerIP.data()] = Application::Settings.HTTPServerIP;
data["HTTP"][StrHTTPServerUseSSL.data()] = Application::Settings.HTTPServerUseSSL;
SetComment(data["HTTP"][StrHTTPServerUseSSL.data()].comments(), " Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files");
data["HTTP"][StrHTTPServerEnabled.data()] = Application::Settings.HTTPServerEnabled;
SetComment(data["HTTP"][StrHTTPServerEnabled.data()].comments(), " Enables the internal HTTP server");
std::stringstream Ss; std::stringstream Ss;
Ss << "# This is the BeamMP-Server config file.\n" Ss << "# This is the BeamMP-Server config file.\n"
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n" "# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under \"Keys\"\n" "# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
<< data; << data;
auto File = std::fopen(mConfigFileName.c_str(), "w+"); auto File = std::fopen(mConfigFileName.c_str(), "w+");
if (!File) { if (!File) {
@@ -153,21 +156,40 @@ void TConfig::CreateConfigFile() {
FlushToFile(); FlushToFile();
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, std::string& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = std::string(envp);
return;
}
}
if (Table[Category.c_str()][Key.data()].is_string()) { if (Table[Category.c_str()][Key.data()].is_string()) {
OutValue = Table[Category.c_str()][Key.data()].as_string(); OutValue = Table[Category.c_str()][Key.data()].as_string();
} }
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, bool& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
auto Str = std::string(envp);
OutValue = Str == "1" || Str == "true";
return;
}
}
if (Table[Category.c_str()][Key.data()].is_boolean()) { if (Table[Category.c_str()][Key.data()].is_boolean()) {
OutValue = Table[Category.c_str()][Key.data()].as_boolean(); OutValue = Table[Category.c_str()][Key.data()].as_boolean();
} }
} }
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, int& OutValue) { void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = int(std::strtol(envp, nullptr, 10));
return;
}
}
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());
} }
} }
@@ -175,28 +197,23 @@ void TConfig::ParseFromFile(std::string_view name) {
try { try {
toml::value data = toml::parse<toml::preserve_comments>(name.data()); toml::value data = toml::parse<toml::preserve_comments>(name.data());
// GENERAL // GENERAL
TryReadValue(data, "General", StrDebug, Application::Settings.DebugModeEnabled); TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
TryReadValue(data, "General", StrPrivate, Application::Settings.Private); TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
TryReadValue(data, "General", StrPort, Application::Settings.Port); TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
TryReadValue(data, "General", StrMaxCars, Application::Settings.MaxCars); TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
TryReadValue(data, "General", StrMaxPlayers, Application::Settings.MaxPlayers); TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
TryReadValue(data, "General", StrMap, Application::Settings.MapName); TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
TryReadValue(data, "General", StrName, Application::Settings.ServerName); TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
TryReadValue(data, "General", StrDescription, Application::Settings.ServerDesc); TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
TryReadValue(data, "General", StrResourceFolder, Application::Settings.Resource); TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
TryReadValue(data, "General", StrAuthKey, Application::Settings.Key); TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
TryReadValue(data, "General", StrLogChat, Application::Settings.LogChat); TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
// Misc // Misc
TryReadValue(data, "Misc", StrSendErrors, Application::Settings.SendErrors); TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
TryReadValue(data, "Misc", StrHideUpdateMessages, Application::Settings.HideUpdateMessages); TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, Application::Settings.SendErrorsMessageEnabled); TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
// HTTP
TryReadValue(data, "HTTP", StrSSLKeyPath, Application::Settings.SSLKeyPath);
TryReadValue(data, "HTTP", StrSSLCertPath, Application::Settings.SSLCertPath);
TryReadValue(data, "HTTP", StrHTTPServerPort, Application::Settings.HTTPServerPort);
TryReadValue(data, "HTTP", StrHTTPServerIP, Application::Settings.HTTPServerIP);
TryReadValue(data, "HTTP", StrHTTPServerEnabled, Application::Settings.HTTPServerEnabled);
TryReadValue(data, "HTTP", StrHTTPServerUseSSL, Application::Settings.HTTPServerUseSSL);
} catch (const std::exception& err) { } catch (const std::exception& err) {
beammp_error("Error parsing config file value: " + std::string(err.what())); beammp_error("Error parsing config file value: " + std::string(err.what()));
mFailed = true; mFailed = true;
@@ -229,14 +246,12 @@ void TConfig::PrintDebug() {
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\""); beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\""); beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\""); beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\""); beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\""); beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
beammp_debug(std::string(StrSSLKeyPath) + ": \"" + Application::Settings.SSLKeyPath + "\"");
beammp_debug(std::string(StrSSLCertPath) + ": \"" + Application::Settings.SSLCertPath + "\"");
beammp_debug(std::string(StrHTTPServerPort) + ": \"" + std::to_string(Application::Settings.HTTPServerPort) + "\"");
beammp_debug(std::string(StrHTTPServerIP) + ": \"" + Application::Settings.HTTPServerIP + "\"");
// special! // special!
beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + ""); beammp_debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
beammp_debug("Password Protected: " + std::string(Application::Settings.Password.empty() ? "false" : "true"));
} }
void TConfig::ParseOldFormat() { void TConfig::ParseOldFormat() {
@@ -291,3 +306,13 @@ void TConfig::ParseOldFormat() {
Str >> std::ws; Str >> std::ws;
} }
} }
std::string TConfig::TagsAsPrettyArray() const {
std::vector<std::string> TagsArray = {};
SplitString(Application::Settings.ServerTags, ',', TagsArray);
std::string Pretty = {};
for (size_t i = 0; i < TagsArray.size() - 1; ++i) {
Pretty += '\"' + TagsArray[i] + "\", ";
}
Pretty += '\"' + TagsArray.at(TagsArray.size() - 1) + "\"";
return Pretty;
}
+116 -92
View File
@@ -2,12 +2,12 @@
#include "Common.h" #include "Common.h"
#include "Compat.h" #include "Compat.h"
#include "Client.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include <ctime> #include <ctime>
#include <mutex>
#include <sstream> #include <sstream>
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) { static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
@@ -51,7 +51,7 @@ TEST_CASE("TrimString") {
CHECK(TrimString("") == ""); CHECK(TrimString("") == "");
} }
std::string GetDate() { 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,14 +144,14 @@ 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();
mCommandline.set_history(mCachedLuaHistory); mCommandline->set_history(mCachedLuaHistory);
} }
} }
@@ -163,9 +163,9 @@ void TConsole::ChangeToRegularConsole() {
} else { } else {
Application::Console().WriteRaw("Detached from Lua."); Application::Console().WriteRaw("Detached from Lua.");
} }
mCachedLuaHistory = mCommandline.history(); mCachedLuaHistory = mCommandline->history();
mCommandline.set_history(mCachedRegularHistory); mCommandline->set_history(mCachedRegularHistory);
mCommandline.set_prompt("> "); mCommandline->set_prompt("> ");
mStateId = mDefaultStateId; mStateId = mDefaultStateId;
} }
} }
@@ -187,10 +187,10 @@ bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min,
return EnsureArgsCount(args, min); return EnsureArgsCount(args, min);
} else { } else {
if (args.size() > max) { if (args.size() > max) {
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead."); Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
return false; return false;
} else if (args.size() < min) { } else if (args.size() < min) {
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(max) + " arguments expected, got " + std::to_string(args.size()) + " instead."); Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
return false; return false;
} }
} }
@@ -245,7 +245,7 @@ void TConsole::Command_Clear(const std::string&, const std::vector<std::string>&
if (!EnsureArgsCount(args, 0, size_t(-1))) { if (!EnsureArgsCount(args, 0, size_t(-1))) {
return; return;
} }
mCommandline.write("\x1b[;H\x1b[2J"); mCommandline->write("\x1b[;H\x1b[2J");
} }
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
@@ -259,22 +259,21 @@ 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 { throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
if (!Client.expired()) { /*mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
auto locked = Client.lock(); if (NameCompare(Client->Name.get(), Name)) {
if (NameCompare(locked->GetName(), Name)) { mLuaEngine->Network().ClientKick(*Client, Reason);
mLuaEngine->Network().ClientKick(*locked, Reason);
Kicked = true; Kicked = true;
return false; return false;
} }
}
return true; return true;
}); });*/
if (!Kicked) { if (!Kicked) {
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found."); Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
} else { } else {
@@ -320,7 +319,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) {
@@ -336,7 +337,7 @@ std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const s
} }
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) { if (!EnsureArgsCount(args, 1, 2)) {
return; return;
} }
} }
@@ -355,23 +356,24 @@ void TConsole::Command_List(const std::string&, const std::vector<std::string>&
if (!EnsureArgsCount(args, 0)) { if (!EnsureArgsCount(args, 0)) {
return; return;
} }
// Implement once running
throw std::runtime_error(fmt::format("NOT IMPLEMENTED: {}", __func__));
/*
if (mLuaEngine->Server().ClientCount() == 0) { if (mLuaEngine->Server().ClientCount() == 0) {
Application::Console().WriteRaw("No players online."); Application::Console().WriteRaw("No players online.");
} else { } else {
std::stringstream ss; std::stringstream ss;
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl; ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { mLuaEngine->Server().ForEachClient([&](const std::shared_ptr<TClient>& Client) -> bool {
if (!Client.expired()) { ss << std::left << std::setw(25) << Client->Name.get()
auto locked = Client.lock(); << std::setw(6) << Client->ID.get()
ss << std::left << std::setw(25) << locked->GetName() << std::setw(6) << Client->GetCarCount() << "\n";
<< std::setw(6) << locked->GetID()
<< std::setw(6) << locked->GetCarCount() << "\n";
}
return true; return true;
}); });
auto Str = ss.str(); auto Str = ss.str();
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1)); Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
} }
*/
} }
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) { void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
@@ -380,29 +382,6 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
} }
std::stringstream Status; std::stringstream Status;
size_t CarCount = 0;
size_t ConnectedCount = 0;
size_t GuestCount = 0;
size_t SyncedCount = 0;
size_t SyncingCount = 0;
size_t MissedPacketQueueSum = 0;
int LargestSecondsSinceLastPing = 0;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto Locked = Client.lock();
CarCount += Locked->GetCarCount();
ConnectedCount += Locked->IsConnected() ? 1 : 0;
GuestCount += Locked->IsGuest() ? 1 : 0;
SyncedCount += Locked->IsSynced() ? 1 : 0;
SyncingCount += Locked->IsSyncing() ? 1 : 0;
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
}
}
return true;
});
size_t SystemsStarting = 0; size_t SystemsStarting = 0;
size_t SystemsGood = 0; size_t SystemsGood = 0;
size_t SystemsBad = 0; size_t SystemsBad = 0;
@@ -436,6 +415,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
@@ -445,16 +426,22 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2); SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2); SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime(); auto ElapsedTime = mUptimeTimer.GetElapsedTime();
auto network = mLuaEngine->Network();
auto clients = network->all_clients();
Status << "BeamMP-Server Status:\n" Status << "BeamMP-Server Status:\n"
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n" << "\tTotal Players: " << clients.size() << "\n"
<< "\tSyncing Players: " << SyncingCount << "\n" << "\tPlayers identifying: " << network->clients_in_state_count(bmp::State::Identification) << "\n"
<< "\tSynced Players: " << SyncedCount << "\n" << "\tPlayers authenticating: " << network->clients_in_state_count(bmp::State::Authentication) << "\n"
<< "\tConnected Players: " << ConnectedCount << "\n" << "\tPlayers downloading mods: " << network->clients_in_state_count(bmp::State::ModDownload) << "\n"
<< "\tGuests: " << GuestCount << "\n" << "\tPlayers spawning in: " << network->clients_in_state_count(bmp::State::SessionSetup) << "\n"
<< "\tCars: " << CarCount << "\n" << "\tPlayers playing: " << network->clients_in_state_count(bmp::State::Playing) << "\n"
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(ElapsedTime / 1000.0 / 60.0 / 60.0) << "h) \n" << "\tPlayers leaving: " << network->clients_in_state_count(bmp::State::Leaving) << "\n"
<< "\tGuests: " << network->guest_count() << "\n"
<< "\tVehicles: " << network->vehicle_count() << "\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"
@@ -462,12 +449,12 @@ void TConsole::Command_Status(const std::string&, const std::vector<std::string>
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n" << "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
<< "\tSubsystems:\n" << "\tSubsystems:\n"
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n" << "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n" << "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
<< "\t\tGood: [ " << SystemsGoodList << " ]\n" << "\t\tGood: [ " << SystemsGoodList << " ]\n"
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n" << "\t\tStarting: [ " << SystemsStartingList << " ]\n"
<< "\t\tBad: [ " << SystemsBadList << " ]\n" << "\t\tBad: [ " << SystemsBadList << " ]\n"
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n" << "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n" << "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
<< ""; << "";
Application::Console().WriteRaw(Status.str()); Application::Console().WriteRaw(Status.str());
@@ -572,16 +559,20 @@ Commands
} }
TConsole::TConsole() { TConsole::TConsole() {
mCommandline.enable_history(); }
mCommandline.set_history_limit(20);
mCommandline.set_prompt("> "); void TConsole::InitializeCommandline() {
mCommandline = std::make_unique<Commandline>();
mCommandline->enable_history();
mCommandline->set_history_limit(20);
mCommandline->set_prompt("> ");
BackupOldLog(); BackupOldLog();
mCommandline.on_command = [this](Commandline& c) { mCommandline->on_command = [this](Commandline& c) {
try { try {
auto TrimmedCmd = c.get_command(); auto TrimmedCmd = c.get_command();
TrimmedCmd = TrimString(TrimmedCmd); TrimmedCmd = TrimString(TrimmedCmd);
auto [cmd, args] = ParseCommand(TrimmedCmd); auto [cmd, args] = ParseCommand(TrimmedCmd);
mCommandline.write(mCommandline.prompt() + TrimmedCmd); mCommandline->write(mCommandline->prompt() + TrimmedCmd);
if (mIsLuaConsole) { if (mIsLuaConsole) {
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");
@@ -589,9 +580,7 @@ TConsole::TConsole() {
HandleLuaInternalCommand(cmd.substr(1)); HandleLuaInternalCommand(cmd.substr(1));
} else { } else {
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" }); auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
while (!Future->Ready) { Future->WaitUntilReady();
std::this_thread::yield(); // TODO: Add a timeout
}
if (Future->Error) { if (Future->Error) {
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage); beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
} }
@@ -618,56 +607,91 @@ TConsole::TConsole() {
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.");
} }
}; };
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;
}; };
} }
void TConsole::Write(const std::string& str) { void TConsole::Write(const std::string& str) {
auto ToWrite = GetDate() + str; auto ToWrite = GetDate() + str;
mCommandline.write(ToWrite); // allows writing to stdout without an initialized console
if (mCommandline) {
mCommandline->write(ToWrite);
} else {
std::cout << ToWrite << std::endl;
}
} }
void TConsole::WriteRaw(const std::string& str) { void TConsole::WriteRaw(const std::string& str) {
mCommandline.write(str); // allows writing to stdout without an initialized console
if (mCommandline) {
mCommandline->write(str);
} else {
std::cout << str << std::endl;
}
} }
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) { void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
+19 -45
View File
@@ -1,8 +1,7 @@
#include "THeartbeatThread.h" #include "THeartbeatThread.h"
#include "Client.h"
#include "Http.h" #include "Http.h"
//#include "SocketIO.h" // #include "SocketIO.h"
#include <rapidjson/document.h> #include <rapidjson/document.h>
#include <rapidjson/rapidjson.h> #include <rapidjson/rapidjson.h>
#include <sstream> #include <sstream>
@@ -40,20 +39,6 @@ void THeartbeatThread::operator()() {
Body += "&ip=" + Application::Settings.CustomIP; Body += "&ip=" + Application::Settings.CustomIP;
} }
Body += "&pps=" + Application::PPS();
beammp_trace("heartbeat body: '" + Body + "'");
auto SentryReportError = [&](const std::string& transaction, int status) {
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("heartbeat",
{ { "response-body", T },
{ "request-body", Body } });
Sentry.SetTransaction(transaction);
beammp_trace("sending log to sentry: " + std::to_string(status) + " for " + transaction);
Sentry.Log(SentryLevel::Error, "default", Http::Status::ToString(status) + " (" + std::to_string(status) + ")");
};
auto Target = "/heartbeat"; auto Target = "/heartbeat";
unsigned int ResponseCode = 0; unsigned int ResponseCode = 0;
@@ -61,17 +46,14 @@ void THeartbeatThread::operator()() {
bool Ok = false; bool Ok = false;
for (const auto& Url : Application::GetBackendUrlsInOrder()) { for (const auto& Url : Application::GetBackendUrlsInOrder()) {
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } }); T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
beammp_trace(T);
Doc.Parse(T.data(), T.size()); Doc.Parse(T.data(), T.size());
if (Doc.HasParseError() || !Doc.IsObject()) { if (Doc.HasParseError() || !Doc.IsObject()) {
if (!Application::Settings.Private) { if (!Application::Settings.Private) {
beammp_error("Backend response failed to parse as valid json"); beammp_trace("Backend response failed to parse as valid json");
beammp_trace("Response was: `" + T + "`"); beammp_trace("Response was: `" + T + "`");
} }
Sentry.SetContext("JSON Response", { { "reponse", T } });
SentryReportError(Url + Target, ResponseCode);
} else if (ResponseCode != 200) { } else if (ResponseCode != 200) {
SentryReportError(Url + Target, ResponseCode); beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
} else { } else {
// all ok // all ok
Ok = true; Ok = true;
@@ -90,24 +72,20 @@ void THeartbeatThread::operator()() {
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) { if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
Status = Doc[StatusKey].GetString(); Status = Doc[StatusKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { StatusKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) { if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
Code = Doc[CodeKey].GetString(); Code = Doc[CodeKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { CodeKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) { if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
Message = Doc[MessageKey].GetString(); Message = Doc[MessageKey].GetString();
} else { } else {
Sentry.SetContext("JSON Response", { { MessageKey, "invalid string / missing" } });
Ok = false; Ok = false;
} }
if (!Ok) { if (!Ok) {
beammp_error("Missing/invalid json members in backend response"); beammp_error("Missing/invalid json members in backend response");
Sentry.LogError("Missing/invalid json members in backend response", __FILE__, std::to_string(__LINE__));
} }
} else { } else {
if (!Application::Settings.Private) { if (!Application::Settings.Private) {
@@ -142,24 +120,25 @@ std::string THeartbeatThread::GenerateCall() {
std::stringstream Ret; std::stringstream Ret;
Ret << "uuid=" << Application::Settings.Key Ret << "uuid=" << Application::Settings.Key
<< "&players=" << mServer.ClientCount() << "&players=" << m_network->authenticated_client_count()
<< "&maxplayers=" << Application::Settings.MaxPlayers << "&maxplayers=" << Application::Settings.MaxPlayers
<< "&port=" << Application::Settings.Port << "&port=" << Application::Settings.Port
<< "&map=" << Application::Settings.MapName << "&map=" << Application::Settings.MapName
<< "&private=" << (Application::Settings.Private ? "true" : "false") << "&private=" << (Application::Settings.Private ? "true" : "false")
<< "&version=" << Application::ServerVersionString() << "&version=" << Application::ServerVersionString()
<< "&clientversion=" << Application::ClientVersionString() << "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
<< "&name=" << Application::Settings.ServerName << "&name=" << Application::Settings.ServerName
<< "&modlist=" << mResourceManager.TrimmedList() << "&tags=" << Application::Settings.ServerTags
<< "&modstotalsize=" << mResourceManager.MaxModSize() << "&modlist=" << "-"//mResourceManager.TrimmedList()
<< "&modstotal=" << mResourceManager.ModsLoaded() << "&modstotalsize=" << 0 //mResourceManager.MaxModSize()
<< "&modstotal=" << 0 // mResourceManager.ModsLoaded()
<< "&playerslist=" << GetPlayers() << "&playerslist=" << GetPlayers()
<< "&desc=" << Application::Settings.ServerDesc; << "&desc=" << Application::Settings.ServerDesc
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
return Ret.str(); return Ret.str();
} }
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server) THeartbeatThread::THeartbeatThread(std::shared_ptr<Network> network)
: mResourceManager(ResourceManager) : m_network(std::move(network)) {
, mServer(Server) {
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting); Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
Application::RegisterShutdownHandler([&] { Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown); Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
@@ -171,15 +150,10 @@ THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& S
Start(); Start();
} }
std::string THeartbeatThread::GetPlayers() { std::string THeartbeatThread::GetPlayers() {
std::string Return; std::string players;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool { for (const auto& [id, client] : m_network->authenticated_clients()) {
ReadLock Lock(mServer.GetClientMutex()); players += client->name.get() + ";";
if (!ClientPtr.expired()) { }
Return += ClientPtr.lock()->GetName() + ";"; return players;
}
return true;
});
return Return;
} }
/*THeartbeatThread::~THeartbeatThread() {
}*/
+153 -60
View File
@@ -1,13 +1,12 @@
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include "Client.h"
#include "CustomAssert.h" #include "CustomAssert.h"
#include "Http.h" #include "Http.h"
#include "LuaAPI.h" #include "LuaAPI.h"
#include "TLuaPlugin.h" #include "TLuaPlugin.h"
#include "sol/object.hpp"
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
#include <httplib.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <random> #include <random>
#include <thread> #include <thread>
@@ -32,7 +31,7 @@ TLuaEngine::TLuaEngine()
} }
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown); Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
}); });
IThreaded::Start(); mThread = boost::scoped_thread<>(&TLuaEngine::Start, this);
} }
TEST_CASE("TLuaEngine ctor & dtor") { TEST_CASE("TLuaEngine ctor & dtor") {
@@ -41,7 +40,7 @@ TEST_CASE("TLuaEngine ctor & dtor") {
Application::GracefullyShutdown(); Application::GracefullyShutdown();
} }
void TLuaEngine::operator()() { void TLuaEngine::Start() {
RegisterThread("LuaEngine"); RegisterThread("LuaEngine");
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good); Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
// lua engine main thread // lua engine main thread
@@ -221,11 +220,72 @@ 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;
size_t ms = 0; size_t ms = 0;
std::set<std::string> WarnedResults; std::set<std::string> WarnedResults;
while (!Result->Ready && !Cancelled) { while (!Result->Ready && !Cancelled) {
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
ms += 10; ms += 10;
@@ -240,6 +300,7 @@ void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, c
} }
} }
} }
if (Cancelled) { if (Cancelled) {
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time."); beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
LuaAPI::MP::Engine->ReportErrors({ Result }); LuaAPI::MP::Engine->ReportErrors({ Result });
@@ -358,7 +419,6 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
if (Fn.valid()) { if (Fn.valid()) {
auto LuaResult = Fn(EventArgs); auto LuaResult = Fn(EventArgs);
auto Result = std::make_shared<TLuaResult>(); auto Result = std::make_shared<TLuaResult>();
Result->Ready = true;
if (LuaResult.valid()) { if (LuaResult.valid()) {
Result->Error = false; Result->Error = false;
Result->Result = LuaResult; Result->Result = LuaResult;
@@ -366,6 +426,7 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string
Result->Error = true; Result->Error = true;
Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid"; Result->ErrorMessage = "Function result in TriggerGlobalEvent was invalid";
} }
Result->MarkAsReady();
Return.push_back(Result); Return.push_back(Result);
} }
} }
@@ -417,14 +478,14 @@ sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string&
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto MaybeClient = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
if (MaybeClient && !MaybeClient.value().expired()) { if (MaybeClient) {
auto IDs = MaybeClient.value().lock()->GetIdentifiers(); auto IDs = MaybeClient.value()->identifiers.synchronize();
if (IDs.empty()) { if (IDs->empty()) {
return sol::lua_nil; return sol::lua_nil;
} }
sol::table Result = mStateView.create_table(); sol::table Result = mStateView.create_table();
for (const auto& Pair : IDs) { for (const auto& Pair : *IDs) {
Result[Pair.first] = Pair.second; Result[Pair.first] = Pair.second;
} }
return Result; return Result;
@@ -434,30 +495,22 @@ sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() { sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
sol::table Result = mStateView.create_table(); sol::table result = mStateView.create_table();
mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool { auto clients = mEngine->Network()->authenticated_clients();
if (!Client.expired()) { for (const auto& [id, client] : clients) {
auto locked = Client.lock(); result[client->id] = client->name.get();
Result[locked->GetID()] = locked->GetName(); }
} return result;
return true;
});
return Result;
} }
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) { int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
int Id = -1; auto clients = mEngine->Network()->authenticated_clients();
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool { for (const auto& [id, client] : clients) {
if (!Client.expired()) { if (client->name.get() == Name) {
auto locked = Client.lock(); return int(client->id);
if (locked->GetName() == Name) {
Id = locked->GetID();
return false;
}
} }
return true; }
}); return -1;
return Id;
} }
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) { sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
@@ -487,34 +540,52 @@ sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string
} }
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) { std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto maybe_client = mEngine->Network()->get_client(ClientID(ID), bmp::State::Authentication);
if (MaybeClient && !MaybeClient.value().expired()) { if (maybe_client) {
return MaybeClient.value().lock()->GetName(); return maybe_client.value()->name.get();
} else { } else {
return ""; return "";
} }
} }
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) { sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID); auto vehicles = mEngine->Network()->get_vehicles_owned_by(ClientID(ID));
if (MaybeClient && !MaybeClient.value().expired()) { if (vehicles.empty()) {
auto Client = MaybeClient.value().lock();
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (VehicleData.empty()) {
return sol::lua_nil;
}
sol::state_view StateView(mState);
sol::table Result = StateView.create_table();
for (const auto& v : VehicleData) {
Result[v.ID()] = v.Data().substr(3);
}
return Result;
} else
return sol::lua_nil; return sol::lua_nil;
}
sol::state_view state_view(mState);
sol::table result = state_view.create_table();
for (const auto& [vid, vehicle] : vehicles) {
result[vid] = vehicle->data.get();
}
return result;
}
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetVehicleStatus(int VID) {
auto maybe_vehicle = mEngine->Network()->get_vehicle(VehicleID(VID));
if (maybe_vehicle) {
sol::state_view state_view(mState);
sol::table result = state_view.create_table();
auto veh = maybe_vehicle.value();
auto status = veh->get_status();
result["pos"]["x"] = status.pos.x;
result["pos"]["y"] = status.pos.y;
result["pos"]["z"] = status.pos.z;
result["vel"]["x"] = status.vel.x;
result["vel"]["y"] = status.vel.y;
result["vel"]["z"] = status.vel.z;
result["rvel"]["x"] = status.rvel.x;
result["rvel"]["y"] = status.rvel.y;
result["rvel"]["z"] = status.rvel.z;
result["rot"]["x"] = status.rot.x;
result["rot"]["y"] = status.rot.y;
result["rot"]["z"] = status.rot.z;
result["rot"]["w"] = status.rot.w;
result["time"] = status.time;
return { result, "" };
} else {
return { sol::lua_nil, fmt::format("Vehicle {} not found", VID) };
}
} }
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) {
@@ -590,6 +661,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 +746,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("GetVehicleStatus", [&](int VID) -> std::pair<sol::table, std::string> {
return Lua_GetVehicleStatus(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();
@@ -772,7 +848,7 @@ TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateI
FSTable.set_function("ListDirectories", [this](const std::string& Path) { FSTable.set_function("ListDirectories", [this](const std::string& Path) {
return Lua_FS_ListDirectories(Path); return Lua_FS_ListDirectories(Path);
}); });
Start(); mThread = boost::scoped_thread<>(&StateThreadData::Start, this);
} }
std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) { std::shared_ptr<TLuaResult> TLuaEngine::StateThreadData::EnqueueScript(const TLuaChunk& Script) {
@@ -818,7 +894,7 @@ void TLuaEngine::StateThreadData::RegisterEvent(const std::string& EventName, co
mEngine->RegisterEvent(EventName, mStateId, FunctionName); mEngine->RegisterEvent(EventName, mStateId, FunctionName);
} }
void TLuaEngine::StateThreadData::operator()() { void TLuaEngine::StateThreadData::Start() {
RegisterThread("Lua:" + mStateId); RegisterThread("Lua:" + mStateId);
while (!Application::IsShuttingDown()) { while (!Application::IsShuttingDown()) {
{ // StateExecuteQueue Scope { // StateExecuteQueue Scope
@@ -855,7 +931,6 @@ void TLuaEngine::StateThreadData::operator()() {
} }
sol::state_view StateView(mState); sol::state_view StateView(mState);
auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName); auto Res = StateView.safe_script(*S.first.Content, sol::script_pass_on_error, S.first.FileName);
S.second->Ready = true;
if (Res.valid()) { if (Res.valid()) {
S.second->Error = false; S.second->Error = false;
S.second->Result = std::move(Res); S.second->Result = std::move(Res);
@@ -864,6 +939,7 @@ void TLuaEngine::StateThreadData::operator()() {
sol::error Err = Res; sol::error Err = Res;
S.second->ErrorMessage = Err.what(); S.second->ErrorMessage = Err.what();
} }
S.second->MarkAsReady();
} }
} }
{ // StateFunctionQueue Scope { // StateFunctionQueue Scope
@@ -901,6 +977,15 @@ void TLuaEngine::StateThreadData::operator()() {
case TLuaArgTypes_Bool: case TLuaArgTypes_Bool:
LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg))); LuaArgs.push_back(sol::make_object(StateView, std::get<bool>(Arg)));
break; break;
case TLuaArgTypes_StringStringMap: {
auto Map = std::get<std::unordered_map<std::string, std::string>>(Arg);
auto Table = StateView.create_table();
for (const auto& [k, v] : Map) {
Table[k] = v;
}
LuaArgs.push_back(sol::make_object(StateView, Table));
break;
}
default: default:
beammp_error("Unknown argument type, passed as nil"); beammp_error("Unknown argument type, passed as nil");
break; break;
@@ -915,11 +1000,11 @@ void TLuaEngine::StateThreadData::operator()() {
sol::error Err = Res; sol::error Err = Res;
Result->ErrorMessage = Err.what(); Result->ErrorMessage = Err.what();
} }
Result->Ready = true; Result->MarkAsReady();
} else { } else {
Result->Error = true; Result->Error = true;
Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later Result->ErrorMessage = BeamMPFnNotFoundError; // special error kind that we can ignore later
Result->Ready = true; Result->MarkAsReady();
} }
} }
} }
@@ -969,11 +1054,19 @@ void TLuaEngine::StateThreadData::AddPath(const fs::path& Path) {
mPaths.push(Path); mPaths.push(Path);
} }
void TLuaResult::WaitUntilReady() { void TLuaResult::MarkAsReady() {
while (!Ready) { {
std::this_thread::yield(); std::lock_guard<std::mutex> readyLock(*this->ReadyMutex);
std::this_thread::sleep_for(std::chrono::milliseconds(10)); this->Ready = true;
} }
this->ReadyCondition->notify_all();
}
void TLuaResult::WaitUntilReady() {
std::unique_lock readyLock(*this->ReadyMutex);
// wait if not ready yet
if (!this->Ready)
this->ReadyCondition->wait(readyLock);
} }
TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath) TLuaChunk::TLuaChunk(std::shared_ptr<std::string> Content, std::string FileName, std::string PluginPath)
-1050
View File
File diff suppressed because it is too large Load Diff
-69
View File
@@ -1,69 +0,0 @@
#include "TPPSMonitor.h"
#include "Client.h"
#include "TNetwork.h"
TPPSMonitor::TPPSMonitor(TServer& Server)
: mServer(Server) {
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
Application::SetPPS("-");
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
if (mThread.joinable()) {
beammp_debug("shutting down PPSMonitor");
mThread.join();
beammp_debug("shut down PPSMonitor");
}
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
});
Start();
}
void TPPSMonitor::operator()() {
RegisterThread("PPSMonitor");
while (!mNetwork) {
// hard(-ish) spin
std::this_thread::yield();
}
beammp_debug("PPSMonitor starting");
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
std::vector<std::shared_ptr<TClient>> TimedOutClients;
while (!Application::IsShuttingDown()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
int C = 0, V = 0;
if (mServer.ClientCount() == 0) {
Application::SetPPS("-");
continue;
}
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> c;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
c = ClientPtr.lock();
} else
return true;
}
if (c->GetCarCount() > 0) {
C++;
V += c->GetCarCount();
}
// kick on "no ping"
if (c->SecondsSinceLastPing() > (20 * 60)) {
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
TimedOutClients.push_back(c);
}
return true;
});
for (auto& ClientToKick : TimedOutClients) {
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
}
TimedOutClients.clear();
if (C == 0 || mInternalPPS == 0) {
Application::SetPPS("-");
} else {
int R = (mInternalPPS / C) / V;
Application::SetPPS(std::to_string(R));
}
mInternalPPS = 0;
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
#include "TPluginMonitor.h" #include "TPluginMonitor.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include <filesystem>
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine) TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
: mEngine(Engine) : mEngine(Engine)
@@ -9,7 +10,7 @@ TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine>
if (!fs::exists(mPath)) { if (!fs::exists(mPath)) {
fs::create_directories(mPath); fs::create_directories(mPath);
} }
for (const auto& Entry : fs::recursive_directory_iterator(mPath)) { for (const auto& Entry : fs::recursive_directory_iterator(mPath, fs::directory_options::follow_directory_symlink)) {
// TODO: trigger an event when a subfolder file changes // TODO: trigger an event when a subfolder file changes
if (Entry.is_regular_file()) { if (Entry.is_regular_file()) {
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path()); mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
-36
View File
@@ -1,36 +0,0 @@
#include "TResourceManager.h"
#include <algorithm>
#include <filesystem>
namespace fs = std::filesystem;
TResourceManager::TResourceManager() {
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
std::string Path = Application::Settings.Resource + "/Client";
if (!fs::exists(Path))
fs::create_directories(Path);
for (const auto& entry : fs::directory_iterator(Path)) {
std::string File(entry.path().string());
if (auto pos = File.find(".zip"); pos != std::string::npos) {
if (File.length() - pos == 4) {
std::replace(File.begin(), File.end(), '\\', '/');
mFileList += File + ';';
if (auto i = File.find_last_of('/'); i != std::string::npos) {
++i;
File = File.substr(i, pos - i);
}
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
mMaxModSize += size_t(fs::file_size(entry.path()));
mModsLoaded++;
}
}
}
if (mModsLoaded) {
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
}
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
}
-138
View File
@@ -1,138 +0,0 @@
#include "TSentry.h"
#include "Common.h"
#include <cstring>
#include <sentry.h>
#include <sstream>
TSentry::TSentry() {
if (std::strlen(S_DSN) == 0) {
mValid = false;
} else {
mValid = true;
sentry_options_t* options = sentry_options_new();
sentry_options_set_dsn(options, S_DSN);
auto ReleaseString = "BeamMP-Server@" + Application::ServerVersionString();
sentry_options_set_symbolize_stacktraces(options, true);
sentry_options_set_release(options, ReleaseString.c_str());
sentry_options_set_max_breadcrumbs(options, 10);
sentry_init(options);
}
}
TSentry::~TSentry() {
if (mValid) {
sentry_close();
}
}
void TSentry::PrintWelcome() {
if (mValid) {
if (!Application::Settings.SendErrors) {
mValid = false;
if (Application::Settings.SendErrorsMessageEnabled) {
beammp_info("Opted out of error reporting (SendErrors), Sentry disabled.");
} else {
beammp_info("Sentry disabled");
}
} else {
if (Application::Settings.SendErrorsMessageEnabled) {
beammp_info("Sentry started! Reporting errors automatically. This sends data to the developers in case of errors and crashes. You can learn more, turn this message off or opt-out of this in the ServerConfig.toml.");
} else {
beammp_info("Sentry started");
}
}
} else {
if (Application::Settings.SendErrorsMessageEnabled) {
beammp_info("Sentry disabled in unofficial build. Automatic error reporting disabled.");
} else {
beammp_info("Sentry disabled in unofficial build");
}
}
}
void TSentry::SetupUser() {
if (!mValid) {
return;
}
Application::SetSubsystemStatus("Sentry", Application::Status::Good);
sentry_value_t user = sentry_value_new_object();
if (Application::Settings.Key.size() == 36) {
sentry_value_set_by_key(user, "id", sentry_value_new_string(Application::Settings.Key.c_str()));
} else {
sentry_value_set_by_key(user, "id", sentry_value_new_string("unauthenticated"));
}
sentry_set_user(user);
}
void TSentry::Log(SentryLevel level, const std::string& logger, const std::string& text) {
if (!mValid) {
return;
}
SetContext("threads", { { "thread-name", ThreadName(true) } });
auto Msg = sentry_value_new_message_event(sentry_level_t(level), logger.c_str(), text.c_str());
sentry_capture_event(Msg);
sentry_set_transaction(nullptr);
}
void TSentry::LogError(const std::string& text, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line);
Log(SentryLevel::Error, "default", file + ": " + text);
}
void TSentry::SetContext(const std::string& context_name, const std::unordered_map<std::string, std::string>& map) {
if (!mValid) {
return;
}
auto ctx = sentry_value_new_object();
for (const auto& pair : map) {
std::string key = pair.first;
if (key == "type") {
// `type` is reserved
key = "_type";
}
sentry_value_set_by_key(ctx, key.c_str(), sentry_value_new_string(pair.second.c_str()));
}
sentry_set_context(context_name.c_str(), ctx);
}
void TSentry::LogException(const std::exception& e, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line);
Log(SentryLevel::Fatal, "exceptions", std::string(e.what()) + " @ " + file + ":" + line);
}
void TSentry::LogAssert(const std::string& condition_string, const std::string& file, const std::string& line, const std::string& function) {
if (!mValid) {
return;
}
SetTransaction(file + ":" + line + ":" + function);
std::stringstream ss;
ss << "\"" << condition_string << "\" failed @ " << file << ":" << line;
Log(SentryLevel::Fatal, "asserts", ss.str());
}
void TSentry::AddErrorBreadcrumb(const std::string& msg, const std::string& file, const std::string& line) {
if (!mValid) {
return;
}
auto crumb = sentry_value_new_breadcrumb("default", (msg + " @ " + file + ":" + line).c_str());
sentry_value_set_by_key(crumb, "level", sentry_value_new_string("error"));
sentry_add_breadcrumb(crumb);
}
void TSentry::SetTransaction(const std::string& id) {
if (!mValid) {
return;
}
sentry_set_transaction(id.c_str());
}
std::unique_lock<std::mutex> TSentry::CreateExclusiveContext() {
return std::unique_lock<std::mutex>(mMutex);
}
-367
View File
@@ -1,367 +0,0 @@
#include "TServer.h"
#include "Client.h"
#include "Common.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include <TLuaPlugin.h>
#include <any>
#include <sstream>
#include <nlohmann/json.hpp>
#include "LuaAPI.h"
#undef GetObject // Fixes Windows
#include "Json.h"
TServer::TServer(const std::vector<std::string_view>& Arguments) {
beammp_info("BeamMP Server v" + Application::ServerVersionString());
Application::SetSubsystemStatus("Server", Application::Status::Starting);
if (Arguments.size() > 1) {
Application::Settings.CustomIP = Arguments[0];
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
Application::Settings.CustomIP.clear();
beammp_warn("IP Specified is invalid! Ignoring");
} else {
beammp_info("server started with custom IP");
}
}
Application::SetSubsystemStatus("Server", Application::Status::Good);
}
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
if (!WeakClientPtr.expired()) {
TClient& Client = *WeakClientPtr.lock();
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
Client.ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock());
}
}
std::weak_ptr<TClient> TServer::InsertNewClient() {
beammp_debug("inserting new client (" + std::to_string(ClientCount()) + ")");
WriteLock Lock(mClientsMutex);
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
return *Iter;
}
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
decltype(mClients) Clients;
{
ReadLock lock(mClientsMutex);
Clients = mClients;
}
for (auto& Client : Clients) {
if (!Fn(Client)) {
break;
}
}
}
size_t TServer::ClientCount() const {
ReadLock Lock(mClientsMutex);
return mClients.size();
}
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
// abort();
}
if (Packet.substr(0, 4) == "ABG:") {
Packet = DeComp(Packet.substr(4));
}
if (Packet.empty()) {
return;
}
if (Client.expired()) {
return;
}
auto LockedClient = Client.lock();
std::any Res;
char Code = Packet.at(0);
// V to Z
if (Code <= 90 && Code >= 86) {
PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false);
return;
}
switch (Code) {
case 'H': // initial connection
beammp_trace(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
if (!Network.SyncClient(Client)) {
// TODO handle
}
return;
case 'p':
if (!Network.Respond(*LockedClient, ("p"), false)) {
// failed to send
if (LockedClient->GetStatus() > -1) {
LockedClient->SetStatus(-1);
}
} else {
Network.UpdatePlayer(*LockedClient);
}
return;
case 'O':
if (Packet.length() > 1000) {
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
}
ParseVehicle(*LockedClient, Packet, Network);
return;
case 'J':
beammp_trace(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(LockedClient.get(), Packet, false, true);
return;
case 'C': {
beammp_trace(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break;
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 2));
TLuaEngine::WaitForAll(Futures);
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), Packet.substr(Packet.find(':', 3) + 1));
if (std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Elem) {
return !Elem->Error
&& Elem->Result.is<int>()
&& bool(Elem->Result.as<int>());
})) {
break;
}
Network.SendToAll(nullptr, Packet, true, true);
return;
}
case 'E':
beammp_trace(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
HandleEvent(*LockedClient, Packet);
return;
case 'N':
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true);
return;
default:
return;
}
}
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
// E:Name:Data
// Data is allowed to have ':'
auto NameDataSep = RawData.find(':', 2);
if (NameDataSep == std::string::npos) {
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
}
std::string Name = RawData.substr(2, NameDataSep - 2);
std::string Data = RawData.substr(NameDataSep + 1);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
}
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
try {
auto Car = nlohmann::json::parse(CarJson);
const std::string jbm = "jbm";
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
return true;
}
} catch (const std::exception& e) {
beammp_error("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'");
}
return false;
}
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
c.SetUnicycleID(ID);
return true;
} else {
return c.GetCarCount() < Application::Settings.MaxCars;
}
}
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
if (Pckt.length() < 4)
return;
std::string Packet = Pckt;
char Code = Packet.at(1);
int PID = -1;
int VID = -1, Pos;
std::string Data = Packet.substr(3), pid, vid;
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
case 's':
beammp_trace(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID();
beammp_debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
std::string CarJson = Packet.substr(5);
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures);
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
});
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
c.AddNewCar(CarID, Packet);
Network.SendToAll(nullptr, Packet, true, true);
} else {
if (!Network.Respond(c, Packet, true)) {
// TODO: handle
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, Destroy, true)) {
// TODO: handle
}
beammp_debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
}
}
return;
case 'c':
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
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));
TLuaEngine::WaitForAll(Futures);
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
});
auto FoundPos = Packet.find('{');
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& !ShouldntAllow) {
Network.SendToAll(&c, Packet, false, true);
Apply(c, VID, Packet);
} else {
if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1);
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
if (!Network.Respond(c, Destroy, true)) {
// TODO: handle
}
c.DeleteCar(VID);
}
}
return;
case 'd':
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
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) {
c.SetUnicycleID(-1);
}
Network.SendToAll(nullptr, Packet, true, true);
// TODO: should this trigger on all vehicle deletions?
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
c.DeleteCar(VID);
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
}
return;
case 'r':
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
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()) {
Data = Data.substr(Data.find('{'));
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
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);
return;
case 'm':
Network.SendToAll(&c, Packet, true, true);
return;
default:
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
return;
}
}
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
auto FoundPos = pckt.find('{');
if (FoundPos == std::string::npos) {
beammp_error("Malformed packet received, no '{' found");
return;
}
std::string Packet = pckt.substr(FoundPos);
std::string VD = c.GetCarData(VID);
if (VD.empty()) {
beammp_error("Tried to apply change to vehicle that does not exist");
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("vehicle-change",
{ { "packet", Packet },
{ "vehicle-id", std::to_string(VID) },
{ "client-car-count", std::to_string(c.GetCarCount()) } });
Sentry.LogError("attempt to apply change to nonexistent vehicle", _file_basename, _line);
return;
}
std::string Header = VD.substr(0, VD.find('{'));
FoundPos = VD.find('{');
if (FoundPos == std::string::npos) {
auto Lock = Sentry.CreateExclusiveContext();
Sentry.SetContext("vehicle-change-packet",
{ { "packet", VD } });
Sentry.LogError("malformed packet", _file_basename, _line);
return;
}
VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack;
Veh.Parse(VD.c_str());
if (Veh.HasParseError()) {
beammp_error("Could not get vehicle config!");
return;
}
Pack.Parse(Packet.c_str());
if (Pack.HasParseError() || Pack.IsNull()) {
beammp_error("Could not get active vehicle config!");
return;
}
for (auto& M : Pack.GetObject()) {
if (Veh[M.name].IsNull()) {
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
} else {
Veh[M.name] = Pack[M.name];
}
}
rapidjson::StringBuffer Buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
Veh.Accept(writer);
c.SetCarData(VID, Header + Buffer.GetString());
}
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
(void)mClients.insert(NewClient);
}
+50 -35
View File
@@ -1,22 +1,18 @@
#include "TSentry.h"
#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"
#include "TConfig.h" #include "TConfig.h"
#include "THeartbeatThread.h" #include "THeartbeatThread.h"
#include "TLuaEngine.h" #include "TLuaEngine.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include "TPluginMonitor.h" #include "TPluginMonitor.h"
#include "TResourceManager.h"
#include "TScopedTimer.h"
#include "TServer.h"
#include <cstdlib>
#include <iostream> #include <iostream>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
#include <thread> #include <thread>
static const std::string sCommandlineArguments = R"( static const std::string sCommandlineArguments = R"(
@@ -56,7 +52,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]);
} }
@@ -66,15 +62,38 @@ int main(int argc, char** argv) {
} catch (const std::exception& e) { } catch (const std::exception& e) {
beammp_error("A fatal exception has occurred and the server is forcefully shutting down."); beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
beammp_error(e.what()); beammp_error(e.what());
Sentry.LogException(e, _file_basename, _line);
MainRet = -1; MainRet = -1;
} }
std::exit(MainRet); std::exit(MainRet);
} }
static std::shared_ptr<spdlog::logger> default_logger;
static void setup_logger() {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
console_sink->set_pattern("[%H:%M:%S] [%^%l%$] %v");
if (Application::Settings.DebugModeEnabled) {
console_sink->set_level(spdlog::level::debug);
} else {
console_sink->set_level(spdlog::level::info);
}
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("Launcher.log", 1024 * 1024, 3, true);
file_sink->set_level(spdlog::level::trace);
file_sink->set_pattern("[%H:%M:%S.%e] [%t] [%l] %v");
default_logger = std::make_shared<spdlog::logger>(spdlog::logger("default", { console_sink, file_sink }));
default_logger->set_level(spdlog::level::trace);
default_logger->flush_on(spdlog::level::trace);
spdlog::set_default_logger(default_logger);
spdlog::debug("Logger initialized");
}
int BeamMPServerMain(MainArguments Arguments) { int BeamMPServerMain(MainArguments Arguments) {
setlocale(LC_ALL, "C"); setlocale(LC_ALL, "C");
Application::InitializeConsole();
ArgsParser Parser; ArgsParser Parser;
Parser.RegisterArgument({ "help" }, ArgsParser::NONE); Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
Parser.RegisterArgument({ "version" }, ArgsParser::NONE); Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
@@ -85,24 +104,26 @@ int BeamMPServerMain(MainArguments Arguments) {
return 1; return 1;
} }
if (Parser.FoundArgument({ "help" })) { if (Parser.FoundArgument({ "help" })) {
Application::Console().Internal().set_prompt("");
Application::Console().WriteRaw(sCommandlineArguments); Application::Console().WriteRaw(sCommandlineArguments);
return 0; return 0;
} }
if (Parser.FoundArgument({ "version" })) { if (Parser.FoundArgument({ "version" })) {
Application::Console().Internal().set_prompt("");
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString()); Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
return 0; return 0;
} }
// badly seed C's rng - this is only because rand() is used here and there for unimportant stuff
std::srand(std::time(0));
std::string ConfigPath = "ServerConfig.toml"; std::string ConfigPath = "ServerConfig.toml";
if (Parser.FoundArgument({ "config" })) { if (Parser.FoundArgument({ "config" })) {
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" }); auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
if (MaybeConfigPath.has_value()) { if (MaybeConfigPath.has_value()) {
ConfigPath = MaybeConfigPath.value(); ConfigPath = MaybeConfigPath.value();
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'"); // beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
} }
} }
setup_logger();
if (Parser.FoundArgument({ "working-directory" })) { if (Parser.FoundArgument({ "working-directory" })) {
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" }); auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
if (MaybeWorkingDirectory.has_value()) { if (MaybeWorkingDirectory.has_value()) {
@@ -115,10 +136,21 @@ int BeamMPServerMain(MainArguments Arguments) {
} }
} }
Application::SetSubsystemStatus("Main", Application::Status::Starting); TConfig Config(ConfigPath);
if (Config.Failed()) {
beammp_info("Closing in 10 seconds");
// loop to make it possible to ctrl+c instead
for (size_t i = 0; i < 20; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return 1;
}
Application::InitializeConsole();
Application::Console().StartLoggingToFile(); Application::Console().StartLoggingToFile();
Application::SetSubsystemStatus("Main", Application::Status::Starting);
SetupSignalHandlers(); SetupSignalHandlers();
bool Shutdown = false; bool Shutdown = false;
@@ -132,32 +164,15 @@ int BeamMPServerMain(MainArguments Arguments) {
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5)); TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
}); });
TServer Server(Arguments.List);
TConfig Config(ConfigPath);
auto LuaEngine = std::make_shared<TLuaEngine>(); auto LuaEngine = std::make_shared<TLuaEngine>();
LuaEngine->SetServer(&Server);
Application::Console().InitializeLuaConsole(*LuaEngine); Application::Console().InitializeLuaConsole(*LuaEngine);
if (Config.Failed()) {
beammp_info("Closing in 10 seconds");
// loop to make it possible to ctrl+c instead
for (size_t i = 0; i < 20; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return 1;
}
RegisterThread("Main"); RegisterThread("Main");
beammp_trace("Running in debug mode on a debug build"); beammp_trace("Running in debug mode on a debug build");
Sentry.SetupUser(); std::shared_ptr<Network> network = std::make_shared<Network>();
Sentry.PrintWelcome(); THeartbeatThread Heartbeat(network);
TResourceManager ResourceManager; LuaEngine->SetNetwork(network);
TPPSMonitor PPSMonitor(Server);
THeartbeatThread Heartbeat(ResourceManager, Server);
TNetwork Network(Server, PPSMonitor, ResourceManager);
LuaEngine->SetNetwork(&Network);
PPSMonitor.SetNetwork(Network);
Application::CheckForUpdates(); Application::CheckForUpdates();
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine); TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
Submodule
+1
Submodule vcpkg added at 8397227251
+24
View File
@@ -0,0 +1,24 @@
{
"name": "server",
"version-string": "0.1.0",
"dependencies": [
"boost-asio",
"boost-spirit",
"boost-uuid",
"boost-variant",
"boost-iostreams",
"cpp-httplib",
"doctest",
"fmt",
"nlohmann-json",
"openssl",
"rapidjson",
"sol2",
"toml11",
"zstd",
"glm",
"libzip",
"spdlog",
"readline"
]
}