Compare commits

..

1264 Commits

Author SHA1 Message Date
Lion Kortlepel a665e6042b fix postfix formatting 2024-01-08 11:52:17 +01:00
Lion Kortlepel eda78f7e57 leave out version if not exists 2024-01-08 11:50:26 +01:00
Lion Kortlepel f0861f7927 adjust update to use new binary naming format 2024-01-08 11:25:23 +01:00
Lion Kortlepel 5efbbaa901 fixed for self update 2023-12-29 00:26:24 +01:00
Lion Kortlepel 38494bb33a remove .delete_me file on startup if it exists
this is an artifact from the --update process on windows
2023-12-29 00:02:56 +01:00
Lion Kortlepel a89b51ca50 add self-update option via --update 2023-12-29 00:00:43 +01:00
Lion Kortlepel b4d6f90012 remove custom ip functionality
because it never worked
2023-12-28 17:20: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 Kortlepel 054016a099 remove debug print 2022-07-20 16:08:56 +02:00
Lion Kortlepel 8b57f6e35a fix missing Lua error messages in ResultCheckThread 2022-07-20 16:07:00 +02:00
Lion Kortlepel f21d3d0389 fix bug which caused Lua hot-reload not to report syntax errors 2022-07-20 14:56:58 +02:00
Lion Kortlepel 2ed92c4aa1 fix plugin monitor eating a whole cpu core
i must have messed this up when i changed the plugin monitor behavior
recently
2022-07-20 14:42:07 +02:00
Lion Kortlepel fd7b11f436 fix event loop timing issue
The event loop tries to run no faster than every 10ms. If it detects
that it goes faster, it would incorrectly calculate the difference, and
then wait (what I assume was) way too long or too short.
Either way, now it's fixed and it correctly works, even when introducing
new lua states.
2022-07-20 14:33:19 +02:00
Lion Kortlepel 6a94060970 update changelog 2022-07-14 02:08:28 +02:00
Lion Kortlepel 51ccf31373 add beammp_debugf 2022-07-14 01:38:35 +02:00
Lion Kortlepel a2cc629153 add onFileChanged (fixes #116) 2022-07-14 01:18:50 +02:00
Lion Kortlepel ad414ec5c9 call onInit on hot-reload, cleanup, remove warnings
onInit is now called on hot-reload, for the whole plugin. Arguably, this
is not expected behavior, since only one file is being reloaded, but
this is the easiest way to do it, and the entire hot-reload process is
only for development purposes. Open an issue if this breaks your stuff
:^)
2022-07-14 00:37:47 +02:00
Lion Kortlepel 0a8e7d8e50 add TriggerLocalEvent 2022-07-14 00:27:44 +02:00
Lion bbd026e399 Merge pull request #114 from Mack29446/rc-v3.1.0
Add support to properly parse IPs
2022-07-13 00:02:40 +02:00
Mackenzie 04bbdff6b7 Add code from EvanMulawski 2022-07-12 22:59:41 +01: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
Lion Kortlepel 2d8ce09b2c Merge remote-tracking branch 'origin/master' into rc-v3.1.0 2022-07-09 23:03:46 +02:00
Lion 05251efc06 Merge pull request #98 from BeamMP/rc-v3.0.2
RC v3.0.2
2022-07-09 22:55:16 +02:00
Lion Kortlepel f8d622352f generate toml from scratch 2022-07-09 22:42:38 +02:00
Lion Kortlepel 6c1d02a425 add fclose 2022-07-09 22:29:12 +02:00
Lion Kortlepel 38eeec39b4 another attempt to fix #105 2022-07-09 22:27:05 +02:00
Lion Kortlepel 696e080e1c fix #105 2022-07-09 22:01:53 +02:00
Lion Kortlepel 98681254e6 update toml11 2022-07-09 21:50:23 +02:00
Lion Kortlepel 420e6c3533 roll back to an ancient version of sentry
sentry-native deprecated compiling without error somewhere around one of
the next version
2022-07-09 21:40:19 +02:00
Lion Kortlepel 06f8ba5a0e update sentry-native to 0.4.18 2022-07-09 21:11:34 +02:00
Lion Kortlepel 9420d8a7a0 update changelog 2022-06-30 21:30:56 +02:00
Lion Kortlepel dfa90da8af check if Resources/Server directory exists, and only create it if it doesnt
While this doesn't make a difference with usual setups, it does if the
server path exists but is a symlink. In that case, the
create_directories call fails, and the server aborts.

this fixes that. :^)
2022-06-30 20:19:48 +02:00
ㄗㄠˋ ㄑㄧˊ d6625187d1 Support build on apple silicon 2022-06-29 13:43:36 +08:00
Lion Kortlepel 6e46d5aca9 start building the clear command 2022-06-28 03:29:01 +02:00
Lion Kortlepel 817bd4b588 start fixing mod download 2022-06-28 03:20:42 +02:00
Lion Kortlepel 25391fa0c7 thank you toml11 maintainer for naming your header some super generic name that clashes with every single other toml library B) 2022-06-04 16:51:34 +03:00
Lion 28270072d4 Merge pull request #102 from Mack29446/master
update version number in git checkout command
2022-05-30 19:16:10 +02:00
Lion Kortlepel 758d5b2c96 Revert "let's try vcpkg"
This reverts commit 8d7505956d.
2022-05-29 14:37:50 +02:00
Lion Kortlepel 1970d97ea4 Revert "Remove unneeded submodules"
This reverts commit a5153e4bc1.
2022-05-29 14:37:41 +02:00
Lion Kortlepel d8526f0649 TNetwork::SplitLoad: Use managed memory 2022-05-29 14:30:57 +02:00
Lion Kortlepel 0621c0bf82 rebase fixup 2022-05-26 21:13:18 +02:00
Lion Kortlepel 36547d1e9e Move PluginMonitor out of TLuaEngine 2022-05-26 20:59:53 +02:00
Lion Kortlepel f06f31c2a0 add moar tests!!! 2022-05-26 16:58:13 +02:00
Lion Kortlepel 46b92b4992 only run termios test if stdin is a tty 2022-05-26 16:14:05 +02:00
Lion Kortlepel 70e53c2a70 fix dependencies
ubuntu's package naming is confusing me
2022-05-26 16:00:36 +02:00
Lion Kortlepel cc35d83834 make linux workflow parallel, add runtime dependencies 2022-05-26 15:54:23 +02:00
Lion Kortlepel b4f97a6da0 make tests executable before running
:^)
2022-05-26 15:44:39 +02:00
Lion Kortlepel 3d7db6d0bc windows
me waiting for MSVC to stop making me write properly, deepls retarded
code: https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.istockphoto.com%2Fphotos%2Fskeleton-reaching-for-a-window-picture-id155154794%3Fk%3D6%26m%3D155154794%26s%3D612x612%26w%3D0%26h%3DKNIrAKdhAsI1FCoMtSLXd99ZnP9MO1zZj8VkThTvwVs%3D&f=1&nofb=1
2022-05-26 15:41:52 +02:00
Lion Kortlepel 1c3b1ecc76 fix workflow test run path 2022-05-26 15:37:33 +02:00
Lion Kortlepel 303da19f48 add -t to linux workflow 2022-05-26 14:43:38 +02:00
Lion Kortlepel c455d4855c possibly fix workflow 2022-05-26 14:40:56 +02:00
Lion Kortlepel 8df61fe44c add g++ to workflow 2022-05-26 13:58:29 +02:00
Lion Kortlepel 7224e90c68 add test workflow 2022-05-26 13:56:58 +02:00
Lion Kortlepel fde5bc7fb6 remove tests from linux action 2022-05-26 13:50:50 +02:00
Lion Kortlepel 22b63220c7 add more tests to LuaAPI::FS, minor fixes to LuaAPI::FS
test config file creation, too
2022-05-26 13:49:13 +02:00
Lion Kortlepel 811ace1999 fix Application::IsOutdated test case types 2022-05-26 13:36:02 +02:00
Lion Kortlepel 2cf083a7e4 run tests in github actions 2022-05-26 13:34:29 +02:00
Lion Kortlepel 28c43a51ee add some tests for LuaAPI FS, termios 2022-05-26 13:33:08 +02:00
Lion Kortlepel 00f156cb86 start adding tests 2022-05-26 13:02:09 +02:00
Lion Kortlepel 67b8565a4d update json 2022-05-26 12:06:36 +02:00
Lion Kortlepel ed8d8a6419 remove unused code 2022-05-26 12:03:03 +02:00
Lion Kortlepel 895058f85f revert sentry to 0.4.9 2022-05-26 12:01:27 +02:00
Lion Kortlepel a0876ed58c update submodules, remove ssl crap 2022-05-26 11:59:36 +02:00
Lion Kortlepel 4f69ca1ad0 remove ssl code
@jimkoen

This was removed because, as useful and as much work as this was, we
can't reasonably take responsibility for this. Instead, a server like
this should *always* be localhost only, and if it's not, it should be
behind an nginx reverse proxy anyways. We're removing the config options
regarding this in one of the next commits.
2022-05-26 11:54:19 +02:00
Lion Kortlepel bc1628afeb fix some sentry and linking related issues 2022-05-26 11:51:26 +02:00
Lion Kortlepel 019c5202ea add tests executable 2022-05-26 11:44:20 +02:00
Lion Kortlepel 2dd181d492 gracefully shutdown on bind() failure 2022-05-26 11:19:48 +02:00
Lion Kortlepel a5153e4bc1 Remove unneeded submodules 2022-04-28 16:28:23 +02:00
Lion Kortlepel 8d7505956d let's try vcpkg 2022-04-28 16:26:30 +02:00
Lion Kortlepel 3b2016d09f Windows moment
Windows deprecated when
2022-04-28 14:59:41 +02:00
Lion Kortlepel ed03096cf5 Windows moment
Windows deprecated when
2022-04-28 14:58:07 +02:00
Lion Kortlepel 88f1976668 Merge branch 'rc-v3.0.2' into rc-v3.1.0 2022-04-28 14:40:57 +02:00
Lion Kortlepel ca52d233c0 Use another git commit id for vcpkg
this should really be done properly, yikes
2022-04-28 14:34:05 +02:00
Lion Kortlepel 34b39aad4d add message to shutdown suggesting Ctrl+C if it takes too long
This is an ongoing issue that needs to be resolved properly,
but I'm not sure what's hanging it.
2022-04-28 14:30:44 +02:00
Lion Kortlepel f4eb492d91 Actions: try to use master as vcpkgGitCommitId 2022-04-28 14:24:02 +02:00
Lion Kortlepel 7f41a2a574 Update Changelog to reflect latest changes 2022-04-28 14:18:10 +02:00
Lion Kortlepel 11c53e0b3a Remove unused error, as Sentry's code fails to build otherwise
Thanks, sentry.
2022-04-28 14:13:51 +02:00
Lion Kortlepel 974dda9f8b HTTPServer: Add config value to specify listen IP
Change default IP to localhost,
Set default SSL to false due to this.
2022-04-28 14:12:26 +02:00
Lion Kortlepel 0979c8b1e4 HTTPServer: Attempt to catch more errors 2022-04-28 14:04:54 +02:00
Lion Kortlepel 0761036c8c TConsole::StartLoggingToFile: implement 2022-04-28 13:46:25 +02:00
Lion Kortlepel 5ded713b4b Application::CheckForUpdates: only print status the first time 2022-04-28 13:33:38 +02:00
Lion Kortlepel 668cc496b6 update commandline, unused are now errors 2022-04-28 13:29:16 +02:00
Lion Kortlepel 056d20292a Make "unable to fetch version" a trace message 2022-04-28 13:14:28 +02:00
Mackenzie 58e2383b2e update version number in git checkout command 2022-04-13 19:48:12 +01:00
Lion Kortlepel d8c33c03ee start work on new logger 2022-04-05 22:27:45 +02:00
Lion Kortlepel 1bab3276e9 fix setsockopt SO_SNDTIMEO for windows, bump version number to 3.0.2, update commandline 2022-04-05 10:59:16 +02:00
Lion Kortlepel 4ff69528bd fix some missing declaration 2022-03-31 23:56:02 +02:00
Lion Kortlepel 5e4c7eac51 add send timeout to client tcp socket 2022-03-31 23:53:10 +02:00
Lion Kortlepel 952631bb80 add send timeout to client tcp socket 2022-03-31 23:48:07 +02:00
Lion Kortlepel 23af76dba1 Only warn once about event handlers taking >60s 2022-03-31 23:12:50 +02:00
Lion Kortlepel 5755ead9be Change :detach to :exit
@20dka
2022-03-31 22:18:55 +02:00
Lion Kortlepel 450f0a6875 Fixup merge 2022-03-31 22:17:10 +02:00
Lion Kortlepel 104737571c Merge branch 'rc-v3.0.2' into rc-v3.1.0
This is a periodic merge to keep 3.1.0 up to date with 3.0.2
2022-03-31 22:10:49 +02:00
Lion Kortlepel d01d79a49a update changelog 2022-03-31 20:27:08 +02:00
Lion Kortlepel d4b30a2583 CreateEventTimer: Implement CallStrategy
There are two CallStrategies:

- BestEffort (default): Will try to get your event to trigger at the specified
  interval, but will refuse to queue handlers if a handler takes too
  long.
- Precise: Will enqueue event handlers at the exact interval specified.
  Can lead to the queue filling up if the handler takes longer than the
  interval.
2022-03-31 20:13:59 +02:00
Lion Kortlepel 81dbf747d5 Kick client if we fail to send them a client event 2022-03-31 16:50:00 +02:00
Lion Kortlepel b97397132d TLuaEngine: improve result queue handling 2022-03-31 15:59:31 +02:00
Lion Kortlepel d86efabb1a Modernize CMakeLists, automatically update submodules
CMake will now find packages in a modern way (include(Find*)), and will
also ensure that submodules are updated, unless told otherwise.

Also removed some apple-specific workarounds, we will need to look at
that again.
2022-03-30 12:14:13 +02:00
Lion Kortlepel de82caef33 Add HideUpdateMessages setting ("ImScaredOfUpdates") and periodic update reminders (every 5th heartbeat) 2022-03-25 13:34:28 +01:00
Lion Kortlepel f8c58f363a Change default MaxPlayers to 8 2022-03-25 13:32:41 +01:00
Lion Kortlepel 71c2d4b859 Simplify "Backend heartbeat response" error (closes #97) 2022-03-25 12:55:35 +01:00
Lion Kortlepel b2f27c21be update changelog 2022-03-24 16:53:39 +01:00
Lion Kortlepel b780a08f73 use MB constant 2022-03-24 15:16:24 +01:00
Lion Kortlepel cd4332b790 prepend . to Threads.log to make it invisible on *nix 2022-03-24 14:47:15 +01:00
Lion Kortlepel 7a814ed35e use fmt properly in beammp_*f logging functions 2022-03-24 14:45:53 +01:00
Lion Kortlepel 9e0d02c6db add fmt library, add beammp_*f 2022-03-24 14:36:39 +01:00
Lion Kortlepel d0bb32ec63 cleanup fixme's, todo's 2022-03-24 14:26:02 +01:00
Lion Kortlepel 5180c96e2b TServer::HandleEvent: Fix mistreatment of ':' in event data 2022-03-24 14:06:50 +01:00
Lion Kortlepel dbfe4a4d11 Fix inconsistencies with handling errors in early network startup
In most cases, when socket creation, bind, listen, or similar fails,
it's best to gracefully shutdown. We do that now.
2022-03-24 14:06:03 +01:00
Lion Kortlepel 4cb299061e add pos argument to on_autocomplete 2022-03-23 16:10:51 +01:00
Lion Kortlepel ef902a03f3 update lionkor/commandline to v2.0.0 2022-03-23 12:06:35 +01:00
Lion Kortlepel c1e216957b move Json* to Util, add Random, RandomRange, RandomIntRange, catch
errors in TPluginMonitor
2022-03-18 01:52:31 +01:00
Lion Kortlepel 39db1a5e42 Fix JsonEncode with mixed key/value index/value tables 2022-03-17 19:27:17 +01:00
Lion Kortlepel be498be661 change TriggerClientEvent to take object, not string, and add TriggerClientEventJson 2022-03-17 18:48:50 +01:00
Lion 0466ae55a4 Merge pull request #96 from 20dka/feature-supressBackend
Ignore backend response if server is Private
2022-03-17 09:57:16 +01:00
20dka 6a43694c0f Ignore backend response if server is Private 2022-03-17 01:30:24 +01:00
Lion Kortlepel fe06726d75 update commandline 2022-03-16 16:03:23 +01:00
20dka 3c08e54471 Add basic autocomplete (fix #95) 2022-03-15 01:58:26 +01:00
Lion a97763a94f Merge pull request #91 from BeamMP/rc-v3.0.1
Release Candidate v3.0.1
2022-03-10 17:03:43 +01:00
Lion Kortlepel daa674f448 add infinite snowmen bug to changelog 2022-03-10 12:31:02 +01:00
Lion Kortlepel 710b15535e Merge branch 'rc-v3.0.1' into rc-v3.1.0 2022-03-10 12:24:44 +01:00
Lion Kortlepel a85fef15c2 only use sentry if URL is specified, possibly fix stupid microsoft compiler error
hey @microsoft, maybe don't have a limit on the size of obj files.
2022-03-10 12:23:24 +01:00
Lion Kortlepel 359faee696 Fix Unicycle "infinite spawning" bug 2022-03-10 12:22:11 +01:00
Lion Kortlepel 299004b14e fix msvc /bigobj issue 2022-03-10 12:21:08 +01:00
Lion Kortlepel b09f5a401d update lionkor/commandline to 1.0.0 (adds cursor left- and right
movement)
2022-03-10 12:19:01 +01:00
Lion Kortlepel 2caa74d913 update lionkor/commandline to 1.0.0 (adds cursor left- and right
movement)
2022-03-10 12:17:46 +01:00
Lion Kortlepel e3d9d11bbd only use sentry if URL is specified, possibly fix stupid microsoft compiler error
hey @microsoft, maybe don't have a limit on the size of obj files.
2022-03-10 01:40:47 +01:00
Lion Kortlepel 09c9b24cbf Fix Unicycle "infinite spawning" bug 2022-03-10 01:27:16 +01:00
Lion Kortlepel a450531b8a Merge branch 'rc-v3.0.1' into rc-v3.1.0 2022-03-05 23:39:02 +01:00
Lion Kortlepel ace7aaada7 Fix issue which caused assignments and similar lua code to not work in the console 2022-03-03 12:38:23 +01:00
Lion Kortlepel ca3314b416 add JsonDiffApply, JsonMinify, JsonPrettify, JsonFlatten, JsonUnflatten 2022-03-03 12:25:06 +01:00
Lion Kortlepel 7d97c3b560 add FS.ListFiles, FS.ListDirectories 2022-03-02 23:41:32 +01:00
Lion Kortlepel dd5cf1a4af move some things in changelog from 3.0.1 to 3.1.0 2022-03-02 13:30:56 +01:00
Lion Kortlepel 9a0cdc6517 rename JsonSerialize to JsonEncode, JsonDeserialize to JsonDecode 2022-03-02 13:26:53 +01:00
Lion Kortlepel 965935a0e6 catch invalid json to JsonDeserialize, use lua_nil instead of nil 2022-03-02 13:25:29 +01:00
Lion Kortlepel 96a0e4b6fb update changelog 2022-03-02 13:23:08 +01:00
Lion Kortlepel b52677e585 Add JsonDeserialize 2022-03-02 13:22:26 +01:00
Lion Kortlepel 95b417bb36 Add MP.JsonSerialize 2022-03-02 11:43:48 +01:00
Lion Kortlepel 8ce3be03a3 make bigobj a linker flag? 2022-02-17 12:00:03 +01:00
Lion Kortlepel 687b4e4235 add bigobj flag 2022-02-17 11:47:28 +01:00
Lion Kortlepel 86ad28abdc Microsoft (R) Windows (TM) needs deprecation 2022-02-17 11:29:51 +01:00
Lion Kortlepel a982d54202 add debug build to windows github actions 2022-02-17 11:13:07 +01:00
Lion Kortlepel 588c68ebe1 Use proper argument parser 2022-02-17 11:08:48 +01:00
Lion Kortlepel 548b2512cc proper command parsing 2022-02-15 16:06:59 +01:00
Lion Kortlepel 8ff94a57d7 Add ParseCommand implementation 2022-02-15 15:34:33 +01:00
Lion Kortlepel a44684f6e7 Add backend provided message to all auth loggings 2022-02-15 15:20:25 +01:00
Lion Kortlepel 944b68c6d5 format backend refused message nicer 2022-02-15 15:19:41 +01:00
Lion Kortlepel 01268821dc Merge branch 'rc-v3.0.1' into rc-v3.1.0 2022-02-15 15:15:51 +01:00
Lion Kortlepel 5553aca0bb set heartbeat status properly 2022-02-12 22:08:49 +01:00
Lion Kortlepel beaea4f624 Fix crash when giving commandline arguments with no console initialized 2022-02-11 11:57:01 +01:00
Lion a4f07c9a4d Merge pull request #86 from BeamMP/rc-v3.0.1
Release Candidate v3.0.1
2022-02-11 11:07:39 +01:00
Lion Kortlepel dada8fe6bf update changelog 2022-02-11 11:01:39 +01:00
Lion Kortlepel 36853ca683 add MSG_NOSIGNAL to all calls to send() to get rid of useless SIGPIPE signals 2022-02-11 10:59:17 +01:00
Lion Kortlepel d969c4a2c2 Use nlohmann/json for IsUnicycle 2022-02-11 10:36:10 +01:00
Lion Kortlepel f26ca6b40d add nlohmann/json
this will conflict with a change in the http branch, but i dont care
right now
2022-02-11 10:19:10 +01:00
Lion Kortlepel 17c571811a Add config option to turn off chat logging
When LogChat is disabled, using the `say` command in the console will
trigger a "chat message sent!" reply, as UX feedback.
2022-02-06 21:46:51 +01:00
Lion b72de4bd0a Merge pull request #82 from BeamMP/rc-v3.0.1
Release Candidate v3.0.1
2022-02-04 04:37:09 +01:00
Lion Kortlepel fdb7c9ce71 update version to 3.1.0 2022-02-03 19:57:25 +01:00
Lion Kortlepel c391abcc93 Merge branch 'rc-v3.0.1' into rc-v3.1.0 2022-02-03 19:56:33 +01:00
Lion Kortlepel 144ccf14ec Add AddResultToCheck 2022-02-03 19:52:19 +01:00
Lion Kortlepel 40b23cbbe6 update changelog 2022-02-03 19:52:19 +01:00
Lion Kortlepel 7b458e3e27 Use yield() where possible
Replaced calls of this_thread::sleep_* with this_thread::yield(), which
yields the thread to the OS' scheduler.
2022-02-03 19:52:18 +01:00
Lion Kortlepel 69656f95db Move commandline initialization after cwd setting
This fixes an issue where the log file is written to the original
directory, even if --working-directory=path was used. This can obviously
be pretty bad.
2022-02-03 19:51:59 +01:00
Lion Kortlepel 0f5c476d09 update libraries 2022-02-03 19:51:59 +01:00
Lion Kortlepel 86b6aed350 UpdateCheck: Try all URLs 2022-02-03 19:51:59 +01:00
Lion Kortlepel 81780294f8 advance to 3.0.1 2022-02-03 19:51:59 +01:00
Lion Kortlepel 7c1fb12625 add api-v header to heartbeat post 2022-02-03 19:51:59 +01:00
Lion Kortlepel 9f892af997 start fixing backend heartbeat 2022-02-03 19:51:59 +01:00
Lion Kortlepel 9494bc70fb fix changelog 2022-02-03 19:46:31 +01:00
Lion Kortlepel 5c44a307bc update changelog 2022-02-03 19:03:21 +01:00
Lion Kortlepel 754053e73f Use yield() where possible
Replaced calls of this_thread::sleep_* with this_thread::yield(), which
yields the thread to the OS' scheduler.
2022-02-03 18:57:52 +01:00
Lion Kortlepel 29f8d29e33 Move commandline initialization after cwd setting
This fixes an issue where the log file is written to the original
directory, even if --working-directory=path was used. This can obviously
be pretty bad.
2022-02-03 18:31:18 +01:00
Lion Kortlepel e043361abb update libraries 2022-02-03 18:30:00 +01:00
Lion Kortlepel fd12ee672d Add various debug functions 2022-01-26 20:33:12 +01:00
Lion Kortlepel fca5bbcec9 UpdateCheck: Try all URLs 2022-01-21 14:26:42 +01:00
Lion Kortlepel 2a588954be advance to 3.0.1 2022-01-20 21:31:00 +01:00
Lion Kortlepel cd4129e05d add api-v header to heartbeat post 2022-01-20 16:09:08 +01:00
Lion Kortlepel c42c748b37 start fixing backend heartbeat 2022-01-20 15:46:13 +01:00
Lion 179b33a7ab Merge pull request #76 from BeamMP/patch-http-server-default
HTTP Server disabled by default
2021-12-23 14:28:33 +01:00
Lion Kortlepel 1b14206a3c HTTP Server disabled by default 2021-12-23 14:24:00 +01:00
Lion 0cf81cf3f4 Merge pull request #73 from BeamMP/lionkor-readme-patch
Patch README Dependency List, fix Changelog
2021-12-16 23:54:33 +01:00
Lion 801780bcb1 Update Changelog.md 2021-12-16 16:02:31 +01:00
Lion 84d52578e0 Merge pull request #75 from BeamMP/release-3-0-0-patch
Release v3.0.0 final patch
2021-12-15 18:26:08 +01:00
Lion Kortlepel 3555cec5fe Simplify fix for event argument bug 2021-12-13 13:48:18 +01:00
Lion Kortlepel 71efe30345 Bump to 3.0.0, possible fix for event argument bug 2021-12-13 13:22:58 +01:00
Lion 5df8aedf08 Update Changelog.md 2021-12-11 10:35:11 +01:00
Lion c3ab4b729a Update README.md 2021-12-09 14:15:50 +01:00
Lion 464aa3b59f Update README.md 2021-12-09 14:13:05 +01:00
Lion cfe63198c7 Merge pull request #50 from BeamMP/rewrite-lua
Rewrite Lua + New Lua Features + New Console + Commandline Args
2021-12-09 13:04:48 +01:00
Lion Kortlepel 435d73f0c1 Remove message thing from master, reimplement this later 2021-12-09 12:09:55 +01:00
Lion Kortlepel a5c23f8dde Add ping packet support 2021-12-09 12:08:41 +01:00
Lion 6c5b2cbeb5 Merge branch 'master' into rewrite-lua 2021-12-09 12:04:33 +01:00
Lion Kortlepel ca5b3956a1 Http: Dont generate ssl key/cert with ssl off, reinterpret_cast for
windows
2021-12-08 17:39:13 +01:00
Lion Kortlepel 924e18c163 Remove /status placeholder 2021-12-08 17:39:13 +01:00
Rouven Himmelstein bbe92dfa0f fix: broken .gitmodules file 2021-12-08 17:35:29 +01:00
Lion Kortlepel a19943c96d Example impl for /status 2021-12-07 15:34:01 +01:00
Lion Kortlepel cd19ae0836 Add shutting down / shutdown states to state keeper 2021-12-07 14:25:04 +01:00
Lion Kortlepel 3ee83904a1 Windows rewrite when
jfc since when is `c_str()` not convertible to `const char*`?
2021-12-06 15:13:55 +01:00
Lion Kortlepel fe652cbf42 Fix server paths 2021-12-06 15:08:01 +01:00
Lion Kortlepel 2c115a2b2c Fix GCC pragma to not appear on windows 2021-12-06 15:04:28 +01:00
Lion Kortlepel 1172420b77 Add https to changelog 2021-12-06 14:21:25 +01:00
Lion Kortlepel 92d9857902 Re-add commandline
Bruh @jimkoen
2021-12-06 14:16:40 +01:00
Lion Kortlepel 816d3d5df8 Re-add split history (?) 2021-12-06 14:12:54 +01:00
Lion Kortlepel 817a146699 Add state id to lua prompt 2021-12-06 13:57:40 +01:00
Lion Kortlepel 3cce875fbb Add UseSSL option to server config 2021-12-06 13:47:07 +01:00
Lion Kortlepel a1335e8c7d Add statuses, status messages 2021-12-06 13:17:54 +01:00
Lion Kortlepel 0f74eca2ee Fix various issues and crashes 2021-12-06 12:28:52 +01:00
Lion Kortlepel 279c93179c Fix segfault in http 2021-12-06 10:22:52 +01:00
Lion Kortlepel 62cc1e9ce4 Http: Add config value to turn it off, move all http settings into a category in the config 2021-12-06 09:53:13 +01:00
Lion Kortlepel bd41382233 Application::TSettings: Improve default initialisation 2021-12-06 09:00:57 +01:00
awesome_milou 9d283738aa Add preliminary work for HTTP health endpoint (#68)
* Add preliminary work for HTTP health endpoint

* Http: Fix infinite loop bug in Tx509KeypairGenerator::generateKey()

* update commandline

* Add TLS Support class for use with http server

* Add preliminary HTTP Server; TLS still broken; fix in later commit

* Fix TLS handshake, due to server being unable to serve key/certfile in 'Http.h/Http.cpp'; Cause was httlib not being threadsafe due to being a blocking http library

* Run clang format

* Add option to configure http server port via ServerConfig

* TConfig: add HTTPServerPort to config parsing step

* Fix SSL Cert / Key path not auto generating when not existing

* Add health endpoint; Fix SSL Cert serial no. not refreshing when regenerating

* Switch arround status codes in /health route

* Run clang format

Co-authored-by: Lion Kortlepel <development@kortlepel.com>
2021-12-05 18:24:55 +01:00
Lion Kortlepel b33d50361c fix typo in --help 2021-12-05 01:40:39 +01:00
Lion Kortlepel 479bb9f931 TLuaEngine: Make WaitForAll timeout optional 2021-12-05 01:32:15 +01:00
Lion Kortlepel 672c7d02d1 Common: Add lua warn 2021-12-05 01:31:44 +01:00
Lion Kortlepel a289d0e872 Add timeout to WaitForAll 2021-12-05 01:09:41 +01:00
Lion Kortlepel 86169ad0fa TConsole: Add notice about help command on wrong command 2021-12-05 00:55:42 +01:00
Lion Kortlepel f477570a1c Add changelog about new console 2021-12-05 00:54:24 +01:00
Lion Kortlepel 7b99ccb08e Add --working-directory flag 2021-12-05 00:42:50 +01:00
Lion Kortlepel 265dd710cf add status command 2021-12-02 01:25:17 +01:00
Lion Kortlepel eb67f483b2 Another possible fix for deadlock 2021-11-29 03:07:20 +01:00
Lion Kortlepel 98c7fea139 Possible fix for event handler timeouts 2021-11-29 02:56:41 +01:00
Lion Kortlepel ccdc5dae17 update commandline 2021-11-29 02:09:05 +01:00
Lion Kortlepel 1bc9a5293e Add kick response 2021-11-29 02:03:20 +01:00
Lion Kortlepel c3151093e2 CMake: remove __linux completely 2021-11-29 01:42:23 +01:00
Lion Kortlepel 8f77f1c8c0 Add kick, fix cmakelists pretending to be on linux all the time
lol
2021-11-29 01:34:35 +01:00
Lion Kortlepel 19d67dee95 Add GetPlayerIDByName, kick, say 2021-11-29 01:14:37 +01:00
Lion Kortlepel fc440bea2a Add ability to switch into other lua states 2021-11-29 00:37:00 +01:00
Lion Kortlepel c91f3ee33c Print entering and leaving lua as raw 2021-11-29 00:17:09 +01:00
Lion Kortlepel 297b646d33 update commandline 2021-11-29 00:17:03 +01:00
Lion Kortlepel 768d0466f4 Add simple command interface 2021-11-28 23:45:03 +01:00
Lion Kortlepel 1e0ab6bbb3 Update commandline 2021-11-28 23:44:56 +01:00
Lion Kortlepel 472ec3390c Update changelog 2021-11-27 12:25:31 +01:00
Lion Kortlepel a4123d7d7c Remove --ip example 2021-11-27 03:28:35 +01:00
Lion Kortlepel 6fd54f7907 Fix server message printing bug
There was a space missing
2021-11-27 02:31:21 +01:00
Lion Kortlepel fd7bea0f36 Add BEAMMP_{WINDOWS,LINUX,APPLE} preprocessor defines instead of platform specific ones 2021-11-27 02:11:22 +01:00
Lion Kortlepel 9d2d4bb221 Remove --ip
This should be re-added later as a ServerConfig value
2021-11-26 19:08:05 +01:00
Lion Kortlepel e1756298af Fix doubled consent settings in ServerConfig 2021-11-26 19:07:08 +01:00
Lion Kortlepel eae27633db Add commandline arguments, implement --config, --version, --help 2021-11-26 19:04:21 +01:00
Lion Kortlepel 938774618c Fix apple + linux compatibility 2021-11-26 13:25:09 +01:00
Lucca Jiménez Könings 1a2a123d87 Fix various macOS compatibility issues 2021-11-25 02:01:44 +01:00
Lucca Jiménez Könings 6247061d09 Replace gettid() call with POSIX compliant getpid() call in 'Common.cpp' 2021-11-25 02:01:44 +01:00
Lucca Jiménez Könings 08a62261e7 Add temporary cmake mods to make project compile on macOS, add ifdefs in 'Compat.h' for target darwin 2021-11-25 02:01:44 +01:00
Lion Kortlepel a7db41ebaa write thread ids to file 2021-11-21 03:31:35 +01:00
Lion Kortlepel 66d4e34a75 print always 2021-11-21 03:29:22 +01:00
Lion Kortlepel 7169e65305 clarify thread names 2021-11-21 03:19:02 +01:00
Lion Kortlepel 097e52674b update commandline 2021-11-21 03:04:50 +01:00
Lion Kortlepel 1ec47252f2 update commandline 2021-11-21 02:31:52 +01:00
Lion Kortlepel 2ddac7f138 update commandline 2021-11-21 02:26:02 +01:00
Lion Kortlepel cf08dee84f Common: Make TID work on Windows 2021-11-19 13:12:27 +01:00
Lion Kortlepel f1148ed1c4 LuaAPI: Show quotes around strings in table dumps (#60) 2021-11-19 13:03:27 +01:00
Lion Kortlepel b6fa3574fd RegisterThread: Add TID print (#63) 2021-11-19 12:46:43 +01:00
Lion Kortlepel 7079e80b71 Lua: Remove leading space in onChatMessage (fix #35) 2021-11-19 12:43:27 +01:00
Lion Kortlepel 48b9aa72dc update commandline 2021-11-10 00:38:03 +01:00
Lion Kortlepel c36ea52f60 Http: Use ipv4 2021-11-08 23:45:35 +01:00
Lion Kortlepel 87f23427a1 CMake: Nail down lua to be 5.3 2021-11-08 23:13:47 +01:00
Lion Kortlepel 7197c23632 TNetwork: Possible ip address fix 2021-11-08 23:10:24 +01:00
Lion Kortlepel b5ea084c9b update commandline 2021-11-08 22:25:23 +01:00
Lion Kortlepel f8af134dc9 start writing http lua stuff, also heartbeat debug printing 2021-11-08 22:08:07 +01:00
Lion Kortlepel 3e7aa763ed fix release build 2021-11-08 00:01:41 +01:00
Lion Kortlepel 5fdd7beac8 remove stray zip.h include 2021-11-07 23:56:22 +01:00
Lion Kortlepel 701a7feee3 remove boost, add httplib, temporarily remove http* lua 2021-11-07 23:54:33 +01:00
Lion Kortlepel 1e305c3c90 Http: cleanup 2021-11-07 23:09:06 +01:00
Lion Kortlepel 9f5fa8fb9b Remove libzip 2021-11-06 13:03:20 +01:00
Lion Kortlepel fdc205f521 Add ScopedTimer, Remove some comments 2021-10-31 01:27:21 +02:00
Lion a18abd6c8b Update README.md 2021-10-27 18:33:50 +01:00
Lion 1b2ea88a71 README: add irc and discord links 2021-10-27 18:33:50 +01:00
Lion Kortlepel 50589fbe3d send 'Om' to self 2021-10-26 17:39:59 +02:00
Lion Kortlepel 7287fce341 possible actions fix
thank you, anon!
2021-10-26 02:22:03 +02:00
Lion Kortlepel 6de625682d fix compiler error, empty content_type does nothing now 2021-10-26 02:12:17 +02:00
Lion Kortlepel 6189aed6e7 broadcast Om packets 2021-10-26 02:08:02 +02:00
Lion Kortlepel c4d6aab08b fix MP.HttpGET (was not passing contentType) 2021-10-08 08:44:20 +02:00
Lion Kortlepel 577d4c429d TNetwork: Use 'K' packet instead of 'E' to kick players 2021-10-02 01:44:13 +02:00
Lion Kortlepel d027f7f29f Lua: Kick properly (with ClientKick), add chat message printing 2021-10-02 01:28:58 +02:00
Lion Kortlepel af14188ec0 remove spammy debug 2021-10-01 04:22:33 +02:00
Lion Kortlepel 1ee45c9d1a Ignore BEAMMP_FN_NOT_FOUND errors 2021-10-01 04:09:40 +02:00
Lion Kortlepel d1f890752a Report errors on WaitForAll 2021-10-01 03:56:18 +02:00
Lion Kortlepel 9eabd19e17 Report more errors, better 2021-10-01 03:52:12 +02:00
Lion Kortlepel ae7a63669f detect recursion in LuaToString 2021-10-01 03:35:13 +02:00
Lion Kortlepel 243e96d503 Check all futures 2021-10-01 03:27:24 +02:00
Lion Kortlepel 932fbe2b2f reintroduce waiting for results 2021-10-01 03:01:28 +02:00
Lion Kortlepel 26ec50b199 Build libzip statically 2021-10-01 02:31:48 +02:00
Lion Kortlepel 87ecc3f9f6 fix readme invalid cmake invocation, show ms in debug output 2021-10-01 02:03:11 +02:00
Lion Kortlepel 7f1d37a0e6 Fix libzip 2021-10-01 01:57:29 +02:00
Lion Kortlepel 255feb4f8e CMake: Fix minor mistake in cmakelists 2021-10-01 01:52:13 +02:00
Lion Kortlepel 013ca14ab8 add libzip module path 2021-10-01 01:51:22 +02:00
Lion Kortlepel e7f29ce04f Fix server event timing 2021-10-01 01:40:37 +02:00
Lion Kortlepel e948edca8d Add zip files with past logs 2021-09-30 23:24:23 +02:00
Lion Kortlepel d0431c0b9d Use v2 api 2021-09-27 15:46:37 +02:00
Lion Kortlepel 0961f86662 Add heartbeat-api-v API version header 2021-09-27 15:46:37 +02:00
Lion Kortlepel 7f2ca025f8 Start using new heartbeat response format 2021-09-27 15:46:37 +02:00
Lion Kortlepel 33ebfa82f0 Remove spammy TRACE 2021-09-22 21:08:01 +02:00
Lion Kortlepel 9d0caf2c7d Lua: Implement Hot-Reload 2021-09-21 16:21:09 +02:00
Lion Kortlepel fe3ccafc1d Lua: Add various FS functions 2021-09-21 00:27:09 +02:00
Lion Kortlepel 23ffa25d78 Lua: Add FS.GetParentFolder 2021-09-20 23:44:17 +02:00
Lion Kortlepel 908f67a799 Fix compile error 2021-09-20 23:40:28 +02:00
Lion Kortlepel 27b5c6d850 Add GetFilename, GetExtension, 2021-09-20 22:45:12 +02:00
Lion Kortlepel 32756ccc4a Use read instead of ifstream rdbuf 2021-09-20 17:19:38 +02:00
Lion Kortlepel 3626f4108e Use filestreams instead of c-lib 2021-09-20 17:05:28 +02:00
Lion Kortlepel d7a4322313 More windows fixes 2021-09-20 17:00:30 +02:00
Lion Kortlepel d84051bdd3 possible fix for windows path issue 2021-09-20 16:59:42 +02:00
Lion Kortlepel 238577a4f7 Remove debug symbols 2021-09-20 16:36:37 +02:00
Lion Kortlepel 041db23a69 Lua: info,debug -> trace 2021-09-20 16:23:38 +02:00
Lion Kortlepel a3a18a3b56 Lua: Add CancelEventTimer 2021-09-20 16:09:17 +02:00
Lion Kortlepel 9efe352e7a Lua: Working MP.CreateEventTimer 2021-09-20 15:41:40 +03:00
Lion Kortlepel 3edb9322d4 Lua: Simple CreateEventTimer improvements 2021-09-20 13:39:14 +03:00
Lion Kortlepel 4bf89706b4 Lua: Add MP.CreateTimedEvent as CreateThread replacement 2021-09-20 12:43:00 +03:00
Lion Kortlepel a97791d4ee Please MSVC stop being so bad 2021-09-20 00:46:13 +02:00
Lion Kortlepel 323184911d Add new FS functions to Changelog 2021-09-20 00:39:12 +02:00
Lion Kortlepel 6f9f790c5b Lua: Add FS.Remove, FS.Rename (move), FS.Copy, FS.Exists 2021-09-20 00:36:22 +02:00
Lion Kortlepel 4de80e0c7a Lua: Remove debug prints, add GetLuaMemoryUsage 2021-09-19 23:55:24 +02:00
Lion Kortlepel 366a7dc9a6 Lua: Add Lua panic handler 2021-09-19 23:34:27 +02:00
Lion Kortlepel 785b858651 Same as last one
yikes.
2021-09-19 12:29:02 +02:00
Lion Kortlepel a4ff9488c5 Satisfy MSVC's weird attraction to using .string() when its not necessary
I cannot bear another minute of msvc, i swear
2021-09-19 12:23:26 +02:00
Lion Kortlepel 60b86e2be6 Create TLuaChunk constructor to satisfy MSVC 2021-09-19 12:12:38 +02:00
Lion Kortlepel 701e613990 Lua: Fix float printing
Now prints 0, not 0.000000, etc.
2021-09-19 12:10:38 +02:00
Lion Kortlepel 7dbf859529 Lua: Implement event arguments 2021-09-19 11:45:58 +02:00
Lion Kortlepel 8419ca2234 possible windows compiler fix 2021-09-19 01:32:30 +02:00
Lion Kortlepel 7f63dd8d7d Lua: Add FS, FS.CreateDirectory 2021-09-19 01:30:59 +02:00
Lion Kortlepel da78d77e6c Changelog: add MP.PrintRaw 2021-09-19 01:21:30 +02:00
Lion Kortlepel 1ff5107707 Lua: Add MP.PrintRaw 2021-09-19 01:20:17 +02:00
Lion Kortlepel dd70e88e4c SignalHandling: ensure that a signal handler is present on compilation 2021-09-18 22:08:20 +02:00
Lion Kortlepel 38dffc5462 Lua: Pass plugin path and filename to queue for later 2021-09-18 01:20:26 +02:00
Lion Kortlepel f98ef7d41c Lua: Call local eventhandlers synchronously when TriggerGlobalEvent is called from inside a handling state 2021-09-18 00:05:51 +02:00
Lion Kortlepel 29a858e74a Network: Fix TConnection related compiler issue 2021-09-17 15:33:16 +02:00
Lion Kortlepel e53f2d9877 Changelog: Add MP.Https* documentation 2021-09-17 15:32:01 +02:00
Lion Kortlepel be3ac45abb add MP.HttpsGET, MP.HttpsPOST 2021-09-17 15:30:30 +02:00
Lion Kortlepel 246f8289b6 CMake: Fix compiler error with mismatching visibility of target_link_libraries 2021-09-17 15:22:06 +02:00
Lion Kortlepel 3c7109b23f Update Changelog, fix assert formatting 2021-09-17 15:21:06 +02:00
Lion Kortlepel 82a5fc3999 Assert: Fix compiler error 2021-09-17 15:06:13 +02:00
Lion Kortlepel 11d4d9ff91 remove old commandline path 2021-09-17 15:02:53 +02:00
Lion Kortlepel 48caae25fd Finalize master&new-lua-features merge 2021-09-17 14:58:40 +02:00
Lion Kortlepel 9dfe9f659a Update cmakelists to remove socket.io 2021-09-17 14:30:33 +02:00
Lion Kortlepel a07b5062de Reintroduce gitmodules 2021-09-17 14:28:45 +02:00
Lion Kortlepel fcbb188ee0 update modules, cmakelists 2021-09-17 14:25:11 +02:00
Lion Kortlepel 883d69ba27 Merge remote-tracking branch 'origin/master' into rewrite-lua 2021-09-17 14:24:12 +02:00
Lion Kortlepel 7459779363 update cmakelists 2021-09-17 14:21:20 +02:00
Lion Kortlepel a0c47d9947 move sentry-native 2021-09-17 14:17:27 +02:00
Lion Kortlepel 7db345cfbc update submodules 2021-09-17 13:36:16 +02:00
Lion Kortlepel 1d3958817f Merge remote-tracking branch 'origin/new-lua-features' into rewrite-lua
This is the first of a few commits to merge the new lua features and the
rewrite
2021-09-17 13:29:44 +02:00
Lion Kortlepel fd3088c78f Re-add SendChatMessage 2021-09-17 12:58:07 +02:00
Lion Kortlepel c2b73d93b5 Lua: Implement more core functions 2021-09-17 12:56:08 +02:00
Lion Kortlepel 9a37ed4341 Lua: Add GetPlayerName 2021-09-17 12:45:34 +02:00
Lion Kortlepel e64114e4fa Possible compiler fix 2021-09-17 02:44:49 +02:00
Lion Kortlepel 79531334dd another nice fix 2021-09-17 02:38:14 +02:00
Lion Kortlepel ed6f5282d9 Nice fix. 2021-09-17 02:36:06 +02:00
Lion Kortlepel 62fd369625 Lua: Fix more compile errors for windows 2021-09-17 02:30:20 +02:00
Lion Kortlepel 1880536276 Lua: Call onInit properly 2021-09-17 02:26:49 +02:00
Lion Kortlepel bac476ec34 Lua: Set package.path and package.cpath before onInit is called 2021-09-17 02:19:45 +02:00
Lion Kortlepel e75e65815c Lua: change a static_cast to a reinterpret_cast, fun times
:^)
2021-09-17 01:27:45 +02:00
Lion Kortlepel b0c467f971 Lua: Add timer 2021-09-17 01:25:52 +02:00
Lion Kortlepel 6b17990d4d Add GetOSTimeMS 2021-09-17 00:57:43 +02:00
Lion Kortlepel c73d56c143 Possible compiler fix 2021-09-17 00:54:41 +02:00
Lion Kortlepel a44050f0f1 Lua: Almost Working events, all triggers working 2021-09-17 00:21:43 +02:00
Lion Kortlepel cb1eb40def Lua: remove unimplemented 2021-09-16 22:31:54 +02:00
Lion Kortlepel 4c03a90157 Lua: Add more old API 2021-09-16 22:31:09 +02:00
Lion Kortlepel be61511bdf Fix CMake, Add more Lua API 2021-09-16 19:38:31 +02:00
Lion Kortlepel 968d9ff999 Lua: Implement most API functions 2021-09-16 19:00:13 +02:00
Lion Kortlepel 1c80a4deb7 Lua: working events, global and local 2021-09-16 18:14:11 +02:00
Lion Kortlepel e602decb96 Lua: Fix multiple issues with events 2021-09-16 14:58:47 +02:00
Lion Kortlepel dca573b15c Fix more compile issues with lua, add TriggerGlobalEvent 2021-09-16 13:06:04 +02:00
Lion Kortlepel 26231c6272 Fix compile issue with asio, implement Lua events 2021-09-16 13:03:00 +02:00
Lion Kortlepel ebe3630ec8 LuaAPI: Implement GetOSName 2021-09-16 12:22:49 +02:00
Lion Kortlepel d7f7a81cb0 LuaAPI: Print: dump tables properly and recursively 2021-09-16 12:21:11 +02:00
Lion Kortlepel 9ef6c32864 CMake: fix include paths 2021-09-16 11:59:00 +02:00
Lion Kortlepel 9b9c18a4c1 Lua: Add variadic print, LuaAPI 2021-09-16 11:54:52 +02:00
Lion Kortlepel 5978665ad6 Lua: Fix threading related crash 2021-09-16 10:07:04 +02:00
Lion Kortlepel 2cf368c2b0 First working console 2021-09-16 03:40:24 +02:00
Lion Kortlepel ba0678dade Continue Lua Rewrite 2021-09-16 03:21:00 +02:00
Lion Kortlepel c309fa28c6 update sol2 to v3.2.3 2021-09-16 01:09:24 +02:00
Lion Kortlepel f5b2be0a03 rename Assert to beammp_assert 2021-09-16 01:04:38 +02:00
Lion Kortlepel dd4e4c4467 Start rewrite of lua, rename all print functions 2021-09-16 01:04:01 +02:00
Lion Kortlepel d082620525 add sol2 2021-09-16 00:34:09 +02:00
Lion Kortlepel be90a8a2c0 add sol2 2021-09-16 00:33:13 +02:00
Lion Kortlepel 8b69127cdd Finish moving deps to deps/ 2021-09-16 00:22:33 +02:00
Lion Kortlepel bb34378b8e Move all dependencies to deps/ 2021-09-16 00:09:39 +02:00
Lion Kortlepel 2355327c21 CMake: Fix typo in SANITIZE codepath 2021-09-15 17:55:34 +02:00
Lion Kortlepel 3837e101e2 CMake: Use gzipped debug info on linux 2021-09-15 17:55:34 +02:00
Lion Kortlepel fa19ba08e3 Sentry: Properly store DSN 2021-09-15 17:55:34 +02:00
Lion Kortlepel 57d0eb735e Add cryptography header for the future 2021-09-15 17:55:34 +02:00
Lion Kortlepel 15704abf6c Http, Heartbeat: Process status < 0 differently, report as "Invalid
Response Code"
2021-09-15 17:55:34 +02:00
Lion Kortlepel 6883c96d33 Http: Add Sentry error breadcrumbs on internal https POST errors 2021-09-15 17:55:34 +02:00
Lion Kortlepel f632606d76 Heartbeat: Dont report 200 + INVALID_KEY to Sentry 2021-09-15 17:55:34 +02:00
Lion Kortlepel c70ada2926 Config: private by default 2021-09-15 17:55:34 +02:00
Lion Kortlepel 80aebcb9a7 Actions: prerelease by default 2021-09-13 11:58:01 +03:00
Lion Kortlepel 3fc397814c Move update check to after initialization (since its blocking) 2021-09-11 11:38:06 +03:00
Lion Kortlepel 6542be09ee Clarify what sentry sends, add a way to turn off the warning 2021-09-11 11:38:06 +03:00
Lion Kortlepel 38b934bc0f Move signal handling into its own translation unit to limit overlap 2021-09-11 11:38:06 +03:00
Lion Kortlepel a2f92b5791 Update changelog, use std::exit instead of exit 2021-09-11 11:38:06 +03:00
Lion Kortlepel 30624c77a2 Update commandline; reset terminal before exit 2021-09-11 11:38:06 +03:00
Lion Kortlepel b1664bb184 Application: Perform hard-shutdown after 3 Ctrl+C's 2021-09-11 11:38:06 +03:00
Lion Kortlepel ffac000cd2 Config: Add basic opt-out for Sentry 2021-09-11 11:38:06 +03:00
Lion Kortlepel 3cd94380e2 Changelog: Add recent additions 2021-09-11 11:38:06 +03:00
Lion Kortlepel b055fd8bda GracefullyShutdown: Add "subsystem x/y shutting down" message
Remove old "X shutting down", "X shut down" messages, they were bad and
confusing
2021-09-11 11:38:06 +03:00
Lion Kortlepel d43ee4b7b6 Bump version to 2.3.2 2021-09-11 11:38:06 +03:00
Lion Kortlepel a514591650 Main: Add Ctrl+C handler for windows 2021-09-11 11:38:06 +03:00
Lion Kortlepel 0f9f81e9fa Http: Add cloudflare 5XX status code strings 2021-09-11 11:38:06 +03:00
Lion Kortlepel 11e94e91a7 Update Changelog.md to reflect latest changes in recent merge from #44 2021-09-10 13:41:45 +03:00
Lion Kortlepel 588242822c CMake: Remove socketio link, forgot 2021-09-09 12:33:59 +03:00
Lion Kortlepel 58da200901 Client: fix socklen_t compile error 2021-09-09 12:32:33 +03:00
Lion Kortlepel f4ccf6c177 add sentry native db folder to gitignore 2021-09-09 12:26:26 +03:00
Lion Kortlepel 27103a73a9 remove socket.io module 2021-09-09 12:26:03 +03:00
Lion Kortlepel 2727f90430 Remove Socket.io for now
it is being built every time and we dont need it
2021-09-09 12:25:08 +03:00
Lion Kortlepel 2a96546c8c Lua: Add GetPluginName, GetPluginPath 2021-09-09 12:15:57 +03:00
Lion Kortlepel 6462636b29 Multiple merge fixes, rebase, working Https::GET 2021-09-09 12:15:55 +03:00
Lion Kortlepel 5742ab0dad possible windows compiler fix 2021-09-09 12:15:19 +03:00
Lion Kortlepel 0087205d55 fix issues caused by rebase 2021-09-09 12:15:17 +03:00
Lion Kortlepel d16843e45d TNetwork: clarify error messages 2021-09-09 12:14:32 +03:00
Lion Kortlepel 24516dbfd7 TNetwork: setsockopt: cast optval to void* 2021-09-09 12:14:32 +03:00
Lion Kortlepel a311d58e11 TNetwork: reuseaddr instead of reuseport 2021-09-09 12:14:32 +03:00
Lion Kortlepel 1444d91e7e Common: missed semicolon 2021-09-09 12:14:32 +03:00
Lion Kortlepel 1e2f060107 improve error reporting, remove duplicate code 2021-09-09 12:14:32 +03:00
Lion Kortlepel fdb5da2ed6 CMake: remove mentions of luasocket again 2021-09-09 12:14:32 +03:00
Lion Kortlepel de57613326 remove luasocket-cmake 2021-09-09 12:14:32 +03:00
Lion Kortlepel b49782e8a3 Common: Add sstream include for std::stringstream 2021-09-09 12:14:32 +03:00
Lion Kortlepel ff80b4cf63 CMake: include luasocket after finding lua 2021-09-09 12:14:32 +03:00
Lion Kortlepel 4c23b78f84 add luasocket 2021-09-09 12:14:32 +03:00
Lion Kortlepel aca3c52c20 remove luasocket again 2021-09-09 12:14:32 +03:00
Lion Kortlepel 51d6c4fb0a add CMakeLists for lib/ 2021-09-09 12:14:32 +03:00
Lion Kortlepel 2af9491fd6 add luasocket submodule 2021-09-09 12:14:32 +03:00
Lion Kortlepel 95c036836e add ws2tcpip.h 2021-09-09 12:14:32 +03:00
Lion Kortlepel a7f2f85e45 fix version printing 2021-09-09 12:14:32 +03:00
Lion Kortlepel 42c5aaad5a use inet_ntop instead of inet_ntoa (STILL BROKEN THOUGH) 2021-09-09 12:14:32 +03:00
Lion Kortlepel 88684bd9af clarify installation 2021-09-09 12:14:32 +03:00
Lion Kortlepel c6457f7df4 Add Settings enum, better print 2021-09-09 12:14:32 +03:00
Lion Kortlepel ba3fd0e144 add GetServerVersion 2021-09-09 12:14:30 +03:00
Lion Kortlepel e3b6fd7998 use fake version for lua update for now 2021-09-09 12:13:45 +03:00
Lion Kortlepel 943159cd40 Lua: add onShutdown 2021-09-09 12:13:37 +03:00
Lion Kortlepel 9423831937 add ip to identifiers, changed value format 2021-09-09 12:13:34 +03:00
Lion Kortlepel 95188042c5 fix luatable in GetPlayerIdentifiers 2021-09-09 12:12:54 +03:00
Lion Kortlepel a0a7b8ecce fix comment 2021-09-09 12:12:54 +03:00
Lion Kortlepel 53617abae4 Add printRaw
Same as print() but does not prefix with time, date, filename, etc.
Use with care.
2021-09-09 12:12:54 +03:00
Lion Kortlepel 853b078124 add MP.HttpsGET, MP.HttpsPOST 2021-09-09 12:12:54 +03:00
Anonymous-275 549517c518 TODO edit 2021-09-09 12:12:54 +03:00
Anonymous-275 2be4b8fd91 Fully working lua_Register 2021-09-09 12:12:54 +03:00
Lion Kortlepel 2cfb27820a switch to toml11
it's better, believe me
2021-09-09 12:12:54 +03:00
Anonymous-275 1ff12cb2bf simpler lua_Register 2021-09-09 12:12:54 +03:00
Lion Kortlepel 518cb0664e rebase 2021-09-09 12:12:54 +03:00
Lion Kortlepel 80432eb718 implement GetOSName, start working on HttpsPOST 2021-09-09 12:12:54 +03:00
Anonymous-275 b1caf5c29a lua Register 2021-09-09 12:12:54 +03:00
Lion Kortlepel 950cee9fd0 README: fix git submodule update command 2021-09-09 12:12:54 +03:00
Lion Kortlepel 046097579e README: ensure that submodules are initialized recursively 2021-09-09 12:12:53 +03:00
Lion Kortlepel cacdc004da Sentry: remove url length print 2021-09-08 19:55:03 +03:00
Lion Kortlepel 8250d5876f bump to 2.3.1, fix sentry
Fix sentry url length print

remove quotes

github actions is cursed

add debug print

test action

Dont use curl on windows

I dont know why the windows build doesnt report to sentry, so ill try
this.

Change timeout to 20 minutes instead of 5

this is a hacky workaround anyways, so i really dont see why it should
only be 5. 5 is barely enough.

temporarily enable debug mode on sentry

CMake: Use breakpad on windows instead of crashpad

CMake: Sentry: use inproc backend

Since cmake refuses to set my variables, I will do it this way.

I am so tired of this github workflow garbage

Sentry: disable debug again, set
sentry_options_set_symbolize_stacktraces to true, fix memory leak

Sentry: hotfix: dont free options

somehow that causes it to crash, and i cannot be bothered to find out
why right now
2021-09-08 19:55:03 +03:00
Lion Kortlepel a7b02c459e Actions: update release action 2021-09-08 19:55:03 +03:00
Lion Kortlepel 0d5ef404f6 Sentry: ensure user is set up before version check 2021-09-08 19:55:03 +03:00
Lion Kortlepel 07cf7d7c21 Actions: Replace " with ' might fix the sentry issue 2021-09-08 19:55:03 +03:00
Lion Kortlepel 809a851c71 add trace() as DEBUG debug()
Replace DEBUG debug() with trace() everywhere
2021-09-08 19:55:03 +03:00
Lion Kortlepel fe36191baf fix github actions
Possible fix for sentry url not showing up in windows build

possible fix for sentry, again

add static_assert in attempt to fix issue with sentry

use target_compile_definitions instead of add_compile_definitions
2021-09-08 19:55:03 +03:00
Lion Kortlepel 7d137eb496 Common: Make threadNameMap static
good practice
2021-09-08 19:55:03 +03:00
Lion Kortlepel fd6234bd21 Minor fixes 2021-09-08 19:55:03 +03:00
Lion Kortlepel 9f0b057c14 TNetwork: Fix crash when auth response is not a JSON object 2021-09-08 19:55:03 +03:00
Lion Kortlepel 0143748953 TLuaFile: Remove RegisterThread calls since it overrides thread names
This is due to the horrible design of TLuaFile. Everything may be called
at any time from any thread. FIXME.
2021-09-08 19:55:03 +03:00
Lion Kortlepel 8ec90d5186 Add Defer<FnT> type to defer actions to the end of scope. 2021-09-08 19:55:03 +03:00
Lion Kortlepel d054214b7f Various fixes 2021-09-08 19:55:03 +03:00
Lion Kortlepel 003a8269aa Fix url 2021-09-08 19:55:03 +03:00
Lion Kortlepel 59b1b45625 Sentry: don't report id=authkey unless it's likely to be valid 2021-09-08 19:55:03 +03:00
Lion Kortlepel 15e5cee166 Common: fix compile error 2021-09-08 19:55:03 +03:00
Lion Kortlepel 12123582ad add non-working GET for version 2021-09-08 19:55:03 +03:00
Lion Kortlepel 3fb227e468 TNetwork: Fix crash on wrong backend response 2021-09-08 19:55:03 +03:00
Lion Kortlepel 31e9004011 CMakeLists: Win32: Set runtime linking mode before compiling sentry
in an attempt to fix windows compile issue
2021-09-08 19:55:03 +03:00
Lion Kortlepel f98c8dabb0 Http: add Status::ToString method, use to report errors to sentry for custom fingerprint 2021-09-08 19:55:03 +03:00
Lion Kortlepel e8665bfb72 CMakeLists: build runtime static on msvc 2021-09-08 19:55:03 +03:00
Lion Kortlepel 3d13381abd CMakeLists: build sentry static 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5352e4ff03 CMakeLists: link against sentry on windows 2021-09-08 19:55:03 +03:00
Lion Kortlepel c571e218c7 Compat: add back types 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5725717e29 possible windows compiler fix, again 2021-09-08 19:55:03 +03:00
Lion Kortlepel 7f5447f25e Sentry: add debug prints for hard-debug mode 2021-09-08 19:55:03 +03:00
Lion Kortlepel b33b396089 Sentry: add debug, remove wrong exception to sentry logging 2021-09-08 19:55:03 +03:00
Lion Kortlepel ff3cbebac0 Sentry: more macro replacements 2021-09-08 19:55:03 +03:00
Lion Kortlepel 0f9a994c10 Sentry: Fix compile error in AssertNotReachable, release version 2021-09-08 19:55:03 +03:00
Lion Kortlepel c4b72be50a debug prints 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5a3140c84a THeartbeatThread: fix error reporting 2021-09-08 19:55:03 +03:00
Lion Kortlepel bea8006a26 Sentry: reword 2021-09-08 19:55:03 +03:00
Lion Kortlepel a2dc42c5f5 THeartbeatThread: fix missing response code 2021-09-08 19:55:03 +03:00
Lion Kortlepel 4b92532203 Sentry: sort by response code 2021-09-08 19:55:03 +03:00
Lion Kortlepel 683e13a4a0 CustomAssert: fix build error in release mode 2021-09-08 19:55:03 +03:00
Lion Kortlepel 9d6dbefb9d Sentry: add request headers 2021-09-08 19:55:03 +03:00
Lion Kortlepel 981b56b846 CustomAssert: fix macro in release being borked 2021-09-08 19:55:03 +03:00
Lion Kortlepel 9f52ab2e54 Senty: add threadname to context 2021-09-08 19:55:03 +03:00
Lion Kortlepel 8fada3ac04 Sentry: add multiple more logging mechanisms, add [CHAT] 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5330013dc3 possible compiler fix by not using SD_BOTH 2021-09-08 19:55:03 +03:00
Lion Kortlepel c7e0461a86 possible compiler fix 2021-09-08 19:55:03 +03:00
Lion Kortlepel 032c1daf30 possible fix for windows compile issue 2021-09-08 19:55:03 +03:00
Lion Kortlepel d1efebe068 handle Rc == "0" case, add sentry info event 2021-09-08 19:55:03 +03:00
Lion Kortlepel c77e2b3fd8 possible fix for windows build 2 2021-09-08 19:55:03 +03:00
Lion Kortlepel e92847e628 possible windows compiler fix 2021-09-08 19:55:03 +03:00
Lion Kortlepel afb18ccff7 THeartbeatThread: fix isAuth being in the wrong scope 2021-09-08 19:55:03 +03:00
Lion Kortlepel 4659a9362d Fix missing semi
didnt do this in a while, wow
2021-09-08 19:55:03 +03:00
Lion Kortlepel fe6e1e6266 Heartbeat: Try backup1 and backup2, refactor sentry reporting 2021-09-08 19:55:03 +03:00
Lion Kortlepel c0faff5b05 THeartbeatThread: remove second try to heartbeat url 2021-09-08 19:55:03 +03:00
Lion Kortlepel f4ffa2cdda Sentry: remove authkey, use id instead 2021-09-08 19:55:03 +03:00
Lion Kortlepel 1409d4ef80 Sentry: use locked contexts to send data to avoid races 2021-09-08 19:55:03 +03:00
Lion Kortlepel 51e662fdda Compat: fix clash with socket() macro, Sentry: Add LogDebug 2021-09-08 19:55:03 +03:00
Lion Kortlepel 72950fdab2 CMakeLists: attempt to use curl on windows instead of winhttp for sentry transport 2021-09-08 19:55:03 +03:00
Lion Kortlepel b9f594896a Sentry: setup user after config init so that we can sent the authkey 2021-09-08 19:55:03 +03:00
Lion Kortlepel 8551e56e42 Sentry: users: add authkey, username 2021-09-08 19:55:03 +03:00
Lion Kortlepel f4fc182d5e movre TSentry include up, possibly fixing windows actions issue with
macros

im really starting to appreciate that windows API includes clash with
each other because of macros, its super fun
2021-09-08 19:55:03 +03:00
Lion Kortlepel ee1e948a65 Sentry: remove IP from user data 2021-09-08 19:55:03 +03:00
Lion Kortlepel e3081a971e CMakeLists, Actions: Introduce env secret url 2021-09-08 19:55:03 +03:00
Lion Kortlepel 7c5bf9473e CMakeLists: fix include paths 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5a44a8e9c5 Sentry: init before setting user 2021-09-08 19:55:03 +03:00
Lion Kortlepel d1a0eaffab Sentry: move print as it was blocking (?) 2021-09-08 19:55:03 +03:00
Lion Kortlepel 10322bf24e THeartbeatThread: Use Target var in both places 2021-09-08 19:55:03 +03:00
Lion Kortlepel 969cd93358 rename Sentry to TSentry
windows filenames arent case-sensitive so it doesnt know which
sentry.h we mean.
2021-09-08 19:55:03 +03:00
Lion Kortlepel b3a8b1a682 CMakeLists: move sentry back in, add C to languages 2021-09-08 19:55:03 +03:00
Lion Kortlepel 2774a73d83 Sentry: move welcome message to after version print 2021-09-08 19:55:03 +03:00
Lion Kortlepel 739eaad199 Sentry: print welcome string on startup 2021-09-08 19:55:03 +03:00
Lion Kortlepel b53b72d604 Sentry: Build sentry before starting project definition
since Sentry is C and we're CXX
2021-09-08 19:55:03 +03:00
Lion Kortlepel 85fd9e9ee3 Sentry: add loads more information 2021-09-08 19:55:03 +03:00
Lion Kortlepel 57e6e98423 Sentry: discern between auth.* and backend.* errors
TNetwork: error for CheckBytes is now warn
2021-09-08 19:55:03 +03:00
Lion Kortlepel e3c6bdb50d add changelog file 2021-09-08 19:55:03 +03:00
Lion Kortlepel 1f89b202b4 git: properly remove curl (woops) 2021-09-08 19:55:03 +03:00
Lion Kortlepel 0a31107e56 Sentry: add x-upstream 2021-09-08 19:55:03 +03:00
Lion Kortlepel 9237f0dd43 Http: add debug print 2021-09-08 19:55:03 +03:00
Lion Kortlepel ce834a634c Actions: add curl 2021-09-08 19:55:03 +03:00
Lion Kortlepel f65607cb00 README: update to include new dependency 2021-09-08 19:55:03 +03:00
Lion Kortlepel b0475f262f remove curl submodule, add it as an external dependency 2021-09-08 19:55:03 +03:00
Lion Kortlepel cee824ad46 Actions: possible fix for the cmake build error C/CXX issue on GH actions 2021-09-08 19:55:03 +03:00
Lion Kortlepel 530e977d9d README: fix git submodule update command 2021-09-08 19:55:03 +03:00
Lion Kortlepel 807cb68f0f README: ensure that submodules are initialized recursively 2021-09-08 19:55:03 +03:00
Lion Kortlepel 3850740ded Actions: checkout submodules recursively 2021-09-08 19:55:03 +03:00
Lion Kortlepel cfc7b302fe fix include path, libcurl library path 2021-09-08 19:55:03 +03:00
Lion Kortlepel a7c28a8d0d fix curl, print segfault 2021-09-08 19:55:03 +03:00
Lion Kortlepel 9fe1a94d42 CURL::libcurl instead of libcurl 2021-09-08 19:55:03 +03:00
Lion Kortlepel 1eee56a666 Maybe curl works now? 2021-09-08 19:55:03 +03:00
Lion Kortlepel 28fe6e9634 add curl as in-tree dependency, add sentry ok/not ok notice on startup 2021-09-08 19:55:03 +03:00
Lion Kortlepel 4512f44ea1 bump version to 2.3.0 for next release 2021-09-08 19:55:03 +03:00
Lion Kortlepel 3efd31bc84 add curl to dependencies 2021-09-08 19:55:03 +03:00
Lion Kortlepel 5684134894 Sentry: report any issue with backend.beammp or auth.beammp responses 2021-09-08 19:55:03 +03:00
Lion Kortlepel e6c97de3c4 CMakeLists: improve documentation, emit warning if no Sentry URL is
supplied
2021-09-08 19:55:03 +03:00
Lion Kortlepel f550d0bba9 add todo 2021-09-08 19:55:03 +03:00
Lion Kortlepel 2b4fec6d11 Sentry: implement basic exception reporting, error breadcrumbs 2021-09-08 19:55:03 +03:00
Lion Kortlepel 550c658ac5 update gitignore 2021-09-08 19:55:03 +03:00
Lion Kortlepel da41862f49 working sentry-native 2021-09-08 19:55:03 +03:00
Lion Kortlepel d5769ce9be add sentry as submodule 2021-09-08 19:55:03 +03:00
Lion 4bf9244005 Update README.md 2021-08-30 18:42:48 +03:00
Lion 89f63024ab Update README.md 2021-08-30 18:42:48 +03:00
Lion f258678751 Update README.md 2021-08-30 18:42:48 +03:00
Lion Kortlepel 35a3dab1ce TNetwork: clarify error messages 2021-08-07 23:51:56 +02:00
Lion 4d2f68068d Add issue templates 2021-08-02 16:23:42 +03:00
Lion Kortlepel 131ade02cd TNetwork: setsockopt: cast optval to void* 2021-08-02 14:23:20 +02:00
Lion Kortlepel 2c2f76b340 TNetwork: reuseaddr instead of reuseport 2021-08-02 14:15:30 +02:00
Lion Kortlepel 106d8e5863 Common: missed semicolon 2021-08-02 14:06:00 +02:00
Lion Kortlepel 1fb7cb6bc1 improve error reporting, remove duplicate code 2021-08-02 14:01:20 +02:00
Lion Kortlepel 9666fff622 CMake: remove mentions of luasocket again 2021-08-02 14:01:20 +02:00
Lion Kortlepel 5d5f155f0c remove luasocket-cmake 2021-08-02 14:01:20 +02:00
Lion Kortlepel cfe348770c Common: Add sstream include for std::stringstream 2021-08-02 14:01:20 +02:00
Lion Kortlepel 206120dcef CMake: include luasocket after finding lua 2021-08-02 14:01:20 +02:00
Lion Kortlepel 2a3bb1bef8 add luasocket 2021-08-02 14:01:20 +02:00
Lion Kortlepel 0faa46d48c remove luasocket again 2021-08-02 14:01:20 +02:00
Lion Kortlepel dae52a71fd add CMakeLists for lib/ 2021-08-02 14:01:20 +02:00
Lion Kortlepel c46c36bf09 add luasocket submodule 2021-08-02 14:01:20 +02:00
Lion Kortlepel ed3d0834e6 add ws2tcpip.h 2021-08-02 14:01:20 +02:00
Lion Kortlepel 9d4c6e880b fix version printing 2021-08-02 14:01:20 +02:00
Lion Kortlepel d39b5d7c77 use inet_ntop instead of inet_ntoa (STILL BROKEN THOUGH) 2021-08-02 14:01:20 +02:00
Lion Kortlepel b071906db5 clarify installation 2021-08-02 14:01:20 +02:00
Lion Kortlepel 8420cdb5bf Add Settings enum, better print 2021-08-02 14:01:20 +02:00
Lion Kortlepel e11211f201 add GetServerVersion 2021-08-02 14:01:20 +02:00
Lion Kortlepel 9595ef164e use fake version for lua update for now 2021-08-02 14:01:17 +02:00
Lion Kortlepel d18afdf84b Lua: add onShutdown 2021-08-02 14:01:01 +02:00
Lion Kortlepel 0acbb70d10 add ip to identifiers, changed value format 2021-08-02 14:01:01 +02:00
Lion Kortlepel 7a3848e640 fix luatable in GetPlayerIdentifiers 2021-08-02 14:01:01 +02:00
Lion Kortlepel 261aa8f320 fix comment 2021-08-02 14:01:01 +02:00
Lion Kortlepel e994cdd8a2 Add printRaw
Same as print() but does not prefix with time, date, filename, etc.
Use with care.
2021-08-02 14:01:01 +02:00
Lion Kortlepel 44e0f3aa21 add MP.HttpsGET, MP.HttpsPOST 2021-08-02 14:01:00 +02:00
Anonymous-275 8853cef809 TODO edit 2021-08-02 14:01:00 +02:00
Anonymous-275 fb76b8309a Fully working lua_Register 2021-08-02 14:01:00 +02:00
Lion Kortlepel a23946dddf switch to toml11
it's better, believe me
2021-08-02 14:01:00 +02:00
Anonymous-275 55ee1d3747 simpler lua_Register 2021-08-02 14:01:00 +02:00
Lion Kortlepel 4cd0093687 rebase 2021-08-02 14:01:00 +02:00
Lion Kortlepel cc88734279 implement GetOSName, start working on HttpsPOST 2021-08-02 14:01:00 +02:00
Anonymous-275 a865c95e2a lua Register 2021-08-02 14:01:00 +02:00
Anonymous-275 9f636345ef Removed abort that causes server crash 2021-08-01 15:42:23 +03:00
Lion Kortlepel 3d0d5e9e4c minor fixes, version bump 2021-07-31 21:57:06 +03:00
Lion Kortlepel a1ca8e0576 bump vcpkg version 2021-07-31 12:34:25 +03:00
Lion Kortlepel b22f21a6b2 Revert "remove vcpkg commit id"
This reverts commit fef069c9df.
2021-07-31 12:34:25 +03:00
Lion Kortlepel 531a901431 remove vcpkg commit id
there's no need for it and it makes runs fail if not updated
2021-07-31 12:34:25 +03:00
Lion Kortlepel 46f778bd01 bump version to 2.1.4 2021-07-29 13:34:28 +02:00
Lion Kortlepel f3b6eea418 update vcpkg 2021-07-29 13:34:28 +02:00
Lion Kortlepel bceb3aefe4 TServer: Avoid blindly using std::string::find's result 2021-07-29 13:34:28 +02:00
Lion Kortlepel 6c72432992 possible fix #37 2021-07-29 13:34:28 +02:00
Lion 17d3f303ca Update README.md 2021-07-21 00:18:36 +02:00
Lion 2cbcf96282 Readme: clarify build instructions are for linux, too 2021-07-18 21:28:58 +02:00
Lion Kortlepel 7d4fd44dbf print heartbeat on heartbeat 2021-07-15 01:04:06 +02:00
Lion Kortlepel 71c2af1224 TNetwork: kick everyone before shutdown
in the future this can be used to show a message to the clients that the
server is shutting down
2021-07-11 20:27:35 +02:00
Lion Kortlepel 2e112fc5f1 fix typo that prevented TCP thread from shutting down properly
sometimes, i guess
2021-07-11 20:00:31 +02:00
Lion 96c93a6aa6 Update README.md
Remove unnecessary and wrong step 4 :)
2021-07-11 00:30:14 +02:00
Lion 9dbb91fd84 Update README.md 2021-07-11 00:29:27 +02:00
Lion 26c33ae2fb README: Add clarification on build steps 2021-07-11 00:28:21 +02:00
Lion Kortlepel 3eb943309e bump version number 2021-07-10 19:20:42 +02:00
Lion Kortlepel 3c8e8399cb Fix issue with not cancelling events on linux (fix #29) 2021-07-04 00:10:10 +02:00
Lion Kortlepel 5b500a3da5 bump version number 2021-07-03 01:04:55 +02:00
Lion Kortlepel ade19123b7 change default map to new gridmap 2021-07-03 01:01:56 +02:00
Lion Kortlepel 5ee18e0576 bump in-server version number 2021-07-02 00:01:58 +02:00
Lion 77d23caa63 Update README.md 2021-06-28 11:39:12 +02:00
Lion 79856cde8e Update README.md 2021-06-28 11:38:59 +02:00
Lion Kortlepel 7bc230974a fix typo 2021-06-23 23:50:18 +02:00
Anonymous-275 b1ab7e65da Possible windows compile fix 2021-06-23 20:03:42 +03:00
Lion Kortlepel c82c53e3d1 remove debug prints 2021-06-23 16:40:08 +02:00
Lion Kortlepel 9e861ab993 parse old Server.cfg if it exists 2021-06-23 16:39:08 +02:00
Lion Kortlepel ae11ba5f0d bump version to 2.0.4 2021-06-23 11:55:47 +02:00
Lion Kortlepel 1427966d1a private false by default 2021-06-23 02:08:21 +02:00
Lion Kortlepel db92f2867d put a line between header and content of toml 2021-06-23 01:54:17 +02:00
Lion Kortlepel 208a41d45f remove unused 2021-06-23 01:54:17 +02:00
Lion Kortlepel f2915f9c2a remove dead code 2021-06-23 01:54:17 +02:00
Lion Kortlepel 1abf6d5adf Fully implement TOML config file, delete .idea folder
The new config is called "ServerConfig.toml" and uses the TOML library.
It's nice.
2021-06-23 01:54:17 +02:00
Lion Kortlepel f626474b4f add TOML++ 2021-06-23 01:54:17 +02:00
Lion Kortlepel 6f3960d2c2 final commit for the fix to linux lua - fix #27 2021-06-23 01:52:39 +02:00
Lion Kortlepel 6cb19a7991 (possibly) Fix linux lua issue 2021-06-23 01:47:37 +02:00
Lion Kortlepel 4fe3c50edd update commandline, fix #24 2021-06-18 11:24:17 +02:00
Lion Kortlepel fe7335fb0e github actions: run only on push, not PR, since then it runs twice 2021-06-18 10:53:44 +02:00
Lion Kortlepel 40cd203047 update commandline library in a fix attempt for #24 2021-06-18 10:44:53 +02:00
Lion Kortlepel 1fc03500f0 update lionkor/commandline to latest 2021-06-17 12:53:21 +02:00
Lion Kortlepel 73729746ff update gitignore with some common unix stuff and notes folder 2021-06-17 12:51:44 +02:00
Anonymous275 ffdf4dce60 Update LICENSE 2021-06-05 21:42:17 +03:00
Anonymous275 bb5d7fdcf4 Update README.md 2021-06-05 21:41:51 +03:00
Anonymous275 2df2475b59 Update LICENSE 2021-06-05 21:40:54 +03:00
Anonymous275 bb32b9cfea Update README.md 2021-06-05 21:40:26 +03:00
Anonymous275 3f034264f9 Update LICENSE 2021-06-05 21:39:53 +03:00
Anonymous275 c67fffed58 Update README.md 2021-06-02 12:16:33 +03:00
Lion f50b821733 Clarify ways to contribute 2021-05-28 12:26:22 +02:00
Lion 1e5d19bca4 Update README.md 2021-05-28 12:13:12 +02:00
Lion 1011de1971 Update README.md
Add a section about contributing
2021-05-27 16:58:50 +02:00
Anonymous-275 7336d63f58 Added N packet flag 2021-05-23 19:21:04 +03:00
Anonymous-275 c5d7369088 fixed std::unique_lock not a member of std 2021-05-22 14:17:55 +03:00
Lion c3a463552f Update README.md 2021-05-01 17:46:59 +02:00
Lion ae9462898e Update README.md
fixes #22 

@Anonymous-275 please look over
2021-05-01 17:46:02 +02:00
Anonymous-275 529b7e2ae4 Potential mod download timeout crash fix 2021-04-25 19:09:08 +03:00
Anonymous-275 1bee72a175 Server config now uses json 2021-04-22 02:28:02 +03:00
Lion Kortlepel f1e1b6cc28 remove boost from runtime dependencies 2021-04-09 23:56:09 +02:00
Lion Kortlepel 573bd77bbd v2.0.3 2021-04-06 12:50:39 +02:00
Lion Kortlepel 770e03e3c6 update lionkor/commandline to include build speedup 2021-04-06 11:25:16 +02:00
Lion Kortlepel 11d4522dc7 update lionkor/commandline to fix windows build 2021-04-05 23:27:32 +02:00
Lion Kortlepel 830bc47987 update lionkor/commandline
Fixes the 100% CPU spin issue when stdin was /dev/null or similar.
Thanks to @Worty for implementing this fix
2021-04-05 14:47:26 +02:00
Lion Kortlepel bec698fbdc temporary fix for timeout during sync 2021-04-04 02:57:25 +02:00
Lion Kortlepel 60cc835daf remove random 2 second sleep on every car sync (!) 2021-04-04 02:26:51 +02:00
Lion Kortlepel a85ce18589 Implement possible ghost player fix
coauthor @Anonymous-275
2021-04-04 01:44:40 +02:00
Lion Kortlepel 1228c2fabe fix release build to not include "Release" in the title, it leads to a
redundant <title>
2021-03-31 20:00:40 +02:00
Anonymous-275 3da0af37e4 V2.0.2 2021-03-31 20:56:08 +03:00
Anonymous-275 baa41dd65a Timeout set to 30 secs 2021-03-31 20:19:19 +03:00
Anonymous-275 534b457f48 Possible ghost connection ellimination 2021-03-31 20:15:42 +03:00
Anonymous-275 029cf94e68 UnicycleID reset 2021-03-31 19:58:02 +03:00
Anonymous-275 15f7a6ba85 Unicycle edit check 2021-03-31 19:49:52 +03:00
Anonymous-275 86b5d91579 Try to fix max car limit 2021-03-31 19:31:45 +03:00
Anonymous-275 31486bcb56 Car limit fix 2021-03-31 19:27:05 +03:00
Anonymous-275 08660d83dc Unicycle bypass vehicle limit 2021-03-31 19:18:32 +03:00
Anonymous-275 6d8f75a577 Queue on player list update 2021-03-31 17:51:38 +03:00
Lion Kortlepel 018246cea5 fix deadlock in GetCarData, SetCarData 2021-03-31 14:50:49 +02:00
Lion Kortlepel a584e25bf3 fix deadlock in DeleteCar 2021-03-31 14:44:50 +02:00
Lion Kortlepel d4d773b769 revert copy-fix, it broke mutex locked contexts 2021-03-31 12:15:26 +02:00
Lion Kortlepel 56a02f0215 fix vehicle copy on GetAllCars, TSetOfVehicleData is now vector<> 2021-03-31 12:12:01 +02:00
Anonymous-275 7231c69e10 Lock when accessing vehicles 2021-03-31 12:42:29 +03:00
Lion 3c68dfaeaf Update LICENSE 2021-03-31 01:31:06 +02:00
Lion Kortlepel 69709968fd fix release action again 2021-03-31 01:15:24 +02:00
Lion Kortlepel 5b9effad85 fix release action 2021-03-31 01:10:33 +02:00
Anonymous-275 808ab94c68 V2.0.1 2021-03-31 01:57:11 +03:00
Anonymous-275 e7ae71513c moved an if block again feeling good 2021-03-31 01:39:50 +03:00
Anonymous-275 b825e5685b moved a if block feeling good 2021-03-31 01:21:31 +03:00
Anonymous-275 e47821416a Queue packets in SendAll 2021-03-31 01:11:22 +03:00
Anonymous-275 50549f3d1a Copy set of shared ptrs 2021-03-31 00:36:15 +03:00
Anonymous-275 f323d50e34 Decreased the scope of read mutex 2021-03-31 00:05:05 +03:00
Anonymous-275 24994d7dde Added 'E' to the filter 2021-03-30 23:02:49 +03:00
Anonymous-275 77337204e5 Specific queue filtering 2021-03-30 23:01:27 +03:00
Anonymous-275 dad1acbb91 Filtering spam packets 2021-03-30 22:32:16 +03:00
Anonymous-275 8b755e6b7b Commented spam print 2021-03-30 22:14:47 +03:00
Anonymous-275 7ccc5a963a Clear the queue if we failed to sync it 2021-03-30 22:10:57 +03:00
Anonymous-275 ca24339c9a Possible deadlock fix 2021-03-30 20:45:57 +03:00
Lion Kortlepel fc201efa4b possibly fix some issues with not disconnecting disconnected players 2021-03-30 17:04:40 +02:00
Lion Kortlepel 533c8c80e1 break if TCPRcv fails 2021-03-30 16:34:49 +02:00
Lion Kortlepel 78fb81004e change timeout to 60s instead of 10, might fix the timeout mass kick 2021-03-30 16:27:25 +02:00
Lion Kortlepel 942b7baa74 update ping time on udp packets 2021-03-30 16:24:05 +02:00
Lion Kortlepel aa72b2507e fix weird macro compile error 2021-03-30 16:21:08 +02:00
Lion Kortlepel 9860240e24 revert change, apparently this doesn't do it 2021-03-30 16:16:55 +02:00
Lion Kortlepel cda8168c58 fix boost crash 2021-03-30 16:15:44 +02:00
Lion Kortlepel 667bd7f7c8 add name to debug print, update ping time each packet 2021-03-30 16:01:23 +02:00
Lion Kortlepel b524aa67de add debug print in timeout ping update 2021-03-30 15:53:55 +02:00
Lion Kortlepel e35d1b5457 attempt to fix mass timeout kick 2021-03-30 15:41:05 +02:00
Lion Kortlepel 1875c8832d update ping time on any packet, not just ping packets, for now 2021-03-30 15:31:44 +02:00
Lion Kortlepel 61726ea3ab fix data race issue no.2 2021-03-30 15:19:11 +02:00
Lion Kortlepel e4d6c86919 fix race condition in packet queueing 2021-03-30 15:13:32 +02:00
Lion Kortlepel eaa6b5322f dont SIGPIPE on broken pipe send() 2021-03-30 15:04:53 +02:00
Lion Kortlepel 2c06a98e00 add debug print to missed packet sending
maybe recursion is killing it, we'll see!
2021-03-30 14:59:39 +02:00
Lion Kortlepel e73d578797 add debug print on timeout kick 2021-03-30 14:58:19 +02:00
Lion Kortlepel 704e25636d possible hotfix for crashes 2021-03-30 14:38:13 +02:00
Lion Kortlepel c7cf0a733e revert changes, they didn't fix it 2021-03-30 14:32:56 +02:00
Lion Kortlepel 24a34d7a97 possible crash fix 2021-03-30 14:20:31 +02:00
Lion Kortlepel 1c98921127 add debug print to diagnose crash 2021-03-30 14:19:03 +02:00
Lion Kortlepel 2d898f8665 possible crash fix for linux
windows fix coming if this works
2021-03-30 14:07:53 +02:00
Lion Kortlepel 229914ac74 remove auth response printing 2021-03-30 13:34:03 +02:00
Lion 3258b04dad Update README.md 2021-03-30 02:31:33 +02:00
Lion Kortlepel 603663ed2c hotfix register thread *again* 2021-03-30 01:56:33 +02:00
Lion Kortlepel 44f2fdfa7c attempt to fix client thread registering again 2021-03-30 01:54:43 +02:00
Lion Kortlepel 19abb5b68c add quotes around player names to clarify further in thread name debug
prints
2021-03-30 01:50:57 +02:00
Lion Kortlepel dd5b0bdd6d add id to debug thread id print 2021-03-30 01:44:32 +02:00
Lion Kortlepel 9c9f503e5c fix debug printing in debug builds (yes) 2021-03-30 01:18:12 +02:00
Lion Kortlepel b4850f09a9 fully switch to new backend urls 2021-03-30 01:02:53 +02:00
Lion Kortlepel 3094d382ff implement thread names in debug mode 2021-03-30 00:30:24 +02:00
Lion Kortlepel 940a39ed4e fix artifact generation for windows 2021-03-29 23:40:02 +02:00
Lion Kortlepel 23b39bb6c7 update workflows to save artifacts 2021-03-29 23:33:25 +02:00
Starystars67 2cd6e21f8c Updating strings to v2 2021-03-29 22:23:56 +01:00
Anonymous-275 3c6aa741ef Update .name 2021-03-26 22:56:07 +02:00
Anonymous-275 e79318e49a Merge branch 'master' of ssh://github.com/BeamMP/BeamMP-Server 2021-03-25 02:39:59 +02:00
Anonymous-275 e8938968f2 update gitignore 2021-03-25 02:37:47 +02:00
Anonymous275 e6f79a8dd1 Delete .idea directory 2021-03-25 02:33:16 +02:00
Anonymous-275 347e72ce90 update .gitignore 2021-03-25 02:26:55 +02:00
Anonymous275 a90c67f47d Update .gitignore 2021-03-25 02:05:58 +02:00
Anonymous275 956b2ef5b5 Fixed setting vehicle data 2021-03-19 19:56:02 +02:00
Lion 31d68249a8 Update README.md 2021-03-19 00:14:31 +01:00
Lion 6d3e053c71 Update README.md 2021-03-19 00:14:00 +01:00
Lion Kortlepel 87a1564c0a actions: also apply vcpkg fix for release-build action 2021-03-18 23:37:18 +01:00
Lion Kortlepel e6109c98bd Application: Move some string literal URLs to functions 2021-03-18 23:30:52 +01:00
Lion Kortlepel c372e63bd1 possible fix for vcpkg github actions cache issue 2021-03-18 22:46:41 +01:00
Anonymous275 709ac1dd58 specify ID for now since vcpkg is not a submodule 2021-03-18 23:44:14 +02:00
Anonymous275 6ead6bbb1e Always aim for latest vcpkg 2021-03-18 23:44:14 +02:00
Anonymous275 50fb023eff Update cmake-windows.yml 2021-03-18 23:44:14 +02:00
Anonymous275 08d043da8d Set C++17 after building libs, added vcpkg root if needed by libs 2021-03-18 23:44:14 +02:00
Anonymous275 c623bdea91 cleaned unused ifdef 2021-03-18 23:44:14 +02:00
Anonymous275 b953bae5da Fixed Vehicle Data being copied on construction 2021-03-18 23:44:14 +02:00
Lion Kortlepel e039eeaab8 don't count pps changes towards heartbeat hot-changes 2021-03-18 23:44:14 +02:00
Anonymous275 15cad02e13 Debug build fix 2021-03-18 23:44:14 +02:00
Anonymous275 67f22c7d76 Tweaks 2021-03-18 23:44:14 +02:00
Lion Kortlepel 632a5f2801 update commandline library 2021-03-18 23:44:14 +02:00
Anonymous275 44fa68e6da Fixed windows build 2021-03-18 23:44:14 +02:00
Lion Kortlepel 33e0cac4c1 update commandline to newer version 2021-03-18 23:44:14 +02:00
Lion a7f1e93ca2 Update README.md 2021-03-18 23:44:14 +02:00
Lion Kortlepel f8a9d01749 add websocketpp to github actions builds 2021-03-18 23:44:14 +02:00
Lion Kortlepel 356354d1eb use recursive checkout for github actions 2021-03-18 23:44:14 +02:00
Lion Kortlepel 40cae31885 Merge TUDPServer and TTCPServer into TNetwork
this gets rid of a bunch of unclear cases which I mistakenly created
while refactoring for this rewrite. One example is having to call into
TTCPServer to do UDP sending in some cases.
2021-03-18 23:44:14 +02:00
Lion Kortlepel 05c5fb047c SendToAll: also send while syncing
the missed packet queue handles this case
2021-03-18 23:44:14 +02:00
Lion Kortlepel 83145d7466 add 1 second delay before we start sending missed data during sync 2021-03-18 23:44:14 +02:00
Lion Kortlepel 3c48ac6145 fix issue with spamming 1kB until death 2021-03-18 23:44:14 +02:00
Anonymous275 3fe8d48ada Packet queuing on syncing 2021-03-18 23:44:14 +02:00
Anonymous275 f0abfcc0ef Added lua GetIdentifiers 2021-03-18 23:44:14 +02:00
Anonymous275 7410e31230 Use of std::move and added DEBUG ifdef 2021-03-18 23:44:14 +02:00
Anonymous275 3bc8744b63 Removed debug printing 2021-03-18 23:44:14 +02:00
Anonymous275 c076c83edc Fxed lua_GetCars 2021-03-18 23:44:14 +02:00
Anonymous275 776ddcbbef x86 support 2021-03-18 23:44:14 +02:00
Anonymous275 9a74434bbb Small edits 2021-03-18 23:44:14 +02:00
Anonymous275 3e2cb3176a Fixed the optional boolean in TCPSend 2021-03-18 23:44:14 +02:00
Lion Kortlepel 7cd420a1a5 partially implement queuing while sycing client 2021-03-18 23:44:14 +02:00
Lion Kortlepel 4edd1ac100 fix various issues 2021-03-18 23:44:14 +02:00
Lion Kortlepel 8e4006fc38 clear up heartbeat code, improve logs in debug builds 2021-03-18 23:44:14 +02:00
Anonymous275 ab44ac8c15 SocketIO authentication 2021-03-18 23:44:14 +02:00
Lion Kortlepel 266303b09d AddNewCar: use insert with make_unique again 2021-03-18 23:44:14 +02:00
Lion Kortlepel b777781c96 possibly fix invisible car bug 2021-03-18 23:44:14 +02:00
Lion Kortlepel 714d31fb45 use emplace instead of insert + make_unique for new cars 2021-03-18 23:44:14 +02:00
Lion Kortlepel d481fcd3a7 debug log if vehicle gets destroyed 2021-03-18 23:44:14 +02:00
Lion Kortlepel df3269756c set locale (do this in the launcher, too, please!) 2021-03-18 23:44:14 +02:00
Anonymous275 aadcd1abe5 SocketIO work 2021-03-18 23:44:14 +02:00
Anonymous275 57fc0ea74d Update TServer.cpp 2021-03-18 23:44:14 +02:00
Anonymous275 fe4a1b28b5 Added onVehicleReset Event 2021-03-18 23:44:14 +02:00
Anonymous275 30916c41c3 Update CMakeLists.txt 2021-03-18 23:44:14 +02:00
Anonymous275 fab20276ff Fixed windows not linking 2021-03-18 23:44:14 +02:00
Anonymous275 7e6d5ce359 Fixed socket.io TLS 2021-03-18 23:44:14 +02:00
Anonymous275 6aed93fbf1 Update TLuaFile.h 2021-03-18 23:44:14 +02:00
Anonymous275 9b1bf071a8 Fixed lua crash caused by lion with optimizations 2021-03-18 23:44:14 +02:00
Anonymous275 f52308c439 Cleanup & optimizations 2021-03-18 23:44:14 +02:00
Anonymous275 0580ad67fd Fixed crash + debug build on windows 2021-03-18 23:44:14 +02:00
Anonymous275 218504e674 Fixed windows build not compiling 2021-03-18 23:44:14 +02:00
Lion Kortlepel f13523fbe5 fixed ghost player issue 2021-03-18 23:44:14 +02:00
Lion Kortlepel b81ac35b37 update internal ping every second while syncing 2021-03-18 23:44:14 +02:00
Lion Kortlepel 8664522d1d fix client kicked on connect because no initialization of some value
that i forgot to initlialize because i literally need coffee and food rn
fuck
2021-03-18 23:44:14 +02:00
Lion Kortlepel c15046f8b1 fix pps dying on startup :^) 2021-03-18 23:44:14 +02:00
Lion Kortlepel c7f8b2b131 add pps monitor print 2021-03-18 23:44:14 +02:00
Lion Kortlepel 84252e892e add seconds since last ping print 2021-03-18 23:44:14 +02:00
Lion Kortlepel 32038046d5 add print on ping 2021-03-18 23:44:14 +02:00
Lion Kortlepel e04a569e33 attempt to fix ghost player issue 2021-03-18 23:44:14 +02:00
Lion Kortlepel 13f8be5d39 update players info 2021-03-18 23:44:14 +02:00
Lion Kortlepel bca4b3f140 fix client insert/create issue 2021-03-18 23:44:14 +02:00
Lion Kortlepel b3256062f7 fix boolean expression (oof) 2021-03-18 23:44:14 +02:00
Lion Kortlepel 51dbfe0482 add debug prints 2021-03-18 23:44:14 +02:00
Lion Kortlepel 92a67c7305 remove debug prints of Http for now 2021-03-18 23:44:14 +02:00
Lion Kortlepel cc5a878692 fix debug prints for now 2021-03-18 23:44:14 +02:00
Lion Kortlepel 5759a6f80f attempt #2 2021-03-18 23:44:14 +02:00
Lion Kortlepel 3dd2e1c278 attempt #1 to fix LuaEngine being nullptr :( 2021-03-18 23:44:14 +02:00
Lion Kortlepel 4826fb5fc2 fix version naming 2021-03-18 23:44:14 +02:00
Lion Kortlepel 8cd35d64e4 fix lua thread never exiting 2021-03-18 23:44:14 +02:00
Lion Kortlepel aec6ad9c14 fix more stuff 2021-03-18 23:44:14 +02:00
Lion Kortlepel d360403c56 finish rewrite, builds fully 2021-03-18 23:44:14 +02:00
Lion Kortlepel bf74b1ae32 add udpserver, tcpserver 2021-03-18 23:44:14 +02:00
Lion Kortlepel f19a012509 add PPSMonitor 2021-03-18 23:44:14 +02:00
Lion Kortlepel 72607583bf add submodules 2021-03-18 23:44:14 +02:00
Lion Kortlepel ef5db013b3 add socketio, http post & get 2021-03-18 23:44:14 +02:00
Lion Kortlepel 4cda6e8bc3 fully implement lua 2021-03-18 23:44:14 +02:00
Lion Kortlepel 459814a6ec add lua engine, lua file, server, client, vehicle data, other stuff 2021-03-18 23:44:14 +02:00
Lion Kortlepel e5e447c7af begin rewrite: add lionkor/commandline 2021-03-18 23:44:14 +02:00
Anonymous275 6a2ce7faab Update README.md 2021-03-17 12:49:15 +02:00
Anonymous275 ce8661159b Update README.md 2021-03-15 12:13:56 +02:00
Lion f5ecc251e7 Update README.md 2021-02-19 10:30:16 +01:00
Lion 45b3057ed5 Update README.md 2021-02-19 10:25:42 +01:00
Lion Kortlepel 0476ffa990 fix release build action 2021-02-13 23:06:09 +01:00
Lion Kortlepel 43690d0833 fix release action 2021-02-13 22:17:08 +01:00
Lion Kortlepel f9cb9af078 add real uptime counter, for use in lua later 2021-02-10 11:21:42 +01:00
Lion Kortlepel e4979bb6e2 change backend url 2021-02-10 11:21:42 +01:00
Lion 5266ac418b Update README.md 2021-02-04 11:00:07 +01:00
Lion ffca27ae6a Add releases link to windows prerequisites 2021-02-04 10:50:57 +01:00
Lion cd1aba7afb Fix headings (oops!) 2021-02-04 10:50:23 +01:00
Lion 50b3a9ea19 README.md: Add more explanations to dependencies 2021-02-04 10:49:58 +01:00
Lion d8f49edb6b Update README.md 2021-02-04 10:41:38 +01:00
Lion Kortlepel ec0987e5c1 heartbeat timeout 5s -> 500ms 2021-02-02 01:16:39 +01:00
Lion Kortlepel e4fa9a23fa use ipv4 always, until backend supports ipv6 2021-02-02 01:13:34 +01:00
Anonymous275 0fe4913928 removed unused includes 2021-02-02 02:01:57 +02:00
Lion bd349556f0 Actions fix (#11)
* update workflows to accomodate new requirements

* add boost to vkpkg

* try without boost again

* use boost just boost

* might cache vcpkg or might not idk

* dont pull everything in boost

* clean up includes

* fix 1

* fix 2

* fix 3

* fix 4

* fix id 6

* remove libssl again

* move to boost 1.71

* add boost to windows cmake

* change from boost 1.71 to 1.70

* fix cmake again

* remove version because f cmake

* remove stuff again

* fix my mistakes

* fix linker args for unix

* openssl

* add openssl to vcpkg

* uhh change whats linked

* rename OpenSSL to OPENSSL????
2021-02-02 00:50:27 +01:00
Anonymous275 dc9c3255de Merge pull request #10 from BeamMP/segfault-fix-1
PostHTTP rebuild, SegFault fix (fixes #8), good work.
2021-02-02 00:17:40 +02:00
Lion Kortlepel d5541ae154 add try/catch to PostHTTP 2021-02-01 23:13:58 +01:00
Lion 467e5a64c3 README: Make status badges clickable 2021-01-31 18:20:49 +01:00
Lion 3bb9b17d47 remove pull_request comment action 2021-01-31 03:25:49 +01:00
Lion 51f0b504b7 Update cmake-windows.yml 2021-01-31 03:25:28 +01:00
Lion 2e48cef647 Add automated release builds for windows & linux 2021-01-31 02:03:53 +01:00
Lion 0fe7050166 Update README.md
Change lionkor user in URL to BeamMP
2021-01-31 00:52:58 +01:00
Lion a25cc00093 add PR comment target to linux GH action 2021-01-31 00:40:47 +01:00
Lion e2e23635bc add PR comment target to linux GH action 2021-01-31 00:40:08 +01:00
Lion a20f632e3e squash commit for adding github actions 2021-01-31 00:31:55 +01:00
Lion Kortlepel 5f3fecb92c heartbeat every 30 seconds, or if anything changed, with a limit of once
every 5 seconds
2021-01-30 02:40:26 +01:00
Lion Kortlepel 710bb939ad change hearbeat update rate to 10 seconds 2021-01-30 02:02:47 +01:00
Lion Kortlepel 00b7d1ca96 Fix POST spamming issue 2021-01-30 02:01:53 +01:00
Lion Kortlepel 7e8b86cf57 return actual body instead of entire response (whoopsie!) 2021-01-30 01:39:55 +01:00
Lion Kortlepel d47e721b38 PostHTTP: try IPv6, then IPv4 on failure to connect() 2021-01-30 01:30:22 +01:00
Lion Kortlepel 33a7d0e1a1 start fixing behavior when IPv6 not supported 2021-01-30 01:23:54 +01:00
Lion Kortlepel 480c78c9f2 Working boost::beast POST request 2021-01-30 01:11:33 +01:00
Lion d0a7b56e75 Update README.md 2021-01-14 19:32:44 +01:00
Lion Kortlepel f6121704df implement SSL POST 2021-01-14 00:17:47 +01:00
Lion Kortlepel c75acbff76 fix hostnames 2021-01-13 22:41:38 +01:00
Lion Kortlepel d394d7b5a6 use boost beast instead of curl 2021-01-13 22:39:45 +01:00
Lion Kortlepel 4e1d2a7ddd try once more 2021-01-13 21:57:13 +01:00
Lion Kortlepel 2571cb1478 possible fix no 2 2021-01-13 21:51:07 +01:00
Lion Kortlepel c387cc3610 possible hotfix? 2021-01-13 21:45:26 +01:00
Lion Kortlepel 769c19b811 possibly fixes segfault issue on connect 2021-01-13 21:34:09 +01:00
Lion Kortlepel b62676daf4 use RAII for log file open/close 2021-01-12 10:55:02 +01:00
Lion cd19cd343a Update README.md
add "releases" link
2021-01-12 09:40:55 +01:00
Anonymous275 e0b7dd76fd Static server build 2021-01-07 23:45:17 +02:00
Anonymous275 fc4bc14ce5 Potential auth fix 2021-01-07 15:29:06 +02:00
Lion Kortlepel 61776d6a1b Client: inline trivial getters & setters 2021-01-02 03:19:51 +01:00
Lion Kortlepel 0f30706a0a Improve UDPRcvFromClient 2021-01-02 02:55:14 +01:00
Lion Kortlepel cb92833bfd Fix useless strlen & substr 2021-01-02 02:42:39 +01:00
Lion Kortlepel a21ca74c58 remove include 2021-01-02 02:39:18 +01:00
Lion Kortlepel e2611e13e0 Console.cpp: Fix console history crashes and inconsistent behavior 2021-01-02 01:00:35 +01:00
Lion Kortlepel 5fb7c459c6 main.cpp: use c++ header naming scheme 2021-01-02 00:10:01 +01:00
Lion d8e1d389bf Update README.md 2021-01-01 16:23:38 +01:00
Anonymous275 ae03b5f5ce Merge pull request #6 from BeamMP/license-file
Create LICENSE
2020-12-31 18:54:02 +02:00
Lion 2c6386013d Update README.md 2020-12-27 23:11:23 +01:00
Lion 3cb4c7cb67 Update README.md 2020-12-27 22:49:24 +01:00
Lion 229010647c Update README.md 2020-12-27 22:30:22 +01:00
Lion 03968f34b1 Update README.md 2020-12-27 22:28:15 +01:00
Lion Kortlepel 941287d22c remove debian build script again, rethinking this 2020-12-27 22:17:10 +01:00
Lion Kortlepel 8e4e0c0896 add debian build script for easier deployment 2020-12-27 22:13:24 +01:00
Lion Kortlepel c5d1682d5e CMake: Change minimum required version to 3.13, due to it being the
default in debian stable which we officially will support now, and
changed "lua" to find_directories result in UNIX linking of libraries
2020-12-27 22:06:48 +01:00
Lion Kortlepel 04cf7ca092 suppress unused variables 2020-12-24 00:42:39 +01:00
Lion Kortlepel 639c94e0f2 fixed my own mistake again again 2020-12-24 00:01:09 +01:00
Lion Kortlepel 623437e864 fix not calling curl_global_init in release mode 2020-12-23 23:57:27 +01:00
Lion Kortlepel fb420eac1b fix not memsetting in release mode (yikes) 2020-12-23 23:56:17 +01:00
Lion Kortlepel 0f33367f6b fixed what i broke 2020-12-23 23:52:51 +01:00
Lion Kortlepel 1a2c956d9e remove dead code in logger's SetThreadName 2020-12-23 23:45:28 +01:00
Lion Kortlepel de859f4762 remove Pos < 0 check as Pos is unsigned and never < 0 (always true) 2020-12-23 23:45:28 +01:00
Lion Kortlepel db152e09e9 reduce scope of some variables
reduce scope of R in Monitor

reduce scope of Temp in TCPSendRaw

reduce scope of Temp in TCPSend
2020-12-23 23:45:21 +01:00
Lion Kortlepel 561c0bb381 fix bug which caused kicking to be logged as normal leaving 2020-12-23 23:45:21 +01:00
Lion Kortlepel f60a44f65f remove some unused variables
remove unused variable

remove unused variable
2020-12-23 23:45:12 +01:00
Lion Kortlepel a944565fb9 reformat all 2020-12-23 23:34:30 +01:00
Lion Kortlepel 0f4c08c068 reformat all 2020-12-23 23:30:33 +01:00
Lion Kortlepel f0ad3732f4 fix misplaced include 2020-12-23 23:29:45 +01:00
Anonymous275 4adfda64c1 Switched to msvc 2019 2020-12-24 00:16:40 +02:00
Anonymous275 306fbc5eb4 Cleaning headers 2020-12-23 23:56:43 +02:00
Lion fac1b43b44 Create LICENSE
please read over this and make sure its solid enough
2020-12-23 21:51:51 +01:00
Anonymous275 b22a9566f9 Update README.md 2020-12-23 21:02:25 +02:00
Anonymous275 6f0c69904c Update README.md 2020-12-23 20:52:09 +02:00
Anonymous275 e049b1bbf4 Folder cleanup 2020-12-22 10:20:30 +02:00
Anonymous275 ef8f8645f7 Final Commit v1.20 2020-12-22 00:25:55 +02:00
Anonymous275 f94252d37b Update Sync.cpp 2020-12-20 16:04:15 +02:00
Anonymous275 8f042a3ee4 Update README.md 2020-12-20 15:29:46 +02:00
Anonymous275 435c397d02 Small edit 2020-12-20 15:14:23 +02:00
Anonymous275 97d8f9506e more cleanup 2020-12-20 14:11:29 +02:00
Anonymous275 2e7f2cc6bd Support of 1Gps+ internet 2020-12-19 01:15:52 +02:00
Anonymous275 19b7f7f579 new auth system + major optimization 2020-12-16 01:36:35 +02:00
Anonymous275 6a29384b5c cleaned comment 2020-11-27 10:34:13 +02:00
Anonymous275 69da77937d UDP Cleanup 2020-11-25 20:26:47 +02:00
Lion Kortlepel 5cf97850d7 add nobuiltin flag for gcc 2020-11-24 01:28:35 +01:00
Anonymous275 ad844db7fe v1.13 2020-11-21 00:29:30 +02:00
Lion Kortlepel 6a8d097dc5 fixup 2020-11-17 23:25:59 +01:00
Lion Kortlepel e2a45601b3 possibly fix recurring backend timeout 2020-11-17 23:21:45 +01:00
Lion Kortlepel a78f65b274 fix getch spin 2020-11-17 23:21:45 +01:00
Anonymous275 04de729d7c console setup errors will no longer deny a server startup 2020-11-17 08:28:02 +02:00
Anonymous275 667a22b0f8 Fixed lua command not registered for console 2020-11-16 21:09:13 +02:00
Lion Kortlepel e12b7da27f lua unique_ptr to shared_ptr 2020-11-16 16:48:00 +01:00
Lion Kortlepel 450f6d7139 rearrange cmakelists 2020-11-16 15:39:23 +01:00
Anonymous275 086bcb5ecc Server 1.1 2020-11-16 02:45:32 +02:00
Anonymous275 ac05cb5d0e Added vehicle 't' case 2020-11-15 17:11:16 +02:00
Anonymous275 92c44b19c5 HotSwap linux fix 2020-11-14 23:26:42 +02:00
Anonymous275 2a0939891b Merge branch 'master' of https://github.com/Starystars67/BeamNG-MP-Server 2020-11-14 00:10:16 +02:00
Anonymous275 e0b1a5c91f Made Config private by default 2020-11-14 00:10:03 +02:00
Lion Kortlepel 5a275580a4 add Resources folder to gitignore 2020-11-13 22:58:18 +01:00
Lion Kortlepel 03ee46d293 fixed filename stuff in lua 2020-11-13 22:57:08 +01:00
Anonymous275 fb7ed95d1d small fix 2020-11-13 23:55:51 +02:00
Lion Kortlepel 21c9ac4f53 fixed missing backslash 2020-11-13 22:52:26 +01:00
Lion Kortlepel ab5da1d94b add boost_ to gitignore for linux dev 2020-11-13 22:45:03 +01:00
Lion Kortlepel 6710c18168 fix lua file stuff and more file stuff 2020-11-13 22:43:35 +01:00
Lion Kortlepel cdd9ef86ae fix history bug 2020-11-13 02:13:02 +01:00
Lion Kortlepel 85edadb6e4 use read(..., ..., 1) instead of getchar 2020-11-13 01:38:36 +01:00
Lion Kortlepel aa29530d92 fix identification & check thread issue with atomic bool 2020-11-13 00:17:27 +01:00
Lion Kortlepel 270cca40ac fix closesocketproper on windows 2020-11-12 23:39:04 +01:00
Lion Kortlepel c1633b6401 remove debug error 2020-11-12 23:22:14 +01:00
Lion Kortlepel fa9bc16038 CloseSocketProper instead of closesocket 2020-11-12 23:20:37 +01:00
Lion Kortlepel fedca58e8e remove Temp < 0 message for now 2020-11-12 23:02:47 +01:00
Anonymous275 6ecf6c58ac Possible debug spam fix 2020-11-12 23:58:23 +02:00
Lion Kortlepel 954d55c1a6 minor format fixes 2020-11-12 17:11:51 +01:00
Lion Kortlepel 58e65cf43f clang-format everything 2020-11-12 17:09:14 +01:00
Lion Kortlepel c9f5ee9729 log any and every time we closesocket 2020-11-12 03:00:32 +01:00
Lion Kortlepel 583819070b add Client( ) around player name in TID output 2020-11-12 02:40:01 +01:00
Lion Kortlepel 9ddab14f01 possibly fix port in use 2020-11-12 02:35:11 +01:00
Lion Kortlepel d44aa86ed1 shutdown the socket on linux as well 2020-11-12 02:31:11 +01:00
Lion Kortlepel 7a5861a917 add tid print to check thread in identification 2020-11-12 02:24:41 +01:00
Lion Kortlepel 5e603c65b6 fix timeout in identification 2020-11-12 02:22:49 +01:00
Lion Kortlepel 3137f4e9db comment out timeout thread for now 2020-11-12 02:02:26 +01:00
Lion Kortlepel 80c5341650 add last error for windows as well 2020-11-12 01:56:50 +01:00
Lion Kortlepel cde41f01b2 error on send failure 2020-11-12 01:52:44 +01:00
Lion Kortlepel be7e2f1616 possible fix for ping=? 2020-11-12 01:33:35 +01:00
Anonymous275 cdb2624367 Made the server make sure there is only 1 connection 2020-11-12 01:40:26 +02:00
Lion Kortlepel 308500c01f Fix multiple small issues :) 2020-11-11 11:24:36 +01:00
Lion Kortlepel 8f05cdcc61 Replace some mutex locks with scoped locks 2020-11-11 00:20:14 +01:00
Anonymous275 94f6a81673 lua error fix 2020-11-11 00:40:22 +02:00
Lion Kortlepel 60c7997c6b Ignore SIGPIPE so we dont crash on broken pipes 2020-11-09 23:34:44 +01:00
Lion Kortlepel 2d11841a68 Fix crashing when port checking, remove debug prints 2020-11-09 23:34:06 +01:00
Lion Kortlepel 01e02edf8c Add clear with "clear", "cls" and Ctrl+L 2020-11-09 00:01:04 +01:00
Lion Kortlepel 52bf3cdd21 YAFFWH - Yet another fix for win32 history 2020-11-08 23:45:59 +01:00
Lion Kortlepel 1bbe88b240 Fix history on win32 again 2020-11-08 23:39:00 +01:00
Lion Kortlepel 5fc6c3ddd7 Implemented history on windows 2020-11-08 23:30:32 +01:00
Lion Kortlepel d226b36f44 enable console history again on win32 2020-11-08 23:24:04 +01:00
Lion Kortlepel 7ab37b7fe9 Properly add RWMutex 2020-11-08 22:39:20 +01:00
Lion Kortlepel 747e948339 Fix console behavior on win32 2020-11-08 22:16:56 +01:00
Lion Kortlepel 7fce274915 Fix printing, make CI into unique_ptr (more) 2020-11-08 21:46:02 +01:00
Anonymous275 b663563f01 TCP header fix 2020-11-08 22:17:45 +02:00
Anonymous275 8e9bf46778 lot of work 2020-11-08 21:48:44 +02:00
Lion Kortlepel c6fbd3dc49 Add more memory safety, fix print(nil) crash 2020-11-08 14:44:49 +01:00
Lion Kortlepel b9758ddaea ProcessCompositeInput: ensure we dont cause UB on memcmp 2020-11-08 14:31:15 +01:00
Lion Kortlepel e42256dd5f Shrink history size to 10 soft 20 hard 2020-11-08 14:21:44 +01:00
Lion Kortlepel 0b71d77a48 Add console history. 2020-11-08 14:18:49 +01:00
Lion Kortlepel 1e5faea1a4 Fix console _getch behavior on unix 2020-11-08 13:32:45 +01:00
Lion Kortlepel 4ecd57fed4 Only show ThreadNames in server debug MODE 2020-11-08 13:06:38 +01:00
root b8bd939bd7 Add build instructions for linux, fix some cmake issues 2020-11-08 06:54:59 -05:00
Lion Kortlepel 1ef6cf53a2 Add endian-correctness to TCPSend&Rcv (parallel to the Launcher commit) 2020-11-08 11:52:32 +01:00
Lion Kortlepel 26383d5346 Add lots of memory safety to client interface 2020-11-08 02:50:17 +01:00
Lion Kortlepel 96668add6e Safety improvements 2020-11-08 02:29:06 +01:00
Lion Kortlepel 437a654b90 Added thread names to logs 2020-11-08 02:28:40 +01:00
Lion Kortlepel a42ab67d2f Minor fixes 2020-11-08 01:31:34 +01:00
Lion Kortlepel fe6cfd027e fix some unix stuff 2020-11-07 23:40:53 +01:00
Anonymous275 a08d29a0ae Vehicle ghost fix, player list fix 2020-11-07 23:29:06 +02:00
Anonymous275 2021f0b461 fixed debug output, server exit hang, crashes 2020-11-07 18:52:03 +02:00
Anonymous275 5b92cbc0be wesocket base 2020-11-07 02:35:50 +02:00
Anonymous275 757c63bddb Update CMakeLists.txt 2020-11-07 00:09:50 +02:00
Anonymous275 77f811b7a8 websocket wip 2020-11-06 23:58:47 +02:00
Lion Kortlepel 6bebc4c160 Fix lua imports, fix linux backspace behaviour in console 2020-11-06 15:50:03 +01:00
Anonymous275 e5a0d43024 fixed windows build 2020-11-06 16:43:18 +02:00
Lion Kortlepel b49abe02eb Merge pull request #4 from Starystars67/cross-platform
Cross platform
2020-11-06 14:30:11 +01:00
Lion Kortlepel 3eb2bd0dfc possibly fixed UDPSend error on unix 2020-11-06 01:58:36 +01:00
Lion Kortlepel 775e46788c fix SendAll again 2020-11-06 01:40:08 +01:00
Lion Kortlepel 1de29dc5e4 fix assert in SendToAll 2020-11-06 01:34:55 +01:00
Lion Kortlepel e41b3df095 fix glaring f*cking error 2020-11-06 01:07:55 +01:00
Lion Kortlepel 24eaa1e079 add even more prints 2020-11-06 00:58:25 +01:00
Lion Kortlepel 8ba89e491f add even more debugging prints 2020-11-06 00:54:05 +01:00
Lion Kortlepel 6a3b933df1 more verbose errors 2020-11-06 00:31:35 +01:00
Lion Kortlepel f0c87341ab implement size header for auth 2020-11-05 23:57:07 +01:00
Anonymous275 fbbdc084a4 Windows compile fix 2020-11-05 16:49:49 +02:00
Lion Kortlepel 36db73b562 Add more safety on some memory handling 2020-11-04 14:35:28 +01:00
Lion Kortlepel f2d87078ae Fix various memory leaks with RAII 2020-11-04 13:10:45 +01:00
Lion Kortlepel 5452aeb558 Fix race condition in debug build printing 2020-11-04 11:58:09 +01:00
Lion Kortlepel 2beff2495f Fix backspace behavior, random printing of > 2020-11-03 13:41:23 +01:00
Lion Kortlepel 9bae155439 dont assert at all in release mode 2020-11-03 12:53:19 +01:00
Lion Kortlepel c5c21c43ad Implement various WIN32 fixes 2020-11-03 12:50:35 +01:00
Lion Kortlepel f144d451c7 Fixup 2020-11-03 12:14:19 +01:00
Lion Kortlepel ddd9c55822 Disable _s warnings on msvc 2020-11-03 12:12:27 +01:00
Lion Kortlepel 801ea3f777 Fix windows naming issue with assert 2020-11-03 12:10:08 +01:00
Lion Kortlepel e986df0579 change __WIN32 to WIN32 (oops) 2020-11-03 12:01:31 +01:00
Lion Kortlepel e9432ac1ca add WIN32 and UNIX specific cmake instructions 2020-11-03 11:48:42 +01:00
Lion Kortlepel aa73a9d16a Assert nullptrs in VehicleData
we'll nuke this file anyways, but for now lets be safe about ptrs.
2020-11-03 10:38:44 +01:00
Lion Kortlepel b2166402a2 Print TIDs in every new thread 2020-11-03 10:22:49 +01:00
Lion Kortlepel 2ec65d5b84 Implement Assertion properly, TID printing in debug builds 2020-11-03 10:13:52 +01:00
Lion Kortlepel 69f20bdf41 Add TID debug printing 2020-11-03 09:36:00 +01:00
Lion Kortlepel 289bb1c1f3 add *Server.cfg* rule to gitignore 2020-11-03 09:03:01 +01:00
Lion Kortlepel eead954bf9 Fix Console on Unix, adapt console behavior to that of a traditional
console, add Assert.h, add clang-format file with modified WebKit style
2020-11-03 09:01:58 +01:00
root 13e79e407c add support for std::filesystem on older compilers 2020-11-01 06:48:31 -05:00
Lion Kortlepel 4d259c9d25 add cmake lists for debian 2020-11-01 12:46:16 +01:00
Lion Kortlepel 953131289d Fix compiler warnings, explicitly cast by default 2020-11-01 12:19:19 +01:00
Lion Kortlepel 8bc35fb82e Refactor to work on Linux / Unix, fix some compiler errors.
CMakeLists was also modified to make this work, but its scuffed
and i will hold on to that for a while longer
2020-11-01 02:00:27 +01:00
Anonymous275 02fbe72eed lib push 2020-10-31 15:18:28 +02:00
Anonymous275 2604308094 lib sync 2020-10-31 15:15:26 +02:00
Anonymous275 6787f43889 removed file 2020-10-31 15:10:11 +02:00
Anonymous275 7e917e99a1 Merge branch 'master' of https://github.com/Starystars67/BeamNG-MP-Server 2020-10-31 15:05:03 +02:00
Anonymous275 9adc633c2f Update .gitignore 2020-10-31 15:03:49 +02:00
Anonymous275 030944ebc2 Add files via upload 2020-10-31 15:01:30 +02:00
Anonymous275 90458cbf72 Delete libcurl_a.lib 2020-10-31 14:57:00 +02:00
Anonymous275 3bdc75b0c0 server input 2020-10-31 14:55:00 +02:00
Anonymous275 71a84b4f1b Server update 0.63.5
- async lua implementation
- cleaner backend heartbeat
- two way encryption on connect
- async tcp buffer
- disconnect handler
- cleaned UDP implementation
2020-10-16 17:05:31 +03:00
Anonymous275 31c96cee94 V0.6
rewrite
2020-08-21 20:58:10 +03:00
Anonymous275 232c4d7b28 Crash Handeling 2020-07-11 00:03:37 +03:00
Anonymous275 303647a8c3 added 2 lua events fixed chat messages lagging 2020-07-09 20:54:02 +03:00
Anonymous275 92cc1cb0fd minor tweaks 2020-07-06 21:30:09 +03:00
Anonymous275 c83bc7864a v1.48 2020-07-04 23:58:47 +03:00
Anonymous275 83c095ba17 memory leak fix, now uses less than 5MB of memory 2020-07-04 15:58:53 +03:00
Anonymous275 69362b2dfd Ready for release 2020-07-03 16:22:54 +03:00
Anonymous275 e7c1bdd872 Server now support over 9 Petabytes of mod 2020-07-03 00:58:00 +03:00
Anonymous275 6c93ea7fb2 v0.43 2020-07-02 00:20:35 +03:00
Anonymous275 1b8c7abea5 stability improvements, tweaks 2020-06-27 16:58:02 +03:00
Anonymous275 c5e1175f1a fixed vehicle spawn issue 2020-06-23 22:11:32 +03:00
Anonymous275 ed0e35400d Security Improvements 2020-06-22 23:03:29 +03:00
Anonymous275 3d29067cab Lua function revisions 2020-06-22 18:59:48 +03:00
Anonymous275 354ff30b90 bug fix 2020-06-21 19:11:26 +03:00
Anonymous275 834db5ecc1 minor bug fix 2020-06-20 17:19:10 +03:00
Anonymous275 62928ece9c statistics 2020-06-20 14:55:27 +03:00
Anonymous275 280e3a8daa Statistic reports mainly packets per second 2020-06-18 21:55:58 +03:00
Anonymous275 a05acee04f Mod Sync 2020-06-13 01:06:28 +03:00
Anonymous275 ed6b2d236a small commit 2020-06-04 17:03:42 +03:00
Anonymous275 80c3280e4e Major rewrite, speed, and stability improvements 2020-06-04 01:52:33 +03:00
Anonymous275 ff2d5d74ae minor adjustments 2020-05-27 10:24:23 +03:00
Anonymous275 375c4a4952 17h of work 2020-05-26 19:13:27 +03:00
Anonymous275 49c38a0f00 Ack system 2020-05-13 21:54:06 +03:00
Anonymous275 ba47f21898 added "isConnected" to the Client Object 2020-05-12 08:56:20 +03:00
Anonymous275 131e64b706 Major rewrite of the network 2020-05-10 23:37:45 +03:00
Anonymous275 b0c6c2bac4 lots of work 2020-05-04 01:17:16 +03:00
Anonymous275 2d360610fc added debug and release libraries 2020-05-02 17:33:55 +03:00
Anonymous275 25a5cd75c6 fixed a crash, added network codes 2020-05-02 17:25:44 +03:00
Anonymous275 851343eedb Fixed timeout, added vehicle data tracker 2020-05-01 18:42:17 +03:00
Anonymous275 a85da1e05e Disconnect handler + role sync 2020-04-24 18:58:59 +03:00
Anonymous275 ce7abdc960 working vehicle sync 2020-04-18 22:40:15 +03:00
Anonymous275 60c38ccd1a Minor Adjustments 2020-04-18 04:48:42 +03:00
Anonymous275 2a3df072d1 small improvement 2020-04-18 03:56:34 +03:00
Anonymous275 1636ae3286 Fixed Crash 2020-04-18 00:50:41 +03:00
Anonymous275 123cb4f1a2 data transfer fixes+handlers 2020-04-18 00:06:37 +03:00
Anonymous275 d368b154c2 Auto name request + parser 2020-04-17 00:47:13 +03:00
Anonymous275 b5dbb70104 high accuracy ping + cleanup 2020-04-16 22:55:22 +03:00
Anonymous275 5cb43950eb cleanup and ping fix 2020-04-16 00:00:10 +03:00
Anonymous275 8d56873335 Map name transfer 2020-04-15 03:04:26 +03:00
Anonymous275 d50f205787 Working Mod Sync 2020-04-14 01:01:06 +03:00
Anonymous275 9a47f651fc 4h of work 2020-04-12 01:14:16 +03:00
Anonymous275 e60790e185 yes 2020-04-10 21:53:08 +03:00
Starystars67 7410625fce xxx 2020-04-10 19:51:19 +01:00
Anonymous275 29e77b147c Fixed 2020-04-10 21:42:04 +03:00
Starystars67 9bdec9e5f8 i broke it some what sorry Anon 2020-04-10 19:14:06 +01:00
Anonymous275 388cffbe01 Curl 2020-04-10 02:14:48 +03:00
Anonymous275 640a9c2e54 Functions and new Config 2020-04-09 21:32:32 +03:00
Anonymous275 3c244c7e7f commit 2020-04-09 20:37:38 +03:00
Anonymous275 104856938a Merge branch 'master' of https://github.com/Starystars67/BeamNG-MP-Server 2020-03-09 23:41:02 +02:00
Anonymous275 f427cb8d06 Fixed Data size 2020-03-09 23:40:29 +02:00
jojos38 fef98347e7 Update .gitignore
Updated gitignore for VS
2020-03-07 12:37:10 +01:00
Anonymous275 e2cae1da59 fixed Crash issue added serverVehicleID and gameVehicleID 2020-02-06 23:20:09 +02:00
Anonymous275 4503338378 fixed time log 2020-02-06 17:40:07 +02:00
Anonymous275 c47e8783e6 Added ClientHandler + Polished some code 2020-02-04 21:55:02 +02:00
Starystars67 4e47f36d84 Merge branch 'master' of https://github.com/Starystars67/BeamNG-MP-Server 2020-02-04 17:29:15 +00:00
Starystars67 3ba8e55e59 added heartbeat cpp + h, needs functionality 2020-02-04 17:29:04 +00:00
Anonymous275 56bd547823 Renamed MaxClients to MaxPlayers 2020-02-04 19:05:27 +02:00
Anonymous275 996d96639c Small Bug fix 2020-02-03 22:07:22 +02:00
Anonymous275 54319f7cdd Fully Polished the loggin system 2020-02-03 21:52:11 +02:00
Anonymous275 60a0d13e63 File Cleaning 2020-01-29 21:33:53 +02:00
Anonymous275 9034319685 Server Implementation 2020-01-29 21:32:31 +02:00
Anonymous275 7d5c5a4526 Update .gitignore 2020-01-29 21:29:03 +02:00
Anonymous275 1f620f4093 Server Listener
Implemented the basic server system and routed the data to a new class for processing.
2020-01-29 21:27:26 +02:00
jojos38 dbaf7d5de0 Using logger for config 2020-01-28 18:37:57 +01:00
Anonymous275 ea3d6204d3 Fixed A lot of stuff + removed color system 2020-01-28 19:30:11 +02:00
Anonymous275 12fc4dfadf Merge pull request #2 from Starystars67/development
Development
2020-01-28 19:03:46 +02:00
Anonymous275 6ab7da167f CMake Update 2020-01-28 19:02:56 +02:00
Anonymous275 791088274e WE NEED THIS xD 2020-01-28 19:01:53 +02:00
Anonymous275 be42564e26 Update .gitignore 2020-01-28 17:28:52 +02:00
Anonymous275 cd3933364f Main Fix
Fixed the Main
2020-01-28 17:10:58 +02:00
Anonymous275 04cc140851 Main Fix
you overwrote my main in the master branch so i added your logger code in the main i had on my local machine
2020-01-28 17:09:16 +02:00
jojos38 35eebe95ad Improved logger
Improved logger
2020-01-28 15:47:55 +01:00
jojos38 b3a26c9897 Added Logger system + Server
Added Logger system + Server
2020-01-28 15:03:51 +01:00
jojos38 4c3f32438c Added enet lib
Added enet lib
2020-01-28 12:22:11 +01:00
jojos38 b63824727a Added network file
Added network file
2020-01-28 11:34:37 +01:00
jojos38 50fe521d47 Revert "c"
This reverts commit 66fa203eb6.
2020-01-28 11:33:10 +01:00
jojos38 66fa203eb6 c
#include <iostream>
2020-01-28 11:33:06 +01:00
Антон b49a2a28f4 init commit 2020-01-28 00:54:49 +05:00
Mitch Durso 713a2af75c Initial commit 2020-01-27 19:33:34 +00:00
108 changed files with 9416 additions and 5887 deletions
+5
View File
@@ -0,0 +1,5 @@
---
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
...
+28
View File
@@ -0,0 +1,28 @@
---
name: Bug report
about: Create a report to help us improve
labels: bug
assignees: ''
---
**Fill out general information**
OS (windows, linux, ...):
BeamMP-Server Version:
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Do x ...
2. Do y ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
Please attach the `Server.log` from the run in which the issue appeared, preferably with Debug turned on in the `ServerConfig.toml`.
**Additional context**
Add any other context about the problem here.
+19
View File
@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
labels: feature
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. For example: "I'm always frustrated when ...".
**Describe the solution you'd like**
A clear and concise description of what you want to happen. Also supply OS information if relevant, for example "*On Linux*, I would like to be able to...".
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context about the feature request here.
+123
View File
@@ -0,0 +1,123 @@
name: Linux
on: [push]
env:
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
CMAKE_BUILD_TYPE: "Release"
jobs:
debian-11-build:
runs-on: ubuntu-latest
container:
image: debian:11
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 || '');
- 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/debian-11/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/debian-11/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-debian
path: ./bin/BeamMP-Server
- name: Archive server debug info artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-debian.debug
path: ./bin/BeamMP-Server.debug
- name: Build Tests
run: bash ./scripts/debian-11/3-build-tests.sh
- name: Install Runtime Dependencies
run: bash ./scripts/debian-11/4-install-runtime-deps.sh
- name: Test
run: ./bin/BeamMP-Server-tests
ubuntu-22-04-build:
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
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 || '');
- 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/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/ubuntu-22.04/3-build.sh
- name: Archive server artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-ubuntu
path: ./bin/BeamMP-Server
- name: Archive server debug info artifact
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-ubuntu.debug
path: ./bin/BeamMP-Server.debug
- name: Build Tests
run: bash ./scripts/ubuntu-22.04/3-build-tests.sh
- name: Install Runtime Dependencies
run: bash ./scripts/ubuntu-22.04/4-install-runtime-deps.sh
- name: Test
run: ./bin/BeamMP-Server-tests
+191
View File
@@ -0,0 +1,191 @@
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"
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. You need to install the [Visual C++ Redistributables](https://aka.ms/vs/17/release/vc_redist.x64.exe) to run this.
- `BeamMP-Server-debian` is a Debian 11 build, requires `liblua5.3-0`.
- `BeamMP-Server-ubuntu` is a Ubuntu 22.04 build, requires `liblua5.3-0`.
upload-release-files-debian-11:
name: Build and upload Debian 11 Release Files
runs-on: ubuntu-22.04
needs: create-release
container:
image: debian:11
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 || '');
- 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/debian-11/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/debian-11/1-install-deps.sh
- name: Setup vcpkg
uses: lukka/run-vcpkg@v11
with:
runVcpkgInstall: true
- name: Create Build Environment
run: bash ./scripts/debian-11/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/debian-11/3-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/BeamMP-Server
asset_name: BeamMP-Server-debian
asset_content_type: application/x-elf
- name: Upload Debug Info
id: upload-debug-info
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_name: debuginfo-debian.debug
asset_content_type: application/x-elf
upload-release-files-ubuntu-22-04:
name: Build and upload Ubuntu 22.04 Release Files
runs-on: ubuntu-22.04
needs: create-release
container:
image: ubuntu:22.04
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 || '');
- 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/ubuntu-22.04/1.5-git-safe.sh
- name: Install Dependencies
run: bash ./scripts/ubuntu-22.04/1-install-deps.sh
- name: Create Build Environment
run: bash ./scripts/ubuntu-22.04/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build Server
run: bash ./scripts/ubuntu-22.04/3-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/BeamMP-Server
asset_name: BeamMP-Server-ubuntu
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:
upload_url: ${{ needs.create-release.outputs.upload_url }}
asset_path: ./bin/BeamMP-Server.debug
asset_name: debuginfo-ubuntu.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
-21
View File
@@ -1,21 +0,0 @@
name: Rust
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
+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
+481 -4
View File
@@ -1,4 +1,481 @@
/target
/.idea
ServerConfig.toml
beammp_rust_server.iml
.idea/
.sentry-native/
*.orig
*.toml
boost_*
Resources
run-in-env.sh
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
#VS Files
out/
#Clion Files
cmake-build-debug/
cmake-build-release/
.idea/
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
out/build/x86-Debug/VSInheritEnvironments.txt
out/build/x86-Debug/rules.ninja
out/build/x86-Debug/CMakeFiles/untitled.dir/manifest.res
out/build/x86-Debug/CMakeFiles/untitled.dir/manifest.rc
out/build/x86-Debug/CMakeFiles/untitled.dir/intermediate.manifest
out/build/x86-Debug/CMakeFiles/untitled.dir/embed.manifest
out/build/x86-Debug/CMakeFiles/TargetDirectories.txt
out/build/x86-Debug/CMakeFiles/ShowIncludes/main.c
out/build/x86-Debug/CMakeFiles/ShowIncludes/foo.h
out/build/x86-Debug/CMakeFiles/cmake.check_cache
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.exe
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.cpp
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.exe
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.c
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeSystem.cmake
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeRCCompiler.cmake
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_CXX.bin
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_C.bin
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCXXCompiler.cmake
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCCompiler.cmake
out/build/x86-Debug/CMakeCache.txt
out/build/x86-Debug/cmake_install.cmake
out/build/x86-Debug/build.ninja
out/build/x86-Debug/.ninja_log
out/build/x86-Debug/.ninja_deps
out/build/x86-Debug/.cmake/api/v1/reply/target-untitled-Debug-03f16c5921ae0bd48990.json
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-27T23-42-34-0718.json
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-2b93246ca751d7a49cd1.json
out/build/x86-Debug/.cmake/api/v1/reply/cmakeFiles-v1-d93b224eb363971ee2c4.json
out/build/x86-Debug/.cmake/api/v1/reply/cache-v2-43521627501184045d13.json
out/build/x86-Debug/.cmake/api/v1/query/client-MicrosoftVS/query.json
out/build/x64-Debug/VSInheritEnvironments.txt
out/build/x64-Debug/rules.ninja
out/build/x64-Debug/CMakeFiles/untitled.dir/manifest.res
out/build/x64-Debug/CMakeFiles/untitled.dir/manifest.rc
out/build/x64-Debug/CMakeFiles/untitled.dir/intermediate.manifest
out/build/x64-Debug/CMakeFiles/untitled.dir/embed.manifest
out/build/x64-Debug/CMakeFiles/TargetDirectories.txt
out/build/x64-Debug/CMakeFiles/ShowIncludes/main.c
out/build/x64-Debug/CMakeFiles/ShowIncludes/foo.h
out/build/x64-Debug/CMakeFiles/cmake.check_cache
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.exe
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.cpp
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.exe
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.c
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeSystem.cmake
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeRCCompiler.cmake
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_CXX.bin
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_C.bin
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCXXCompiler.cmake
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCCompiler.cmake
out/build/x64-Debug/CMakeCache.txt
out/build/x64-Debug/cmake_install.cmake
out/build/x64-Debug/build.ninja
out/build/x64-Debug/.ninja_log
out/build/x64-Debug/.ninja_deps
out/build/x64-Debug/.cmake/api/v1/reply/target-untitled-Debug-8918286eee207fe0275b.json
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-27T23-42-03-0431.json
out/build/x64-Debug/.cmake/api/v1/reply/codemodel-v2-ee254da00ecbf4b22928.json
out/build/x64-Debug/.cmake/api/v1/reply/cmakeFiles-v1-ee926bd040d82c324cbe.json
out/build/x64-Debug/.cmake/api/v1/reply/cache-v2-6f7cb0917968b934d35c.json
out/build/x64-Debug/.cmake/api/v1/query/client-MicrosoftVS/query.json
CMakeSettings.json
cmake-build-debug/Resource1.resx
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T10-34-19-0746.json
out/build/x64-Debug/untitled.exe
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T11-19-41-0061.json
out/build/x64-Debug/.cmake/api/v1/reply/cmakeFiles-v1-52c1d9386071c1490278.json
out/build/x86-Debug/CMakeFiles/cmake-main.dir/manifest.res
out/build/x86-Debug/CMakeFiles/cmake-main.dir/manifest.rc
out/build/x86-Debug/CMakeFiles/cmake-main.dir/intermediate.manifest
out/build/x86-Debug/CMakeFiles/cmake-main.dir/embed.manifest
out/build/x86-Debug/cmake-main.exe
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-1cc90e5d191bd520f961.json
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-0c9bd3464adc40e447af.json
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T11-21-26-0362.json
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-1850e17888d5bab56568.json
out/build/x86-Debug/.cmake/api/v1/reply/cmakeFiles-v1-7c376457f6b736ad28ac.json
out/build/x64-Debug/CMakeFiles/cmake-main.dir/manifest.res
out/build/x64-Debug/CMakeFiles/cmake-main.dir/manifest.rc
out/build/x64-Debug/CMakeFiles/cmake-main.dir/intermediate.manifest
out/build/x64-Debug/CMakeFiles/cmake-main.dir/embed.manifest
out/build/x64-Debug/cmake-main.exe
out/build/x64-Debug/.cmake/api/v1/reply/target-enet-Debug-645fd45f5bd4fab53aa9.json
out/build/x64-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-b124668c8fb6ca5df286.json
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T11-21-06-0706.json
out/build/x64-Debug/.cmake/api/v1/reply/codemodel-v2-63a6ab1789a1732f4563.json
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-d301abed48f6c38bdcfb.json
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T12-30-44-0946.json
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-3eaabe43603befc605b1.json
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-70eff68e1e381b42992e.json
*.xml
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-48db38ae5d08e27876b8.json
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-540e487569703b71c785.json
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T17-35-38-0764.json
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-6a61e390ef8eaf17e9f8.json
out/build/x86-Debug/Server.cfg
*Server.cfg*
*.cmake
*.make
*.xml
*.includecache
cmake-build-release/include/commandline/Makefile
*.lib
*.cbp
*.marks
*.internal
*.xml
cmake-build-debug/include/commandline/Makefile
*.manifest
*.rc
*.res
BeamMP-Server
*.patch
callgrind.*
notes/*
compile_commands.json
nohup.out
+6
View File
@@ -0,0 +1,6 @@
[submodule "deps/commandline"]
path = deps/commandline
url = https://github.com/lionkor/commandline
[submodule "vcpkg"]
path = vcpkg
url = https://github.com/Microsoft/vcpkg.git
-82
View File
@@ -1,82 +0,0 @@
# BeamMP Protocol Documentation
WIP of course, but hope it helps others
## TCP
### Basic message format
All messages are sent as strings (?).
Every packet starts with a 4 byte header, denoting how many bytes the packet data is.
This means that you first must read 4 bytes from your socket, to get the header data, and afterwards read the data ready for reading.
### Communication flow
Upon client connection:
1. Authentication
2. Sync with client?
#### Authentication
1. C->S - Client sends the server a single byte. The BeamMP source checks for 3 letters, but I only saw C
2. C->S - Client sends a packet containing the client version
3. S->C - Server sends the server a regular packet containing only 1 byte: `S` (the ascii character)
4. C->S - Client sends the server its public key
5. S->C - Server sends the client their assigned server ID
#### Syncing resources
1. C->S - Client sends the server a packet with the code `SR`
2. S->C - Server sends the client a packet containing a filelist containing the name and size of files to download, or "-" if it's empty
### Packets
All packets start with a single character, denoted as "Packet Code" or simply "Code" down below.
The data mentioned is merely example data, to show the data format. This includes the code!
Example:
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `C` | C->S | Client version | VC2.0 |
#### Uncategorized
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `J` | S->C | Show a message in the top left on the clients screen | JWelcome Luuk! |
#### Authentication
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `C` | C->S | Client version | VC2.0 |
| `S` | S->C | Confirmation? | None |
| `D` | C->S | Start download phase? Seems unused from testing | None |
| `P` | S->C | Send client their assigned ID | P123 |
#### Syncing resources
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `SR` | C->S | Client requests a list containing all mods, containing their name and file size | None |
| `f` | C->S | Client requests file with name | fcool_mod.zip |
| `-` | S->C | Technically not a packet, see [Syncing Resources](https://github.com/Lucky4Luuk/beammp_rust_server/blob/master/BEAMMP_PROTOCOL_DOCS.md#syncing-resources), step 2. | * |
#### Syncing client state
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `H` | C->S | Client requests a full sync with the server state | None |
### Vehicle packets
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `Os` | C->S | Client informs server they are spawning a car | Os:C_ID:{car_json} |
| `Os` | S->C | Server sends this packet to all clients, informing them a client has spawned a car | Os:C_ROLES:C_NAME:C_ID-CAR_ID:CAR_JSON |
| `Or` | C->S | Client informs server they are respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
| `Or` | S->C | Server informs all other clients that a client is respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
| `Od` | C->S | Client informs server they are deleting their car | Od:C_ID-CAR_ID |
| `Od` | S->C | Server informs all other clients that a client is deleting their car | Od:C_ID-CAR_ID |
| `Oc` | C->S | Client informs server they are editing their car | Oc:?... |
| `Oc` | S->C | Server informs all other clients that a client has edited their car | Oc:?... |
## UDP
### Packets
#### Uncategorized
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `p` | C->S | Ping! | None |
| `p` | S->C | Pong! | None |
#### Vehicle related
| Code | Dir | Explanation | Data |
| ---- | --- | ----------- | ---- |
| `Zp` | C->S | Positional packet | Zp:C_ID-CAR_ID:{transform_json} |
+215
View File
@@ -0,0 +1,215 @@
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
if (WIN32)
set(VCPKG_TARGET_TRIPLET x64-windows-static)
endif()
include(cmake/Vcpkg.cmake) # needs to happen before project()
project(
"BeamMP-Server" # replace this
VERSION 3.3.0
)
include(cmake/StandardSettings.cmake)
include(cmake/StaticAnalyzers.cmake)
include(cmake/Git.cmake)
# below are options which should be changed
### SETTINGS ###
# add all headers (.h, .hpp) to this
set(PRJ_HEADERS
include/ArgsParser.h
include/BoostAliases.h
include/Client.h
include/Common.h
include/Compat.h
include/Cryptography.h
include/CustomAssert.h
include/Defer.h
include/Environment.h
include/Http.h
include/IThreaded.h
include/Json.h
include/LuaAPI.h
include/RWMutex.h
include/SignalHandling.h
include/TConfig.h
include/TConsole.h
include/THeartbeatThread.h
include/TLuaEngine.h
include/TLuaPlugin.h
include/TNetwork.h
include/TPluginMonitor.h
include/TPPSMonitor.h
include/TResourceManager.h
include/TScopedTimer.h
include/TServer.h
include/VehicleData.h
include/Update.h
)
# add all source files (.cpp) to this, except the one with main()
set(PRJ_SOURCES
src/ArgsParser.cpp
src/Client.cpp
src/Common.cpp
src/Compat.cpp
src/Http.cpp
src/LuaAPI.cpp
src/SignalHandling.cpp
src/TConfig.cpp
src/TConsole.cpp
src/THeartbeatThread.cpp
src/TLuaEngine.cpp
src/TLuaPlugin.cpp
src/TNetwork.cpp
src/TPluginMonitor.cpp
src/TPPSMonitor.cpp
src/TResourceManager.cpp
src/TScopedTimer.cpp
src/TServer.cpp
src/VehicleData.cpp
src/Update.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
${LUA_LIBRARIES}
)
# 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)
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)
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()
+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.
Generated
-1801
View File
File diff suppressed because it is too large Load Diff
-36
View File
@@ -1,36 +0,0 @@
[package]
name = "beammp_rust_server"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4"
pretty_env_logger = "0.4.0"
argh = "0.1.12"
lazy_static = "1"
anyhow = "1.0.66"
glam = "0.24.2"
num_enum = "0.5.7"
async-trait = "0.1.58"
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "net", "io-util", "sync"] }
futures = "0.3.29"
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1.0", features = ["derive"] }
serde-aux = "4.2.0"
serde_json = "*"
toml = "0.5"
flate2 = "1.0"
mlua = { version = "0.9.1", features = ["lua54", "vendored", "send"] }
ratatui = "0.24.0"
crossterm = "0.27.0"
uuid = "1.6.1"
-37
View File
@@ -1,37 +0,0 @@
# This is the BeamMP-Server config file.
# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`
# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under "Keys"
[General]
Name = "bepis big gaming"
Port = 30814
# AuthKey has to be filled out in order to run the server
AuthKey = "test"
# Whether to log chat messages in the console / log
LogChat = true
Debug = false
Private = true
MaxCars = 20
MaxPlayers = 800000
Map = "/levels/west_coast_usa/info.json"
Description = "BeamMP Default Description"
ResourceFolder = "Resources"
[Misc]
# 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.
ImScaredOfUpdates = false
# 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`
SendErrorsShowMessage = true
# You can turn on/off the SendErrors message you get on startup here
SendErrors = true
[HTTP]
# 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.
HTTPServerIP = "127.0.0.1"
SSLKeyPath = "./.ssl/HttpServer/key.pem"
SSLCertPath = "./.ssl/HttpServer/cert.pem"
HTTPServerPort = 8080
# Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files
UseSSL = false
# Enables the internal HTTP server
HTTPServerEnabled = false
+2
View File
@@ -0,0 +1,2 @@
Copyright (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor). BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
-661
View File
@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
BeamMP Server implemented in Rust
Copyright (C) 2023 - Luuk van Oijen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
+89 -4
View File
@@ -1,5 +1,90 @@
# BeamMP Server
A BeamMP server implementation in Rust, meant to (hopefully) replace the official server implementation one day.
# BeamMP-Server
## Features
TODO
[![CMake Windows Build](https://github.com/BeamMP/BeamMP-Server/workflows/CMake%20Windows%20Build/badge.svg?branch=master)](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Windows+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/).
The server is the point through which all clients communicate. You can write Lua mods for the server, there are detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
**For Linux, you __need__ the runtime dependencies, which are listed below under [Runtime Dependencies](#runtime-dependencies)**
## Support + Contact
Feel free to ask any questions via the following channels:
- **Discord**: [click for invite](https://discord.gg/beammp)
- **BeamMP Forum**: [BeamMP Forum Support](https://forum.beammp.com/c/support/33)
## Minimum Requirements
These values are guesstimated and are subject to change with each release.
* RAM: 50+ MiB usable (not counting OS overhead)
* CPU: >1GHz, preferably multicore
* OS: Windows, Linux (theoretically any POSIX)
* GPU: None
* HDD: 10 MiB + Mods/Plugins
* Bandwidth: 5-10 Mb/s upload
## Contributing
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). 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.
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
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
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.
You can find precompiled binaries under [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
## Build Instructions
On Linux, you need some dependencies to **build** the server (on Windows, you don't):
For Debian, Ubuntu and others you can find scripts that do this in `scripts/`.
```
liblua5.3-dev curl zip unzip tar cmake make git g++
```
The names of each package may change depending on your platform. See in `scripts/` or use a search engine to find out what they're called for you.
You can build on **Windows, Linux** or other platforms by following these steps:
1. Check out the repository with git: `git clone --recursive https://github.com/BeamMP/BeamMP-Server`.
2. Go into the directory `cd BeamMP-Server`.
3. Run CMake `cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release` - this can take a few minutes and may take a lot of disk space and bandwidth.
4. Build via `cmake --build bin --parallel -t BeamMP-Server`.
5. Your executable can be found in `bin/`.
When you make changes to the code, you only have to run step 4 again.
### Runtime Dependencies
These are needed to *run* the 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 (c) 2019-present Anonymous275 (@Anonymous-275), Lion Kortlepel (@lionkor).
BeamMP-Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder(s) in order to modify or distribute any part of the source or binaries. Special permission to modify the source-code is implicitly granted only for the purpose of upstreaming those changes directly to github.com/BeamMP/BeamMP-Server via a GitHub pull-request.
Commercial usage is prohibited, unless explicit permission has been granted prior to usage.
Binary file not shown.
Binary file not shown.
-61
View File
@@ -1,61 +0,0 @@
print("test from lua")
print("Player count: " .. MP.GetPlayerCount())
function onPluginLoaded()
print("HI!")
end
function onShutdown()
print("BYE!")
end
function onPlayerAuthenticated(joined_name, role, is_guest, identifiers)
print("hi welcome mista " .. joined_name)
print("u a guest? " .. tostring(is_guest))
print("current players:")
for id, name in pairs(MP.GetPlayers()) do
print("- [" .. id .. "]" .. name)
end
print("yipee")
print("Player count: " .. MP.GetPlayerCount())
for key, value in pairs(identifiers) do
print(key .. ": " .. value)
end
-- print("now trying with getting it ourself")
-- for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
-- print(key .. ": " .. value)
-- end
return 0 -- 0 = do not cancel
end
function onPlayerDisconnect(pid, name, identifiers)
-- Player is already gone here, so for now, player data is no longer
-- requestable for player with the id `pid`
print("Player " .. name .. " (" .. pid .. ") has left!")
end
function onChatMessage(pid, name, message)
MP.SendChatMessage(-1, "i hate this " .. name .. " guy!")
MP.SendChatMessage(pid, "hiii babe i didnt mean it :3")
print("" .. name .. " (" .. pid .. "): " .. message)
print("identifiers:")
for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
print(key .. ": " .. value)
end
print("unknown identifiers (nil): " .. tostring(MP.GetPlayerIdentifiers(100)))
return message .. " (edited by lua!!!)"
end
MP.RegisterEventHandler("onInit", "onPluginLoaded")
MP.RegisterEventHandler("onShutdown", "onShutdown")
MP.RegisterEventHandler("onPlayerAuth", "onPlayerAuthenticated")
MP.RegisterEventHandler("onPlayerDisconnect", "onPlayerDisconnect")
MP.RegisterEventHandler("onChatMessage", "onChatMessage")
+115
View File
@@ -0,0 +1,115 @@
# 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=missing-field-initializers
-Werror=ctor-dtor-privacy
-Werror=switch-enum
-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/commandline added at 0ff46d25b1
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <initializer_list>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
/*
* Allows syntax:
* --help : long flags
* --path=/home/lion : long assignments
*/
class ArgsParser {
public:
enum Flags : int {
NONE = 0,
REQUIRED = 1, // argument is required
HAS_VALUE = 2, // argument must have a value
};
ArgsParser() = default;
void Parse(const std::vector<std::string_view>& ArgList);
// prints errors if any errors occurred, in that case also returns false
bool Verify();
void RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags);
// pass all possible names for this argument (short, long, etc)
bool FoundArgument(const std::vector<std::string>& Names);
std::optional<std::string> GetValueOfArgument(const std::vector<std::string>& Names);
private:
void ConsumeLongAssignment(const std::string& Arg);
void ConsumeLongFlag(const std::string& Arg);
bool IsRegistered(const std::string& Name);
struct Argument {
std::string Name;
std::optional<std::string> Value;
};
struct RegisteredArgument {
std::vector<std::string> Names;
int Flags;
};
std::vector<RegisteredArgument> mRegisteredArguments;
std::vector<Argument> mFoundArgs;
};
+6
View File
@@ -0,0 +1,6 @@
#pragma once
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
using namespace boost::asio;
+116
View File
@@ -0,0 +1,116 @@
#pragma once
#include <chrono>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <unordered_set>
#include "BoostAliases.h"
#include "Common.h"
#include "Compat.h"
#include "VehicleData.h"
class TServer;
#ifdef BEAMMP_WINDOWS
// for socklen_t
#include <WS2tcpip.h>
#endif // WINDOWS
struct TConnection final {
ip::tcp::socket Socket;
ip::tcp::endpoint SockAddr;
};
class TClient final {
public:
using TSetOfVehicleData = std::vector<TVehicleData>;
struct TVehicleDataLockPair {
TSetOfVehicleData* VehicleData;
std::unique_lock<std::mutex> Lock;
};
TClient(TServer& Server, ip::tcp::socket&& Socket);
TClient(const TClient&) = delete;
~TClient();
TClient& operator=(const TClient&) = delete;
void AddNewCar(int Ident, const std::string& Data);
void SetCarData(int Ident, const std::string& Data);
void SetCarPosition(int Ident, const std::string& Data);
TVehicleDataLockPair GetAllCars();
void SetName(const std::string& Name) { mName = Name; }
void SetRoles(const std::string& Role) { mRole = Role; }
void SetIdentifier(const std::string& key, const std::string& value) { mIdentifiers[key] = value; }
std::string GetCarData(int Ident);
std::string GetCarPositionRaw(int Ident);
void SetUDPAddr(const ip::udp::endpoint& Addr) { mUDPAddress = Addr; }
void SetDownSock(ip::tcp::socket&& CSock) { mDownSocket = std::move(CSock); }
void SetTCPSock(ip::tcp::socket&& CSock) { mSocket = std::move(CSock); }
void Disconnect(std::string_view Reason);
bool IsDisconnected() const { return !mSocket.is_open(); }
// locks
void DeleteCar(int Ident);
[[nodiscard]] const std::unordered_map<std::string, std::string>& GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] const ip::udp::endpoint& GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] ip::udp::endpoint& GetUDPAddr() { return mUDPAddress; }
[[nodiscard]] ip::tcp::socket& GetDownSock() { return mDownSocket; }
[[nodiscard]] const ip::tcp::socket& GetDownSock() const { return mDownSocket; }
[[nodiscard]] ip::tcp::socket& GetTCPSock() { return mSocket; }
[[nodiscard]] const ip::tcp::socket& GetTCPSock() const { return mSocket; }
[[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; }
void SetID(int ID) { mID = ID; }
[[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const;
void ClearCars();
[[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::vector<uint8_t>& Packet);
[[nodiscard]] std::queue<std::vector<uint8_t>>& MissedPacketQueue() { return mPacketsSync; }
[[nodiscard]] const std::queue<std::vector<uint8_t>>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
[[nodiscard]] TServer& Server() const;
void UpdatePingTime();
int SecondsSinceLastPing();
private:
void InsertVehicle(int ID, const std::string& Data);
TServer& mServer;
bool mIsConnected = false;
bool mIsSynced = false;
bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex;
std::queue<std::vector<uint8_t>> mPacketsSync;
std::unordered_map<std::string, std::string> mIdentifiers;
bool mIsGuest = false;
mutable std::mutex mVehicleDataMutex;
mutable std::mutex mVehiclePositionMutex;
TSetOfVehicleData mVehicleData;
SparseArray<std::string> mVehiclePosition;
std::string mName = "Unknown Client";
ip::tcp::socket mSocket;
ip::tcp::socket mDownSocket;
ip::udp::endpoint mUDPAddress {};
int mUnicycleID = -1;
std::string mRole;
std::string mDID;
int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
};
std::optional<std::weak_ptr<TClient>> GetClient(class TServer& Server, int ID);
+321
View File
@@ -0,0 +1,321 @@
#pragma once
#include <array>
#include <atomic>
#include <cstring>
#include <deque>
#include <filesystem>
#include <fmt/format.h>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <sstream>
#include <unordered_map>
#include <zlib.h>
#include <doctest/doctest.h>
#include <filesystem>
namespace fs = std::filesystem;
#include "TConsole.h"
struct Version {
uint8_t major;
uint8_t minor;
uint8_t patch;
Version(uint8_t major, uint8_t minor, uint8_t patch);
Version(const std::array<uint8_t, 3>& v);
std::string AsString();
};
template <typename T>
using SparseArray = std::unordered_map<size_t, T>;
// static class handling application start, shutdown, etc.
// yes, static classes, singletons, globals are all pretty
// bad idioms. In this case we need a central way to access
// stuff like graceful shutdown, global settings (its in the name),
// etc.
class Application final {
public:
// types
struct TSettings {
std::string ServerName { "BeamMP Server" };
std::string ServerDesc { "BeamMP Default Description" };
std::string ServerTags { "Freeroam" };
std::string Resource { "Resources" };
std::string MapName { "/levels/gridmap_v2/info.json" };
std::string Key {};
std::string Password{};
std::string SSLKeyPath { "./.ssl/HttpServer/key.pem" };
std::string SSLCertPath { "./.ssl/HttpServer/cert.pem" };
bool HTTPServerEnabled { false };
int MaxPlayers { 8 };
bool Private { true };
int MaxCars { 1 };
bool DebugModeEnabled { false };
int Port { 30814 };
std::string CustomIP {};
bool LogChat { true };
bool SendErrors { true };
bool SendErrorsMessageEnabled { true };
int HTTPServerPort { 8080 };
std::string HTTPServerIP { "127.0.0.1" };
bool HTTPServerUseSSL { false };
bool HideUpdateMessages { false };
[[nodiscard]] bool HasCustomIP() const { return !CustomIP.empty(); }
};
using TShutdownHandler = std::function<void()>;
// methods
Application() = delete;
// 'Handler' is called when GracefullyShutdown is called
static void RegisterShutdownHandler(const TShutdownHandler& Handler);
// Causes all threads to finish up and exit gracefull gracefully
static void GracefullyShutdown();
static TConsole& Console() { return mConsole; }
static std::string ServerVersionString();
static const Version& ServerVersion() { return mVersion; }
static uint8_t ClientMajorVersion() { return 2; }
static std::string PPS() { return mPPS; }
static void SetPPS(const std::string& NewPPS) { mPPS = NewPPS; }
static TSettings Settings;
static std::vector<std::string> GetBackendUrlsInOrder() {
return {
"backend.beammp.com",
"backup1.beammp.com",
"backup2.beammp.com"
};
}
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
static void CheckForUpdates();
static std::array<uint8_t, 3> VersionStrToInts(const std::string& str);
static bool IsOutdated(const Version& Current, const Version& Newest);
static bool IsShuttingDown();
static void SleepSafeSeconds(size_t Seconds);
static void InitializeConsole() {
mConsole.InitializeCommandline();
}
enum class Status {
Starting,
Good,
Bad,
ShuttingDown,
Shutdown,
};
using SystemStatusMap = std::unordered_map<std::string /* system name */, Status /* status */>;
static const SystemStatusMap& GetSubsystemStatuses() {
std::unique_lock Lock(mSystemStatusMapMutex);
return mSystemStatusMap;
}
static void SetSubsystemStatus(const std::string& Subsystem, Status status);
private:
static void SetShutdown(bool Val);
static inline SystemStatusMap mSystemStatusMap {};
static inline std::mutex mSystemStatusMapMutex {};
static inline std::string mPPS;
static inline TConsole mConsole;
static inline std::shared_mutex mShutdownMtx {};
static inline bool mShutdown { false };
static inline std::mutex mShutdownHandlersMutex {};
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
static inline Version mVersion { 3, 2, 0 };
};
void SplitString(std::string const& str, const char delim, std::vector<std::string>& out);
std::string ThreadName(bool DebugModeOverride = false);
void RegisterThread(const std::string& str);
#define RegisterThreadAuto() RegisterThread(__func__)
#define KB 1024llu
#define MB (KB * 1024llu)
#define GB (MB * 1024llu)
#define SSU_UNRAW SECRET_SENTRY_URL
#define _file_basename std::filesystem::path(__FILE__).filename().string()
#define _line std::to_string(__LINE__)
#define _in_lambda (std::string(__func__) == "operator()")
// for those times when you just need to ignore something :^)
// explicity disables a [[nodiscard]] warning
#define beammp_ignore(x) (void)x
// clang-format off
#ifdef DOCTEST_CONFIG_DISABLE
// we would like the full function signature 'void a::foo() const'
// on windows this is __FUNCSIG__, on GCC it's __PRETTY_FUNCTION__,
// feel free to add more
#if defined(WIN32)
#define _function_name std::string(__FUNCSIG__)
#elif defined(__unix) || defined(__unix__)
#define _function_name std::string(__PRETTY_FUNCTION__)
#else
#define _function_name std::string(__func__)
#endif
#ifndef NDEBUG
#define DEBUG
#endif
#if defined(DEBUG)
// if this is defined, we will show the full function signature infront of
// each info/debug/warn... call instead of the 'filename:line' format.
#if defined(BMP_FULL_FUNCTION_NAMES)
#define _this_location (ThreadName() + _function_name + " ")
#else
#define _this_location (ThreadName() + _file_basename + ":" + _line + " ")
#endif
#endif // defined(DEBUG)
#define beammp_warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
#define beammp_info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
#define beammp_error(x) \
do { \
Application::Console().Write(_this_location + std::string("[ERROR] ") + (x)); \
} while (false)
#define beammp_lua_error(x) \
do { \
Application::Console().Write(_this_location + std::string("[LUA ERROR] ") + (x)); \
} while (false)
#define beammp_lua_warn(x) \
do { \
Application::Console().Write(_this_location + std::string("[LUA WARN] ") + (x)); \
} while (false)
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
#define beammp_debug(x) \
do { \
if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
} \
} while (false)
#define beammp_event(x) \
do { \
if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[EVENT] ") + (x)); \
} \
} while (false)
// trace() is a debug-build debug()
#if defined(DEBUG)
#define beammp_trace(x) \
do { \
if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[TRACE] ") + (x)); \
} \
} while (false)
#else
#define beammp_trace(x)
#endif // defined(DEBUG)
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
#else // DOCTEST_CONFIG_DISABLE
#define beammp_error(x) /* x */
#define beammp_lua_error(x) /* x */
#define beammp_warn(x) /* x */
#define beammp_lua_warn(x) /* x */
#define beammp_info(x) /* x */
#define beammp_event(x) /* x */
#define beammp_debug(x) /* x */
#define beammp_trace(x) /* x */
#define luaprint(x) /* x */
#define beammp_errorf(...) beammp_error(fmt::format(__VA_ARGS__))
#define beammp_infof(...) beammp_info(fmt::format(__VA_ARGS__))
#define beammp_warnf(...) beammp_warn(fmt::format(__VA_ARGS__))
#define beammp_debugf(...) beammp_debug(fmt::format(__VA_ARGS__))
#define beammp_tracef(...) beammp_trace(fmt::format(__VA_ARGS__))
#define beammp_lua_errorf(...) beammp_lua_error(fmt::format(__VA_ARGS__))
#define beammp_lua_warnf(...) beammp_lua_warn(fmt::format(__VA_ARGS__))
#endif // DOCTEST_CONFIG_DISABLE
#if defined(DEBUG)
#define SU_RAW SSU_UNRAW
#else
#define SU_RAW RAWIFY(SSU_UNRAW)
#define _this_location (ThreadName())
#endif
// clang-format on
void LogChatMessage(const std::string& name, int id, const std::string& msg);
#define Biggest 30000
template <typename T>
inline T Comp(const T& Data) {
std::array<char, Biggest> C {};
// obsolete
C.fill(0);
z_stream defstream;
defstream.zalloc = nullptr;
defstream.zfree = nullptr;
defstream.opaque = nullptr;
defstream.avail_in = uInt(Data.size());
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
size_t TotalOut = defstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}
template <typename T>
inline T DeComp(const T& Compressed) {
std::array<char, Biggest> C {};
// not needed
C.fill(0);
z_stream infstream;
infstream.zalloc = nullptr;
infstream.zfree = nullptr;
infstream.opaque = nullptr;
infstream.avail_in = Biggest;
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
infstream.avail_out = Biggest;
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH);
inflateEnd(&infstream);
size_t TotalOut = infstream.total_out;
T Ret;
Ret.resize(TotalOut);
std::fill(Ret.begin(), Ret.end(), 0);
std::copy_n(C.begin(), TotalOut, Ret.begin());
return Ret;
}
std::string GetPlatformAgnosticErrorString();
#define S_DSN SU_RAW
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include "Environment.h"
// ======================= UNIX ========================
#ifdef BEAMMP_LINUX
#include <errno.h>
#include <termios.h>
#include <unistd.h>
char _getch();
#endif // unix
// ======================= APPLE ========================
#ifdef BEAMMP_APPLE
#include <errno.h>
#include <termios.h>
#include <unistd.h>
char _getch();
#endif // unix
// ======================= WINDOWS =======================
#ifdef BEAMMP_WINDOWS
#include <conio.h>
#endif // WIN32
+114
View File
@@ -0,0 +1,114 @@
// Copyright Anonymous275 8/11/2020
#pragma once
#include <array>
#include <cstdarg>
#include <string>
namespace Crypto {
constexpr auto time = __TIME__;
constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast<int>(time[1]) * 3600 + static_cast<int>(time[0]) * 36000;
// 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division
template <int N>
struct RandomGenerator {
private:
static constexpr unsigned a = 16807; // 7^5
static constexpr unsigned m = 2147483647; // 2^31 - 1
static constexpr unsigned s = RandomGenerator<N - 1>::value;
static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807
static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807
static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits
static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi
static constexpr unsigned lo3 = lo2 + hi;
public:
static constexpr unsigned max = m;
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};
template <>
struct RandomGenerator<0> {
static constexpr unsigned value = seed;
};
template <int N, int M>
struct RandomInt {
static constexpr auto value = RandomGenerator<N + 1>::value % M;
};
template <int N>
struct RandomChar {
static const char value = static_cast<char>(1 + RandomInt<N, 0x7F - 1>::value);
};
template <size_t N, int K, typename Char>
struct MangleString {
private:
const char _key;
std::array<Char, N + 1> _encrypted;
constexpr Char enc(Char c) const {
return c ^ _key;
}
Char dec(Char c) const {
return c ^ _key;
}
public:
template <size_t... Is>
constexpr MangleString(const Char* str, std::index_sequence<Is...>)
: _key(RandomChar<K>::value)
, _encrypted { enc(str[Is])... } { }
decltype(auto) decrypt() {
for (size_t i = 0; i < N; ++i) {
_encrypted[i] = dec(_encrypted[i]);
}
_encrypted[N] = '\0';
return _encrypted.data();
}
};
static auto w_printf = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
};
static auto w_printf_s = [](const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
};
static auto w_sprintf_s = [](char* buf, size_t, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
};
static auto w_sprintf_s_ret = [](char* buf, size_t, const char* fmt, ...) {
int ret;
va_list args;
va_start(args, fmt);
ret = vsprintf(buf, fmt, args);
va_end(args);
return ret;
};
#define XOR_C(s) [] { constexpr Crypto::MangleString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
#define XOR_W(s) [] { constexpr Crypto::MangleString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
#define RAWIFY(s) XOR_C(s)
}
+72
View File
@@ -0,0 +1,72 @@
// Author: lionkor
/*
* Asserts are to be used anywhere where assumptions about state are made
* implicitly. AssertNotReachable is used where code should never go, like in
* default switch cases which shouldn't trigger. They make it explicit
* that a place cannot normally be reached and make it an error if they do.
*/
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <thread>
#include "Common.h"
static const char* const ANSI_RESET = "\u001b[0m";
static const char* const ANSI_BLACK = "\u001b[30m";
static const char* const ANSI_RED = "\u001b[31m";
static const char* const ANSI_GREEN = "\u001b[32m";
static const char* const ANSI_YELLOW = "\u001b[33m";
static const char* const ANSI_BLUE = "\u001b[34m";
static const char* const ANSI_MAGENTA = "\u001b[35m";
static const char* const ANSI_CYAN = "\u001b[36m";
static const char* const ANSI_WHITE = "\u001b[37m";
static const char* const ANSI_BLACK_BOLD = "\u001b[30;1m";
static const char* const ANSI_RED_BOLD = "\u001b[31;1m";
static const char* const ANSI_GREEN_BOLD = "\u001b[32;1m";
static const char* const ANSI_YELLOW_BOLD = "\u001b[33;1m";
static const char* const ANSI_BLUE_BOLD = "\u001b[34;1m";
static const char* const ANSI_MAGENTA_BOLD = "\u001b[35;1m";
static const char* const ANSI_CYAN_BOLD = "\u001b[36;1m";
static const char* const ANSI_WHITE_BOLD = "\u001b[37;1m";
static const char* const ANSI_BOLD = "\u001b[1m";
static const char* const ANSI_UNDERLINE = "\u001b[4m";
#ifdef DEBUG
#include <iostream>
inline void _assert([[maybe_unused]] const char* file, [[maybe_unused]] const char* function, [[maybe_unused]] unsigned line,
[[maybe_unused]] const char* condition_string, [[maybe_unused]] bool result) {
if (!result) {
std::cout << std::flush << "(debug build) TID "
<< std::this_thread::get_id() << ": ASSERTION FAILED: at "
<< file << ":" << line << " \n\t-> in "
<< function << ", Line " << line << ": \n\t\t-> "
<< "Failed Condition: " << condition_string << std::endl;
std::cout << "... terminating ..." << std::endl;
abort();
}
}
#define beammp_assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
#define beammp_assert_not_reachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
#else
#define beammp_assert(cond) \
do { \
bool result = (cond); \
if (!result) { \
beammp_errorf("Assertion failed in '{}:{}': {}.", __func__, _line, #cond); \
} \
} while (false)
#define beammp_assert_not_reachable() \
do { \
beammp_errorf("Assertion failed in '{}:{}': Unreachable code reached. This may result in a crash or undefined state of the program.", __func__, _line); \
} while (false)
#endif // DEBUG
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <functional>
template <typename FnT>
class Defer final {
public:
Defer(FnT fn)
: mFunction([&fn] { (void)fn(); }) { }
~Defer() {
if (mFunction) {
mFunction();
}
}
private:
std::function<void()> mFunction;
};
+17
View File
@@ -0,0 +1,17 @@
#pragma once
// one of BEAMMP_{WINDOWS,LINUX,APPLE} will be set at the end of this
// clang-format off
#if !defined(BEAMMP_WINDOWS) && !defined(BEAMMP_UNIX) && !defined(BEAMMP_APPLE)
#if defined(_WIN32) || defined(__CYGWIN__)
#define BEAMMP_WINDOWS
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__unix__) || defined(__unix) || defined(unix)
#define BEAMMP_LINUX
#elif defined(__APPLE__) || defined(__MACH__)
#define BEAMMP_APPLE
#else
#error "This platform is not known. Please define one of the above for your OS."
#endif
#endif
// clang-format on
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <Common.h>
#include <IThreaded.h>
#include <filesystem>
#include <string>
#include <unordered_map>
#if defined(BEAMMP_LINUX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#include <httplib.h>
#if defined(BEAMMP_LINUX)
#pragma GCC diagnostic pop
#endif
namespace fs = std::filesystem;
namespace Http {
std::string GET(const std::string& host, int port, const std::string& target, unsigned int* status = nullptr);
std::string POST(const std::string& host, int port, const std::string& target, const std::string& body, const std::string& ContentType, unsigned int* status = nullptr, const httplib::Headers& headers = {});
namespace Status {
std::string ToString(int code);
}
const std::string ErrorString = "-1";
namespace Server {
class THttpServerInstance {
public:
THttpServerInstance();
protected:
void operator()();
private:
std::thread mThread;
};
}
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <thread>
// pure virtual class to be inherited from by classes which intend to be threaded
class IThreaded {
public:
IThreaded()
// invokes operator() on this object
: mThread() { }
virtual ~IThreaded() noexcept {
if (mThread.joinable()) {
mThread.join();
}
}
virtual void Start() final {
mThread = std::thread([this] { (*this)(); });
}
virtual void operator()() = 0;
protected:
std::thread mThread;
};
+9
View File
@@ -0,0 +1,9 @@
//
// Created by anon on 4/21/21.
//
#pragma once
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include "TLuaEngine.h"
#include <tuple>
namespace LuaAPI {
int PanicHandler(lua_State* State);
std::string LuaToString(const sol::object Value, size_t Indent = 1, bool QuoteStrings = false);
void Print(sol::variadic_args);
namespace MP {
extern TLuaEngine* Engine;
std::string GetOSName();
std::tuple<int, int, int> GetServerVersion();
std::pair<bool, std::string> TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& Data);
std::pair<bool, std::string> TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data);
inline size_t GetPlayerCount() { return Engine->Server().ClientCount(); }
std::pair<bool, std::string> DropPlayer(int ID, std::optional<std::string> MaybeReason);
std::pair<bool, std::string> SendChatMessage(int ID, const std::string& Message);
std::pair<bool, std::string> RemoveVehicle(int PlayerID, int VehicleID);
void Set(int ConfigID, sol::object NewValue);
bool IsPlayerGuest(int ID);
bool IsPlayerConnected(int ID);
void Sleep(size_t Ms);
void PrintRaw(sol::variadic_args);
std::string JsonEncode(const sol::table& object);
std::string JsonDiff(const std::string& a, const std::string& b);
std::string JsonDiffApply(const std::string& data, const std::string& patch);
std::string JsonPrettify(const std::string& json);
std::string JsonMinify(const std::string& json);
std::string JsonFlatten(const std::string& json);
std::string JsonUnflatten(const std::string& json);
}
namespace FS {
std::pair<bool, std::string> CreateDirectory(const std::string& Path);
std::pair<bool, std::string> Remove(const std::string& Path);
std::pair<bool, std::string> Rename(const std::string& Path, const std::string& NewPath);
std::pair<bool, std::string> Copy(const std::string& Path, const std::string& NewPath);
std::string GetFilename(const std::string& Path);
std::string GetExtension(const std::string& Path);
std::string GetParentFolder(const std::string& Path);
bool Exists(const std::string& Path);
bool IsDirectory(const std::string& Path);
bool IsFile(const std::string& Path);
std::string ConcatPaths(sol::variadic_args Args);
}
}
+20
View File
@@ -0,0 +1,20 @@
// Author: lionkor
#pragma once
/*
* An RWMutex allows multiple simultaneous readlocks but only one writelock at a time,
* and write locks and read locks are mutually exclusive.
*/
#include <shared_mutex>
#include <mutex>
// Use ReadLock(m) and WriteLock(m) to lock it.
using RWMutex = std::shared_mutex;
// Construct with an RWMutex as a non-const reference.
// locks the mutex in lock_shared mode (for reading). Locking in a thread that already owns a lock
// i.e. locking multiple times successively is UB. Construction may be blocking. Destruction is guaranteed to release the lock.
using ReadLock = std::shared_lock<RWMutex>;
// Construct with an RWMutex as a non-const reference.
// locks the mutex for writing. Construction may be blocking. Destruction is guaranteed to release the lock.
using WriteLock = std::unique_lock<RWMutex>;
+3
View File
@@ -0,0 +1,3 @@
#pragma once
void SetupSignalHandlers();
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "Common.h"
#include <atomic>
#include <filesystem>
#define TOML11_PRESERVE_COMMENTS_BY_DEFAULT
#include <toml.hpp> // header-only version of TOML++
namespace fs = std::filesystem;
class TConfig {
public:
explicit TConfig(const std::string& ConfigFileName);
[[nodiscard]] bool Failed() const { return mFailed; }
void FlushToFile();
private:
void CreateConfigFile();
void ParseFromFile(std::string_view name);
void PrintDebug();
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue);
void TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue);
void ParseOldFormat();
std::string TagsAsPrettyArray() const;
bool IsDefault();
bool mFailed { false };
std::string mConfigFileName;
};
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "Cryptography.h"
#include "commandline.h"
#include <atomic>
#include <fstream>
#include <functional>
#include <mutex>
#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>
class TLuaEngine;
class TConsole {
public:
TConsole();
// Initializes the commandline app to take over I/O
void InitializeCommandline();
void Write(const std::string& str);
void WriteRaw(const std::string& str);
void InitializeLuaConsole(TLuaEngine& Engine);
void BackupOldLog();
void StartLoggingToFile();
Commandline& Internal() { return *mCommandline; }
private:
void RunAsCommand(const std::string& cmd, bool IgnoreNotACommand = false);
void ChangeToLuaConsole(const std::string& LuaStateId);
void ChangeToRegularConsole();
void HandleLuaInternalCommand(const std::string& cmd);
void Command_Lua(const std::string& cmd, const std::vector<std::string>& args);
void Command_Help(const std::string& cmd, const std::vector<std::string>& args);
void Command_Kick(const std::string& cmd, const std::vector<std::string>& args);
void Command_List(const std::string& cmd, const std::vector<std::string>& args);
void Command_Status(const std::string& cmd, const std::vector<std::string>& args);
void Command_Settings(const std::string& cmd, const std::vector<std::string>& args);
void Command_Clear(const std::string&, const std::vector<std::string>& args);
void Command_Say(const std::string& FullCommand);
bool EnsureArgsCount(const std::vector<std::string>& args, size_t n);
bool EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max);
static std::tuple<std::string, std::vector<std::string>> ParseCommand(const std::string& cmd);
static std::string ConcatArgs(const std::vector<std::string>& args, char space = ' ');
std::unordered_map<std::string, std::function<void(const std::string&, const std::vector<std::string>&)>> mCommandMap = {
{ "lua", [this](const auto& a, const auto& b) { Command_Lua(a, b); } },
{ "help", [this](const auto& a, const auto& b) { Command_Help(a, b); } },
{ "kick", [this](const auto& a, const auto& b) { Command_Kick(a, b); } },
{ "list", [this](const auto& a, const auto& b) { Command_List(a, b); } },
{ "status", [this](const auto& a, const auto& b) { Command_Status(a, b); } },
{ "settings", [this](const auto& a, const auto& b) { Command_Settings(a, b); } },
{ "clear", [this](const auto& a, const auto& b) { Command_Clear(a, b); } },
{ "say", [this](const auto&, const auto&) { Command_Say(""); } }, // shouldn't actually be called
};
std::unique_ptr<Commandline> mCommandline { nullptr };
std::vector<std::string> mCachedLuaHistory;
std::vector<std::string> mCachedRegularHistory;
TLuaEngine* mLuaEngine { nullptr };
bool mIsLuaConsole { false };
bool mFirstTime { true };
std::string mStateId;
const std::string mDefaultStateId = "BEAMMP_SERVER_CONSOLE";
std::ofstream mLogFileStream;
std::mutex mLogFileStreamMtx;
};
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "Common.h"
#include "IThreaded.h"
#include "TResourceManager.h"
#include "TServer.h"
class THeartbeatThread : public IThreaded {
public:
THeartbeatThread(TResourceManager& ResourceManager, TServer& Server);
//~THeartbeatThread();
void operator()() override;
private:
std::string GenerateCall();
std::string GetPlayers();
TResourceManager& mResourceManager;
TServer& mServer;
};
+280
View File
@@ -0,0 +1,280 @@
#pragma once
#include "TNetwork.h"
#include "TServer.h"
#include <any>
#include <condition_variable>
#include <filesystem>
#include <initializer_list>
#include <list>
#include <lua.hpp>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <set>
#include <toml.hpp>
#include <unordered_map>
#include <vector>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
using TLuaStateId = std::string;
namespace fs = std::filesystem;
/**
* std::variant means, that TLuaArgTypes may be one of the Types listed as template args
*/
using TLuaArgTypes = std::variant<std::string, int, sol::variadic_args, bool, std::unordered_map<std::string, std::string>>;
static constexpr size_t TLuaArgTypes_String = 0;
static constexpr size_t TLuaArgTypes_Int = 1;
static constexpr size_t TLuaArgTypes_VariadicArgs = 2;
static constexpr size_t TLuaArgTypes_Bool = 3;
static constexpr size_t TLuaArgTypes_StringStringMap = 4;
class TLuaPlugin;
struct TLuaResult {
bool Ready;
bool Error;
std::string ErrorMessage;
sol::object Result { sol::lua_nil };
TLuaStateId StateId;
std::string Function;
std::shared_ptr<std::mutex> ReadyMutex {
std::make_shared<std::mutex>()
};
std::shared_ptr<std::condition_variable> ReadyCondition {
std::make_shared<std::condition_variable>()
};
void MarkAsReady();
void WaitUntilReady();
};
struct TLuaPluginConfig {
static inline const std::string FileName = "PluginConfig.toml";
TLuaStateId StateId;
// TODO: Add execute list
// TODO: Build a better toml serializer, or some way to do this in an easier way
};
struct TLuaChunk {
TLuaChunk(std::shared_ptr<std::string> Content,
std::string FileName,
std::string PluginPath);
std::shared_ptr<std::string> Content;
std::string FileName;
std::string PluginPath;
};
class TLuaEngine : public std::enable_shared_from_this<TLuaEngine>, IThreaded {
public:
enum CallStrategy : int {
BestEffort,
Precise,
};
struct QueuedFunction {
std::string FunctionName;
std::shared_ptr<TLuaResult> Result;
std::vector<TLuaArgTypes> Args;
std::string EventName; // optional, may be empty
};
TLuaEngine();
virtual ~TLuaEngine() noexcept {
beammp_debug("Lua Engine terminated");
}
void operator()() override;
TNetwork& Network() { return *mNetwork; }
TServer& Server() { return *mServer; }
void SetNetwork(TNetwork* Network) { mNetwork = Network; }
void SetServer(TServer* Server) { mServer = Server; }
size_t GetResultsToCheckSize() {
std::unique_lock Lock(mResultsToCheckMutex);
return mResultsToCheck.size();
}
size_t GetLuaStateCount() {
std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.size();
}
std::vector<std::string> GetLuaStateNames() {
std::vector<std::string> names {};
for (auto const& [stateId, _] : mLuaStates) {
names.push_back(stateId);
}
return names;
}
size_t GetTimedEventsCount() {
std::unique_lock Lock(mTimedEventsMutex);
return mTimedEvents.size();
}
size_t GetRegisteredEventHandlerCount() {
std::unique_lock Lock(mLuaEventsMutex);
size_t LuaEventsCount = 0;
for (const auto& State : mLuaEvents) {
for (const auto& Events : State.second) {
LuaEventsCount += Events.second.size();
}
}
return LuaEventsCount - GetLuaStateCount();
}
static void WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results,
const std::optional<std::chrono::high_resolution_clock::duration>& Max = std::nullopt);
void ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results);
bool HasState(TLuaStateId StateId);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
void EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit = false);
void RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName);
/**
*
* @tparam ArgsT Template Arguments for the event (Metadata) todo: figure out what this means
* @param EventName Name of the event
* @param IgnoreId
* @param Args
* @return
*/
template <typename... ArgsT>
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerEvent(const std::string& EventName, TLuaStateId IgnoreId, ArgsT&&... Args) {
std::unique_lock Lock(mLuaEventsMutex);
beammp_event(EventName);
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
return {};
}
std::vector<std::shared_ptr<TLuaResult>> Results;
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
for (const auto& Event : mLuaEvents.at(EventName)) {
for (const auto& Function : Event.second) {
if (Event.first != IgnoreId) {
Results.push_back(EnqueueFunctionCall(Event.first, Function, Arguments));
}
}
}
return Results; //
}
template <typename... ArgsT>
[[nodiscard]] std::vector<std::shared_ptr<TLuaResult>> TriggerLocalEvent(const TLuaStateId& StateId, const std::string& EventName, ArgsT&&... Args) {
std::unique_lock Lock(mLuaEventsMutex);
beammp_event(EventName + " in '" + StateId + "'");
if (mLuaEvents.find(EventName) == mLuaEvents.end()) { // if no event handler is defined for 'EventName', return immediately
return {};
}
std::vector<std::shared_ptr<TLuaResult>> Results;
std::vector<TLuaArgTypes> Arguments { TLuaArgTypes { std::forward<ArgsT>(Args) }... };
const auto Handlers = GetEventHandlersForState(EventName, StateId);
for (const auto& Handler : Handlers) {
Results.push_back(EnqueueFunctionCall(StateId, Handler, Arguments));
}
return Results;
}
std::set<std::string> GetEventHandlersForState(const std::string& EventName, TLuaStateId StateId);
void CreateEventTimer(const std::string& EventName, TLuaStateId StateId, size_t IntervalMS, CallStrategy Strategy);
void CancelEventTimers(const std::string& EventName, TLuaStateId StateId);
sol::state_view GetStateForPlugin(const fs::path& PluginPath);
TLuaStateId GetStateIDForPlugin(const fs::path& PluginPath);
void AddResultToCheck(const std::shared_ptr<TLuaResult>& Result);
static constexpr const char* BeamMPFnNotFoundError = "BEAMMP_FN_NOT_FOUND";
std::vector<std::string> GetStateGlobalKeysForState(TLuaStateId StateId);
std::vector<std::string> GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys);
// Debugging functions (slow)
std::unordered_map<std::string /*event name */, std::vector<std::string> /* handlers */> Debug_GetEventsForState(TLuaStateId StateId);
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueueForState(TLuaStateId StateId);
std::vector<QueuedFunction> Debug_GetStateFunctionQueueForState(TLuaStateId StateId);
std::vector<TLuaResult> Debug_GetResultsToCheckForState(TLuaStateId StateId);
private:
void CollectAndInitPlugins();
void InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config);
void FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config);
size_t CalculateMemoryUsage();
class StateThreadData : IThreaded {
public:
StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine);
StateThreadData(const StateThreadData&) = delete;
virtual ~StateThreadData() noexcept { beammp_debug("\"" + mStateId + "\" destroyed"); }
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueScript(const TLuaChunk& Script);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCall(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args);
[[nodiscard]] std::shared_ptr<TLuaResult> EnqueueFunctionCallFromCustomEvent(const std::string& FunctionName, const std::vector<TLuaArgTypes>& Args, const std::string& EventName, CallStrategy Strategy);
void RegisterEvent(const std::string& EventName, const std::string& FunctionName);
void AddPath(const fs::path& Path); // to be added to path and cpath
void operator()() override;
sol::state_view State() { return sol::state_view(mState); }
std::vector<std::string> GetStateGlobalKeys();
std::vector<std::string> GetStateTableKeys(const std::vector<std::string>& keys);
// Debug functions, slow
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Debug_GetStateExecuteQueue();
std::vector<TLuaEngine::QueuedFunction> Debug_GetStateFunctionQueue();
private:
sol::table Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs);
sol::table Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs);
sol::table Lua_GetPlayerIdentifiers(int ID);
sol::table Lua_GetPlayers();
std::string Lua_GetPlayerName(int ID);
sol::table Lua_GetPlayerVehicles(int ID);
std::pair<sol::table, std::string> Lua_GetPositionRaw(int PID, int VID);
sol::table Lua_HttpCreateConnection(const std::string& host, uint16_t port);
sol::table Lua_JsonDecode(const std::string& str);
int Lua_GetPlayerIDByName(const std::string& Name);
sol::table Lua_FS_ListFiles(const std::string& Path);
sol::table Lua_FS_ListDirectories(const std::string& Path);
std::string mName;
TLuaStateId mStateId;
lua_State* mState;
std::thread mThread;
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> mStateExecuteQueue;
std::recursive_mutex mStateExecuteQueueMutex;
std::vector<QueuedFunction> mStateFunctionQueue;
std::mutex mStateFunctionQueueMutex;
std::condition_variable mStateFunctionQueueCond;
TLuaEngine* mEngine;
sol::state_view mStateView { mState };
std::queue<fs::path> mPaths;
std::recursive_mutex mPathsMutex;
std::mt19937 mMersenneTwister;
std::uniform_real_distribution<double> mUniformRealDistribution01;
};
struct TimedEvent {
std::chrono::high_resolution_clock::duration Duration {};
std::chrono::high_resolution_clock::time_point LastCompletion {};
std::string EventName;
TLuaStateId StateId;
CallStrategy Strategy;
bool Expired();
void Reset();
};
TNetwork* mNetwork;
TServer* mServer;
const fs::path mResourceServerPath;
std::vector<std::shared_ptr<TLuaPlugin>> mLuaPlugins;
std::unordered_map<TLuaStateId, std::unique_ptr<StateThreadData>> mLuaStates;
std::recursive_mutex mLuaStatesMutex;
std::unordered_map<std::string /* event name */, std::unordered_map<TLuaStateId, std::set<std::string>>> mLuaEvents;
std::recursive_mutex mLuaEventsMutex;
std::vector<TimedEvent> mTimedEvents;
std::recursive_mutex mTimedEventsMutex;
std::list<std::shared_ptr<TLuaResult>> mResultsToCheck;
std::mutex mResultsToCheckMutex;
std::condition_variable mResultsToCheckCond;
};
// std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaPlugin* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
+19
View File
@@ -0,0 +1,19 @@
#include "TLuaEngine.h"
class TLuaPlugin {
public:
TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder);
TLuaPlugin(const TLuaPlugin&) = delete;
TLuaPlugin& operator=(const TLuaPlugin&) = delete;
~TLuaPlugin() noexcept = default;
const TLuaPluginConfig& GetConfig() const { return mConfig; }
fs::path GetFolder() const { return mFolder; }
private:
TLuaPluginConfig mConfig;
TLuaEngine& mEngine;
fs::path mFolder;
std::string mPluginName;
std::unordered_map<std::string, std::shared_ptr<std::string>> mFileContents;
};
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "BoostAliases.h"
#include "Compat.h"
#include "TResourceManager.h"
#include "TServer.h"
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/udp.hpp>
struct TConnection;
class TNetwork {
public:
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
[[nodiscard]] bool TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync = false);
[[nodiscard]] bool SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync = false);
[[nodiscard]] bool Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync = false);
std::shared_ptr<TClient> CreateClient(ip::tcp::socket&& TCPSock);
std::vector<uint8_t> TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(TConnection&& client);
std::shared_ptr<TClient> Authentication(TConnection&& ClientConnection);
void SyncResources(TClient& c);
[[nodiscard]] bool UDPSend(TClient& Client, std::vector<uint8_t> Data);
void SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel);
void UpdatePlayer(TClient& Client);
private:
void UDPServerMain();
void TCPServerMain();
TServer& mServer;
TPPSMonitor& mPPSMonitor;
ip::udp::socket mUDPSock;
TResourceManager& mResourceManager;
std::thread mUDPThread;
std::thread mTCPThread;
std::vector<uint8_t> UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint);
void HandleDownload(TConnection&& TCPSock);
void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::weak_ptr<TClient>& c);
void Looper(const std::weak_ptr<TClient>& c);
int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr);
void Parse(TClient& c, const std::vector<uint8_t>& Packet);
void SendFile(TClient& c, const std::string& Name);
static bool TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size);
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
static const uint8_t* SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size);
};
std::string HashPassword(const std::string& str);
std::vector<uint8_t> StringToVector(const std::string& Str);
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include "Common.h"
#include "TServer.h"
#include <optional>
class TNetwork;
class TPPSMonitor : public IThreaded {
public:
explicit TPPSMonitor(TServer& Server);
virtual ~TPPSMonitor() {}
void operator()() override;
void SetInternalPPS(int NewPPS) { mInternalPPS = NewPPS; }
void IncrementInternalPPS() { ++mInternalPPS; }
[[nodiscard]] int InternalPPS() const { return mInternalPPS; }
void SetNetwork(TNetwork& Server) { mNetwork = std::ref(Server); }
private:
TNetwork& Network() { return mNetwork->get(); }
TServer& mServer;
std::optional<std::reference_wrapper<TNetwork>> mNetwork { std::nullopt };
int mInternalPPS { 0 };
};
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "Common.h"
#include "IThreaded.h"
#include <atomic>
#include <memory>
#include <unordered_map>
class TLuaEngine;
class TPluginMonitor : IThreaded, public std::enable_shared_from_this<TPluginMonitor> {
public:
TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine);
void operator()();
private:
std::shared_ptr<TLuaEngine> mEngine;
fs::path mPath;
std::unordered_map<std::string, fs::file_time_type> mFileTimes;
};
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "Common.h"
class TResourceManager {
public:
TResourceManager();
[[nodiscard]] size_t MaxModSize() const { return mMaxModSize; }
[[nodiscard]] std::string FileList() const { return mFileList; }
[[nodiscard]] std::string TrimmedList() const { return mTrimmedList; }
[[nodiscard]] std::string FileSizes() const { return mFileSizes; }
[[nodiscard]] int ModsLoaded() const { return mModsLoaded; }
private:
size_t mMaxModSize = 0;
std::string mFileSizes;
std::string mFileList;
std::string mTrimmedList;
int mModsLoaded = 0;
};
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <chrono>
#include <functional>
#include <string>
class TScopedTimer {
public:
TScopedTimer();
TScopedTimer(const std::string& Name);
TScopedTimer(std::function<void(size_t)> OnDestroy);
~TScopedTimer();
auto GetElapsedTime() const {
auto EndTime = std::chrono::high_resolution_clock::now();
auto Delta = EndTime - mStartTime;
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
return TimeDelta;
}
std::function<void(size_t /* time_ms */)> OnDestroy { nullptr };
private:
std::chrono::high_resolution_clock::time_point mStartTime;
std::string Name;
};
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "IThreaded.h"
#include "RWMutex.h"
#include "TScopedTimer.h"
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_set>
#include "BoostAliases.h"
class TClient;
class TNetwork;
class TPPSMonitor;
class TServer final {
public:
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
TServer(const std::vector<std::string_view>& Arguments);
void InsertClient(const std::shared_ptr<TClient>& Ptr);
void RemoveClient(const std::weak_ptr<TClient>&);
// in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; }
const TScopedTimer UptimeTimer;
// asio io context
io_context& IoCtx() { return mIoCtx; }
private:
io_context mIoCtx {};
TClientSet mClients;
mutable RWMutex mClientsMutex;
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt);
static void HandlePosition(TClient& c, const std::string& Packet);
};
struct BufferView {
uint8_t* Data { nullptr };
size_t Size { 0 };
const uint8_t* data() const { return Data; }
uint8_t* data() { return Data; }
size_t size() const { return Size; }
};
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <string>
namespace Update {
[[noreturn]] void PerformUpdate(const std::string& InvokedAs);
}
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <string>
class TVehicleData final {
public:
TVehicleData(int ID, std::string Data);
~TVehicleData();
// We cannot delete this, since vector needs to be able to copy when it resizes.
// Deleting this causes some wacky template errors which are hard to decipher,
// and end up making no sense, so let's just leave the copy ctor.
// TVehicleData(const TVehicleData&) = delete;
[[nodiscard]] bool IsInvalid() const { return mID == -1; }
[[nodiscard]] int ID() const { return mID; }
[[nodiscard]] std::string Data() const { return mData; }
void SetData(const std::string& Data) { mData = Data; }
bool operator==(const TVehicleData& v) const { return mID == v.mID; }
private:
int mID { -1 };
std::string mData;
};
// TODO: unused now, remove?
namespace std {
template <>
struct hash<TVehicleData> {
std::size_t operator()(const TVehicleData& s) const noexcept {
return s.ID();
}
};
}
+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++
+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
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
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++
+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
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
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
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
set -ex
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
+170
View File
@@ -0,0 +1,170 @@
#include "ArgsParser.h"
#include "Common.h"
#include <algorithm>
#include <doctest/doctest.h>
void ArgsParser::Parse(const std::vector<std::string_view>& ArgList) {
for (const auto& Arg : ArgList) {
if (Arg.size() > 2 && Arg.substr(0, 2) == "--") {
// long arg
if (Arg.find("=") != Arg.npos) {
ConsumeLongAssignment(std::string(Arg));
} else {
ConsumeLongFlag(std::string(Arg));
}
} else {
beammp_errorf("Error parsing commandline arguments: Supplied argument '{}' is not a valid argument and was ignored.", Arg);
}
}
}
bool ArgsParser::Verify() {
bool Ok = true;
for (const auto& RegisteredArg : mRegisteredArguments) {
if (RegisteredArg.Flags & Flags::REQUIRED && !FoundArgument(RegisteredArg.Names)) {
beammp_errorf("Error in commandline arguments: Argument '{}' is required but wasn't found.", RegisteredArg.Names.at(0));
Ok = false;
continue;
} else if (FoundArgument(RegisteredArg.Names)) {
if (RegisteredArg.Flags & Flags::HAS_VALUE) {
if (!GetValueOfArgument(RegisteredArg.Names).has_value()) {
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' expects a value, but no value was given.");
Ok = false;
}
} else if (GetValueOfArgument(RegisteredArg.Names).has_value()) {
beammp_error("Error in commandline arguments: Argument '" + std::string(RegisteredArg.Names.at(0)) + "' does not expect a value, but one was given.");
Ok = false;
}
}
}
return Ok;
}
void ArgsParser::RegisterArgument(std::vector<std::string>&& ArgumentNames, int Flags) {
mRegisteredArguments.push_back({ ArgumentNames, Flags });
}
bool ArgsParser::FoundArgument(const std::vector<std::string>& Names) {
// if any of the found args match any of the names
return std::any_of(mFoundArgs.begin(), mFoundArgs.end(),
[&Names](const Argument& Arg) -> bool {
// if any of the names match this arg's name
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string& Name) -> bool {
return Arg.Name == Name;
});
});
}
std::optional<std::string> ArgsParser::GetValueOfArgument(const std::vector<std::string>& Names) {
// finds an entry which has a name that is any of the names in 'Names'
auto Found = std::find_if(mFoundArgs.begin(), mFoundArgs.end(), [&Names](const Argument& Arg) -> bool {
return std::any_of(Names.begin(), Names.end(), [&Arg](const std::string_view& Name) -> bool {
return Arg.Name == Name;
});
});
if (Found != mFoundArgs.end()) {
// found
return Found->Value;
} else {
return std::nullopt;
}
}
bool ArgsParser::IsRegistered(const std::string& Name) {
return std::any_of(mRegisteredArguments.begin(), mRegisteredArguments.end(), [&Name](const RegisteredArgument& Arg) {
auto Iter = std::find(Arg.Names.begin(), Arg.Names.end(), Name);
return Iter != Arg.Names.end();
});
}
void ArgsParser::ConsumeLongAssignment(const std::string& Arg) {
auto Value = Arg.substr(Arg.rfind("=") + 1);
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
if (!IsRegistered(Name)) {
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
}
mFoundArgs.push_back({ Name, Value });
}
void ArgsParser::ConsumeLongFlag(const std::string& Arg) {
auto Name = Arg.substr(2, Arg.rfind("=") - 2);
mFoundArgs.push_back({ Name, std::nullopt });
if (!IsRegistered(Name)) {
beammp_warn("Argument '" + Name + "' was supplied but isn't a known argument, so it is likely being ignored.");
}
}
TEST_CASE("ArgsParser") {
ArgsParser parser;
SUBCASE("Simple args") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
parser.Parse({ "--a", "--hello" });
CHECK(parser.Verify());
CHECK(parser.FoundArgument({ "a" }));
CHECK(parser.FoundArgument({ "hello" }));
CHECK(parser.FoundArgument({ "a", "hello" }));
CHECK(!parser.FoundArgument({ "b" }));
CHECK(!parser.FoundArgument({ "goodbye" }));
}
SUBCASE("No args") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::NONE);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
parser.Parse({});
CHECK(parser.Verify());
CHECK(!parser.FoundArgument({ "a" }));
CHECK(!parser.FoundArgument({ "hello" }));
CHECK(!parser.FoundArgument({ "a", "hello" }));
CHECK(!parser.FoundArgument({ "b" }));
CHECK(!parser.FoundArgument({ "goodbye" }));
CHECK(!parser.FoundArgument({ "" }));
}
SUBCASE("Value args") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::HAS_VALUE);
parser.Parse({ "--a=5", "--hello=world" });
CHECK(parser.Verify());
REQUIRE(parser.FoundArgument({ "a" }));
REQUIRE(parser.FoundArgument({ "hello" }));
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
CHECK(parser.GetValueOfArgument({ "hello" }).has_value());
CHECK(parser.GetValueOfArgument({ "hello" }).value() == "world");
}
SUBCASE("Mixed value & no-value args") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::HAS_VALUE);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::NONE);
parser.Parse({ "--a=5", "--hello" });
CHECK(parser.Verify());
REQUIRE(parser.FoundArgument({ "a" }));
REQUIRE(parser.FoundArgument({ "hello" }));
CHECK(parser.GetValueOfArgument({ "a" }).has_value());
CHECK(parser.GetValueOfArgument({ "a" }).value() == "5");
CHECK(!parser.GetValueOfArgument({ "hello" }).has_value());
}
SUBCASE("Required args") {
SUBCASE("Two required, two present") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
parser.Parse({ "--a", "--hello" });
CHECK(parser.Verify());
}
SUBCASE("Two required, one present") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
parser.Parse({ "--a" });
CHECK(!parser.Verify());
}
SUBCASE("Two required, none present") {
parser.RegisterArgument({ "a" }, ArgsParser::Flags::REQUIRED);
parser.RegisterArgument({ "hello" }, ArgsParser::Flags::REQUIRED);
parser.Parse({ "--b" });
CHECK(!parser.Verify());
}
}
}
+153
View File
@@ -0,0 +1,153 @@
#include "Client.h"
#include "CustomAssert.h"
#include "TServer.h"
#include <memory>
#include <optional>
void TClient::DeleteCar(int Ident) {
// TODO: Send delete packets
std::unique_lock lock(mVehicleDataMutex);
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
return Ident == elem.ID();
});
if (iter != mVehicleData.end()) {
mVehicleData.erase(iter);
} else {
beammp_debug("tried to erase a vehicle that doesn't exist (not an error)");
}
}
void TClient::ClearCars() {
std::unique_lock lock(mVehicleDataMutex);
mVehicleData.clear();
}
int TClient::GetOpenCarID() const {
int OpenID = 0;
bool found;
std::unique_lock lock(mVehicleDataMutex);
do {
found = true;
for (auto& v : mVehicleData) {
if (v.ID() == OpenID) {
OpenID++;
found = false;
}
}
} while (!found);
return OpenID;
}
void TClient::AddNewCar(int Ident, const std::string& Data) {
std::unique_lock lock(mVehicleDataMutex);
mVehicleData.emplace_back(Ident, Data);
}
TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
}
std::string TClient::GetCarPositionRaw(int Ident) {
std::unique_lock lock(mVehiclePositionMutex);
try {
return mVehiclePosition.at(size_t(Ident));
} catch (const std::out_of_range& oor) {
return "";
}
return "";
}
void TClient::Disconnect(std::string_view Reason) {
beammp_debugf("Disconnecting client {} for reason: {}", GetID(), Reason);
boost::system::error_code ec;
mSocket.shutdown(socket_base::shutdown_both, ec);
if (ec) {
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
}
mSocket.close(ec);
if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message());
}
}
void TClient::SetCarPosition(int Ident, const std::string& Data) {
std::unique_lock lock(mVehiclePositionMutex);
mVehiclePosition[size_t(Ident)] = Data;
}
std::string TClient::GetCarData(int Ident) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
return v.Data();
}
}
} // unlock
DeleteCar(Ident);
return "";
}
void TClient::SetCarData(int Ident, const std::string& Data) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
v.SetData(Data);
return;
}
}
} // unlock
DeleteCar(Ident);
}
int TClient::GetCarCount() const {
return int(mVehicleData.size());
}
TServer& TClient::Server() const {
return mServer;
}
void TClient::EnqueuePacket(const std::vector<uint8_t>& Packet) {
std::unique_lock Lock(mMissedPacketsMutex);
mPacketsSync.push(Packet);
}
TClient::TClient(TServer& Server, ip::tcp::socket&& Socket)
: mServer(Server)
, mSocket(std::move(Socket))
, mDownSocket(ip::tcp::socket(Server.IoCtx()))
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
}
TClient::~TClient() {
beammp_debugf("client destroyed: {} ('{}')", this->GetID(), this->GetName());
}
void TClient::UpdatePingTime() {
mLastPingTime = std::chrono::high_resolution_clock::now();
}
int TClient::SecondsSinceLastPing() {
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - mLastPingTime)
.count();
return int(seconds);
}
std::optional<std::weak_ptr<TClient>> GetClient(TServer& Server, int ID) {
std::optional<std::weak_ptr<TClient>> MaybeClient { std::nullopt };
Server.ForEachClient([&](std::weak_ptr<TClient> CPtr) -> bool {
ReadLock Lock(Server.GetClientMutex());
if (!CPtr.expired()) {
auto C = CPtr.lock();
if (C->GetID() == ID) {
MaybeClient = CPtr;
return false;
}
}
return true;
});
return MaybeClient;
}
+361
View File
@@ -0,0 +1,361 @@
#include "Common.h"
#include "TConsole.h"
#include <array>
#include <charconv>
#include <iostream>
#include <map>
#include <regex>
#include <sstream>
#include <thread>
#include "Compat.h"
#include "CustomAssert.h"
#include "Http.h"
Application::TSettings Application::Settings = {};
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
std::unique_lock Lock(mShutdownHandlersMutex);
if (Handler) {
mShutdownHandlers.push_front(Handler);
}
}
void Application::GracefullyShutdown() {
SetShutdown(true);
static bool AlreadyShuttingDown = false;
static uint8_t ShutdownAttempts = 0;
if (AlreadyShuttingDown) {
++ShutdownAttempts;
// hard shutdown at 2 additional tries
if (ShutdownAttempts == 2) {
beammp_info("hard shutdown forced by multiple shutdown requests");
std::exit(0);
}
beammp_info("already shutting down!");
return;
} else {
AlreadyShuttingDown = true;
}
beammp_trace("waiting for lock release");
std::unique_lock Lock(mShutdownHandlersMutex);
beammp_info("please wait while all subsystems are shutting down...");
for (size_t i = 0; i < mShutdownHandlers.size(); ++i) {
beammp_info("Subsystem " + std::to_string(i + 1) + "/" + std::to_string(mShutdownHandlers.size()) + " shutting down");
mShutdownHandlers[i]();
}
// std::exit(-1);
}
std::string Application::ServerVersionString() {
return mVersion.AsString();
}
std::array<uint8_t, 3> Application::VersionStrToInts(const std::string& str) {
std::array<uint8_t, 3> Version;
std::stringstream ss(str);
for (uint8_t& i : Version) {
std::string Part;
std::getline(ss, Part, '.');
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), i);
}
return Version;
}
TEST_CASE("Application::VersionStrToInts") {
auto v = Application::VersionStrToInts("1.2.3");
CHECK(v[0] == 1);
CHECK(v[1] == 2);
CHECK(v[2] == 3);
v = Application::VersionStrToInts("10.20.30");
CHECK(v[0] == 10);
CHECK(v[1] == 20);
CHECK(v[2] == 30);
v = Application::VersionStrToInts("100.200.255");
CHECK(v[0] == 100);
CHECK(v[1] == 200);
CHECK(v[2] == 255);
}
bool Application::IsOutdated(const Version& Current, const Version& Newest) {
if (Newest.major > Current.major) {
return true;
} else if (Newest.major == Current.major && Newest.minor > Current.minor) {
return true;
} else if (Newest.major == Current.major && Newest.minor == Current.minor && Newest.patch > Current.patch) {
return true;
} else {
return false;
}
}
bool Application::IsShuttingDown() {
std::shared_lock Lock(mShutdownMtx);
return mShutdown;
}
void Application::SleepSafeSeconds(size_t Seconds) {
// Sleeps for 500 ms, checks if a shutdown occurred, and so forth
for (size_t i = 0; i < Seconds * 2; ++i) {
if (Application::IsShuttingDown()) {
return;
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
}
TEST_CASE("Application::IsOutdated (version check)") {
SUBCASE("Same version") {
CHECK(!Application::IsOutdated({ 1, 2, 3 }, { 1, 2, 3 }));
}
// we need to use over 1-2 digits to test against lexical comparisons
SUBCASE("Patch outdated") {
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
for (uint8_t Major = 0; Major < 10; ++Major) {
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor), uint8_t(Patch + 1) }));
}
}
}
}
SUBCASE("Minor outdated") {
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
for (uint8_t Major = 0; Major < 10; ++Major) {
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major), uint8_t(Minor + 1), uint8_t(Patch) }));
}
}
}
}
SUBCASE("Major outdated") {
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
for (uint8_t Major = 0; Major < 10; ++Major) {
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor), uint8_t(Patch) }));
}
}
}
}
SUBCASE("All outdated") {
for (uint8_t Patch = 0; Patch < 10; ++Patch) {
for (uint8_t Minor = 0; Minor < 10; ++Minor) {
for (uint8_t Major = 0; Major < 10; ++Major) {
CHECK(Application::IsOutdated({ uint8_t(Major), uint8_t(Minor), uint8_t(Patch) }, { uint8_t(Major + 1), uint8_t(Minor + 1), uint8_t(Patch + 1) }));
}
}
}
}
}
void Application::SetSubsystemStatus(const std::string& Subsystem, Status status) {
switch (status) {
case Status::Good:
beammp_trace("Subsystem '" + Subsystem + "': Good");
break;
case Status::Bad:
beammp_trace("Subsystem '" + Subsystem + "': Bad");
break;
case Status::Starting:
beammp_trace("Subsystem '" + Subsystem + "': Starting");
break;
case Status::ShuttingDown:
beammp_trace("Subsystem '" + Subsystem + "': Shutting down");
break;
case Status::Shutdown:
beammp_trace("Subsystem '" + Subsystem + "': Shutdown");
break;
default:
beammp_assert_not_reachable();
}
std::unique_lock Lock(mSystemStatusMapMutex);
mSystemStatusMap[Subsystem] = status;
}
void Application::SetShutdown(bool Val) {
std::unique_lock Lock(mShutdownMtx);
mShutdown = Val;
}
TEST_CASE("Application::SetSubsystemStatus") {
Application::SetSubsystemStatus("Test", Application::Status::Good);
auto Map = Application::GetSubsystemStatuses();
CHECK(Map.at("Test") == Application::Status::Good);
Application::SetSubsystemStatus("Test", Application::Status::Bad);
Map = Application::GetSubsystemStatuses();
CHECK(Map.at("Test") == Application::Status::Bad);
}
void Application::CheckForUpdates() {
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Starting);
static bool FirstTime = true;
// checks current version against latest version
std::regex VersionRegex { R"(\d+\.\d+\.\d+\n*)" };
for (const auto& url : GetBackendUrlsInOrder()) {
auto Response = Http::GET(url, 443, "/v/s");
bool Matches = std::regex_match(Response, VersionRegex);
if (Matches) {
auto MyVersion = ServerVersion();
auto RemoteVersion = Version(VersionStrToInts(Response));
if (IsOutdated(MyVersion, RemoteVersion)) {
std::string RealVersionString = RemoteVersion.AsString();
beammp_warn(std::string(ANSI_YELLOW_BOLD) + "NEW VERSION IS OUT! Please update to the new version (v" + RealVersionString + ") of the BeamMP-Server! Download it here: https://beammp.com/! For a guide on how to update, visit: https://wiki.beammp.com/en/home/server-maintenance#updating-the-server" + std::string(ANSI_RESET));
} else {
if (FirstTime) {
beammp_info("Server up-to-date!");
}
}
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Good);
break;
} else {
if (FirstTime) {
beammp_debug("Failed to fetch version from: " + url);
beammp_trace("got " + Response);
Application::SetSubsystemStatus("UpdateCheck", Application::Status::Bad);
}
}
}
if (Application::GetSubsystemStatuses().at("UpdateCheck") == Application::Status::Bad) {
if (FirstTime) {
beammp_warn("Unable to fetch version info from backend.");
}
}
FirstTime = false;
}
// thread name stuff
static std::map<std::thread::id, std::string> threadNameMap {};
static std::mutex ThreadNameMapMutex {};
std::string ThreadName(bool DebugModeOverride) {
auto Lock = std::unique_lock(ThreadNameMapMutex);
if (DebugModeOverride || Application::Settings.DebugModeEnabled) {
auto id = std::this_thread::get_id();
if (threadNameMap.find(id) != threadNameMap.end()) {
// found
return threadNameMap.at(id) + " ";
}
}
return "";
}
TEST_CASE("ThreadName") {
RegisterThread("MyThread");
auto OrigDebug = Application::Settings.DebugModeEnabled;
// ThreadName adds a space at the end, legacy but we need it still
SUBCASE("Debug mode enabled") {
Application::Settings.DebugModeEnabled = true;
CHECK(ThreadName(true) == "MyThread ");
CHECK(ThreadName(false) == "MyThread ");
}
SUBCASE("Debug mode disabled") {
Application::Settings.DebugModeEnabled = false;
CHECK(ThreadName(true) == "MyThread ");
CHECK(ThreadName(false) == "");
}
// cleanup
Application::Settings.DebugModeEnabled = OrigDebug;
}
void RegisterThread(const std::string& str) {
std::string ThreadId;
#ifdef BEAMMP_WINDOWS
ThreadId = std::to_string(GetCurrentThreadId());
#elif defined(BEAMMP_APPLE)
ThreadId = std::to_string(getpid()); // todo: research if 'getpid()' is a valid, posix compliant alternative to 'gettid()'
#elif defined(BEAMMP_LINUX)
ThreadId = std::to_string(gettid());
#endif
if (Application::Settings.DebugModeEnabled) {
std::ofstream ThreadFile(".Threads.log", std::ios::app);
ThreadFile << ("Thread \"" + str + "\" is TID " + ThreadId) << std::endl;
}
auto Lock = std::unique_lock(ThreadNameMapMutex);
threadNameMap[std::this_thread::get_id()] = str;
}
TEST_CASE("RegisterThread") {
RegisterThread("MyThread");
CHECK(threadNameMap.at(std::this_thread::get_id()) == "MyThread");
}
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
: major(major)
, minor(minor)
, patch(patch) { }
Version::Version(const std::array<uint8_t, 3>& v)
: Version(v[0], v[1], v[2]) {
}
std::string Version::AsString() {
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
}
TEST_CASE("Version::AsString") {
CHECK(Version { 0, 0, 0 }.AsString() == "0.0.0");
CHECK(Version { 1, 2, 3 }.AsString() == "1.2.3");
CHECK(Version { 255, 255, 255 }.AsString() == "255.255.255");
}
void LogChatMessage(const std::string& name, int id, const std::string& msg) {
if (Application::Settings.LogChat) {
std::stringstream ss;
ss << ThreadName();
ss << "[CHAT] ";
if (id != -1) {
ss << "(" << id << ") <" << name << "> ";
} else {
ss << name << "";
}
ss << msg;
#ifdef DOCTEST_CONFIG_DISABLE
Application::Console().Write(ss.str());
#endif
}
}
std::string GetPlatformAgnosticErrorString() {
#ifdef BEAMMP_WINDOWS
// This will provide us with the error code and an error message, all in one.
int err;
char msgbuf[256];
msgbuf[0] = '\0';
err = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msgbuf,
sizeof(msgbuf),
nullptr);
if (*msgbuf) {
return std::to_string(GetLastError()) + " - " + std::string(msgbuf);
} else {
return std::to_string(GetLastError());
}
#elif defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
return std::strerror(errno);
#else
return "(no human-readable errors on this platform)";
#endif
}
// TODO: add unit tests to SplitString
void SplitString(const std::string& str, const char delim, std::vector<std::string>& out) {
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
+64
View File
@@ -0,0 +1,64 @@
#include "Compat.h"
#include <cstring>
#include <doctest/doctest.h>
#ifndef WIN32
static struct termios old, current;
static void initTermios(int echo) {
tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */
if (echo) {
current.c_lflag |= ECHO; /* set echo mode */
} else {
current.c_lflag &= ~ECHO; /* set no echo mode */
}
tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}
static void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
TEST_CASE("init and reset termios") {
if (isatty(STDIN_FILENO)) {
struct termios original;
tcgetattr(0, &original);
SUBCASE("no echo") {
initTermios(false);
}
SUBCASE("yes echo") {
initTermios(true);
}
resetTermios();
struct termios current;
tcgetattr(0, &current);
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);
}
}
static char getch_(int echo) {
char ch;
initTermios(echo);
if (read(STDIN_FILENO, &ch, 1) < 0) {
// ignore, not much we can do
}
resetTermios();
return ch;
}
char _getch(void) {
return getch_(0);
}
#endif // !WIN32
+205
View File
@@ -0,0 +1,205 @@
#include "Http.h"
#include "Client.h"
#include "Common.h"
#include "CustomAssert.h"
#include "LuaAPI.h"
#include <map>
#include <nlohmann/json.hpp>
#include <random>
#include <stdexcept>
// TODO: Add sentry error handling back
using json = nlohmann::json;
std::string Http::GET(const std::string& host, int port, const std::string& target, unsigned int* status) {
httplib::SSLClient client(host, port);
client.enable_server_certificate_verification(false);
client.set_address_family(AF_INET);
auto res = client.Get(target.c_str());
if (res) {
if (status) {
*status = res->status;
}
return res->body;
} else {
return Http::ErrorString;
}
}
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);
client.set_read_timeout(std::chrono::seconds(10));
beammp_assert(client.is_valid());
client.enable_server_certificate_verification(false);
client.set_address_family(AF_INET);
auto res = client.Post(target.c_str(), headers, body.c_str(), body.size(), ContentType.c_str());
if (res) {
if (status) {
*status = res->status;
}
return res->body;
} else {
beammp_debug("POST failed: " + httplib::to_string(res.error()));
return Http::ErrorString;
}
}
// RFC 2616, RFC 7231
static std::map<size_t, const char*> Map = {
{ -1, "Invalid Response Code" },
{ 100, "Continue" },
{ 101, "Switching Protocols" },
{ 102, "Processing" },
{ 103, "Early Hints" },
{ 200, "OK" },
{ 201, "Created" },
{ 202, "Accepted" },
{ 203, "Non-Authoritative Information" },
{ 204, "No Content" },
{ 205, "Reset Content" },
{ 206, "Partial Content" },
{ 207, "Multi-Status" },
{ 208, "Already Reported" },
{ 226, "IM Used" },
{ 300, "Multiple Choices" },
{ 301, "Moved Permanently" },
{ 302, "Found" },
{ 303, "See Other" },
{ 304, "Not Modified" },
{ 305, "Use Proxy" },
{ 306, "(Unused)" },
{ 307, "Temporary Redirect" },
{ 308, "Permanent Redirect" },
{ 400, "Bad Request" },
{ 401, "Unauthorized" },
{ 402, "Payment Required" },
{ 403, "Forbidden" },
{ 404, "Not Found" },
{ 405, "Method Not Allowed" },
{ 406, "Not Acceptable" },
{ 407, "Proxy Authentication Required" },
{ 408, "Request Timeout" },
{ 409, "Conflict" },
{ 410, "Gone" },
{ 411, "Length Required" },
{ 412, "Precondition Failed" },
{ 413, "Payload Too Large" },
{ 414, "URI Too Long" },
{ 415, "Unsupported Media Type" },
{ 416, "Range Not Satisfiable" },
{ 417, "Expectation Failed" },
{ 421, "Misdirected Request" },
{ 422, "Unprocessable Entity" },
{ 423, "Locked" },
{ 424, "Failed Dependency" },
{ 425, "Too Early" },
{ 426, "Upgrade Required" },
{ 428, "Precondition Required" },
{ 429, "Too Many Requests" },
{ 431, "Request Header Fields Too Large" },
{ 451, "Unavailable For Legal Reasons" },
{ 500, "Internal Server Error" },
{ 501, "Not Implemented" },
{ 502, "Bad Gateway" },
{ 503, "Service Unavailable" },
{ 504, "Gateway Timeout" },
{ 505, "HTTP Version Not Supported" },
{ 506, "Variant Also Negotiates" },
{ 507, "Insufficient Storage" },
{ 508, "Loop Detected" },
{ 510, "Not Extended" },
{ 511, "Network Authentication Required" },
// cloudflare status codes
{ 520, "(CDN) Web Server Returns An Unknown Error" },
{ 521, "(CDN) Web Server Is Down" },
{ 522, "(CDN) Connection Timed Out" },
{ 523, "(CDN) Origin Is Unreachable" },
{ 524, "(CDN) A Timeout Occurred" },
{ 525, "(CDN) SSL Handshake Failed" },
{ 526, "(CDN) Invalid SSL Certificate" },
{ 527, "(CDN) Railgun Listener To Origin Error" },
{ 530, "(CDN) 1XXX Internal Error" },
};
static const char Magic[] = {
0x20, 0x2f, 0x5c, 0x5f,
0x2f, 0x5c, 0x0a, 0x28,
0x20, 0x6f, 0x2e, 0x6f,
0x20, 0x29, 0x0a, 0x20,
0x3e, 0x20, 0x5e, 0x20,
0x3c, 0x0a, 0x00
};
std::string Http::Status::ToString(int Code) {
if (Map.find(Code) != Map.end()) {
return Map.at(Code);
} else {
return std::to_string(Code);
}
}
TEST_CASE("Http::Status::ToString") {
CHECK(Http::Status::ToString(200) == "OK");
CHECK(Http::Status::ToString(696969) == "696969");
CHECK(Http::Status::ToString(-1) == "Invalid Response Code");
}
Http::Server::THttpServerInstance::THttpServerInstance() {
Application::SetSubsystemStatus("HTTPServer", Application::Status::Starting);
mThread = std::thread(&Http::Server::THttpServerInstance::operator(), this);
mThread.detach();
}
void Http::Server::THttpServerInstance::operator()() try {
beammp_info("HTTP(S) Server started on port " + std::to_string(Application::Settings.HTTPServerPort));
std::unique_ptr<httplib::Server> HttpLibServerInstance;
HttpLibServerInstance = std::make_unique<httplib::Server>();
// todo: make this IP agnostic so people can set their own IP
HttpLibServerInstance->Get("/", [](const httplib::Request&, httplib::Response& res) {
res.set_content("<!DOCTYPE html><article><h1>Hello World!</h1><section><p>BeamMP Server can now serve HTTP requests!</p></section></article></html>", "text/html");
});
HttpLibServerInstance->Get("/health", [](const httplib::Request&, httplib::Response& res) {
size_t SystemsGood = 0;
size_t SystemsBad = 0;
auto Statuses = Application::GetSubsystemStatuses();
for (const auto& NameStatusPair : Statuses) {
switch (NameStatusPair.second) {
case Application::Status::Starting:
case Application::Status::ShuttingDown:
case Application::Status::Shutdown:
case Application::Status::Good:
SystemsGood++;
break;
case Application::Status::Bad:
SystemsBad++;
break;
default:
beammp_assert_not_reachable();
}
}
res.set_content(
json {
{ "ok", SystemsBad == 0 },
}
.dump(),
"application/json");
res.status = 200;
});
// magic endpoint
HttpLibServerInstance->Get({ 0x2f, 0x6b, 0x69, 0x74, 0x74, 0x79 }, [](const httplib::Request&, httplib::Response& res) {
res.set_content(std::string(Magic), "text/plain");
});
HttpLibServerInstance->set_logger([](const httplib::Request& Req, const httplib::Response& Res) {
beammp_debug("Http Server: " + Req.method + " " + Req.target + " -> " + std::to_string(Res.status));
});
Application::SetSubsystemStatus("HTTPServer", Application::Status::Good);
auto ret = HttpLibServerInstance->listen(Application::Settings.HTTPServerIP.c_str(), Application::Settings.HTTPServerPort);
if (!ret) {
beammp_error("Failed to start http server (failed to listen). Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it.");
}
} catch (const std::exception& e) {
beammp_error("Failed to start http server. Please ensure the http server is configured properly in the ServerConfig.toml, or turn it off if you don't need it. Error: " + std::string(e.what()));
}
+680
View File
@@ -0,0 +1,680 @@
#include "LuaAPI.h"
#include "Client.h"
#include "Common.h"
#include "CustomAssert.h"
#include "TLuaEngine.h"
#include <nlohmann/json.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
std::string LuaAPI::LuaToString(const sol::object Value, size_t Indent, bool QuoteStrings) {
if (Indent > 80) {
return "[[possible recursion, refusing to keep printing]]";
}
switch (Value.get_type()) {
case sol::type::userdata: {
std::stringstream ss;
ss << "[[userdata: " << Value.as<sol::userdata>().pointer() << "]]";
return ss.str();
}
case sol::type::thread: {
std::stringstream ss;
ss << "[[thread: " << Value.as<sol::thread>().pointer() << "]] {"
<< "\n";
for (size_t i = 0; i < Indent; ++i) {
ss << "\t";
}
ss << "status: " << std::to_string(int(Value.as<sol::thread>().status())) << "\n}";
return ss.str();
}
case sol::type::lightuserdata: {
std::stringstream ss;
ss << "[[lightuserdata: " << Value.as<sol::lightuserdata>().pointer() << "]]";
return ss.str();
}
case sol::type::string:
if (QuoteStrings) {
return "\"" + Value.as<std::string>() + "\"";
} else {
return Value.as<std::string>();
}
case sol::type::number: {
std::stringstream ss;
ss << Value.as<float>();
return ss.str();
}
case sol::type::lua_nil:
case sol::type::none:
return "<nil>";
case sol::type::boolean:
return Value.as<bool>() ? "true" : "false";
case sol::type::table: {
std::stringstream Result;
auto Table = Value.as<sol::table>();
Result << "[[table: " << Table.pointer() << "]]: {";
if (!Table.empty()) {
for (const auto& Entry : Table) {
Result << "\n";
for (size_t i = 0; i < Indent; ++i) {
Result << "\t";
}
Result << LuaToString(Entry.first, Indent + 1) << ": " << LuaToString(Entry.second, Indent + 1, true) << ",";
}
Result << "\n";
}
for (size_t i = 0; i < Indent - 1; ++i) {
Result << "\t";
}
Result << "}";
return Result.str();
}
case sol::type::function: {
std::stringstream ss;
ss << "[[function: " << Value.as<sol::function>().pointer() << "]]";
return ss.str();
}
case sol::type::poly:
return "<poly>";
default:
return "<unprintable type>";
}
}
std::string LuaAPI::MP::GetOSName() {
#if WIN32
return "Windows";
#elif __linux
return "Linux";
#else
return "Other";
#endif
}
std::tuple<int, int, int> LuaAPI::MP::GetServerVersion() {
return { Application::ServerVersion().major, Application::ServerVersion().minor, Application::ServerVersion().patch };
}
void LuaAPI::Print(sol::variadic_args Args) {
std::string ToPrint = "";
for (const auto& Arg : Args) {
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
ToPrint += "\t";
}
luaprint(ToPrint);
}
TEST_CASE("LuaAPI::MP::GetServerVersion") {
const auto [ma, mi, pa] = LuaAPI::MP::GetServerVersion();
const auto real = Application::ServerVersion();
CHECK(ma == real.major);
CHECK(mi == real.minor);
CHECK(pa == real.patch);
}
static inline std::pair<bool, std::string> InternalTriggerClientEvent(int PlayerID, const std::string& EventName, const std::string& Data) {
std::string Packet = "E:" + EventName + ":" + Data;
if (PlayerID == -1) {
LuaAPI::MP::Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
return { true, "" };
} else {
auto MaybeClient = GetClient(LuaAPI::MP::Engine->Server(), PlayerID);
if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_errorf("TriggerClientEvent invalid Player ID '{}'", PlayerID);
return { false, "Invalid Player ID" };
}
auto c = MaybeClient.value().lock();
if (!LuaAPI::MP::Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_lua_errorf("Respond failed, dropping client {}", PlayerID);
LuaAPI::MP::Engine->Network().ClientKick(*c, "Disconnected after failing to receive packets");
return { false, "Respond failed, dropping client" };
}
return { true, "" };
}
}
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEvent(int PlayerID, const std::string& EventName, const sol::object& DataObj) {
std::string Data = DataObj.as<std::string>();
return InternalTriggerClientEvent(PlayerID, EventName, Data);
}
std::pair<bool, std::string> LuaAPI::MP::DropPlayer(int ID, std::optional<std::string> MaybeReason) {
auto MaybeClient = GetClient(Engine->Server(), ID);
if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_errorf("Tried to drop client with id {}, who doesn't exist", ID);
return { false, "Player does not exist" };
}
auto c = MaybeClient.value().lock();
LuaAPI::MP::Engine->Network().ClientKick(*c, MaybeReason.value_or("No reason"));
return { true, "" };
}
std::pair<bool, std::string> LuaAPI::MP::SendChatMessage(int ID, const std::string& Message) {
std::pair<bool, std::string> Result;
std::string Packet = "C:Server: " + Message;
if (ID == -1) {
LogChatMessage("<Server> (to everyone) ", -1, Message);
Engine->Network().SendToAll(nullptr, StringToVector(Packet), true, true);
Result.first = true;
} else {
auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto c = MaybeClient.value().lock();
if (!c->IsSynced()) {
Result.first = false;
Result.second = "Player still syncing data";
return Result;
}
LogChatMessage("<Server> (to \"" + c->GetName() + "\")", -1, Message);
if (!Engine->Network().Respond(*c, StringToVector(Packet), true)) {
beammp_errorf("Failed to send chat message back to sender (id {}) - did the sender disconnect?", ID);
// TODO: should we return an error here?
}
Result.first = true;
} else {
beammp_lua_error("SendChatMessage invalid argument [1] invalid ID");
Result.first = false;
Result.second = "Invalid Player ID";
}
return Result;
}
return Result;
}
std::pair<bool, std::string> LuaAPI::MP::RemoveVehicle(int PID, int VID) {
std::pair<bool, std::string> Result;
auto MaybeClient = GetClient(Engine->Server(), PID);
if (!MaybeClient || MaybeClient.value().expired()) {
beammp_lua_error("RemoveVehicle invalid Player ID");
Result.first = false;
Result.second = "Invalid Player ID";
return Result;
}
auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine->Network().SendToAll(nullptr, StringToVector(Destroy), true, true);
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) {
switch (ConfigID) {
case 0: // debug
if (NewValue.is<bool>()) {
Application::Settings.DebugModeEnabled = NewValue.as<bool>();
beammp_info(std::string("Set `Debug` to ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
} else {
beammp_lua_error("set invalid argument [2] expected boolean");
}
break;
case 1: // private
if (NewValue.is<bool>()) {
Application::Settings.Private = NewValue.as<bool>();
beammp_info(std::string("Set `Private` to ") + (Application::Settings.Private ? "true" : "false"));
} else {
beammp_lua_error("set invalid argument [2] expected boolean");
}
break;
case 2: // max cars
if (NewValue.is<int>()) {
Application::Settings.MaxCars = NewValue.as<int>();
beammp_info(std::string("Set `MaxCars` to ") + std::to_string(Application::Settings.MaxCars));
} else {
beammp_lua_error("set invalid argument [2] expected integer");
}
break;
case 3: // max players
if (NewValue.is<int>()) {
Application::Settings.MaxPlayers = NewValue.as<int>();
beammp_info(std::string("Set `MaxPlayers` to ") + std::to_string(Application::Settings.MaxPlayers));
} else {
beammp_lua_error("set invalid argument [2] expected integer");
}
break;
case 4: // Map
if (NewValue.is<std::string>()) {
Application::Settings.MapName = NewValue.as<std::string>();
beammp_info(std::string("Set `Map` to ") + Application::Settings.MapName);
} else {
beammp_lua_error("set invalid argument [2] expected string");
}
break;
case 5: // Name
if (NewValue.is<std::string>()) {
Application::Settings.ServerName = NewValue.as<std::string>();
beammp_info(std::string("Set `Name` to ") + Application::Settings.ServerName);
} else {
beammp_lua_error("set invalid argument [2] expected string");
}
break;
case 6: // Desc
if (NewValue.is<std::string>()) {
Application::Settings.ServerDesc = NewValue.as<std::string>();
beammp_info(std::string("Set `Description` to ") + Application::Settings.ServerDesc);
} else {
beammp_lua_error("set invalid argument [2] expected string");
}
break;
default:
beammp_warn("Invalid config ID \"" + std::to_string(ConfigID) + "\". Use `MP.Settings.*` enum for this.");
break;
}
}
void LuaAPI::MP::Sleep(size_t Ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(Ms));
}
bool LuaAPI::MP::IsPlayerConnected(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value().lock()->IsConnected();
} else {
return false;
}
}
bool LuaAPI::MP::IsPlayerGuest(int ID) {
auto MaybeClient = GetClient(Engine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value().lock()->IsGuest();
} else {
return false;
}
}
void LuaAPI::MP::PrintRaw(sol::variadic_args Args) {
std::string ToPrint = "";
for (const auto& Arg : Args) {
ToPrint += LuaToString(static_cast<const sol::object>(Arg));
ToPrint += "\t";
}
#ifdef DOCTEST_CONFIG_DISABLE
Application::Console().WriteRaw(ToPrint);
#endif
}
int LuaAPI::PanicHandler(lua_State* State) {
beammp_lua_error("PANIC: " + sol::stack::get<std::string>(State, 1));
return 0;
}
template <typename FnT, typename... ArgsT>
static std::pair<bool, std::string> FSWrapper(FnT Fn, ArgsT&&... Args) {
std::error_code errc;
std::pair<bool, std::string> Result;
Fn(std::forward<ArgsT>(Args)..., errc);
Result.first = errc == std::error_code {};
if (!Result.first) {
Result.second = errc.message();
}
return Result;
}
std::pair<bool, std::string> LuaAPI::FS::CreateDirectory(const std::string& Path) {
std::error_code errc;
std::pair<bool, std::string> Result;
fs::create_directories(Path, errc);
Result.first = errc == std::error_code {};
if (!Result.first) {
Result.second = errc.message();
}
return Result;
}
TEST_CASE("LuaAPI::FS::CreateDirectory") {
std::string TestDir = "beammp_test_dir";
fs::remove_all(TestDir);
SUBCASE("Single level dir") {
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
CHECK(Ok);
CHECK(Err == "");
CHECK(fs::exists(TestDir));
}
SUBCASE("Multi level dir") {
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir + "/a/b/c");
CHECK(Ok);
CHECK(Err == "");
CHECK(fs::exists(TestDir + "/a/b/c"));
}
SUBCASE("Already exists") {
const auto [Ok, Err] = LuaAPI::FS::CreateDirectory(TestDir);
CHECK(Ok);
CHECK(Err == "");
CHECK(fs::exists(TestDir));
const auto [Ok2, Err2] = LuaAPI::FS::CreateDirectory(TestDir);
CHECK(Ok2);
CHECK(Err2 == "");
}
fs::remove_all(TestDir);
}
std::pair<bool, std::string> LuaAPI::FS::Remove(const std::string& Path) {
std::error_code errc;
std::pair<bool, std::string> Result;
fs::remove(fs::relative(Path), errc);
Result.first = errc == std::error_code {};
if (!Result.first) {
Result.second = errc.message();
}
return Result;
}
TEST_CASE("LuaAPI::FS::Remove") {
const std::string TestFileOrDir = "beammp_test_thing";
SUBCASE("Remove existing directory") {
fs::create_directory(TestFileOrDir);
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
CHECK(Ok);
CHECK_EQ(Err, "");
CHECK(!fs::exists(TestFileOrDir));
}
SUBCASE("Remove non-existing directory") {
fs::remove_all(TestFileOrDir);
const auto [Ok, Err] = LuaAPI::FS::Remove(TestFileOrDir);
CHECK(Ok);
CHECK_EQ(Err, "");
CHECK(!fs::exists(TestFileOrDir));
}
// TODO: add tests for files
// TODO: add tests for files and folders without access permissions (failure)
}
std::pair<bool, std::string> LuaAPI::FS::Rename(const std::string& Path, const std::string& NewPath) {
std::error_code errc;
std::pair<bool, std::string> Result;
fs::rename(Path, NewPath, errc);
Result.first = errc == std::error_code {};
if (!Result.first) {
Result.second = errc.message();
}
return Result;
}
TEST_CASE("LuaAPI::FS::Rename") {
const auto TestDir = "beammp_test_dir";
const auto OtherTestDir = "beammp_test_dir_2";
fs::remove_all(OtherTestDir);
fs::create_directory(TestDir);
const auto [Ok, Err] = LuaAPI::FS::Rename(TestDir, OtherTestDir);
CHECK(Ok);
CHECK_EQ(Err, "");
CHECK(!fs::exists(TestDir));
CHECK(fs::exists(OtherTestDir));
fs::remove_all(OtherTestDir);
fs::remove_all(TestDir);
}
std::pair<bool, std::string> LuaAPI::FS::Copy(const std::string& Path, const std::string& NewPath) {
std::error_code errc;
std::pair<bool, std::string> Result;
fs::copy(Path, NewPath, fs::copy_options::recursive, errc);
Result.first = errc == std::error_code {};
if (!Result.first) {
Result.second = errc.message();
}
return Result;
}
TEST_CASE("LuaAPI::FS::Copy") {
const auto TestDir = "beammp_test_dir";
const auto OtherTestDir = "beammp_test_dir_2";
fs::remove_all(OtherTestDir);
fs::create_directory(TestDir);
const auto [Ok, Err] = LuaAPI::FS::Copy(TestDir, OtherTestDir);
CHECK(Ok);
CHECK_EQ(Err, "");
CHECK(fs::exists(TestDir));
CHECK(fs::exists(OtherTestDir));
fs::remove_all(OtherTestDir);
fs::remove_all(TestDir);
}
bool LuaAPI::FS::Exists(const std::string& Path) {
return fs::exists(Path);
}
TEST_CASE("LuaAPI::FS::Exists") {
const auto TestDir = "beammp_test_dir";
const auto OtherTestDir = "beammp_test_dir_2";
fs::remove_all(OtherTestDir);
fs::create_directory(TestDir);
CHECK(LuaAPI::FS::Exists(TestDir));
CHECK(!LuaAPI::FS::Exists(OtherTestDir));
fs::remove_all(OtherTestDir);
fs::remove_all(TestDir);
}
std::string LuaAPI::FS::GetFilename(const std::string& Path) {
return fs::path(Path).filename().string();
}
TEST_CASE("LuaAPI::FS::GetFilename") {
CHECK(LuaAPI::FS::GetFilename("test.txt") == "test.txt");
CHECK(LuaAPI::FS::GetFilename("/test.txt") == "test.txt");
CHECK(LuaAPI::FS::GetFilename("place/test.txt") == "test.txt");
CHECK(LuaAPI::FS::GetFilename("/some/../place/test.txt") == "test.txt");
}
std::string LuaAPI::FS::GetExtension(const std::string& Path) {
return fs::path(Path).extension().string();
}
TEST_CASE("LuaAPI::FS::GetExtension") {
CHECK(LuaAPI::FS::GetExtension("test.txt") == ".txt");
CHECK(LuaAPI::FS::GetExtension("/test.txt") == ".txt");
CHECK(LuaAPI::FS::GetExtension("place/test.txt") == ".txt");
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.txt") == ".txt");
CHECK(LuaAPI::FS::GetExtension("/some/../place/test") == "");
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.c") == ".c");
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.") == ".");
CHECK(LuaAPI::FS::GetExtension("/some/../place/test.a.b.") == ".");
}
std::string LuaAPI::FS::GetParentFolder(const std::string& Path) {
return fs::path(Path).parent_path().string();
}
TEST_CASE("LuaAPI::FS::GetParentFolder") {
CHECK(LuaAPI::FS::GetParentFolder("test.txt") == "");
CHECK(LuaAPI::FS::GetParentFolder("/test.txt") == "/");
CHECK(LuaAPI::FS::GetParentFolder("place/test.txt") == "place");
CHECK(LuaAPI::FS::GetParentFolder("/some/../place/test.txt") == "/some/../place");
}
// TODO: add tests
bool LuaAPI::FS::IsDirectory(const std::string& Path) {
return fs::is_directory(Path);
}
// TODO: add tests
bool LuaAPI::FS::IsFile(const std::string& Path) {
return fs::is_regular_file(Path);
}
// TODO: add tests
std::string LuaAPI::FS::ConcatPaths(sol::variadic_args Args) {
fs::path Path;
for (size_t i = 0; i < Args.size(); ++i) {
auto Obj = Args[i];
if (!Obj.is<std::string>()) {
beammp_lua_error("FS.Concat called with non-string argument");
return "";
}
Path += Obj.as<std::string>();
if (i < Args.size() - 1 && !Path.empty()) {
Path += fs::path::preferred_separator;
}
}
auto Result = Path.lexically_normal().string();
return Result;
}
static void JsonEncodeRecursive(nlohmann::json& json, const sol::object& left, const sol::object& right, bool is_array, size_t depth = 0) {
if (depth > 100) {
beammp_lua_error("json serialize will not go deeper than 100 nested tables, internal references assumed, aborted this path");
return;
}
std::string key {};
switch (left.get_type()) {
case sol::type::lua_nil:
case sol::type::none:
case sol::type::poly:
case sol::type::boolean:
case sol::type::lightuserdata:
case sol::type::userdata:
case sol::type::thread:
case sol::type::function:
case sol::type::table:
beammp_lua_error("JsonEncode: left side of table field is unexpected type");
return;
case sol::type::string:
key = left.as<std::string>();
break;
case sol::type::number:
key = std::to_string(left.as<double>());
break;
default:
beammp_assert_not_reachable();
}
nlohmann::json value;
switch (right.get_type()) {
case sol::type::lua_nil:
case sol::type::none:
return;
case sol::type::poly:
beammp_lua_warn("unsure what to do with poly type in JsonEncode, ignoring");
return;
case sol::type::boolean:
value = right.as<bool>();
break;
case sol::type::lightuserdata:
beammp_lua_warn("unsure what to do with lightuserdata in JsonEncode, ignoring");
return;
case sol::type::userdata:
beammp_lua_warn("unsure what to do with userdata in JsonEncode, ignoring");
return;
case sol::type::thread:
beammp_lua_warn("unsure what to do with thread in JsonEncode, ignoring");
return;
case sol::type::string:
value = right.as<std::string>();
break;
case sol::type::number:
value = right.as<double>();
break;
case sol::type::function:
beammp_lua_warn("unsure what to do with function in JsonEncode, ignoring");
return;
case sol::type::table: {
bool local_is_array = true;
for (const auto& pair : right.as<sol::table>()) {
if (pair.first.get_type() != sol::type::number) {
local_is_array = false;
}
}
for (const auto& pair : right.as<sol::table>()) {
JsonEncodeRecursive(value, pair.first, pair.second, local_is_array, depth + 1);
}
break;
}
default:
beammp_assert_not_reachable();
}
if (is_array) {
json.push_back(value);
} else {
json[key] = value;
}
}
std::string LuaAPI::MP::JsonEncode(const sol::table& object) {
nlohmann::json json;
// table
bool is_array = true;
for (const auto& pair : object.as<sol::table>()) {
if (pair.first.get_type() != sol::type::number) {
is_array = false;
}
}
for (const auto& entry : object) {
JsonEncodeRecursive(json, entry.first, entry.second, is_array);
}
return json.dump();
}
std::string LuaAPI::MP::JsonDiff(const std::string& a, const std::string& b) {
if (!nlohmann::json::accept(a)) {
beammp_lua_error("JsonDiff first argument is not valid json: `" + a + "`");
return "";
}
if (!nlohmann::json::accept(b)) {
beammp_lua_error("JsonDiff second argument is not valid json: `" + b + "`");
return "";
}
auto a_json = nlohmann::json::parse(a);
auto b_json = nlohmann::json::parse(b);
return nlohmann::json::diff(a_json, b_json).dump();
}
std::string LuaAPI::MP::JsonDiffApply(const std::string& data, const std::string& patch) {
if (!nlohmann::json::accept(data)) {
beammp_lua_error("JsonDiffApply first argument is not valid json: `" + data + "`");
return "";
}
if (!nlohmann::json::accept(patch)) {
beammp_lua_error("JsonDiffApply second argument is not valid json: `" + patch + "`");
return "";
}
auto a_json = nlohmann::json::parse(data);
auto b_json = nlohmann::json::parse(patch);
a_json.patch(b_json);
return a_json.dump();
}
std::string LuaAPI::MP::JsonPrettify(const std::string& json) {
if (!nlohmann::json::accept(json)) {
beammp_lua_error("JsonPrettify argument is not valid json: `" + json + "`");
return "";
}
return nlohmann::json::parse(json).dump(4);
}
std::string LuaAPI::MP::JsonMinify(const std::string& json) {
if (!nlohmann::json::accept(json)) {
beammp_lua_error("JsonMinify argument is not valid json: `" + json + "`");
return "";
}
return nlohmann::json::parse(json).dump(-1);
}
std::string LuaAPI::MP::JsonFlatten(const std::string& json) {
if (!nlohmann::json::accept(json)) {
beammp_lua_error("JsonFlatten argument is not valid json: `" + json + "`");
return "";
}
return nlohmann::json::parse(json).flatten().dump(-1);
}
std::string LuaAPI::MP::JsonUnflatten(const std::string& json) {
if (!nlohmann::json::accept(json)) {
beammp_lua_error("JsonUnflatten argument is not valid json: `" + json + "`");
return "";
}
return nlohmann::json::parse(json).unflatten().dump(-1);
}
std::pair<bool, std::string> LuaAPI::MP::TriggerClientEventJson(int PlayerID, const std::string& EventName, const sol::table& Data) {
return InternalTriggerClientEvent(PlayerID, EventName, JsonEncode(Data));
}
+62
View File
@@ -0,0 +1,62 @@
#include "SignalHandling.h"
#include "Common.h"
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
#include <csignal>
static void UnixSignalHandler(int sig) {
switch (sig) {
case SIGPIPE:
beammp_warn("ignoring SIGPIPE");
break;
case SIGTERM:
beammp_info("gracefully shutting down via SIGTERM");
Application::GracefullyShutdown();
break;
case SIGINT:
beammp_info("gracefully shutting down via SIGINT");
Application::GracefullyShutdown();
break;
default:
beammp_debug("unhandled signal: " + std::to_string(sig));
break;
}
}
#endif // UNIX
#ifdef BEAMMP_WINDOWS
#include <windows.h>
// return TRUE if handled, FALSE if not
BOOL WINAPI Win32CtrlC_Handler(DWORD CtrlType) {
switch (CtrlType) {
case CTRL_C_EVENT:
beammp_info("gracefully shutting down via CTRL+C");
Application::GracefullyShutdown();
return TRUE;
case CTRL_BREAK_EVENT:
beammp_info("gracefully shutting down via CTRL+BREAK");
Application::GracefullyShutdown();
return TRUE;
case CTRL_CLOSE_EVENT:
beammp_info("gracefully shutting down via close");
Application::GracefullyShutdown();
return TRUE;
}
// we dont care for any others like CTRL_LOGOFF_EVENT and CTRL_SHUTDOWN_EVENT
return FALSE;
}
#endif // WINDOWS
void SetupSignalHandlers() {
// signal handlers for unix#include <windows.h>
#if defined(BEAMMP_LINUX) || defined(BEAMMP_APPLE)
beammp_trace("registering handlers for signals");
signal(SIGPIPE, UnixSignalHandler);
signal(SIGTERM, UnixSignalHandler);
#ifndef DEBUG
signal(SIGINT, UnixSignalHandler);
#endif // DEBUG
#elif defined(BEAMMP_WINDOWS)
beammp_trace("registering handlers for CTRL_*_EVENTs");
SetConsoleCtrlHandler(Win32CtrlC_Handler, TRUE);
#endif
}
+318
View File
@@ -0,0 +1,318 @@
#include "Common.h"
#include "TConfig.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <istream>
#include <sstream>
// General
static constexpr std::string_view StrDebug = "Debug";
static constexpr std::string_view EnvStrDebug = "BEAMMP_DEBUG";
static constexpr std::string_view StrPrivate = "Private";
static constexpr std::string_view EnvStrPrivate = "BEAMMP_PRIVATE";
static constexpr std::string_view StrPort = "Port";
static constexpr std::string_view EnvStrPort = "BEAMMP_PORT";
static constexpr std::string_view StrMaxCars = "MaxCars";
static constexpr std::string_view EnvStrMaxCars = "BEAMMP_MAX_CARS";
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
static constexpr std::string_view EnvStrMaxPlayers = "BEAMMP_MAX_PLAYERS";
static constexpr std::string_view StrMap = "Map";
static constexpr std::string_view EnvStrMap = "BEAMMP_MAP";
static constexpr std::string_view StrName = "Name";
static constexpr std::string_view EnvStrName = "BEAMMP_NAME";
static constexpr std::string_view StrDescription = "Description";
static constexpr std::string_view EnvStrDescription = "BEAMMP_DESCRIPTION";
static constexpr std::string_view StrTags = "Tags";
static constexpr std::string_view EnvStrTags = "BEAMMP_TAGS";
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
static constexpr std::string_view EnvStrResourceFolder = "BEAMMP_RESOURCE_FOLDER";
static constexpr std::string_view StrAuthKey = "AuthKey";
static constexpr std::string_view EnvStrAuthKey = "BEAMMP_AUTH_KEY";
static constexpr std::string_view StrLogChat = "LogChat";
static constexpr std::string_view EnvStrLogChat = "BEAMMP_LOG_CHAT";
static constexpr std::string_view StrPassword = "Password";
// Misc
static constexpr std::string_view StrSendErrors = "SendErrors";
static constexpr std::string_view StrSendErrorsMessageEnabled = "SendErrorsShowMessage";
static constexpr std::string_view StrHideUpdateMessages = "ImScaredOfUpdates";
TEST_CASE("TConfig::TConfig") {
const std::string CfgFile = "beammp_server_testconfig.toml";
fs::remove(CfgFile);
TConfig Cfg(CfgFile);
CHECK(fs::file_size(CfgFile) != 0);
std::string buf;
{
buf.resize(fs::file_size(CfgFile));
auto fp = std::fopen(CfgFile.c_str(), "r");
auto res = std::fread(buf.data(), 1, buf.size(), fp);
if (res != buf.size()) {
// IGNORE?
}
std::fclose(fp);
}
INFO("file contents are:", buf);
const auto table = toml::parse(CfgFile);
CHECK(table.at("General").is_table());
CHECK(table.at("Misc").is_table());
fs::remove(CfgFile);
}
TConfig::TConfig(const std::string& ConfigFileName)
: mConfigFileName(ConfigFileName) {
Application::SetSubsystemStatus("Config", Application::Status::Starting);
if (!fs::exists(mConfigFileName) || !fs::is_regular_file(mConfigFileName)) {
beammp_info("No config file found! Generating one...");
CreateConfigFile();
}
if (!mFailed) {
if (fs::exists("Server.cfg")) {
beammp_warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(mConfigFileName) + "\" is used. You can safely delete the \"Server.cfg\".");
}
ParseFromFile(mConfigFileName);
}
}
template <typename CommentsT>
void SetComment(CommentsT& Comments, const std::string& Comment) {
Comments.clear();
Comments.push_back(Comment);
}
/**
* @brief Writes out the loaded application state into ServerConfig.toml
*
* This writes out the current state of application settings that are
* applied to the server instance (i.e. the current application settings loaded in the server).
* If the state of the application settings changes during runtime,
* call this function whenever something about the config changes
* whether it is in TConfig.cpp or the configuration file.
*/
void TConfig::FlushToFile() {
// auto data = toml::parse<toml::preserve_comments>(mConfigFileName);
auto data = toml::value {};
data["General"][StrAuthKey.data()] = Application::Settings.Key;
SetComment(data["General"][StrAuthKey.data()].comments(), " AuthKey has to be filled out in order to run the server");
data["General"][StrLogChat.data()] = Application::Settings.LogChat;
SetComment(data["General"][StrLogChat.data()].comments(), " Whether to log chat messages in the console / log");
data["General"][StrDebug.data()] = Application::Settings.DebugModeEnabled;
data["General"][StrPrivate.data()] = Application::Settings.Private;
data["General"][StrPort.data()] = Application::Settings.Port;
data["General"][StrName.data()] = Application::Settings.ServerName;
SetComment(data["General"][StrTags.data()].comments(), " Add custom identifying tags to your server to make it easier to find. Format should be TagA,TagB,TagC. Note the comma seperation.");
data["General"][StrTags.data()] = Application::Settings.ServerTags;
data["General"][StrMaxCars.data()] = Application::Settings.MaxCars;
data["General"][StrMaxPlayers.data()] = Application::Settings.MaxPlayers;
data["General"][StrMap.data()] = Application::Settings.MapName;
data["General"][StrDescription.data()] = Application::Settings.ServerDesc;
data["General"][StrResourceFolder.data()] = Application::Settings.Resource;
// data["General"][StrPassword.data()] = Application::Settings.Password;
// SetComment(data["General"][StrPassword.data()].comments(), " Sets a password on this server, which restricts people from joining. To join, a player must enter this exact password. Leave empty ("") to disable the password.");
// Misc
data["Misc"][StrHideUpdateMessages.data()] = Application::Settings.HideUpdateMessages;
SetComment(data["Misc"][StrHideUpdateMessages.data()].comments(), " Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.");
data["Misc"][StrSendErrors.data()] = Application::Settings.SendErrors;
SetComment(data["Misc"][StrSendErrors.data()].comments(), " You can turn on/off the SendErrors message you get on startup here");
data["Misc"][StrSendErrorsMessageEnabled.data()] = Application::Settings.SendErrorsMessageEnabled;
SetComment(data["Misc"][StrSendErrorsMessageEnabled.data()].comments(), " 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`");
std::stringstream Ss;
Ss << "# This is the BeamMP-Server config file.\n"
"# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`\n"
"# IMPORTANT: Fill in the AuthKey with the key you got from `https://keymaster.beammp.com/` on the left under \"Keys\"\n"
<< data;
auto File = std::fopen(mConfigFileName.c_str(), "w+");
if (!File) {
beammp_error("Failed to create/write to config file: " + GetPlatformAgnosticErrorString());
throw std::runtime_error("Failed to create/write to config file");
}
auto Str = Ss.str();
auto N = std::fwrite(Str.data(), sizeof(char), Str.size(), File);
if (N != Str.size()) {
beammp_error("Failed to write to config file properly, config file might be misshapen");
}
std::fclose(File);
}
void TConfig::CreateConfigFile() {
// build from old config Server.cfg
try {
if (fs::exists("Server.cfg")) {
// parse it (this is weird and bad and should be removed in some future version)
ParseOldFormat();
}
} catch (const std::exception& e) {
beammp_error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
}
FlushToFile();
}
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, std::string& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = std::string(envp);
return;
}
}
if (Table[Category.c_str()][Key.data()].is_string()) {
OutValue = Table[Category.c_str()][Key.data()].as_string();
}
}
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, bool& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
auto Str = std::string(envp);
OutValue = Str == "1" || Str == "true";
return;
}
}
if (Table[Category.c_str()][Key.data()].is_boolean()) {
OutValue = Table[Category.c_str()][Key.data()].as_boolean();
}
}
void TConfig::TryReadValue(toml::value& Table, const std::string& Category, const std::string_view& Key, const std::string_view& Env, int& OutValue) {
if (!Env.empty()) {
if (const char* envp = std::getenv(Env.data()); envp != nullptr && std::strcmp(envp, "") != 0) {
OutValue = int(std::strtol(envp, nullptr, 10));
return;
}
}
if (Table[Category.c_str()][Key.data()].is_integer()) {
OutValue = int(Table[Category.c_str()][Key.data()].as_integer());
}
}
void TConfig::ParseFromFile(std::string_view name) {
try {
toml::value data = toml::parse<toml::preserve_comments>(name.data());
// GENERAL
TryReadValue(data, "General", StrDebug, EnvStrDebug, Application::Settings.DebugModeEnabled);
TryReadValue(data, "General", StrPrivate, EnvStrPrivate, Application::Settings.Private);
TryReadValue(data, "General", StrPort, EnvStrPort, Application::Settings.Port);
TryReadValue(data, "General", StrMaxCars, EnvStrMaxCars, Application::Settings.MaxCars);
TryReadValue(data, "General", StrMaxPlayers, EnvStrMaxPlayers, Application::Settings.MaxPlayers);
TryReadValue(data, "General", StrMap, EnvStrMap, Application::Settings.MapName);
TryReadValue(data, "General", StrName, EnvStrName, Application::Settings.ServerName);
TryReadValue(data, "General", StrDescription, EnvStrDescription, Application::Settings.ServerDesc);
TryReadValue(data, "General", StrTags, EnvStrTags, Application::Settings.ServerTags);
TryReadValue(data, "General", StrResourceFolder, EnvStrResourceFolder, Application::Settings.Resource);
TryReadValue(data, "General", StrAuthKey, EnvStrAuthKey, Application::Settings.Key);
TryReadValue(data, "General", StrLogChat, EnvStrLogChat, Application::Settings.LogChat);
TryReadValue(data, "General", StrPassword, "", Application::Settings.Password);
// Misc
TryReadValue(data, "Misc", StrSendErrors, "", Application::Settings.SendErrors);
TryReadValue(data, "Misc", StrHideUpdateMessages, "", Application::Settings.HideUpdateMessages);
TryReadValue(data, "Misc", StrSendErrorsMessageEnabled, "", Application::Settings.SendErrorsMessageEnabled);
} catch (const std::exception& err) {
beammp_error("Error parsing config file value: " + std::string(err.what()));
mFailed = true;
Application::SetSubsystemStatus("Config", Application::Status::Bad);
return;
}
PrintDebug();
// Update in any case
FlushToFile();
// all good so far, let's check if there's a key
if (Application::Settings.Key.empty()) {
beammp_error("No AuthKey specified in the \"" + std::string(mConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
Application::SetSubsystemStatus("Config", Application::Status::Bad);
mFailed = true;
return;
}
Application::SetSubsystemStatus("Config", Application::Status::Good);
if (Application::Settings.Key.size() != 36) {
beammp_warn("AuthKey specified is the wrong length and likely isn't valid.");
}
}
void TConfig::PrintDebug() {
beammp_debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
beammp_debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
beammp_debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
beammp_debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
beammp_debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
beammp_debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
beammp_debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
beammp_debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
beammp_debug(std::string(StrTags) + ": " + TagsAsPrettyArray());
beammp_debug(std::string(StrLogChat) + ": \"" + (Application::Settings.LogChat ? "true" : "false") + "\"");
beammp_debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
// special!
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() {
std::ifstream File("Server.cfg");
// read all, strip comments
std::string Content;
for (;;) {
std::string Line;
std::getline(File, Line);
if (!Line.empty() && Line.at(0) != '#') {
Line = Line.substr(0, Line.find_first_of('#'));
Content += Line + "\n";
}
if (!File.good()) {
break;
}
}
std::stringstream Str(Content);
std::string Key, Ignore, Value;
for (;;) {
Str >> Key >> std::ws >> Ignore >> std::ws;
std::getline(Str, Value);
if (Str.eof()) {
break;
}
std::stringstream ValueStream(Value);
ValueStream >> std::ws; // strip leading whitespace if any
Value = ValueStream.str();
if (Key == "Debug") {
Application::Settings.DebugModeEnabled = Value.find("true") != std::string::npos;
} else if (Key == "Private") {
Application::Settings.Private = Value.find("true") != std::string::npos;
} else if (Key == "Port") {
ValueStream >> Application::Settings.Port;
} else if (Key == "Cars") {
ValueStream >> Application::Settings.MaxCars;
} else if (Key == "MaxPlayers") {
ValueStream >> Application::Settings.MaxPlayers;
} else if (Key == "Map") {
Application::Settings.MapName = Value.substr(1, Value.size() - 3);
} else if (Key == "Name") {
Application::Settings.ServerName = Value.substr(1, Value.size() - 3);
} else if (Key == "Desc") {
Application::Settings.ServerDesc = Value.substr(1, Value.size() - 3);
} else if (Key == "use") {
Application::Settings.Resource = Value.substr(1, Value.size() - 3);
} else if (Key == "AuthKey") {
Application::Settings.Key = Value.substr(1, Value.size() - 3);
} else {
beammp_warn("unknown key in old auth file (ignored): " + Key);
}
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;
}
+718
View File
@@ -0,0 +1,718 @@
#include "TConsole.h"
#include "Common.h"
#include "Compat.h"
#include "Client.h"
#include "CustomAssert.h"
#include "LuaAPI.h"
#include "TLuaEngine.h"
#include <ctime>
#include <mutex>
#include <sstream>
static inline bool StringStartsWith(const std::string& What, const std::string& StartsWith) {
return What.size() >= StartsWith.size() && What.substr(0, StartsWith.size()) == StartsWith;
}
TEST_CASE("StringStartsWith") {
CHECK(StringStartsWith("Hello, World", "Hello"));
CHECK(StringStartsWith("Hello, World", "H"));
CHECK(StringStartsWith("Hello, World", ""));
CHECK(!StringStartsWith("Hello, World", "ello"));
CHECK(!StringStartsWith("Hello, World", "World"));
CHECK(StringStartsWith("", ""));
CHECK(!StringStartsWith("", "hello"));
}
// Trims leading and trailing spaces, newlines, tabs, etc.
static inline std::string TrimString(std::string S) {
S.erase(S.begin(), std::find_if(S.begin(), S.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
S.erase(std::find_if(S.rbegin(), S.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(),
S.end());
return S;
}
TEST_CASE("TrimString") {
CHECK(TrimString("hel lo") == "hel lo");
CHECK(TrimString(" hel lo") == "hel lo");
CHECK(TrimString(" hel lo ") == "hel lo");
CHECK(TrimString("hel lo ") == "hel lo");
CHECK(TrimString(" hel lo") == "hel lo");
CHECK(TrimString("hel lo ") == "hel lo");
CHECK(TrimString(" hel lo ") == "hel lo");
CHECK(TrimString("\t\thel\nlo\n\n") == "hel\nlo");
CHECK(TrimString("\n\thel\tlo\n\t") == "hel\tlo");
CHECK(TrimString(" ") == "");
CHECK(TrimString(" \t\n\r ") == "");
CHECK(TrimString("") == "");
}
static std::string GetDate() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t(now);
auto local_tm = std::localtime(&tt);
char buf[30];
std::string date;
if (Application::Settings.DebugModeEnabled) {
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T.", local_tm);
date += buf;
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
size_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(fraction).count();
char fracstr[5];
std::sprintf(fracstr, "%03lu", ms);
date += fracstr;
date += "] ";
} else {
std::strftime(buf, sizeof(buf), "[%d/%m/%y %T] ", local_tm);
date += buf;
}
return date;
}
void TConsole::BackupOldLog() {
fs::path Path = "Server.log";
if (fs::exists(Path)) {
auto OldLog = Path.filename().stem().string() + ".old.log";
try {
fs::rename(Path, OldLog);
beammp_debug("renamed old log file to '" + OldLog + "'");
} catch (const std::exception& e) {
beammp_warn(e.what());
}
/*
int err = 0;
zip* z = zip_open("ServerLogs.zip", ZIP_CREATE, &err);
if (!z) {
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
return;
}
FILE* File = std::fopen(Path.string().c_str(), "r");
if (!File) {
std::cerr << GetPlatformAgnosticErrorString() << std::endl;
return;
}
std::vector<uint8_t> Buffer;
Buffer.resize(fs::file_size(Path));
std::fread(Buffer.data(), 1, Buffer.size(), File);
std::fclose(File);
auto s = zip_source_buffer(z, Buffer.data(), Buffer.size(), 0);
auto TimePoint = fs::last_write_time(Path);
auto Secs = TimePoint.time_since_epoch().count();
auto MyTimeT = std::time(&Secs);
std::string NewName = Path.stem().string();
NewName += "_";
std::string Time;
Time.resize(32);
size_t n = strftime(Time.data(), Time.size(), "%F_%H.%M.%S", localtime(&MyTimeT));
Time.resize(n);
NewName += Time;
NewName += ".log";
zip_file_add(z, NewName.c_str(), s, 0);
zip_close(z);
*/
}
}
void TConsole::StartLoggingToFile() {
mLogFileStream.open("Server.log");
Application::Console().Internal().on_write = [this](const std::string& ToWrite) {
// TODO: Sanitize by removing all ansi escape codes (vt100)
std::unique_lock Lock(mLogFileStreamMtx);
mLogFileStream.write(ToWrite.c_str(), ToWrite.size());
mLogFileStream.write("\n", 1);
mLogFileStream.flush();
};
}
void TConsole::ChangeToLuaConsole(const std::string& LuaStateId) {
if (!mIsLuaConsole) {
if (!mLuaEngine) {
beammp_error("Lua engine not initialized yet, please wait and try again");
return;
}
mLuaEngine->EnsureStateExists(mDefaultStateId, "Console");
mStateId = LuaStateId;
mIsLuaConsole = true;
if (mStateId != mDefaultStateId) {
Application::Console().WriteRaw("Attached to Lua state '" + mStateId + "'. For help, type `:help`. To detach, type `:exit`");
mCommandline->set_prompt("lua @" + LuaStateId + "> ");
} else {
Application::Console().WriteRaw("Attached to Lua. For help, type `:help`. To detach, type `:exit`");
mCommandline->set_prompt("lua> ");
}
mCachedRegularHistory = mCommandline->history();
mCommandline->set_history(mCachedLuaHistory);
}
}
void TConsole::ChangeToRegularConsole() {
if (mIsLuaConsole) {
mIsLuaConsole = false;
if (mStateId != mDefaultStateId) {
Application::Console().WriteRaw("Detached from Lua state '" + mStateId + "'.");
} else {
Application::Console().WriteRaw("Detached from Lua.");
}
mCachedLuaHistory = mCommandline->history();
mCommandline->set_history(mCachedRegularHistory);
mCommandline->set_prompt("> ");
mStateId = mDefaultStateId;
}
}
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t n) {
if (n == 0 && args.size() != 0) {
Application::Console().WriteRaw("This command expects no arguments.");
return false;
} else if (args.size() != n) {
Application::Console().WriteRaw("Expected " + std::to_string(n) + " argument(s), instead got " + std::to_string(args.size()));
return false;
} else {
return true;
}
}
bool TConsole::EnsureArgsCount(const std::vector<std::string>& args, size_t min, size_t max) {
if (min == max) {
return EnsureArgsCount(args, min);
} else {
if (args.size() > max) {
Application::Console().WriteRaw("Too many arguments. At most " + std::to_string(max) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
return false;
} else if (args.size() < min) {
Application::Console().WriteRaw("Too few arguments. At least " + std::to_string(min) + " argument(s) expected, got " + std::to_string(args.size()) + " instead.");
return false;
}
}
return true;
}
void TConsole::Command_Lua(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0, 1)) {
return;
}
if (args.size() == 1) {
auto NewStateId = args.at(0);
beammp_assert(!NewStateId.empty());
if (mLuaEngine->HasState(NewStateId)) {
ChangeToLuaConsole(NewStateId);
} else {
Application::Console().WriteRaw("Lua state '" + NewStateId + "' is not a known state. Didn't switch to Lua.");
}
} else if (args.size() == 0) {
ChangeToLuaConsole(mDefaultStateId);
}
}
void TConsole::Command_Help(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) {
return;
}
static constexpr const char* sHelpString = R"(
Commands:
help displays this help
exit shuts down the server
kick <name> [reason] kicks specified player with an optional reason
list lists all players and info about them
say <message> sends the message to all players in chat
lua [state id] switches to lua, optionally into a specific state id's lua
settings [command] sets or gets settings for the server, run `settings help` for more info
status how the server is doing and what it's up to
clear clears the console window)";
Application::Console().WriteRaw("BeamMP-Server Console: " + std::string(sHelpString));
}
std::string TConsole::ConcatArgs(const std::vector<std::string>& args, char space) {
std::string Result;
for (const auto& arg : args) {
Result += arg + space;
}
Result = Result.substr(0, Result.size() - 1); // strip trailing space
return Result;
}
void TConsole::Command_Clear(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0, size_t(-1))) {
return;
}
mCommandline->write("\x1b[;H\x1b[2J");
}
void TConsole::Command_Kick(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 1, size_t(-1))) {
return;
}
auto Name = args.at(0);
std::string Reason = "Kicked by server console";
if (args.size() > 1) {
Reason = ConcatArgs({ args.begin() + 1, args.end() });
}
beammp_trace("attempt to kick '" + Name + "' for '" + Reason + "'");
bool Kicked = false;
// TODO: this sucks, tolower is locale-dependent.
auto NameCompare = [](std::string Name1, std::string Name2) -> bool {
std::for_each(Name1.begin(), Name1.end(), [](char& c) { c = char(std::tolower(char(c))); });
std::for_each(Name2.begin(), Name2.end(), [](char& c) { c = char(std::tolower(char(c))); });
return StringStartsWith(Name1, Name2) || StringStartsWith(Name2, Name1);
};
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto locked = Client.lock();
if (NameCompare(locked->GetName(), Name)) {
mLuaEngine->Network().ClientKick(*locked, Reason);
Kicked = true;
return false;
}
}
return true;
});
if (!Kicked) {
Application::Console().WriteRaw("Error: No player with name matching '" + Name + "' was found.");
} else {
Application::Console().WriteRaw("Kicked player '" + Name + "' for reason: '" + Reason + "'.");
}
}
std::tuple<std::string, std::vector<std::string>> TConsole::ParseCommand(const std::string& CommandWithArgs) {
// Algorithm designed and implemented by Lion Kortlepel (c) 2022
// It correctly splits arguments, including respecting single and double quotes, as well as backticks
auto End_i = CommandWithArgs.find_first_of(' ');
std::string Command = CommandWithArgs.substr(0, End_i);
std::string ArgsStr {};
if (End_i != std::string::npos) {
ArgsStr = CommandWithArgs.substr(End_i);
}
std::vector<std::string> Args;
char* PrevPtr = ArgsStr.data();
char* Ptr = ArgsStr.data();
const char* End = ArgsStr.data() + ArgsStr.size();
while (Ptr != End) {
std::string Arg = "";
// advance while space
while (Ptr != End && std::isspace(*Ptr))
++Ptr;
PrevPtr = Ptr;
// advance while NOT space, also handle quotes
while (Ptr != End && !std::isspace(*Ptr)) {
// TODO: backslash escaping quotes
for (char Quote : { '"', '\'', '`' }) {
if (*Ptr == Quote) {
// seek if there's a closing quote
// if there is, go there and continue, otherwise ignore
char* Seeker = Ptr + 1;
while (Seeker != End && *Seeker != Quote)
++Seeker;
if (Seeker != End) {
// found closing quote
Ptr = Seeker;
}
break; // exit for loop
}
}
++Ptr;
}
// this is required, otherwise we get negative int to unsigned cast in the next operations
beammp_assert(PrevPtr <= Ptr);
Arg = std::string(PrevPtr, std::string::size_type(Ptr - PrevPtr));
// remove quotes if enclosed in quotes
for (char Quote : { '"', '\'', '`' }) {
if (!Arg.empty() && Arg.at(0) == Quote && Arg.at(Arg.size() - 1) == Quote) {
Arg = Arg.substr(1, Arg.size() - 2);
break;
}
}
if (!Arg.empty()) {
Args.push_back(Arg);
}
}
return { Command, Args };
}
void TConsole::Command_Settings(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 1, 2)) {
return;
}
}
void TConsole::Command_Say(const std::string& FullCmd) {
if (FullCmd.size() > 3) {
auto Message = FullCmd.substr(4);
LuaAPI::MP::SendChatMessage(-1, Message);
if (!Application::Settings.LogChat) {
Application::Console().WriteRaw("Chat message sent!");
}
}
}
void TConsole::Command_List(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) {
return;
}
if (mLuaEngine->Server().ClientCount() == 0) {
Application::Console().WriteRaw("No players online.");
} else {
std::stringstream ss;
ss << std::left << std::setw(25) << "Name" << std::setw(6) << "ID" << std::setw(6) << "Cars" << std::endl;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto locked = Client.lock();
ss << std::left << std::setw(25) << locked->GetName()
<< std::setw(6) << locked->GetID()
<< std::setw(6) << locked->GetCarCount() << "\n";
}
return true;
});
auto Str = ss.str();
Application::Console().WriteRaw(Str.substr(0, Str.size() - 1));
}
}
void TConsole::Command_Status(const std::string&, const std::vector<std::string>& args) {
if (!EnsureArgsCount(args, 0)) {
return;
}
std::stringstream Status;
size_t CarCount = 0;
size_t ConnectedCount = 0;
size_t GuestCount = 0;
size_t SyncedCount = 0;
size_t SyncingCount = 0;
size_t MissedPacketQueueSum = 0;
int LargestSecondsSinceLastPing = 0;
mLuaEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto Locked = Client.lock();
CarCount += Locked->GetCarCount();
ConnectedCount += Locked->IsConnected() ? 1 : 0;
GuestCount += Locked->IsGuest() ? 1 : 0;
SyncedCount += Locked->IsSynced() ? 1 : 0;
SyncingCount += Locked->IsSyncing() ? 1 : 0;
MissedPacketQueueSum += Locked->MissedPacketQueueSize();
if (Locked->SecondsSinceLastPing() < LargestSecondsSinceLastPing) {
LargestSecondsSinceLastPing = Locked->SecondsSinceLastPing();
}
}
return true;
});
size_t SystemsStarting = 0;
size_t SystemsGood = 0;
size_t SystemsBad = 0;
size_t SystemsShuttingDown = 0;
size_t SystemsShutdown = 0;
std::string SystemsBadList {};
std::string SystemsGoodList {};
std::string SystemsStartingList {};
std::string SystemsShuttingDownList {};
std::string SystemsShutdownList {};
auto Statuses = Application::GetSubsystemStatuses();
for (const auto& NameStatusPair : Statuses) {
switch (NameStatusPair.second) {
case Application::Status::Good:
SystemsGood++;
SystemsGoodList += NameStatusPair.first + ", ";
break;
case Application::Status::Bad:
SystemsBad++;
SystemsBadList += NameStatusPair.first + ", ";
break;
case Application::Status::Starting:
SystemsStarting++;
SystemsStartingList += NameStatusPair.first + ", ";
break;
case Application::Status::ShuttingDown:
SystemsShuttingDown++;
SystemsShuttingDownList += NameStatusPair.first + ", ";
break;
case Application::Status::Shutdown:
SystemsShutdown++;
SystemsShutdownList += NameStatusPair.first + ", ";
break;
default:
beammp_assert_not_reachable();
}
}
// remove ", " at the end
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
SystemsGoodList = SystemsGoodList.substr(0, SystemsGoodList.size() - 2);
SystemsStartingList = SystemsStartingList.substr(0, SystemsStartingList.size() - 2);
SystemsShuttingDownList = SystemsShuttingDownList.substr(0, SystemsShuttingDownList.size() - 2);
SystemsShutdownList = SystemsShutdownList.substr(0, SystemsShutdownList.size() - 2);
auto ElapsedTime = mLuaEngine->Server().UptimeTimer.GetElapsedTime();
Status << "BeamMP-Server Status:\n"
<< "\tTotal Players: " << mLuaEngine->Server().ClientCount() << "\n"
<< "\tSyncing Players: " << SyncingCount << "\n"
<< "\tSynced Players: " << SyncedCount << "\n"
<< "\tConnected Players: " << ConnectedCount << "\n"
<< "\tGuests: " << GuestCount << "\n"
<< "\tCars: " << CarCount << "\n"
<< "\tUptime: " << ElapsedTime << "ms (~" << size_t(double(ElapsedTime) / 1000.0 / 60.0 / 60.0) << "h) \n"
<< "\tLua:\n"
<< "\t\tQueued results to check: " << mLuaEngine->GetResultsToCheckSize() << "\n"
<< "\t\tStates: " << mLuaEngine->GetLuaStateCount() << "\n"
<< "\t\tEvent timers: " << mLuaEngine->GetTimedEventsCount() << "\n"
<< "\t\tEvent handlers: " << mLuaEngine->GetRegisteredEventHandlerCount() << "\n"
<< "\tSubsystems:\n"
<< "\t\tGood/Starting/Bad: " << SystemsGood << "/" << SystemsStarting << "/" << SystemsBad << "\n"
<< "\t\tShutting down/Shut down: " << SystemsShuttingDown << "/" << SystemsShutdown << "\n"
<< "\t\tGood: [ " << SystemsGoodList << " ]\n"
<< "\t\tStarting: [ " << SystemsStartingList << " ]\n"
<< "\t\tBad: [ " << SystemsBadList << " ]\n"
<< "\t\tShutting down: [ " << SystemsShuttingDownList << " ]\n"
<< "\t\tShut down: [ " << SystemsShutdownList << " ]\n"
<< "";
Application::Console().WriteRaw(Status.str());
}
void TConsole::RunAsCommand(const std::string& cmd, bool IgnoreNotACommand) {
auto FutureIsNonNil =
[](const std::shared_ptr<TLuaResult>& Future) {
if (!Future->Error && Future->Result.valid()) {
auto Type = Future->Result.get_type();
return Type != sol::type::lua_nil && Type != sol::type::none;
}
return false;
};
std::vector<std::shared_ptr<TLuaResult>> NonNilFutures;
{ // Futures scope
auto Futures = mLuaEngine->TriggerEvent("onConsoleInput", "", cmd);
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
size_t Count = 0;
for (auto& Future : Futures) {
if (!Future->Error) {
++Count;
}
}
for (const auto& Future : Futures) {
if (FutureIsNonNil(Future)) {
NonNilFutures.push_back(Future);
}
}
}
if (NonNilFutures.size() == 0) {
if (!IgnoreNotACommand) {
Application::Console().WriteRaw("Error: Unknown command: '" + cmd + "'. Type 'help' to see a list of valid commands.");
}
} else {
std::stringstream Reply;
if (NonNilFutures.size() > 1) {
for (size_t i = 0; i < NonNilFutures.size(); ++i) {
Reply << NonNilFutures[i]->StateId << ": \n"
<< LuaAPI::LuaToString(NonNilFutures[i]->Result);
if (i < NonNilFutures.size() - 1) {
Reply << "\n";
}
}
} else {
Reply << LuaAPI::LuaToString(NonNilFutures[0]->Result);
}
Application::Console().WriteRaw(Reply.str());
}
}
void TConsole::HandleLuaInternalCommand(const std::string& cmd) {
if (cmd == "exit") {
ChangeToRegularConsole();
} else if (cmd == "queued") {
auto QueuedFunctions = LuaAPI::MP::Engine->Debug_GetStateFunctionQueueForState(mStateId);
Application::Console().WriteRaw("Pending functions in State '" + mStateId + "'");
std::unordered_map<std::string, size_t> FunctionsCount;
std::vector<std::string> FunctionsInOrder;
while (!QueuedFunctions.empty()) {
auto Tuple = QueuedFunctions.front();
QueuedFunctions.erase(QueuedFunctions.begin());
FunctionsInOrder.push_back(Tuple.FunctionName);
FunctionsCount[Tuple.FunctionName] += 1;
}
std::set<std::string> Uniques;
for (const auto& Function : FunctionsInOrder) {
if (Uniques.count(Function) == 0) {
Uniques.insert(Function);
if (FunctionsCount.at(Function) > 1) {
Application::Console().WriteRaw(" " + Function + " (" + std::to_string(FunctionsCount.at(Function)) + "x)");
} else {
Application::Console().WriteRaw(" " + Function);
}
}
}
Application::Console().WriteRaw("Executed functions waiting to be checked in State '" + mStateId + "'");
for (const auto& Function : LuaAPI::MP::Engine->Debug_GetResultsToCheckForState(mStateId)) {
Application::Console().WriteRaw(" '" + Function.Function + "' (Ready? " + (Function.Ready ? "Yes" : "No") + ", Error? " + (Function.Error ? "Yes: '" + Function.ErrorMessage + "'" : "No") + ")");
}
} else if (cmd == "events") {
auto Events = LuaAPI::MP::Engine->Debug_GetEventsForState(mStateId);
Application::Console().WriteRaw("Registered Events + Handlers for State '" + mStateId + "'");
for (const auto& EventHandlerPair : Events) {
Application::Console().WriteRaw(" Event '" + EventHandlerPair.first + "'");
for (const auto& Handler : EventHandlerPair.second) {
Application::Console().WriteRaw(" " + Handler);
}
}
} else if (cmd == "help") {
Application::Console().WriteRaw(R"(BeamMP Lua Debugger
All commands must be prefixed with a `:`. Non-prefixed commands are interpreted as Lua.
Commands
:exit detaches (exits) from this Lua console
:help displays this help
:events shows a list of currently registered events
:queued shows a list of all pending and queued functions)");
} else {
beammp_error("internal command '" + cmd + "' is not known");
}
}
TConsole::TConsole() {
}
void TConsole::InitializeCommandline() {
mCommandline = std::make_unique<Commandline>();
mCommandline->enable_history();
mCommandline->set_history_limit(20);
mCommandline->set_prompt("> ");
BackupOldLog();
mCommandline->on_command = [this](Commandline& c) {
try {
auto TrimmedCmd = c.get_command();
TrimmedCmd = TrimString(TrimmedCmd);
auto [cmd, args] = ParseCommand(TrimmedCmd);
mCommandline->write(mCommandline->prompt() + TrimmedCmd);
if (mIsLuaConsole) {
if (!mLuaEngine) {
beammp_info("Lua not started yet, please try again in a second");
} else if (!cmd.empty() && cmd.at(0) == ':') {
HandleLuaInternalCommand(cmd.substr(1));
} else {
auto Future = mLuaEngine->EnqueueScript(mStateId, { std::make_shared<std::string>(TrimmedCmd), "", "" });
Future->WaitUntilReady();
if (Future->Error) {
beammp_lua_error("error in " + mStateId + ": " + Future->ErrorMessage);
}
}
} else {
if (!mLuaEngine) {
beammp_error("Attempted to run a command before Lua engine started. Please wait and try again.");
} else if (cmd == "exit") {
beammp_info("gracefully shutting down");
Application::GracefullyShutdown();
} else if (cmd == "say") {
RunAsCommand(TrimmedCmd, true);
Command_Say(TrimmedCmd);
} else {
if (mCommandMap.find(cmd) != mCommandMap.end()) {
mCommandMap.at(cmd)(cmd, args);
RunAsCommand(TrimmedCmd, true);
} else {
RunAsCommand(TrimmedCmd);
}
}
}
} catch (const std::exception& e) {
beammp_error("Console died with: " + std::string(e.what()) + ". This could be a fatal error and could cause the server to terminate.");
}
};
mCommandline->on_autocomplete = [this](Commandline&, std::string stub, int) {
std::vector<std::string> suggestions;
try {
if (mIsLuaConsole) { // if lua
if (!mLuaEngine) {
beammp_info("Lua not started yet, please try again in a second");
} else {
std::string prefix {}; // stores non-table part of input
for (size_t i = stub.length(); i > 0; i--) { // separate table from input
if (!std::isalnum(stub[i - 1]) && stub[i - 1] != '_' && stub[i - 1] != '.') {
prefix = stub.substr(0, i);
stub = stub.substr(i);
break;
}
}
// turn string into vector of keys
std::vector<std::string> tablekeys;
SplitString(stub, '.', tablekeys);
// remove last key if incomplete
if (stub.rfind('.') != stub.size() - 1 && !tablekeys.empty()) {
tablekeys.pop_back();
}
auto keys = mLuaEngine->GetStateTableKeysForState(mStateId, tablekeys);
for (const auto& key : keys) { // go through each bottom-level key
auto last_dot = stub.rfind('.');
std::string last_atom;
if (last_dot != std::string::npos) {
last_atom = stub.substr(last_dot + 1);
}
std::string before_last_atom = stub.substr(0, last_dot + 1); // get last confirmed key
auto last = stub.substr(stub.rfind('.') + 1);
std::string::size_type n = key.find(last);
if (n == 0) {
suggestions.push_back(prefix + before_last_atom + key);
}
}
}
} else { // if not lua
if (stub.find("lua") == 0) { // starts with "lua" means we should suggest state names
std::string after_prefix = TrimString(stub.substr(3));
auto stateNames = mLuaEngine->GetLuaStateNames();
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) {
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;
};
}
void TConsole::Write(const std::string& str) {
auto ToWrite = GetDate() + str;
// allows writing to stdout without an initialized console
if (mCommandline) {
mCommandline->write(ToWrite);
} else {
std::cout << ToWrite << std::endl;
}
}
void TConsole::WriteRaw(const std::string& str) {
// allows writing to stdout without an initialized console
if (mCommandline) {
mCommandline->write(str);
} else {
std::cout << str << std::endl;
}
}
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
mLuaEngine = &Engine;
}
+166
View File
@@ -0,0 +1,166 @@
#include "THeartbeatThread.h"
#include "Client.h"
#include "Http.h"
//#include "SocketIO.h"
#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>
#include <sstream>
namespace json = rapidjson;
void THeartbeatThread::operator()() {
RegisterThread("Heartbeat");
std::string Body;
std::string T;
// these are "hot-change" related variables
static std::string Last;
static std::chrono::high_resolution_clock::time_point LastNormalUpdateTime = std::chrono::high_resolution_clock::now();
bool isAuth = false;
size_t UpdateReminderCounter = 0;
while (!Application::IsShuttingDown()) {
++UpdateReminderCounter;
Body = GenerateCall();
// a hot-change occurs when a setting has changed, to update the backend of that change.
auto Now = std::chrono::high_resolution_clock::now();
bool Unchanged = Last == Body;
auto TimePassed = (Now - LastNormalUpdateTime);
auto Threshold = Unchanged ? 30 : 5;
if (TimePassed < std::chrono::seconds(Threshold)) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
beammp_debug("heartbeat (after " + std::to_string(std::chrono::duration_cast<std::chrono::seconds>(TimePassed).count()) + "s)");
Last = Body;
LastNormalUpdateTime = Now;
if (!Application::Settings.CustomIP.empty()) {
Body += "&ip=" + Application::Settings.CustomIP;
}
auto Target = "/heartbeat";
unsigned int ResponseCode = 0;
json::Document Doc;
bool Ok = false;
for (const auto& Url : Application::GetBackendUrlsInOrder()) {
T = Http::POST(Url, 443, Target, Body, "application/x-www-form-urlencoded", &ResponseCode, { { "api-v", "2" } });
Doc.Parse(T.data(), T.size());
if (Doc.HasParseError() || !Doc.IsObject()) {
if (!Application::Settings.Private) {
beammp_trace("Backend response failed to parse as valid json");
beammp_trace("Response was: `" + T + "`");
}
} else if (ResponseCode != 200) {
beammp_errorf("Response code from the heartbeat: {}", ResponseCode);
} else {
// all ok
Ok = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::string Status {};
std::string Code {};
std::string Message {};
const auto StatusKey = "status";
const auto CodeKey = "code";
const auto MessageKey = "msg";
if (Ok) {
if (Doc.HasMember(StatusKey) && Doc[StatusKey].IsString()) {
Status = Doc[StatusKey].GetString();
} else {
Ok = false;
}
if (Doc.HasMember(CodeKey) && Doc[CodeKey].IsString()) {
Code = Doc[CodeKey].GetString();
} else {
Ok = false;
}
if (Doc.HasMember(MessageKey) && Doc[MessageKey].IsString()) {
Message = Doc[MessageKey].GetString();
} else {
Ok = false;
}
if (!Ok) {
beammp_error("Missing/invalid json members in backend response");
}
} else {
if (!Application::Settings.Private) {
beammp_warn("Backend failed to respond to a heartbeat. Your server may temporarily disappear from the server list. This is not an error, and will likely resolve itself soon. Direct connect will still work.");
}
}
if (Ok && !isAuth && !Application::Settings.Private) {
if (Status == "2000") {
beammp_info(("Authenticated! " + Message));
isAuth = true;
} else if (Status == "200") {
beammp_info(("Resumed authenticated session! " + Message));
isAuth = true;
} else {
if (Message.empty()) {
Message = "Backend didn't provide a reason.";
}
beammp_error("Backend REFUSED the auth key. Reason: " + Message);
}
}
if (isAuth || Application::Settings.Private) {
Application::SetSubsystemStatus("Heartbeat", Application::Status::Good);
}
if (!Application::Settings.HideUpdateMessages && UpdateReminderCounter % 5) {
Application::CheckForUpdates();
}
}
}
std::string THeartbeatThread::GenerateCall() {
std::stringstream Ret;
Ret << "uuid=" << Application::Settings.Key
<< "&players=" << mServer.ClientCount()
<< "&maxplayers=" << Application::Settings.MaxPlayers
<< "&port=" << Application::Settings.Port
<< "&map=" << Application::Settings.MapName
<< "&private=" << (Application::Settings.Private ? "true" : "false")
<< "&version=" << Application::ServerVersionString()
<< "&clientversion=" << std::to_string(Application::ClientMajorVersion()) + ".0" // FIXME: Wtf.
<< "&name=" << Application::Settings.ServerName
<< "&tags=" << Application::Settings.ServerTags
<< "&modlist=" << mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.MaxModSize()
<< "&modstotal=" << mResourceManager.ModsLoaded()
<< "&playerslist=" << GetPlayers()
<< "&desc=" << Application::Settings.ServerDesc
<< "&pass=" << (Application::Settings.Password.empty() ? "false" : "true");
return Ret.str();
}
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
: mResourceManager(ResourceManager)
, mServer(Server) {
Application::SetSubsystemStatus("Heartbeat", Application::Status::Starting);
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("Heartbeat", Application::Status::ShuttingDown);
if (mThread.joinable()) {
mThread.join();
}
Application::SetSubsystemStatus("Heartbeat", Application::Status::Shutdown);
});
Start();
}
std::string THeartbeatThread::GetPlayers() {
std::string Return;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Return += ClientPtr.lock()->GetName() + ";";
}
return true;
});
return Return;
}
/*THeartbeatThread::~THeartbeatThread() {
}*/
+1103
View File
File diff suppressed because it is too large Load Diff
+52
View File
@@ -0,0 +1,52 @@
#include "TLuaPlugin.h"
#include <chrono>
#include <functional>
#include <random>
#include <utility>
TLuaPlugin::TLuaPlugin(TLuaEngine& Engine, const TLuaPluginConfig& Config, const fs::path& MainFolder)
: mConfig(Config)
, mEngine(Engine)
, mFolder(MainFolder)
, mPluginName(MainFolder.stem().string())
, mFileContents(0) {
beammp_debug("Lua plugin \"" + mPluginName + "\" starting in \"" + mFolder.string() + "\"");
std::vector<fs::path> Entries;
for (const auto& Entry : fs::directory_iterator(mFolder)) {
if (Entry.is_regular_file() && Entry.path().extension() == ".lua") {
Entries.push_back(Entry);
}
}
// sort alphabetically (not needed if config is used to determine call order)
// TODO: Use config to figure out what to run in which order
std::sort(Entries.begin(), Entries.end(), [](const fs::path& first, const fs::path& second) {
auto firstStr = first.string();
auto secondStr = second.string();
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
return firstStr < secondStr;
});
std::vector<std::pair<fs::path, std::shared_ptr<TLuaResult>>> ResultsToCheck;
for (const auto& Entry : Entries) {
// read in entire file
try {
std::ifstream FileStream(Entry.string(), std::ios::in | std::ios::binary);
auto Size = std::filesystem::file_size(Entry);
auto Contents = std::make_shared<std::string>();
Contents->resize(Size);
FileStream.read(Contents->data(), Contents->size());
mFileContents[fs::relative(Entry).string()] = Contents;
// Execute first time
auto Result = mEngine.EnqueueScript(mConfig.StateId, TLuaChunk(Contents, Entry.string(), MainFolder.string()));
ResultsToCheck.emplace_back(Entry.string(), std::move(Result));
} catch (const std::exception& e) {
beammp_error("Error loading file \"" + Entry.string() + "\": " + e.what());
}
}
for (auto& Result : ResultsToCheck) {
Result.second->WaitUntilReady();
if (Result.second->Error) {
beammp_lua_error("Failed: \"" + Result.first.string() + "\": " + Result.second->ErrorMessage);
}
}
}
+999
View File
@@ -0,0 +1,999 @@
#include "TNetwork.h"
#include "Client.h"
#include "Common.h"
#include "LuaAPI.h"
#include "TLuaEngine.h"
#include "nlohmann/json.hpp"
#include <CustomAssert.h>
#include <Http.h>
#include <array>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <cstring>
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option;
std::vector<uint8_t> StringToVector(const std::string& Str) {
return std::vector<uint8_t>(Str.data(), Str.data() + Str.size());
}
static void CompressProperly(std::vector<uint8_t>& Data) {
constexpr std::string_view ABG = "ABG:";
auto CombinedData = std::vector<uint8_t>(ABG.begin(), ABG.end());
auto CompData = Comp(Data);
CombinedData.resize(ABG.size() + CompData.size());
std::copy(CompData.begin(), CompData.end(), CombinedData.begin() + ABG.size());
Data = CombinedData;
}
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
: mServer(Server)
, mPPSMonitor(PPSMonitor)
, mUDPSock(Server.IoCtx())
, mResourceManager(ResourceManager) {
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Starting);
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Starting);
Application::RegisterShutdownHandler([&] {
beammp_debug("Kicking all players due to shutdown");
Server.ForEachClient([&](std::weak_ptr<TClient> client) -> bool {
if (!client.expired()) {
ClientKick(*client.lock(), "Server shutdown");
}
return true;
});
});
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("UDPNetwork", Application::Status::ShuttingDown);
if (mUDPThread.joinable()) {
mUDPThread.detach();
}
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Shutdown);
});
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("TCPNetwork", Application::Status::ShuttingDown);
if (mTCPThread.joinable()) {
mTCPThread.detach();
}
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Shutdown);
});
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
}
void TNetwork::UDPServerMain() {
RegisterThread("UDPServer");
ip::udp::endpoint UdpListenEndpoint(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
boost::system::error_code ec;
mUDPSock.open(UdpListenEndpoint.protocol(), ec);
if (ec) {
beammp_error("open() failed: " + ec.message());
std::this_thread::sleep_for(std::chrono::seconds(5));
Application::GracefullyShutdown();
}
mUDPSock.bind(UdpListenEndpoint, ec);
if (ec) {
beammp_error("bind() failed: " + ec.message());
std::this_thread::sleep_for(std::chrono::seconds(5));
Application::GracefullyShutdown();
}
Application::SetSubsystemStatus("UDPNetwork", Application::Status::Good);
beammp_info(("Vehicle data network online on port ") + std::to_string(Application::Settings.Port) + (" with a Max of ")
+ std::to_string(Application::Settings.MaxPlayers) + (" Clients"));
while (!Application::IsShuttingDown()) {
try {
ip::udp::endpoint client {};
std::vector<uint8_t> Data = UDPRcvFromClient(client); // Receives any data from Socket
auto Pos = std::find(Data.begin(), Data.end(), ':');
if (Data.empty() || Pos > Data.begin() + 2)
continue;
uint8_t ID = uint8_t(Data.at(0)) - 1;
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
std::shared_ptr<TClient> Client;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Client = ClientPtr.lock();
} else
return true;
}
if (Client->GetID() == ID) {
Client->SetUDPAddr(client);
Client->SetIsConnected(true);
Data.erase(Data.begin(), Data.begin() + 2);
TServer::GlobalParser(ClientPtr, std::move(Data), mPPSMonitor, *this);
}
return true;
});
} catch (const std::exception& e) {
beammp_error(("fatal: ") + std::string(e.what()));
}
}
}
void TNetwork::TCPServerMain() {
RegisterThread("TCPServer");
ip::tcp::endpoint ListenEp(ip::address::from_string("0.0.0.0"), Application::Settings.Port);
ip::tcp::socket Listener(mServer.IoCtx());
boost::system::error_code ec;
Listener.open(ListenEp.protocol(), ec);
if (ec) {
beammp_errorf("Failed to open socket: {}", ec.message());
return;
}
socket_base::linger LingerOpt {};
LingerOpt.enabled(false);
Listener.set_option(LingerOpt, ec);
if (ec) {
beammp_errorf("Failed to set up listening socket to not linger / reuse address. "
"This may cause the socket to refuse to bind(). Error: {}",
ec.message());
}
ip::tcp::acceptor Acceptor(mServer.IoCtx(), ListenEp);
Acceptor.listen(socket_base::max_listen_connections, ec);
if (ec) {
beammp_errorf("listen() failed, which is needed for the server to operate. "
"Shutting down. Error: {}",
ec.message());
Application::GracefullyShutdown();
}
Application::SetSubsystemStatus("TCPNetwork", Application::Status::Good);
beammp_info("Vehicle event network online");
do {
try {
if (Application::IsShuttingDown()) {
beammp_debug("shutdown during TCP wait for accept loop");
break;
}
ip::tcp::endpoint ClientEp;
ip::tcp::socket ClientSocket = Acceptor.accept(ClientEp, ec);
if (ec) {
beammp_errorf("failed to accept: {}", ec.message());
}
TConnection Conn { std::move(ClientSocket), ClientEp };
std::thread ID(&TNetwork::Identify, this, std::move(Conn));
ID.detach(); // TODO: Add to a queue and attempt to join periodically
} catch (const std::exception& e) {
beammp_error("fatal: " + std::string(e.what()));
}
} while (!Application::IsShuttingDown());
}
#undef GetObject // Fixes Windows
#include "Json.h"
namespace json = rapidjson;
void TNetwork::Identify(TConnection&& RawConnection) {
RegisterThreadAuto();
char Code;
boost::system::error_code ec;
read(RawConnection.Socket, buffer(&Code, 1), ec);
if (ec) {
// TODO: is this right?!
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
return;
}
std::shared_ptr<TClient> Client { nullptr };
try {
if (Code == 'C') {
Client = Authentication(std::move(RawConnection));
} else if (Code == 'D') {
HandleDownload(std::move(RawConnection));
} else if (Code == 'P') {
boost::system::error_code ec;
write(RawConnection.Socket, buffer("P"), ec);
return;
} else {
beammp_errorf("Invalid code got in Identify: '{}'", Code);
}
} catch(const std::exception& e) {
beammp_errorf("Error during handling of code {} - client left in invalid state, closing socket", Code);
boost::system::error_code ec;
RawConnection.Socket.shutdown(socket_base::shutdown_both, ec);
if (ec) {
beammp_debugf("Failed to shutdown client socket: {}", ec.message());
}
RawConnection.Socket.close(ec);
if (ec) {
beammp_debugf("Failed to close client socket: {}", ec.message());
}
}
}
void TNetwork::HandleDownload(TConnection&& Conn) {
char D;
boost::system::error_code ec;
read(Conn.Socket, buffer(&D, 1), ec);
if (ec) {
Conn.Socket.shutdown(socket_base::shutdown_both, ec);
// ignore ec
return;
}
auto ID = uint8_t(D);
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
if (c->GetID() == ID) {
c->SetDownSock(std::move(Conn.Socket));
}
}
return true;
});
}
std::string HashPassword(const std::string& str) {
std::stringstream ret;
unsigned char* hash = SHA256(reinterpret_cast<const unsigned char*>(str.c_str()), str.length(), nullptr);
for (int i = 0; i < 32; i++) {
ret << std::hex << static_cast<int>(hash[i]);
}
return ret.str();
}
std::shared_ptr<TClient> TNetwork::Authentication(TConnection&& RawConnection) {
auto Client = CreateClient(std::move(RawConnection.Socket));
Client->SetIdentifier("ip", RawConnection.SockAddr.address().to_string());
beammp_tracef("This thread is ip {}", RawConnection.SockAddr.address().to_string());
beammp_info("Identifying new ClientConnection...");
auto Data = TCPRcv(*Client);
constexpr std::string_view VC = "VC";
if (Data.size() > 3 && std::equal(Data.begin(), Data.begin() + VC.size(), VC.begin(), VC.end())) {
std::string ClientVersionStr(reinterpret_cast<const char*>(Data.data() + 2), Data.size() - 2);
Version ClientVersion = Application::VersionStrToInts(ClientVersionStr + ".0");
if (ClientVersion.major != Application::ClientMajorVersion()) {
beammp_errorf("Client tried to connect with version '{}', but only versions '{}.x.x' is allowed",
ClientVersion.AsString(), Application::ClientMajorVersion());
ClientKick(*Client, "Outdated Version!");
return nullptr;
}
} else {
ClientKick(*Client, fmt::format("Invalid version header: '{}' ({})", std::string(reinterpret_cast<const char*>(Data.data()), Data.size()), Data.size()));
return nullptr;
}
if (!TCPSend(*Client, StringToVector("A"))) { //changed to A for Accepted version
// TODO: handle
}
Data = TCPRcv(*Client);
if (Data.size() > 50) {
ClientKick(*Client, "Invalid Key (too long)!");
return nullptr;
}
std::string key(reinterpret_cast<const char*>(Data.data()), Data.size());
nlohmann::json AuthReq{};
std::string AuthResStr{};
try {
AuthReq = nlohmann::json {
{ "key", key }
};
auto Target = "/pkToUser";
unsigned int ResponseCode = 0;
AuthResStr = Http::POST(Application::GetBackendUrlForAuth(), 443, Target, AuthReq.dump(), "application/json", &ResponseCode);
} catch (const std::exception& e) {
beammp_debugf("Invalid json sent by client, kicking: {}", e.what());
ClientKick(*Client, "Invalid Key (invalid UTF8 string)!");
return nullptr;
}
try {
nlohmann::json AuthRes = nlohmann::json::parse(AuthResStr);
if (AuthRes["username"].is_string() && AuthRes["roles"].is_string()
&& AuthRes["guest"].is_boolean() && AuthRes["identifiers"].is_array()) {
Client->SetName(AuthRes["username"]);
Client->SetRoles(AuthRes["roles"]);
Client->SetIsGuest(AuthRes["guest"]);
for (const auto& ID : AuthRes["identifiers"]) {
auto Raw = std::string(ID);
auto SepIndex = Raw.find(':');
Client->SetIdentifier(Raw.substr(0, SepIndex), Raw.substr(SepIndex + 1));
}
} else {
beammp_error("Invalid authentication data received from authentication backend");
ClientKick(*Client, "Invalid authentication data!");
return nullptr;
}
} catch (const std::exception& e) {
beammp_errorf("Client sent invalid key. Error was: {}", e.what());
// TODO: we should really clarify that this was a backend response or parsing error
ClientKick(*Client, "Invalid key! Please restart your game.");
return nullptr;
}
if(!Application::Settings.Password.empty()) { // ask password
if(!TCPSend(*Client, StringToVector("S"))) {
// TODO: handle
}
beammp_info("Waiting for password");
Data = TCPRcv(*Client);
std::string Pass = std::string(reinterpret_cast<const char*>(Data.data()), Data.size());
if(Pass != HashPassword(Application::Settings.Password)) {
beammp_debug(Client->GetName() + " attempted to connect with a wrong password");
ClientKick(*Client, "Wrong password!");
return {};
} else {
beammp_debug(Client->GetName() + " used the correct password");
}
}
beammp_debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> Cl;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
Cl = ClientPtr.lock();
} else
return true;
}
if (Cl->GetName() == Client->GetName() && Cl->IsGuest() == Client->IsGuest()) {
Cl->Disconnect("Stale Client (not a real player)");
return false;
}
return true;
});
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerAuth", "", Client->GetName(), Client->GetRoles(), Client->IsGuest(), Client->GetIdentifiers());
TLuaEngine::WaitForAll(Futures);
bool NotAllowed = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && bool(Result->Result.as<int>());
});
std::string Reason;
bool NotAllowedWithReason = std::any_of(Futures.begin(), Futures.end(),
[&Reason](const std::shared_ptr<TLuaResult>& Result) -> bool {
if (!Result->Error && Result->Result.is<std::string>()) {
Reason = Result->Result.as<std::string>();
return true;
}
return false;
});
if (NotAllowed) {
ClientKick(*Client, "you are not allowed on the server!");
return {};
} else if (NotAllowedWithReason) {
ClientKick(*Client, Reason);
return {};
}
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
beammp_info("Identification success");
mServer.InsertClient(Client);
TCPClient(Client);
} else {
ClientKick(*Client, "Server full!");
}
return Client;
}
std::shared_ptr<TClient> TNetwork::CreateClient(ip::tcp::socket&& TCPSock) {
auto c = std::make_shared<TClient>(mServer, std::move(TCPSock));
return c;
}
bool TNetwork::TCPSend(TClient& c, const std::vector<uint8_t>& Data, bool IsSync) {
if (!IsSync) {
if (c.IsSyncing()) {
if (!Data.empty()) {
if (Data.at(0) == 'O' || Data.at(0) == 'A' || Data.at(0) == 'C' || Data.at(0) == 'E') {
c.EnqueuePacket(Data);
}
}
return true;
}
}
auto& Sock = c.GetTCPSock();
/*
* our TCP protocol sends a header of 4 bytes, followed by the data.
*
* [][][][][][]...[]
* ^------^^---...-^
* size data
*/
const auto Size = int32_t(Data.size());
std::vector<uint8_t> ToSend;
ToSend.resize(Data.size() + sizeof(Size));
std::memcpy(ToSend.data(), &Size, sizeof(Size));
std::memcpy(ToSend.data() + sizeof(Size), Data.data(), Data.size());
boost::system::error_code ec;
write(Sock, buffer(ToSend), ec);
if (ec) {
beammp_debugf("write(): {}", ec.message());
c.Disconnect("write() failed");
return false;
}
c.UpdatePingTime();
return true;
}
std::vector<uint8_t> TNetwork::TCPRcv(TClient& c) {
if (c.IsDisconnected()) {
beammp_error("Client disconnected, cancelling TCPRcv");
return {};
}
int32_t Header {};
auto& Sock = c.GetTCPSock();
boost::system::error_code ec;
std::array<uint8_t, sizeof(Header)> HeaderData;
read(Sock, buffer(HeaderData), ec);
if (ec) {
// TODO: handle this case (read failed)
beammp_debugf("TCPRcv: Reading header failed: {}", ec.message());
return {};
}
Header = *reinterpret_cast<int32_t*>(HeaderData.data());
if (Header < 0) {
ClientKick(c, "Invalid packet - header negative");
beammp_errorf("Client {} send negative TCP header, ignoring packet", c.GetID());
return {};
}
std::vector<uint8_t> Data;
// TODO: This is arbitrary, this needs to be handled another way
if (Header < int32_t(100 * MB)) {
Data.resize(Header);
} else {
ClientKick(c, "Header size limit exceeded");
beammp_warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
return {};
}
auto N = read(Sock, buffer(Data), ec);
if (ec) {
// TODO: handle this case properly
beammp_debugf("TCPRcv: Reading data failed: {}", ec.message());
return {};
}
if (N != Header) {
beammp_errorf("Expected to read {} bytes, instead got {}", Header, N);
}
constexpr std::string_view ABG = "ABG:";
if (Data.size() >= ABG.size() && std::equal(Data.begin(), Data.begin() + ABG.size(), ABG.begin(), ABG.end())) {
Data.erase(Data.begin(), Data.begin() + ABG.size());
return DeComp(Data);
} else {
return Data;
}
}
void TNetwork::ClientKick(TClient& c, const std::string& R) {
beammp_info("Client kicked: " + R);
if (!TCPSend(c, StringToVector("K" + R))) {
beammp_debugf("tried to kick player '{}' (id {}), but was already disconnected", c.GetName(), c.GetID());
}
c.Disconnect("Kicked");
}
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
RegisterThreadAuto();
while (!c.expired()) {
auto Client = c.lock();
if (Client->IsDisconnected()) {
beammp_debug("client is disconnected, breaking client loop");
break;
}
if (!Client->IsSyncing() && Client->IsSynced() && Client->MissedPacketQueueSize() != 0) {
// debug("sending " + std::to_string(Client->MissedPacketQueueSize()) + " queued packets");
while (Client->MissedPacketQueueSize() > 0) {
std::vector<uint8_t> QData {};
{ // locked context
std::unique_lock lock(Client->MissedPacketQueueMutex());
if (Client->MissedPacketQueueSize() <= 0) {
break;
}
QData = Client->MissedPacketQueue().front();
Client->MissedPacketQueue().pop();
} // end locked context
// beammp_debug("sending a missed packet: " + QData);
if (!TCPSend(*Client, QData, true)) {
Client->Disconnect("Failed to TCPSend while clearing the missed packet queue");
std::unique_lock lock(Client->MissedPacketQueueMutex());
while (!Client->MissedPacketQueue().empty()) {
Client->MissedPacketQueue().pop();
}
break;
}
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
}
void TNetwork::TCPClient(const std::weak_ptr<TClient>& c) {
// TODO: the c.expired() might cause issues here, remove if you end up here with your debugger
if (c.expired() || !c.lock()->GetTCPSock().is_open()) {
mServer.RemoveClient(c);
return;
}
OnConnect(c);
RegisterThread("(" + std::to_string(c.lock()->GetID()) + ") \"" + c.lock()->GetName() + "\"");
std::thread QueueSync(&TNetwork::Looper, this, c);
while (true) {
if (c.expired())
break;
auto Client = c.lock();
if (Client->IsDisconnected()) {
beammp_debug("client status < 0, breaking client loop");
break;
}
auto res = TCPRcv(*Client);
if (res.empty()) {
beammp_debug("TCPRcv empty");
Client->Disconnect("TCPRcv failed");
break;
}
TServer::GlobalParser(c, std::move(res), mPPSMonitor, *this);
}
if (QueueSync.joinable())
QueueSync.join();
if (!c.expired()) {
auto Client = c.lock();
OnDisconnect(c);
} else {
beammp_warn("client expired in TCPClient, should never happen");
}
}
void TNetwork::UpdatePlayer(TClient& Client) {
std::string Packet = ("Ss") + std::to_string(mServer.ClientCount()) + "/" + std::to_string(Application::Settings.MaxPlayers) + ":";
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
Packet += c->GetName() + ",";
}
return true;
});
Packet = Packet.substr(0, Packet.length() - 1);
Client.EnqueuePacket(StringToVector(Packet));
//(void)Respond(Client, Packet, true);
}
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr) {
std::shared_ptr<TClient> LockedClientPtr { nullptr };
try {
LockedClientPtr = ClientPtr.lock();
} catch (const std::exception&) {
beammp_warn("Client expired in OnDisconnect, this is unexpected");
return;
}
beammp_assert(LockedClientPtr != nullptr);
TClient& c = *LockedClientPtr;
beammp_info(c.GetName() + (" Connection Terminated"));
std::string Packet;
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = c.GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
for (auto& v : VehicleData) {
Packet = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(v.ID());
SendToAll(&c, StringToVector(Packet), false, true);
}
Packet = ("L") + c.GetName() + (" left the server!");
SendToAll(&c, StringToVector(Packet), false, true);
Packet.clear();
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onPlayerDisconnect", "", c.GetID());
LuaAPI::MP::Engine->WaitForAll(Futures);
c.Disconnect("Already Disconnected (OnDisconnect)");
mServer.RemoveClient(ClientPtr);
}
int TNetwork::OpenID() {
int ID = 0;
bool found;
do {
found = true;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
auto c = ClientPtr.lock();
if (c->GetID() == ID) {
found = false;
ID++;
}
}
return true;
});
} while (!found);
return ID;
}
void TNetwork::OnConnect(const std::weak_ptr<TClient>& c) {
beammp_assert(!c.expired());
beammp_info("Client connected");
auto LockedClient = c.lock();
LockedClient->SetID(OpenID());
beammp_info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerConnecting", "", LockedClient->GetID()));
SyncResources(*LockedClient);
if (LockedClient->IsDisconnected())
return;
(void)Respond(*LockedClient, StringToVector("M" + Application::Settings.MapName), true); // Send the Map on connect
beammp_info(LockedClient->GetName() + " : Connected");
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoining", "", LockedClient->GetID()));
}
void TNetwork::SyncResources(TClient& c) {
if (!TCPSend(c, StringToVector("P" + std::to_string(c.GetID())))) {
// TODO handle
}
std::vector<uint8_t> Data;
while (!c.IsDisconnected()) {
Data = TCPRcv(c);
if (Data.empty()) {
break;
}
constexpr std::string_view Done = "Done";
if (std::equal(Data.begin(), Data.end(), Done.begin(), Done.end()))
break;
Parse(c, Data);
}
}
void TNetwork::Parse(TClient& c, const std::vector<uint8_t>& Packet) {
if (Packet.empty())
return;
char Code = Packet.at(0), SubCode = 0;
if (Packet.size() > 1)
SubCode = Packet.at(1);
switch (Code) {
case 'f':
SendFile(c, std::string(reinterpret_cast<const char*>(Packet.data() + 1), Packet.size() - 1));
return;
case 'S':
if (SubCode == 'R') {
beammp_debug("Sending Mod Info");
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
if (ToSend.empty())
ToSend = "-";
if (!TCPSend(c, StringToVector(ToSend))) {
// TODO: error
}
}
return;
default:
return;
}
}
void TNetwork::SendFile(TClient& c, const std::string& UnsafeName) {
beammp_info(c.GetName() + " requesting : " + UnsafeName.substr(UnsafeName.find_last_of('/')));
if (!fs::path(UnsafeName).has_filename()) {
if (!TCPSend(c, StringToVector("CO"))) {
// TODO: handle
}
beammp_warn("File " + UnsafeName + " is not a file!");
return;
}
auto FileName = fs::path(UnsafeName).filename().string();
FileName = Application::Settings.Resource + "/Client/" + FileName;
if (!std::filesystem::exists(FileName)) {
if (!TCPSend(c, StringToVector("CO"))) {
// TODO: handle
}
beammp_warn("File " + UnsafeName + " could not be accessed!");
return;
}
if (!TCPSend(c, StringToVector("AG"))) {
// TODO: handle
}
/// Wait for connections
int T = 0;
while (!c.GetDownSock().is_open() && T < 50) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
T++;
}
if (!c.GetDownSock().is_open()) {
beammp_error("Client doesn't have a download socket!");
if (!c.IsDisconnected())
c.Disconnect("Missing download socket");
return;
}
size_t Size = size_t(std::filesystem::file_size(FileName)), MSize = Size / 2;
std::thread SplitThreads[2] {
std::thread([&] {
RegisterThread("SplitLoad_0");
SplitLoad(c, 0, MSize, false, FileName);
}),
std::thread([&] {
RegisterThread("SplitLoad_1");
SplitLoad(c, MSize, Size, true, FileName);
})
};
for (auto& SplitThread : SplitThreads) {
if (SplitThread.joinable()) {
SplitThread.join();
}
}
}
static std::pair<size_t /* count */, size_t /* last chunk */> SplitIntoChunks(size_t FullSize, size_t ChunkSize) {
if (FullSize < ChunkSize) {
return { 0, FullSize };
}
size_t Count = FullSize / (FullSize / ChunkSize);
size_t LastChunkSize = FullSize - (Count * ChunkSize);
return { Count, LastChunkSize };
}
TEST_CASE("SplitIntoChunks") {
size_t FullSize;
size_t ChunkSize;
SUBCASE("Normal case") {
FullSize = 1234567;
ChunkSize = 1234;
}
SUBCASE("Zero original size") {
FullSize = 0;
ChunkSize = 100;
}
SUBCASE("Equal full size and chunk size") {
FullSize = 125;
ChunkSize = 125;
}
SUBCASE("Even split") {
FullSize = 10000;
ChunkSize = 100;
}
SUBCASE("Odd split") {
FullSize = 13;
ChunkSize = 2;
}
SUBCASE("Large sizes") {
FullSize = 10 * GB;
ChunkSize = 125 * MB;
}
auto [Count, LastSize] = SplitIntoChunks(FullSize, ChunkSize);
CHECK((Count * ChunkSize) + LastSize == FullSize);
}
const uint8_t* /* end ptr */ TNetwork::SendSplit(TClient& c, ip::tcp::socket& Socket, const uint8_t* DataPtr, size_t Size) {
if (TCPSendRaw(c, Socket, DataPtr, Size)) {
return DataPtr + Size;
} else {
return nullptr;
}
}
void TNetwork::SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name) {
std::ifstream f(Name.c_str(), std::ios::binary);
uint32_t Split = 125 * MB;
std::vector<uint8_t> Data;
if (Size > Split)
Data.resize(Split);
else
Data.resize(Size);
ip::tcp::socket* TCPSock { nullptr };
if (D)
TCPSock = &c.GetDownSock();
else
TCPSock = &c.GetTCPSock();
while (!c.IsDisconnected() && Sent < Size) {
size_t Diff = Size - Sent;
if (Diff > Split) {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Split);
if (!TCPSendRaw(c, *TCPSock, Data.data(), Split)) {
if (!c.IsDisconnected())
c.Disconnect("TCPSendRaw failed in mod download (1)");
break;
}
Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(reinterpret_cast<char*>(Data.data()), Diff);
if (!TCPSendRaw(c, *TCPSock, Data.data(), int32_t(Diff))) {
if (!c.IsDisconnected())
c.Disconnect("TCPSendRaw failed in mod download (2)");
break;
}
Sent += Diff;
}
}
}
bool TNetwork::TCPSendRaw(TClient& C, ip::tcp::socket& socket, const uint8_t* Data, size_t Size) {
boost::system::error_code ec;
write(socket, buffer(Data, Size), ec);
if (ec) {
beammp_errorf("Failed to send raw data to client: {}", ec.message());
return false;
}
C.UpdatePingTime();
return true;
}
bool TNetwork::SendLarge(TClient& c, std::vector<uint8_t> Data, bool isSync) {
if (Data.size() > 400) {
CompressProperly(Data);
}
return TCPSend(c, Data, isSync);
}
bool TNetwork::Respond(TClient& c, const std::vector<uint8_t>& MSG, bool Rel, bool isSync) {
char C = MSG.at(0);
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
if (C == 'O' || C == 'T' || MSG.size() > 1000) {
return SendLarge(c, MSG, isSync);
} else {
return TCPSend(c, MSG, isSync);
}
} else {
return UDPSend(c, MSG);
}
}
bool TNetwork::SyncClient(const std::weak_ptr<TClient>& c) {
if (c.expired()) {
return false;
}
auto LockedClient = c.lock();
if (LockedClient->IsSynced())
return true;
// Syncing, later set isSynced
// after syncing is done, we apply all packets they missed
if (!Respond(*LockedClient, StringToVector("Sn" + LockedClient->GetName()), true)) {
return false;
}
// ignore error
(void)SendToAll(LockedClient.get(), StringToVector("JWelcome " + LockedClient->GetName() + "!"), false, true);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onPlayerJoin", "", LockedClient->GetID()));
LockedClient->SetIsSyncing(true);
bool Return = false;
bool res = true;
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> client;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
client = ClientPtr.lock();
} else
return true;
}
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (client != LockedClient) {
for (auto& v : VehicleData) {
if (LockedClient->IsDisconnected()) {
Return = true;
res = false;
return false;
}
res = Respond(*LockedClient, StringToVector(v.Data()), true, true);
}
}
return true;
});
LockedClient->SetIsSyncing(false);
if (Return) {
return res;
}
LockedClient->SetIsSynced(true);
beammp_info(LockedClient->GetName() + (" is now synced!"));
return true;
}
void TNetwork::SendToAll(TClient* c, const std::vector<uint8_t>& Data, bool Self, bool Rel) {
if (!Self)
beammp_assert(c);
char C = Data.at(0);
bool ret = true;
mServer.ForEachClient([&](std::weak_ptr<TClient> ClientPtr) -> bool {
std::shared_ptr<TClient> Client;
try {
ReadLock Lock(mServer.GetClientMutex());
Client = ClientPtr.lock();
} catch (const std::exception&) {
// continue
beammp_warn("Client expired, shouldn't happen - if a client disconnected recently, you can ignore this");
return true;
}
if (Self || Client.get() != c) {
if (Client->IsSynced() || Client->IsSyncing()) {
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
if (C == 'O' || C == 'T' || Data.size() > 1000) {
if (Data.size() > 400) {
auto CompressedData = Data;
CompressProperly(CompressedData);
Client->EnqueuePacket(CompressedData);
} else {
Client->EnqueuePacket(Data);
}
// ret = SendLarge(*Client, Data);
} else {
Client->EnqueuePacket(Data);
// ret = TCPSend(*Client, Data);
}
} else {
ret = UDPSend(*Client, Data);
}
}
}
return true;
});
if (!ret) {
// TODO: handle
}
return;
}
bool TNetwork::UDPSend(TClient& Client, std::vector<uint8_t> Data) {
if (!Client.IsConnected() || Client.IsDisconnected()) {
// this can happen if we try to send a packet to a client that is either
// 1. not yet fully connected, or
// 2. disconnected and not yet fully removed
// this is fine can can be ignored :^)
return true;
}
const auto Addr = Client.GetUDPAddr();
if (Data.size() > 400) {
CompressProperly(Data);
}
boost::system::error_code ec;
mUDPSock.send_to(buffer(Data), Addr, 0, ec);
if (ec) {
beammp_debugf("UDP sendto() failed: {}", ec.message());
if (!Client.IsDisconnected())
Client.Disconnect("UDP send failed");
return false;
}
return true;
}
std::vector<uint8_t> TNetwork::UDPRcvFromClient(ip::udp::endpoint& ClientEndpoint) {
std::array<char, 1024> Ret {};
boost::system::error_code ec;
const auto Rcv = mUDPSock.receive_from(mutable_buffer(Ret.data(), Ret.size()), ClientEndpoint, 0, ec);
if (ec) {
beammp_errorf("UDP recvfrom() failed: {}", ec.message());
return {};
}
beammp_assert(Rcv <= Ret.size());
return std::vector<uint8_t>(Ret.begin(), Ret.begin() + Rcv);
}
+69
View File
@@ -0,0 +1,69 @@
#include "TPPSMonitor.h"
#include "Client.h"
#include "TNetwork.h"
TPPSMonitor::TPPSMonitor(TServer& Server)
: mServer(Server) {
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Starting);
Application::SetPPS("-");
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("PPSMonitor", Application::Status::ShuttingDown);
if (mThread.joinable()) {
beammp_debug("shutting down PPSMonitor");
mThread.join();
beammp_debug("shut down PPSMonitor");
}
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Shutdown);
});
Start();
}
void TPPSMonitor::operator()() {
RegisterThread("PPSMonitor");
while (!mNetwork) {
// hard(-ish) spin
std::this_thread::yield();
}
beammp_debug("PPSMonitor starting");
Application::SetSubsystemStatus("PPSMonitor", Application::Status::Good);
std::vector<std::shared_ptr<TClient>> TimedOutClients;
while (!Application::IsShuttingDown()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
int C = 0, V = 0;
if (mServer.ClientCount() == 0) {
Application::SetPPS("-");
continue;
}
mServer.ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> c;
{
ReadLock Lock(mServer.GetClientMutex());
if (!ClientPtr.expired()) {
c = ClientPtr.lock();
} else
return true;
}
if (c->GetCarCount() > 0) {
C++;
V += c->GetCarCount();
}
// kick on "no ping"
if (c->SecondsSinceLastPing() > (20 * 60)) {
beammp_debug("client " + std::string("(") + std::to_string(c->GetID()) + ")" + c->GetName() + " timing out: " + std::to_string(c->SecondsSinceLastPing()) + ", pps: " + Application::PPS());
TimedOutClients.push_back(c);
}
return true;
});
for (auto& ClientToKick : TimedOutClients) {
Network().ClientKick(*ClientToKick, "Timeout (no ping for way too long)");
}
TimedOutClients.clear();
if (C == 0 || mInternalPPS == 0) {
Application::SetPPS("-");
} else {
int R = (mInternalPPS / C) / V;
Application::SetPPS(std::to_string(R));
}
mInternalPPS = 0;
}
}
+76
View File
@@ -0,0 +1,76 @@
#include "TPluginMonitor.h"
#include "TLuaEngine.h"
#include <filesystem>
TPluginMonitor::TPluginMonitor(const fs::path& Path, std::shared_ptr<TLuaEngine> Engine)
: mEngine(Engine)
, mPath(Path) {
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Starting);
if (!fs::exists(mPath)) {
fs::create_directories(mPath);
}
for (const auto& Entry : fs::recursive_directory_iterator(mPath, fs::directory_options::follow_directory_symlink)) {
// TODO: trigger an event when a subfolder file changes
if (Entry.is_regular_file()) {
mFileTimes[Entry.path().string()] = fs::last_write_time(Entry.path());
}
}
Application::RegisterShutdownHandler([this] {
if (mThread.joinable()) {
mThread.join();
}
});
Start();
}
void TPluginMonitor::operator()() {
RegisterThread("PluginMonitor");
beammp_info("PluginMonitor started");
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Good);
while (!Application::IsShuttingDown()) {
std::vector<std::string> ToRemove;
for (const auto& Pair : mFileTimes) {
try {
auto CurrentTime = fs::last_write_time(Pair.first);
if (CurrentTime > Pair.second) {
mFileTimes[Pair.first] = CurrentTime;
// grandparent of the path should be Resources/Server
if (fs::equivalent(fs::path(Pair.first).parent_path().parent_path(), mPath)) {
beammp_infof("File \"{}\" changed, reloading", Pair.first);
// is in root folder, so reload
std::ifstream FileStream(Pair.first, std::ios::in | std::ios::binary);
auto Size = std::filesystem::file_size(Pair.first);
auto Contents = std::make_shared<std::string>();
Contents->resize(Size);
FileStream.read(Contents->data(), Contents->size());
TLuaChunk Chunk(Contents, Pair.first, fs::path(Pair.first).parent_path().string());
auto StateID = mEngine->GetStateIDForPlugin(fs::path(Pair.first).parent_path());
auto Res = mEngine->EnqueueScript(StateID, Chunk);
Res->WaitUntilReady();
if (Res->Error) {
beammp_lua_errorf("Error while hot-reloading \"{}\": {}", Pair.first, Res->ErrorMessage);
} else {
mEngine->ReportErrors(mEngine->TriggerLocalEvent(StateID, "onInit"));
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
}
} else {
// is in subfolder, dont reload, just trigger an event
beammp_debugf("File \"{}\" changed, not reloading because it's in a subdirectory. Triggering 'onFileChanged' event instead", Pair.first);
mEngine->ReportErrors(mEngine->TriggerEvent("onFileChanged", "", Pair.first));
}
}
} catch (const std::exception& e) {
ToRemove.push_back(Pair.first);
}
}
Application::SleepSafeSeconds(3);
for (const auto& File : ToRemove) {
mFileTimes.erase(File);
beammp_warnf("File \"{}\" couldn't be accessed, so it was removed from plugin hot reload monitor (probably got deleted)", File);
}
}
Application::SetSubsystemStatus("PluginMonitor", Application::Status::Shutdown);
}
+36
View File
@@ -0,0 +1,36 @@
#include "TResourceManager.h"
#include <algorithm>
#include <filesystem>
namespace fs = std::filesystem;
TResourceManager::TResourceManager() {
Application::SetSubsystemStatus("ResourceManager", Application::Status::Starting);
std::string Path = Application::Settings.Resource + "/Client";
if (!fs::exists(Path))
fs::create_directories(Path);
for (const auto& entry : fs::directory_iterator(Path)) {
std::string File(entry.path().string());
if (auto pos = File.find(".zip"); pos != std::string::npos) {
if (File.length() - pos == 4) {
std::replace(File.begin(), File.end(), '\\', '/');
mFileList += File + ';';
if (auto i = File.find_last_of('/'); i != std::string::npos) {
++i;
File = File.substr(i, pos - i);
}
mTrimmedList += "/" + fs::path(File).filename().string() + ';';
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
mMaxModSize += size_t(fs::file_size(entry.path()));
mModsLoaded++;
}
}
}
if (mModsLoaded) {
beammp_info("Loaded " + std::to_string(mModsLoaded) + " Mods");
}
Application::SetSubsystemStatus("ResourceManager", Application::Status::Good);
}
+27
View File
@@ -0,0 +1,27 @@
#include "TScopedTimer.h"
#include "Common.h"
TScopedTimer::TScopedTimer()
: mStartTime(std::chrono::high_resolution_clock::now()) {
}
TScopedTimer::TScopedTimer(const std::string& mName)
: mStartTime(std::chrono::high_resolution_clock::now())
, Name(mName) {
}
TScopedTimer::TScopedTimer(std::function<void(size_t)> OnDestroy)
: OnDestroy(OnDestroy)
, mStartTime(std::chrono::high_resolution_clock::now()) {
}
TScopedTimer::~TScopedTimer() {
auto EndTime = std::chrono::high_resolution_clock::now();
auto Delta = EndTime - mStartTime;
size_t TimeDelta = Delta / std::chrono::milliseconds(1);
if (OnDestroy) {
OnDestroy(TimeDelta);
} else {
beammp_info("Scoped timer: \"" + Name + "\" took " + std::to_string(TimeDelta) + "ms ");
}
}
+445
View File
@@ -0,0 +1,445 @@
#include "TServer.h"
#include "Client.h"
#include "Common.h"
#include "CustomAssert.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include <TLuaPlugin.h>
#include <algorithm>
#include <any>
#include <sstream>
#include <nlohmann/json.hpp>
#include "LuaAPI.h"
#undef GetObject // Fixes Windows
#include "Json.h"
static std::optional<std::pair<int, int>> GetPidVid(const std::string& str) {
auto IDSep = str.find('-');
std::string pid = str.substr(0, IDSep);
std::string vid = str.substr(IDSep + 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
try {
int PID = stoi(pid);
int VID = stoi(vid);
return { { PID, VID } };
} catch (const std::exception&) {
return std::nullopt;
}
}
return std::nullopt;
}
TEST_CASE("GetPidVid") {
SUBCASE("Valid singledigit") {
const auto MaybePidVid = GetPidVid("0-1");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 0);
CHECK_EQ(vid, 1);
}
SUBCASE("Valid doubledigit") {
const auto MaybePidVid = GetPidVid("10-12");
CHECK(MaybePidVid);
auto [pid, vid] = MaybePidVid.value();
CHECK_EQ(pid, 10);
CHECK_EQ(vid, 12);
}
SUBCASE("Empty string") {
const auto MaybePidVid = GetPidVid("");
CHECK(!MaybePidVid);
}
SUBCASE("Invalid separator") {
const auto MaybePidVid = GetPidVid("0x0");
CHECK(!MaybePidVid);
}
SUBCASE("Missing pid") {
const auto MaybePidVid = GetPidVid("-0");
CHECK(!MaybePidVid);
}
SUBCASE("Missing vid") {
const auto MaybePidVid = GetPidVid("0-");
CHECK(!MaybePidVid);
}
SUBCASE("Invalid pid") {
const auto MaybePidVid = GetPidVid("x-0");
CHECK(!MaybePidVid);
}
SUBCASE("Invalid vid") {
const auto MaybePidVid = GetPidVid("0-x");
CHECK(!MaybePidVid);
}
}
TServer::TServer(const std::vector<std::string_view>& Arguments) {
beammp_info("BeamMP Server v" + Application::ServerVersionString());
Application::SetSubsystemStatus("Server", Application::Status::Starting);
Application::SetSubsystemStatus("Server", Application::Status::Good);
}
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
std::shared_ptr<TClient> LockedClientPtr { nullptr };
try {
LockedClientPtr = WeakClientPtr.lock();
} catch (const std::exception&) {
// silently fail, as there's nothing to do
return;
}
beammp_assert(LockedClientPtr != nullptr);
TClient& Client = *LockedClientPtr;
beammp_debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
// TODO: Send delete packets for all cars
Client.ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock());
}
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
decltype(mClients) Clients;
{
ReadLock lock(mClientsMutex);
Clients = mClients;
}
for (auto& Client : Clients) {
if (!Fn(Client)) {
break;
}
}
}
size_t TServer::ClientCount() const {
ReadLock Lock(mClientsMutex);
return mClients.size();
}
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::vector<uint8_t>&& Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
constexpr std::string_view ABG = "ABG:";
if (Packet.size() >= ABG.size() && std::equal(Packet.begin(), Packet.begin() + ABG.size(), ABG.begin(), ABG.end())) {
Packet.erase(Packet.begin(), Packet.begin() + ABG.size());
Packet = DeComp(Packet);
}
if (Packet.empty()) {
return;
}
if (Client.expired()) {
return;
}
auto LockedClient = Client.lock();
std::any Res;
char Code = Packet.at(0);
std::string StringPacket(reinterpret_cast<const char*>(Packet.data()), Packet.size());
// V to Y
if (Code <= 89 && Code >= 86) {
PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false);
return;
}
switch (Code) {
case 'H': // initial connection
if (!Network.SyncClient(Client)) {
// TODO handle
}
return;
case 'p':
if (!Network.Respond(*LockedClient, StringToVector("p"), false)) {
// failed to send
LockedClient->Disconnect("Failed to send ping");
} else {
Network.UpdatePlayer(*LockedClient);
}
return;
case 'O':
if (Packet.size() > 1000) {
beammp_debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.size()));
}
ParseVehicle(*LockedClient, StringPacket, Network);
return;
case 'C': {
if (Packet.size() < 4 || std::find(Packet.begin() + 3, Packet.end(), ':') == Packet.end())
break;
const auto PacketAsString = std::string(reinterpret_cast<const char*>(Packet.data()), Packet.size());
std::string Message = "";
const auto ColonPos = PacketAsString.find(':', 3);
if (ColonPos != std::string::npos && ColonPos + 2 < PacketAsString.size()) {
Message = PacketAsString.substr(ColonPos + 2);
}
if (Message.empty()) {
beammp_debugf("Empty chat message received from '{}' ({}), ignoring it", LockedClient->GetName(), LockedClient->GetID());
return;
}
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onChatMessage", "", LockedClient->GetID(), LockedClient->GetName(), Message);
TLuaEngine::WaitForAll(Futures);
LogChatMessage(LockedClient->GetName(), LockedClient->GetID(), PacketAsString.substr(PacketAsString.find(':', 3) + 1));
if (std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Elem) {
return !Elem->Error
&& Elem->Result.is<int>()
&& bool(Elem->Result.as<int>());
})) {
break;
}
std::string SanitizedPacket = fmt::format("C:{}: {}", LockedClient->GetName(), Message);
Network.SendToAll(nullptr, StringToVector(SanitizedPacket), true, true);
return;
}
case 'E':
HandleEvent(*LockedClient, StringPacket);
return;
case 'N':
beammp_trace("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true);
return;
case 'Z': // position packet
PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false);
HandlePosition(*LockedClient, StringPacket);
default:
return;
}
}
void TServer::HandleEvent(TClient& c, const std::string& RawData) {
// E:Name:Data
// Data is allowed to have ':'
if (RawData.size() < 2) {
beammp_debugf("Client '{}' ({}) tried to send an empty event, ignoring", c.GetName(), c.GetID());
return;
}
auto NameDataSep = RawData.find(':', 2);
if (NameDataSep == std::string::npos) {
beammp_warn("received event in invalid format (missing ':'), got: '" + RawData + "'");
}
std::string Name = RawData.substr(2, NameDataSep - 2);
std::string Data = RawData.substr(NameDataSep + 1);
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent(Name, "", c.GetID(), Data));
}
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
try {
auto Car = nlohmann::json::parse(CarJson);
const std::string jbm = "jbm";
if (Car.contains(jbm) && Car[jbm].is_string() && Car[jbm] == "unicycle") {
return true;
}
} catch (const std::exception& e) {
beammp_warn("Failed to parse vehicle data as json for client " + std::to_string(c.GetID()) + ": '" + CarJson + "'.");
}
return false;
}
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
if (IsUnicycle(c, CarJson) && c.GetUnicycleID() < 0) {
c.SetUnicycleID(ID);
return true;
} else {
return c.GetCarCount() < Application::Settings.MaxCars;
}
}
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
if (Pckt.length() < 6)
return;
std::string Packet = Pckt;
char Code = Packet.at(1);
int PID = -1;
int VID = -1;
std::string Data = Packet.substr(3), pid, vid;
switch (Code) { // Spawned Destroyed Switched/Moved NotFound Reset
case 's':
beammp_tracef("got 'Os' packet: '{}' ({})", Packet, Packet.size());
if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID();
beammp_debugf("'{}' created a car with ID {}", c.GetName(), CarID);
std::string CarJson = Packet.substr(5);
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleSpawn", "", c.GetID(), CarID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures);
bool ShouldntSpawn = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
});
if (ShouldSpawn(c, CarJson, CarID) && !ShouldntSpawn) {
c.AddNewCar(CarID, Packet);
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
} else {
if (!Network.Respond(c, StringToVector(Packet), true)) {
// TODO: handle
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, StringToVector(Destroy), true)) {
// TODO: handle
}
beammp_debugf("{} (force : car limit/lua) removed ID {}", c.GetName(), CarID);
}
}
return;
case 'c': {
beammp_trace(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value();
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onVehicleEdited", "", c.GetID(), VID, Packet.substr(3));
TLuaEngine::WaitForAll(Futures);
bool ShouldntAllow = std::any_of(Futures.begin(), Futures.end(),
[](const std::shared_ptr<TLuaResult>& Result) {
return !Result->Error && Result->Result.is<int>() && Result->Result.as<int>() != 0;
});
auto FoundPos = Packet.find('{');
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& !ShouldntAllow) {
Network.SendToAll(&c, StringToVector(Packet), false, true);
Apply(c, VID, Packet);
} else {
if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1);
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
Network.SendToAll(nullptr, StringToVector(Destroy), true, true);
c.DeleteCar(VID);
}
}
return;
}
case 'd': {
beammp_trace(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value();
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1);
}
Network.SendToAll(nullptr, StringToVector(Packet), true, true);
// TODO: should this trigger on all vehicle deletions?
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleDeleted", "", c.GetID(), VID));
c.DeleteCar(VID);
beammp_debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
}
return;
}
case 'r': {
beammp_trace(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
auto MaybePidVid = GetPidVid(Data.substr(0, Data.find(':', 1)));
if (MaybePidVid) {
std::tie(PID, VID) = MaybePidVid.value();
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
Data = Data.substr(Data.find('{'));
LuaAPI::MP::Engine->ReportErrors(LuaAPI::MP::Engine->TriggerEvent("onVehicleReset", "", c.GetID(), VID, Data));
Network.SendToAll(&c, StringToVector(Packet), false, true);
}
return;
}
case 't':
beammp_trace(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
Network.SendToAll(&c, StringToVector(Packet), false, true);
return;
case 'm':
Network.SendToAll(&c, StringToVector(Packet), true, true);
return;
default:
beammp_trace(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
return;
}
}
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
auto FoundPos = pckt.find('{');
if (FoundPos == std::string::npos) {
beammp_error("Malformed packet received, no '{' found");
return;
}
std::string Packet = pckt.substr(FoundPos);
std::string VD = c.GetCarData(VID);
if (VD.empty()) {
beammp_error("Tried to apply change to vehicle that does not exist");
return;
}
std::string Header = VD.substr(0, VD.find('{'));
FoundPos = VD.find('{');
if (FoundPos == std::string::npos) {
return;
}
VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack;
Veh.Parse(VD.c_str());
if (Veh.HasParseError()) {
beammp_error("Could not get vehicle config!");
return;
}
Pack.Parse(Packet.c_str());
if (Pack.HasParseError() || Pack.IsNull()) {
beammp_error("Could not get active vehicle config!");
return;
}
for (auto& M : Pack.GetObject()) {
if (Veh[M.name].IsNull()) {
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
} else {
Veh[M.name] = Pack[M.name];
}
}
rapidjson::StringBuffer Buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
Veh.Accept(writer);
c.SetCarData(VID, Header + Buffer.GetString());
}
void TServer::InsertClient(const std::shared_ptr<TClient>& NewClient) {
beammp_debug("inserting client (" + std::to_string(ClientCount()) + ")");
WriteLock Lock(mClientsMutex); // TODO why is there 30+ threads locked here
(void)mClients.insert(NewClient);
}
void TServer::HandlePosition(TClient& c, const std::string& Packet) {
if (Packet.size() < 3) {
// invalid packet
return;
}
// Zp:serverVehicleID:data
// Zp:0:data
std::string withoutCode = Packet.substr(3);
auto NameDataSep = withoutCode.find(':', 2);
if (NameDataSep == std::string::npos || NameDataSep < 2) {
// invalid packet
return;
}
// FIXME: ensure that -2 does what it should... it seems weird.
std::string ServerVehicleID = withoutCode.substr(2, NameDataSep - 2);
if (NameDataSep + 1 > withoutCode.size()) {
// invalid packet
return;
}
std::string Data = withoutCode.substr(NameDataSep + 1);
// parse veh ID
auto MaybePidVid = GetPidVid(ServerVehicleID);
if (MaybePidVid) {
int PID = -1;
int VID = -1;
// FIXME: check that the VID and PID are valid, so that we don't waste memory
std::tie(PID, VID) = MaybePidVid.value();
c.SetCarPosition(VID, Data);
}
}
+249
View File
@@ -0,0 +1,249 @@
#include "Update.h"
#include "Common.h"
#include <algorithm>
#include <boost/predef.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <httplib.h>
#include <nlohmann/json.hpp>
#if defined(__linux)
#include <unistd.h>
#elif defined(WIN32)
#include <windows.h>
#endif
static bool ProgressReport(uint64_t current, uint64_t total) {
if (current == total) {
fmt::print("100% ({:.2f} / {:.2f} KiB)\n", float(current) / 1024.0f, float(total) / 1024.0f);
}
if (total != 0) {
auto percent = (float(current) / float(total)) * 100.0f;
fmt::print("{:3.0f}% ({:.2f} / {:.2f} KiB)\r", percent, float(current) / 1024.0f, float(total) / 1024.0f);
}
return true;
}
void Update::PerformUpdate(const std::string& InvokedAs) {
using json = nlohmann::json;
namespace http = httplib;
constexpr auto GH = "api.github.com";
std::string ReleasesAPI = "/repos/BeamMP/BeamMP-Server/releases";
http::Headers APIHeaders {};
APIHeaders.emplace("X-GitHub-Api-Version", "2022-11-28");
APIHeaders.emplace("Accept", "application/vnd.github+json");
http::SSLClient c(GH);
c.set_read_timeout(std::chrono::seconds(30));
beammp_infof("Checking for latest release...");
// check if there is a new release
auto Res = c.Get(ReleasesAPI + "/latest", APIHeaders);
if (!Res || Res->status < 200 || Res->status >= 300) {
beammp_errorf("Failed to fetch latest release: {}", to_string(Res.error()));
std::exit(1);
}
Version NewVersion { 0, 0, 0 };
json ReleaseInfo;
try {
ReleaseInfo = json::parse(Res->body);
std::string TagName = ReleaseInfo["tag_name"].get<std::string>();
if (!TagName.starts_with("v") || std::count(TagName.begin(), TagName.end(), '.') != 2) {
beammp_errorf("Invalid version provided by GitHub: '{}', exiting", TagName);
std::exit(1);
}
TagName = TagName.substr(1);
auto Tag = Application::VersionStrToInts(TagName);
NewVersion = Version { Tag[0], Tag[1], Tag[2] };
beammp_infof("Latest release is v{}", NewVersion.AsString());
} catch (const std::exception& e) {
beammp_errorf("Failed to fetch latest release info from GitHub");
beammp_errorf("Error: {}", e.what());
std::exit(1);
}
// check if the new release is patch, minor or major
auto Current = Application::ServerVersion();
bool MajorOutdated = NewVersion.major > Current.major;
bool MinorOutdated = !MajorOutdated && Application::IsOutdated(Current, NewVersion);
if (!MajorOutdated && !MinorOutdated) {
beammp_infof("BeamMP-Server is already the latest version (v{})!", Current.AsString());
std::exit(0);
} else {
beammp_infof("New update available, updating from v{} to v{}", Current.AsString(), NewVersion.AsString());
}
std::string Arch = "";
#if BOOST_ARCH_ARM && BOOST_ARCH_WORD_BITS == 64
Arch = "arm64";
#elif BOOST_ARCH_X86_64
Arch = "x86_64";
#else
beammp_errorf("The current architecture is not supported, please update manually.");
std::exit(1);
#endif
std::string Postfix = {};
// figure out current platform
#if WIN32
beammp_infof("Current platform is Windows");
Postfix = ".exe";
#elif __linux
beammp_infof("Current platform is Linux, checking distribution");
const std::string OsReleasePath = "/etc/os-release";
std::string DistroID = "";
std::string DistroVersion = "";
if (fs::exists(OsReleasePath)) {
std::ifstream OsRelease(OsReleasePath);
std::string Line {};
while (std::getline(OsRelease, Line)) {
if (Line.starts_with("ID=")) {
DistroID = Line.substr(3);
} else if (Line.starts_with("VERSION_ID=\"")) {
DistroVersion = Line.substr(strlen("VERSION_ID=\""));
// skip closing quote
DistroVersion = DistroVersion.substr(0, DistroVersion.size() - 1);
} else if (Line.starts_with("VERSION_ID=")) {
DistroVersion = Line.substr(strlen("VERSION_ID="));
}
}
}
beammp_infof("Distribution: {} {}", DistroID, DistroVersion);
std::string Distro = {};
if (DistroVersion.empty()) {
Distro = DistroID;
} else {
Distro = DistroID + "." + DistroVersion;
}
Postfix = fmt::format(".{}.{}", Distro, Arch);
#else
beammp_infof("BeamMP doesn't provide binaries for this OS, please update manually");
std::exit(1);
#endif
beammp_infof("Looking for BeamMP-Server{}", Postfix);
// check if the release exists for that platform
std::string DownloadURL = "";
try {
for (const auto& Asset : ReleaseInfo.at("assets")) {
if (Asset.at("name").get<std::string>() == "BeamMP-Server" + Postfix) {
DownloadURL = Asset.at("browser_download_url");
break;
}
}
} catch (const std::exception& e) {
beammp_errorf("Failed to parse GitHub API's release assets: {}", e.what());
std::exit(1);
}
if (DownloadURL.empty()) {
beammp_infof("BeamMP doesn't provide binaries for this platform or distribution (release 'BeamMP-Server{}' not found in the release assets), please update manually", Postfix);
std::exit(1);
}
// download urls exist, ask if the user wants to do a major update
if (MajorOutdated) {
beammp_warnf("The update from v{} to v{} is a major update, which is likely to *break* any Lua Plugins. Please make sure you have read the release notes at {} before proceeding!", Current.AsString(), NewVersion.AsString(), ReleaseInfo.at("html_url").get<std::string>());
#if !defined(WIN32)
if (!isatty(STDIN_FILENO)) {
beammp_errorf("Refusing to do a major version update non-interactively. Run this again in a TTY or update manually");
std::exit(1);
}
#endif
fmt::print("\n");
int ch;
do {
fmt::print("Do you wish to proceed with this update? [y/n] ");
std::string Input;
std::getline(std::cin, Input);
if (Input.empty()) {
continue;
}
ch = Input.at(0);
} while (tolower(ch) != 'y' && tolower(ch) != 'n');
if (tolower(ch) == 'n') {
beammp_error("Cancelling update");
std::exit(2);
}
}
beammp_info("Downloading latest release from github.com...");
http::SSLClient DlClient("github.com");
DlClient.set_follow_location(true);
auto ReleaseRes = DlClient.Get(DownloadURL.substr(strlen("https://github.com")), ProgressReport);
if (!ReleaseRes || ReleaseRes->status < 200 || ReleaseRes->status >= 300) {
beammp_errorf("Failed to fetch binary: {}. Please update manually", to_string(ReleaseRes.error()));
std::exit(1);
}
beammp_info("Download complete!");
auto Temp = InvokedAs + ".temp";
beammp_infof("Creating '{}'", Temp);
FILE* Out = std::fopen(Temp.c_str(), "w+");
if (!Out) {
beammp_errorf("Failed to update executable, because a temporary file couldn't be created: {}", std::strerror(errno));
std::exit(1);
}
auto n = std::fwrite(ReleaseRes->body.data(), 1, ReleaseRes->body.size(), Out);
if (n != ReleaseRes->body.size()) {
beammp_errorf("Failed to update executable, because a temporary file couldn't be written to: {}", std::strerror(errno));
std::fclose(Out);
std::exit(1);
}
std::fclose(Out);
#if defined(__linux)
beammp_infof("Removing '{}'", InvokedAs);
struct stat st;
if (stat(InvokedAs.c_str(), &st) != 0) {
// shouldn't happen at this point
beammp_errorf("Failed to stat original executable: {}", std::strerror(errno));
std::exit(1);
}
auto Ret = unlink(InvokedAs.c_str());
if (Ret != 0) {
beammp_errorf("Failed to remove executable: {}", std::strerror(errno));
std::exit(1);
}
beammp_infof("Replacing '{}' with '{}'", InvokedAs, Temp);
fs::rename(Temp, InvokedAs);
if (chmod(InvokedAs.c_str(), st.st_mode) != 0) {
beammp_warnf("Failed to set file mode to 0{:o}: {}. File may not be executable.", st.st_mode, std::strerror(errno));
}
#elif defined(WIN32)
auto DeleteMe = InvokedAs + ".delete_me";
std::filesystem::rename(InvokedAs, DeleteMe);
std::filesystem::rename(Temp, InvokedAs);
int Attr = GetFileAttributesA(DeleteMe.c_str());
if ((Attr & FILE_ATTRIBUTE_HIDDEN) == 0) {
SetFileAttributesA(DeleteMe.c_str(), Attr | FILE_ATTRIBUTE_HIDDEN);
}
#else
beammp_error("Not implemented");
std::exit(4);
#endif
// make sure the user knows that it was a success, on windows wait for return???
beammp_infof("SUCCESSFULLY UPDATED to v{}. Please launch the server manually to start the new version!", NewVersion.AsString());
std::exit(0);
}
+14
View File
@@ -0,0 +1,14 @@
#include "VehicleData.h"
#include "Common.h"
#include <utility>
TVehicleData::TVehicleData(int ID, std::string Data)
: mID(ID)
, mData(std::move(Data)) {
beammp_trace("vehicle " + std::to_string(mID) + " constructed");
}
TVehicleData::~TVehicleData() {
beammp_trace("vehicle " + std::to_string(mID) + " destroyed");
}
-76
View File
@@ -1,76 +0,0 @@
use std::path::{Path, PathBuf};
use serde::Deserialize;
use uuid::Uuid;
use crate::fs_util;
#[derive(Deserialize)]
pub struct Config {
#[serde(skip)] // Skipping uses Default::default, which makes a new vector for us :)
pub mods: Vec<(String, usize)>,
#[serde(rename = "General")]
pub general: GeneralSettings,
}
#[derive(Deserialize)]
pub struct GeneralSettings {
#[serde(rename = "Port")]
pub port: Option<u16>,
#[serde(rename = "Name")]
pub name: String,
#[serde(rename = "Description")]
pub description: String,
#[serde(rename = "AuthKey")]
pub auth_key: Option<String>,
#[serde(rename = "MaxCars")]
pub max_cars: Option<u8>,
#[serde(rename = "MaxPlayers")]
pub max_players: usize,
#[serde(rename = "Private")]
pub private: bool,
#[serde(rename = "Map")]
pub map: String,
#[serde(rename = "ResourceFolder")]
pub resource_folder: String,
#[serde(rename = "Debug")]
pub debug: bool,
// Options below are not yet supported
#[serde(rename = "LogChat")]
pub log_chat: bool,
}
impl GeneralSettings {
pub fn is_auth_key_valid(&self) -> bool {
if let Some(auth_key) = &self.auth_key {
Uuid::parse_str(auth_key.as_str()).is_ok()
} else {
false
}
}
/// Returns the client resource path, and ensures it exists.
/// Default is Resources/Client.
pub fn get_client_resource_folder(&self) -> anyhow::Result<String> {
let res_client_path = Path::new(self.resource_folder.as_str()).join("Client");
fs_util::ensure_path_exists(&res_client_path)?;
Ok(fs_util::path_to_string(res_client_path))
}
/// Returns the server resource path, and ensures it exists.
/// Default is Resources/Server.
pub fn get_server_resource_folder(&self) -> anyhow::Result<String> {
let res_server_path = Path::new(self.resource_folder.as_str()).join("Server");
fs_util::ensure_path_exists(&res_server_path)?;
Ok(fs_util::path_to_string(res_server_path))
}
}
-22
View File
@@ -1,22 +0,0 @@
use std::path::{Path, PathBuf};
/// Ensures the given path exists by creating it if it doesn't.
pub fn ensure_path_exists(path: &PathBuf) -> anyhow::Result<()> {
if !path.exists() {
debug!("Path {:?} doesn't exist, creating it", path);
std::fs::create_dir_all(path)?;
}
Ok(())
}
/// Joins a parent folder and a sub-path, resolving the subpath beforehand to ensure that
/// the resulting path is still within the parent folder, regardless of ".." in the sub-path.
pub fn join_path_secure(parent: &Path, sub: &Path) -> anyhow::Result<PathBuf> {
Ok(parent.join(sub.file_name().unwrap_or("".as_ref())))
}
/// Converts a PathBuf into a String in a lossy way. This is generally the way we want to do it
/// in the server.
pub fn path_to_string(path: PathBuf) -> String {
path.into_os_string().to_string_lossy().to_string()
}
-80
View File
@@ -1,80 +0,0 @@
use serde::Serialize;
use tokio::sync::mpsc::Receiver;
#[derive(Serialize)]
struct HeartbeatInfo {
uuid: String,
players: usize,
maxplayers: usize,
port: u16,
map: String,
private: String, // Needs to be either "true" or "false"
version: String,
clientversion: String,
name: String,
modlist: String,
modstotalsize: usize,
modstotal: usize,
playerslist: String,
desc: String,
}
pub async fn backend_heartbeat(config: std::sync::Arc<crate::config::Config>, mut hb_rx: Receiver<crate::server::ServerStatus>) {
if !config.general.is_auth_key_valid() {
if config.general.private {
warn!("AuthKey has invalid format. This is not an error, since your server is private.");
} else {
error!("AuthKey has invalid format. The server will not appear on the server list.");
}
// FIXME: The heartbeat should be started if the config is ever changed/reloaded.
return;
}
let mut info = HeartbeatInfo {
uuid: config.general.auth_key.clone().unwrap_or(String::from("Unknown name!")),
players: 0,
maxplayers: config.general.max_players,
port: config.general.port.unwrap_or(30814),
map: config.general.map.clone(),
private: if config.general.private { String::from("true") } else { String::from("false") },
version: String::from("3.3.0"), // TODO: Don't hardcode this
clientversion: String::from("2.0"), // TODO: What? I think for now I can fill in 2.0
name: config.general.name.clone(),
modlist: String::from("-"), // TODO: Implement this
modstotalsize: 0, // TODO: Implement this
modstotal: 0, // TODO: Implement this
playerslist: String::new(),
desc: config.general.description.clone(),
};
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
loop {
interval.tick().await;
tokio::select! {
_ = heartbeat_post(&info) => {}
status = hb_rx.recv() => {
if let Some(status) = status {
trace!("status update: {:?}", status);
info.players = status.player_count;
info.playerslist = status.player_list.iter().map(|(_id, name)| format!("{};", name)).collect();
}
}
}
}
}
async fn heartbeat_post(heartbeat_info: &HeartbeatInfo) {
match reqwest::Client::builder()
.local_address("0.0.0.0".parse::<std::net::IpAddr>().unwrap())
.build().unwrap()
.post("https://backend.beammp.com/heartbeat")
.form(heartbeat_info)
.send()
.await
{
Ok(resp) => {
trace!("heartbeat response:\n{:?}", resp.text().await);
},
Err(e) => error!("Heartbeat error occured: {e}"),
}
}
-44
View File
@@ -1,44 +0,0 @@
use log::{Record, Level, Metadata, SetLoggerError, LevelFilter};
use std::sync::Mutex;
lazy_static! {
static ref LOG_BUFFER: Mutex<Vec<(Level, String)>> = Mutex::new(Vec::new());
}
struct BufferedLogger;
impl log::Log for BufferedLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
let mut enabled = true;
if metadata.level() != Level::Error {
if metadata.target().starts_with("rustls") {
enabled = false;
}
}
enabled
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let msg = format!("{}", record.args());
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
lock.push((record.level(), msg));
}
}
fn flush(&self) {}
}
static LOGGER: BufferedLogger = BufferedLogger;
pub fn init(filter: LevelFilter) -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(filter))
}
pub async fn drain_log_buffer() -> Vec<(Level, String)> {
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
let v = lock.drain(..).collect();
drop(lock);
v
}
+216
View File
@@ -0,0 +1,216 @@
#include "ArgsParser.h"
#include "Common.h"
#include "Http.h"
#include "LuaAPI.h"
#include "SignalHandling.h"
#include "TConfig.h"
#include "THeartbeatThread.h"
#include "TLuaEngine.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include "TPluginMonitor.h"
#include "TResourceManager.h"
#include "TServer.h"
#include "Update.h"
#include <filesystem>
#include <iostream>
#include <thread>
static const std::string sCommandlineArguments = R"(
USAGE:
BeamMP-Server [arguments]
ARGUMENTS:
--help
Displays this help and exits.
--config=/path/to/ServerConfig.toml
Absolute or relative path to the
Server Config file, including the
filename. For paths and filenames with
spaces, put quotes around the path.
--working-directory=/path/to/folder
Sets the working directory of the Server.
All paths are considered relative to this,
including the path given in --config.
--version
Prints version info and exits.
--update
Starts an interactive update to the newest
version of BeamMP-Server.
EXAMPLES:
BeamMP-Server --config=../MyWestCoastServerConfig.toml
Runs the BeamMP-Server and uses the server config file
which is one directory above it and is named
'MyWestCoastServerConfig.toml'.
)";
struct MainArguments {
int argc {};
char** argv {};
std::vector<std::string_view> List;
std::string InvokedAs;
};
int BeamMPServerMain(MainArguments Arguments);
int main(int argc, char** argv) {
MainArguments Args { argc, argv, {}, argv[0] };
Args.List.reserve(size_t(argc));
for (int i = 1; i < argc; ++i) {
Args.List.push_back(argv[i]);
}
int MainRet = 0;
try {
MainRet = BeamMPServerMain(std::move(Args));
} catch (const std::exception& e) {
beammp_error("A fatal exception has occurred and the server is forcefully shutting down.");
beammp_error(e.what());
MainRet = -1;
}
std::exit(MainRet);
}
int BeamMPServerMain(MainArguments Arguments) {
setlocale(LC_ALL, "C");
ArgsParser Parser;
Parser.RegisterArgument({ "help" }, ArgsParser::NONE);
Parser.RegisterArgument({ "version" }, ArgsParser::NONE);
Parser.RegisterArgument({ "update" }, ArgsParser::NONE);
Parser.RegisterArgument({ "config" }, ArgsParser::HAS_VALUE);
Parser.RegisterArgument({ "working-directory" }, ArgsParser::HAS_VALUE);
Parser.Parse(Arguments.List);
if (!Parser.Verify()) {
return 1;
}
if (Parser.FoundArgument({ "help" })) {
Application::Console().WriteRaw(sCommandlineArguments);
return 0;
}
if (Parser.FoundArgument({ "version" })) {
Application::Console().WriteRaw("BeamMP-Server v" + Application::ServerVersionString());
return 0;
}
if (Parser.FoundArgument({ "update" })) {
Update::PerformUpdate(Arguments.InvokedAs);
return 123;
}
// check that there is no old update file
auto OldFile = Arguments.InvokedAs + ".delete_me";
if (fs::exists(OldFile)) {
fs::remove(OldFile);
}
std::string ConfigPath = "ServerConfig.toml";
if (Parser.FoundArgument({ "config" })) {
auto MaybeConfigPath = Parser.GetValueOfArgument({ "config" });
if (MaybeConfigPath.has_value()) {
ConfigPath = MaybeConfigPath.value();
beammp_info("Custom config requested via commandline arguments: '" + ConfigPath + "'");
}
}
if (Parser.FoundArgument({ "working-directory" })) {
auto MaybeWorkingDirectory = Parser.GetValueOfArgument({ "working-directory" });
if (MaybeWorkingDirectory.has_value()) {
beammp_info("Custom working directory requested via commandline arguments: '" + MaybeWorkingDirectory.value() + "'");
try {
fs::current_path(fs::path(MaybeWorkingDirectory.value()));
} catch (const std::exception& e) {
beammp_errorf("Could not set working directory to '{}': {}", MaybeWorkingDirectory.value(), e.what());
}
}
}
TConfig Config(ConfigPath);
if (Config.Failed()) {
beammp_info("Closing in 10 seconds");
// loop to make it possible to ctrl+c instead
for (size_t i = 0; i < 20; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return 1;
}
Application::InitializeConsole();
Application::Console().StartLoggingToFile();
Application::SetSubsystemStatus("Main", Application::Status::Starting);
SetupSignalHandlers();
bool Shutdown = false;
Application::RegisterShutdownHandler([&Shutdown] {
beammp_info("If this takes too long, you can press Ctrl+C repeatedly to force a shutdown.");
Application::SetSubsystemStatus("Main", Application::Status::ShuttingDown);
Shutdown = true;
});
Application::RegisterShutdownHandler([] {
auto Futures = LuaAPI::MP::Engine->TriggerEvent("onShutdown", "");
TLuaEngine::WaitForAll(Futures, std::chrono::seconds(5));
});
TServer Server(Arguments.List);
auto LuaEngine = std::make_shared<TLuaEngine>();
LuaEngine->SetServer(&Server);
Application::Console().InitializeLuaConsole(*LuaEngine);
RegisterThread("Main");
beammp_trace("Running in debug mode on a debug build");
TResourceManager ResourceManager;
TPPSMonitor PPSMonitor(Server);
THeartbeatThread Heartbeat(ResourceManager, Server);
TNetwork Network(Server, PPSMonitor, ResourceManager);
LuaEngine->SetNetwork(&Network);
PPSMonitor.SetNetwork(Network);
Application::CheckForUpdates();
TPluginMonitor PluginMonitor(fs::path(Application::Settings.Resource) / "Server", LuaEngine);
if (Application::Settings.HTTPServerEnabled) {
Http::Server::THttpServerInstance HttpServerInstance {};
}
Application::SetSubsystemStatus("Main", Application::Status::Good);
RegisterThread("Main(Waiting)");
std::set<std::string> IgnoreSubsystems {
"UpdateCheck" // Ignore as not to confuse users (non-vital system)
};
bool FullyStarted = false;
while (!Shutdown) {
if (!FullyStarted) {
FullyStarted = true;
bool WithErrors = false;
std::string SystemsBadList {};
auto Statuses = Application::GetSubsystemStatuses();
for (const auto& NameStatusPair : Statuses) {
if (IgnoreSubsystems.count(NameStatusPair.first) > 0) {
continue; // ignore
}
if (NameStatusPair.second == Application::Status::Starting) {
FullyStarted = false;
} else if (NameStatusPair.second == Application::Status::Bad) {
SystemsBadList += NameStatusPair.first + ", ";
WithErrors = true;
}
}
// remove ", "
SystemsBadList = SystemsBadList.substr(0, SystemsBadList.size() - 2);
if (FullyStarted) {
if (!WithErrors) {
beammp_info("ALL SYSTEMS STARTED SUCCESSFULLY, EVERYTHING IS OKAY");
} else {
beammp_error("STARTUP NOT SUCCESSFUL, SYSTEMS " + SystemsBadList + " HAD ERRORS. THIS MAY OR MAY NOT CAUSE ISSUES.");
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
Application::SetSubsystemStatus("Main", Application::Status::Shutdown);
beammp_info("Shutdown.");
return 0;
}
-165
View File
@@ -1,165 +0,0 @@
#[macro_use] extern crate log;
#[macro_use] extern crate async_trait;
#[macro_use] extern crate lazy_static;
use std::path::Path;
use argh::FromArgs;
use std::sync::Arc;
use tokio::sync::mpsc;
mod logger;
mod tui;
mod server;
mod config;
mod heartbeat;
mod fs_util;
#[derive(FromArgs)]
/// BeamMP Server v3.3.0
struct Args {
/// disables the TUI and shows a simple console log instead
#[argh(switch)]
disable_tui: bool,
}
#[tokio::main]
async fn main() {
let args: Args = argh::from_env();
let mut user_config: config::Config = toml::from_str(
&std::fs::read_to_string("ServerConfig.toml")
.map_err(|_| error!("Failed to read config file!"))
.expect("Failed to read config file!")
)
.map_err(|_| eprintln!("Failed to parse config file!"))
.expect("Failed to parse config file!");
let level_filter = if user_config.general.debug { log::LevelFilter::max() } else { log::LevelFilter::Info };
if !args.disable_tui {
logger::init(level_filter).expect("Failed to enable logger!");
} else {
pretty_env_logger::formatted_timed_builder()
.filter_level(level_filter)
.filter_module("rustls", log::LevelFilter::Error)
.init();
}
let client_resources = user_config.general
.get_client_resource_folder()
.expect("Failed to create the client resource folder");
for entry in std::fs::read_dir(client_resources).expect("Failed to read client resource folder!") {
if let Ok(entry) = entry {
if entry.path().is_file() {
if let Ok(metadata) = entry.metadata() {
if let Some(filename) = entry.path().file_name().map(|s| s.to_string_lossy()) {
let mut name = filename.to_string();
if !name.starts_with("/") {
name = format!("/{name}");
}
user_config.mods.push((name, metadata.len() as usize));
}
}
}
}
}
debug!("Mods: {:?}", user_config.mods);
let user_config = Arc::new(user_config);
let (cmd_tx, cmd_rx) = mpsc::channel(100);
let (status_tx, status_rx) = mpsc::channel(100);
if !args.disable_tui {
tokio::spawn(tui::tui_main(user_config.clone(), cmd_tx, status_rx));
}
server_main(user_config, cmd_rx, status_tx).await;
}
async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receiver<Vec<String>>, status_tx: mpsc::Sender<server::ServerStatus>) {
let (hb_tx, hb_rx) = mpsc::channel(100);
tokio::spawn(heartbeat::backend_heartbeat(user_config.clone(), hb_rx));
let mut server = server::Server::new(user_config)
.await
.map_err(|e| error!("{:?}", e))
.expect("Failed to start server!");
let mut status = server.get_server_status();
hb_tx.send(status.clone()).await;
status_tx.send(status.clone()).await;
'server: loop {
// TODO: Error handling
if server.clients.len() > 0 {
tokio::select! {
ret = server::read_tcp(&mut server.clients) => {
match ret {
Ok(ret) => if let Some((index, packet)) = ret {
server.process_tcp(index, packet).await;
},
Err(e) => error!("Error: {e}"),
}
}
ret = server::read_udp(&mut server.udp_socket) => {
if let Some((addr, packet)) = ret {
server.process_udp(addr, packet).await;
}
}
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {}
}
} else {
// TODO: Scuffed?
tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
}
if let Err(e) = server.process().await {
error!("{:?}", e);
}
let new_status = server.get_server_status();
if status != new_status {
status = new_status;
hb_tx.send(status.clone()).await;
status_tx.send(status.clone()).await;
}
// Process commands
match cmd_rx.try_recv() {
Ok(cmd) => if cmd.len() > 0 {
match cmd[0].as_str() {
"exit" => {
server.close().await;
break 'server;
},
"players" => {
let mut pl = "Players:\n".to_string();
for (i, (id, player)) in status.player_list.iter().enumerate() {
pl.push_str(&format!("\t[{: >2}] - {player}", id));
if i + 1 < status.player_list.len() {
pl.push('\n');
}
}
info!("{}", pl);
},
"say" => {
let msg = cmd[1..].iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
server.send_chat_message(&msg, None).await;
},
_ => info!("Unknown command!"),
}
} else {
// what!
},
Err(mpsc::error::TryRecvError::Empty) => {},
Err(e) => {
error!("Error: {e}");
break;
},
}
}
}
-19
View File
@@ -1,19 +0,0 @@
use serde::de::DeserializeOwned;
use std::collections::HashMap;
static BACKEND_URL: &'static str = "backend.beammp.com";
static AUTH_URL: &'static str = "auth.beammp.com";
pub async fn authentication_request<R: DeserializeOwned>(
target: &str,
map: HashMap<String, String>,
) -> anyhow::Result<R> {
let client = reqwest::Client::new();
let resp = client
.post(format!("https://{}/{}", AUTH_URL, target))
.json(&map)
.send()
.await?;
// panic!("json: {:?}", resp.text().await);
Ok(resp.json().await?)
}
-43
View File
@@ -1,43 +0,0 @@
use glam::*;
use std::time::Instant;
#[derive(Default, Clone, Debug)]
pub struct Car {
pub car_json: String,
pub pos: DVec3,
pub rot: DQuat,
pub vel: DVec3,
pub rvel: DVec3,
pub tim: f64,
pub ping: f64,
pub last_pos_update: Option<Instant>,
}
impl Car {
pub fn new(car_json: String) -> Self {
Self {
car_json: car_json,
..Default::default()
}
}
pub fn raw_position(&self) -> DVec3 {
self.pos
}
pub fn raw_rotation(&self) -> DQuat {
self.rot
}
pub fn position(&self) -> DVec3 {
self.pos + self.vel * self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0)
}
pub fn rotation(&self) -> DQuat {
let t = self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
self.rot + DQuat::from_euler(glam::EulerRot::YXZ, self.rvel.x * t, self.rvel.y * t, self.rvel.z * t)
}
}
-535
View File
@@ -1,535 +0,0 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::path::Path;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream,
};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
use serde::Deserialize;
use crate::fs_util;
use super::backend::*;
use super::car::*;
use super::packet::*;
lazy_static! {
pub static ref TAKEN_PLAYER_IDS: Mutex<Vec<u8>> = Mutex::new(Vec::new());
pub static ref CLIENT_MOD_PROGRESS: Mutex<HashMap<u8, isize>> = Mutex::new(HashMap::new());
}
// TODO: Return a proper error?
async fn claim_id() -> Result<u8, ()> {
let mut lock = TAKEN_PLAYER_IDS.lock().await;
for index in 0..=255 {
if !lock.contains(&index) {
lock.push(index);
return Ok(index);
}
}
// requires more then 255 players on the server to error
Err(())
}
async fn free_id(id: u8) {
let mut lock = TAKEN_PLAYER_IDS.lock().await;
*lock = lock.drain(..).filter(|i| *i != id).collect::<Vec<u8>>();
}
#[derive(PartialEq)]
pub enum ClientState {
None,
Connecting,
SyncingResources,
Syncing,
Disconnect,
}
#[derive(Deserialize, Debug, PartialEq, Clone)]
pub struct UserData {
pub uid: String,
pub createdAt: String,
pub guest: bool,
pub roles: String,
pub username: String,
}
pub struct Client {
pub id: u8,
pub udp_addr: Option<SocketAddr>,
socket: OwnedReadHalf,
write_half: Arc<Mutex<OwnedWriteHalf>>,
write_runtime: JoinHandle<()>,
write_runtime_sender: Sender<Packet>,
pub state: ClientState,
pub info: Option<UserData>,
pub cars: Vec<(u8, Car)>,
}
impl Drop for Client {
fn drop(&mut self) {
tokio::spawn(free_id(self.id));
self.write_runtime.abort();
}
}
impl Client {
pub async fn new(socket: TcpStream) -> Self {
let id = match claim_id().await {
Ok(v) => v,
Err(_) => panic!("CRITICAL: Saturated Player ID's"),
};
trace!("Client with ID #{} created!", id);
let (read_half, write_half) = socket.into_split();
let (tx, mut rx): (Sender<Packet>, Receiver<Packet>) = tokio::sync::mpsc::channel(128);
let write_half = Arc::new(Mutex::new(write_half));
let write_half_ref = Arc::clone(&write_half);
let handle: JoinHandle<()> = tokio::spawn(async move {
loop {
if let Some(packet) = rx.recv().await {
// trace!("Runtime received packet...");
let mut lock = write_half_ref.lock().await;
// trace!("Runtime sending packet!");
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
error!("{:?}", e);
};
// trace!("Runtime sent packet!");
drop(lock);
}
}
});
Self {
id: id,
udp_addr: None,
socket: read_half,
write_half: write_half,
write_runtime: handle,
write_runtime_sender: tx,
state: ClientState::Connecting,
info: None,
cars: Vec::new(),
}
}
pub async fn authenticate(&mut self, config: &super::Config) -> anyhow::Result<bool> {
debug!("Authenticating client {}...", self.id);
// TODO: Check client version
trace!("Client version packet");
self.socket.readable().await?;
let packet = self.read_packet_waiting().await?;
debug!("{:?}", packet);
self.write_packet(Packet::Raw(RawPacket::from_code('S')))
.await?;
self.socket.readable().await?;
if let Some(packet) = self.read_packet_waiting().await? {
debug!("packet: {:?}", packet);
if packet.data.len() > 50 {
self.kick("Player key too big!").await;
return Err(ClientError::AuthenticateError.into());
}
let mut json = HashMap::new();
let key = packet.data_as_string();
debug!("[AUTH] key: {}", key);
json.insert("key".to_string(), key);
let user_data: UserData =
authentication_request("pkToUser", json)
.await
.map_err(|e| {
error!("[AUTH] {:?}", e);
e
})?;
debug!("user_data: {:?}", user_data);
self.info = Some(user_data);
// self.write_packet(Packet::Raw(RawPacket::from_code('S')))
// .await?;
} else {
self.kick(
"Client never sent public key! If this error persists, try restarting your game.",
)
.await;
}
self.write_packet(Packet::Raw(RawPacket::from_str(&format!("P{}", self.id))))
.await?;
self.state = ClientState::SyncingResources;
debug!(
"Authentication of client {} succesfully completed! Syncing now...",
self.id
);
self.sync(config).await?;
Ok(true)
}
// TODO: https://github.com/BeamMP/BeamMP-Server/blob/master/src/TNetwork.cpp#L619
pub async fn sync(&mut self, config: &super::Config) -> anyhow::Result<()> {
'syncing: while self.state == ClientState::SyncingResources {
self.socket.readable().await?;
if let Some(packet) = self.read_packet().await? {
if (packet.data.len() == 4 && packet.data == [68, 111, 110, 101]) || packet.data.len() == 0 {
{
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
lock.insert(self.id, -1);
}
break 'syncing;
}
match packet.data[0] as char {
'S' if packet.data.len() > 1 => match packet.data[1] as char {
'R' => {
let file_packet = if config.mods.len() == 0 {
RawPacket::from_code('-')
} else {
let mut file_data = String::new();
// TODO: Collapse these 2 loops into 1
for (name, _size) in &config.mods {
let mut mod_name = name.clone();
if mod_name.starts_with("/") == false {
mod_name = format!("/{mod_name}");
}
file_data.push_str(&format!("{mod_name};"));
}
for (_name, size) in &config.mods {
file_data.push_str(&format!("{size};"));
}
RawPacket::from_str(&file_data)
};
// let file_packet = RawPacket::from_code('-');
self.write_packet(Packet::Raw(file_packet))
.await?;
}
_ => error!("Unknown packet! {:?}", packet),
}
'f' => {
// Handle file download
let mut mod_name = packet.data_as_string().clone();
mod_name.remove(0); // Remove f
debug!("Client is requesting file {}", mod_name);
let client_resources = config.general.get_client_resource_folder()?;
let mod_path = fs_util::join_path_secure(Path::new(&client_resources), Path::new(&mod_name))?;
if !mod_path.exists() || !mod_path.is_file() {
error!("Client requested mod which doesn't exist: {:?}. Disconnecting", mod_path);
self.kick("Invalid mod request").await;
return Ok(()) // client requested mod that doesnt exists within "Resources/Client/*"
}
self.write_packet(Packet::Raw(RawPacket::from_str("AG"))).await?;
let mut mod_id = 0;
for (i, (bmod_name, _bmod_size)) in config.mods.iter().enumerate() {
if bmod_name == &mod_name {
mod_id = i;
}
}
// Send the first half of the file over this socket and the other over the DSocket
let file_data = std::fs::read(mod_path)?;
{
let mut lock = self.write_half.lock().await;
lock.writable().await?;
trace!("Sending packets!");
if let Err(e) = lock.write(&file_data[..(file_data.len()/2)]).await {
error!("{:?}", e);
}
trace!("Packets sent!");
drop(lock);
}
{
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
lock.insert(self.id, mod_id as isize);
}
}
_ => error!("Unknown packet! {:?}", packet),
}
}
}
self.state = ClientState::None;
trace!("Done syncing! Sending map name...");
self.write_packet(Packet::Raw(RawPacket::from_str(&format!(
"M{}",
config.general.map
))))
.await?;
trace!("Map name sent!");
Ok(())
}
/// This function should never block. It should simply check if there's a
/// packet, and then and only then should it read it. If this were to block, the server
/// would come to a halt until this function unblocks.
pub async fn process(&mut self) -> anyhow::Result<Option<RawPacket>> {
if let Some(packet) = self.read_packet().await? {
return Ok(Some(packet));
}
Ok(None)
}
pub async fn process_blocking(&mut self) -> anyhow::Result<Option<RawPacket>> {
if let Some(packet) = self.read_packet_waiting().await? {
return Ok(Some(packet));
}
Ok(None)
}
pub fn disconnect(&mut self) {
self.state = ClientState::Disconnect;
}
pub async fn kick(&mut self, msg: &str) {
// let _ = self.socket.writable().await;
// let _ = self.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg)))).await;
// self.disconnect();
let _ = self
.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg))))
.await;
self.disconnect();
}
pub fn get_userdata(&self) -> UserData {
self.info.as_ref().unwrap().clone()
}
// Panics when userdata is not set!
pub fn get_name(&self) -> &str {
&self.info.as_ref().unwrap().username
}
pub fn get_id(&self) -> u8 {
self.id
}
// Panics when userdata is not set!
pub fn get_roles(&self) -> &str {
&self.info.as_ref().unwrap().roles
}
pub fn register_car(&mut self, car: Car) -> u8 {
let mut free_num = 0;
for (num, _) in &self.cars {
if num == &free_num {
free_num += 1;
} else {
break;
}
}
self.cars.push((free_num, car));
free_num
}
pub fn unregister_car(&mut self, car_id: u8) {
let prev_len = self.cars.len();
self.cars.retain(|(id, _)| id != &car_id);
if prev_len == self.cars.len() {
error!(
"Failed to unregister car #{} for client #{}! Ignoring for now...",
car_id, self.id
);
}
}
pub fn get_car_mut(&mut self, mut car_id: u8) -> Option<&mut Car> {
for (num, car) in &mut self.cars {
if num == &mut car_id {
return Some(car);
}
}
None
}
async fn read_raw(&mut self, count: usize) -> anyhow::Result<Vec<u8>> {
let mut b = vec![0u8; count];
self.socket.read_exact(&mut b).await?;
Ok(b)
}
async fn read_packet_waiting(&mut self) -> anyhow::Result<Option<RawPacket>> {
let start = std::time::Instant::now();
'wait: loop {
if let Some(packet) = self.read_packet().await? {
return Ok(Some(packet));
}
if start.elapsed().as_secs() >= 5 {
break 'wait;
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
Err(ClientError::ConnectionTimeout.into())
}
/// Must be non-blocking
async fn read_packet(&mut self) -> anyhow::Result<Option<RawPacket>> {
let mut header = [0u8; 4];
match self.socket.try_read(&mut header) {
Ok(0) => {
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
self.disconnect();
return Ok(None);
}
Ok(_n) => {}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
return Ok(None);
}
Err(e) => return Err(e.into()),
}
let expected_size = u32::from_le_bytes(header) as usize;
let mut data = Vec::new();
let mut tmp_data = vec![0u8; expected_size];
let mut data_size = 0;
while data_size < expected_size {
match self.socket.try_read(&mut tmp_data) {
Ok(0) => {
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
self.disconnect();
return Ok(None);
}
Ok(n) => {
data_size += n;
data.extend_from_slice(&tmp_data[..n]);
},
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// debug!("Packet appears to be ready, yet can't be read yet!");
// self.socket.read(&mut data).await?;
return Ok(None);
}
Err(e) => return Err(e.into()),
}
}
Ok(Some(RawPacket {
header: data_size as u32,
data: data[..data_size].to_vec(),
}))
}
/// Blocking write
pub async fn write_packet(&mut self, packet: Packet) -> anyhow::Result<()> {
let mut lock = self.write_half.lock().await;
lock.writable().await?;
trace!("Sending packet!");
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
error!("{:?}", e);
}
trace!("Packet sent!");
drop(lock);
Ok(())
}
pub async fn queue_packet(&self, packet: Packet) {
// TODO: If packet gets lost, put it back at the front of the queue?
let _ = self.write_runtime_sender.send(packet).await;
}
pub async fn trigger_client_event<S: Into<String>, D: Into<String>>(&self, event_name: S, data: D) {
let event_name = event_name.into();
let data = data.into();
debug!("Calling client event '{}' with data '{}'", event_name, data);
let packet_data = format!("E:{}:{}", event_name, data);
self.queue_packet(Packet::Raw(RawPacket::from_str(&packet_data))).await;
}
}
#[derive(Debug)]
pub enum ClientError {
AuthenticateError,
ConnectionTimeout,
IsDownloader,
}
impl std::fmt::Display for ClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{:?}", self)?;
Ok(())
}
}
impl std::error::Error for ClientError {}
#[async_trait]
trait Writable {
async fn writable(&self) -> std::io::Result<()>;
}
#[async_trait]
impl Writable for TcpStream {
async fn writable(&self) -> std::io::Result<()> {
self.writable().await
}
}
#[async_trait]
impl Writable for OwnedWriteHalf {
async fn writable(&self) -> std::io::Result<()> {
self.writable().await
}
}
async fn tcp_write<W: AsyncWriteExt + Writable + std::marker::Unpin>(
w: &mut W,
mut packet: Packet,
) -> anyhow::Result<()> {
let compressed = match packet.get_code() {
Some('O') => true,
Some('T') => true,
_ => packet.get_data().len() > 400,
};
if compressed {
let mut compressed: Vec<u8> = Vec::with_capacity(100_000);
let mut compressor = flate2::Compress::new(flate2::Compression::best(), true);
compressor.compress_vec(
packet.get_data(),
&mut compressed,
flate2::FlushCompress::Sync,
)?;
let mut new_data = "ABG:".as_bytes()[..4].to_vec();
new_data.append(&mut compressed);
packet.set_header(new_data.len() as u32);
packet.set_data(new_data);
}
tcp_write_raw(w, packet).await?;
Ok(())
}
async fn tcp_write_raw<W: AsyncWriteExt + Writable + std::marker::Unpin>(
w: &mut W,
mut packet: Packet,
) -> anyhow::Result<()> {
let mut raw_data: Vec<u8> = packet.get_header().to_le_bytes().to_vec();
raw_data.extend_from_slice(packet.get_data());
w.writable().await?;
w.write(&raw_data).await?;
Ok(())
}
async fn tcp_send_file<W: AsyncWriteExt + Writable + std::marker::Unpin>(
w: &mut W,
file_name: String,
) -> anyhow::Result<()> {
debug!("Sending file '{}'", file_name);
tcp_write(w, Packet::Raw(RawPacket::from_str("KYou have not downloaded the mod manually!"))).await?;
Ok(())
}
-14
View File
@@ -1,14 +0,0 @@
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream,
};
pub async fn handle_http_get(socket: TcpStream) {
let (read_half, write_half) = socket.into_split();
todo!()
}
async fn read_get_request(socket: &mut OwnedReadHalf) {
todo!()
}

Some files were not shown because too many files have changed in this diff Show More