Compare commits

...

480 Commits

Author SHA1 Message Date
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 fef069c9df72a0473c6eed6b767199633327e4db.
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
72 changed files with 4539 additions and 1456 deletions

5
.clang-format Normal file
View File

@@ -0,0 +1,5 @@
---
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
...

41
.github/workflows/cmake-linux.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: CMake Linux Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
linux-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev
sudo add-apt-repository ppa:mhier/libboost-latest
sudo apt-get install -y libboost1.70-dev libboost1.70
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Archive artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server-linux
path: ${{github.workspace}}/build-linux/BeamMP-Server

45
.github/workflows/cmake-windows.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: CMake Windows Build
on: [push]
env:
BUILD_TYPE: Release
jobs:
windows-build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@main
id: runvcpkg
with:
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Archive artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Server.exe
path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe

114
.github/workflows/release-build.yml vendored Normal file
View File

@@ -0,0 +1,114 @@
name: Release Create & Build
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
env:
BUILD_TYPE: Release
jobs:
create-release:
runs-on: ubuntu-latest
name: Create Release
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: false
body: |
Files included in this release:
- `BeamMP-Server.exe` is the windows build
- `BeamMP-Server-linux` is a ubuntu build, so you need the dependencies listed in README.md to run it. For any other distros please build from source as described in README.md.
upload-release-files-linux:
name: Upload Linux Release Files
runs-on: ubuntu-latest
needs: create-release
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libz-dev rapidjson-dev liblua5.3 libssl-dev libwebsocketpp-dev
sudo add-apt-repository ppa:mhier/libboost-latest
sudo apt-get install -y libboost1.70-dev libboost1.70
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_CXX_COMPILER=g++-10
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-linux/BeamMP-Server
asset_name: BeamMP-Server-linux
asset_content_type: application/x-elf
upload-release-files-windows:
name: Upload Windows Release Files
runs-on: windows-latest
needs: create-release
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@main
id: runvcpkg
with:
vcpkgArguments: 'lua zlib rapidjson boost-beast boost-asio openssl websocketpp'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '8dddc6c899ce6fdbeab38b525a31e7f23cb2d5bb'
vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-windows
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-windows
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake' -DVCPKG_TARGET_TRIPLET=x64-windows-static
- name: Build
working-directory: ${{github.workspace}}/build-windows
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Server.exe
asset_name: BeamMP-Server.exe
asset_content_type: application/vnd.microsoft.portable-executable

33
.gitignore vendored
View File

@@ -1,3 +1,7 @@
.idea/
*.toml
boost_*
Resources
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
@@ -16,6 +20,13 @@
# Mono auto generated files
mono_crash.*
#VS Files
out/
#Clion Files
cmake-build-debug/
cmake-build-release/
.idea/
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@@ -35,7 +46,6 @@ bld/
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
@@ -445,3 +455,24 @@ out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-540e487569703b71
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

15
.gitmodules vendored Normal file
View File

@@ -0,0 +1,15 @@
[submodule "include/commandline"]
path = include/commandline
url = https://github.com/lionkor/commandline
[submodule "socket.io-client-cpp"]
path = socket.io-client-cpp
url = https://github.com/socketio/socket.io-client-cpp
[submodule "asio"]
path = asio
url = https://github.com/chriskohlhoff/asio
[submodule "rapidjson"]
path = rapidjson
url = https://github.com/Tencent/rapidjson
[submodule "include/tomlplusplus"]
path = include/tomlplusplus
url = https://github.com/marzer/tomlplusplus

2
.idea/.gitignore generated vendored
View File

@@ -1,2 +0,0 @@
# Default ignored files
/workspace.xml

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

7
.idea/misc.xml generated
View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/BeamNG-MP-Server.iml" filepath="$PROJECT_DIR$/.idea/BeamNG-MP-Server.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -1,11 +1,68 @@
cmake_minimum_required(VERSION 3.15)
project(BeamNG-MP-Server)
set(CMAKE_CXX_STANDARD 14)
add_executable(cmake-main src/main.cpp src/network.cpp src/logger.cpp src/config.cpp)
ADD_LIBRARY(
enet STATIC
enet.lib
)
set_target_properties(enet PROPERTIES LINKER_LANGUAGE CXX)
cmake_minimum_required(VERSION 3.0)
project(Server)
if (WIN32)
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
include_directories(${VcpkgRoot}/include)
link_directories(${VcpkgRoot}/lib)
elseif (UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -s -fno-builtin")
if (SANITIZE)
message(STATUS "sanitize is ON")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined,thread")
endif (SANITIZE)
endif ()
# this has to happen before -DDEBUG since it wont compile properly with -DDEBUG
include_directories("asio/asio/include")
include_directories("rapidjson/include")
include_directories("websocketpp")
add_subdirectory("socket.io-client-cpp")
add_subdirectory("include/commandline")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
find_package(Boost REQUIRED COMPONENTS system thread)
add_executable(BeamMP-Server
src/main.cpp
include/TConsole.h src/TConsole.cpp
include/TServer.h src/TServer.cpp
include/Compat.h src/Compat.cpp
include/Common.h src/Common.cpp
include/Client.h src/Client.cpp
include/VehicleData.h src/VehicleData.cpp
include/TConfig.h src/TConfig.cpp
include/TLuaEngine.h src/TLuaEngine.cpp
include/TLuaFile.h src/TLuaFile.cpp
include/TResourceManager.h src/TResourceManager.cpp
include/THeartbeatThread.h src/THeartbeatThread.cpp
include/Http.h src/Http.cpp
#include/SocketIO.h src/SocketIO.cpp
include/TPPSMonitor.h src/TPPSMonitor.cpp
include/TNetwork.h src/TNetwork.cpp)
target_include_directories(BeamMP-Server PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/commandline")
find_package(Lua REQUIRED)
target_include_directories(BeamMP-Server PUBLIC ${Boost_INCLUDE_DIRS} ${LUA_INCLUDE_DIR} "socket.io-client-cpp/src" "include/tomlplusplus")
find_package(OpenSSL REQUIRED)
if (UNIX)
target_link_libraries(BeamMP-Server z pthread stdc++fs ${LUA_LIBRARIES} crypto ${OPENSSL_LIBRARIES} commandline sioclient_tls)
elseif (WIN32)
include(FindLua)
find_package(ZLIB REQUIRED)
find_package(RapidJSON CONFIG REQUIRED)
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
target_link_libraries(BeamMP-Server PRIVATE ws2_32 ZLIB::ZLIB ${LUA_LIBRARIES} ${OPENSSL_LIBRARIES} commandline sioclient_tls)
endif ()

2
LICENSE Normal file
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.

View File

@@ -1 +1,93 @@
# BeamNG-MP-Server
# BeamMP-Server
[![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 throug which all clients communicate. You can write lua mods for the server, detailed instructions on the [BeamMP Wiki](https://wiki.beammp.com).
## Minimum Requirements
These values are guesstimated and are subject to change with each release.
* RAM: 50+ MiB usable (not counting OS overhead)
* CPU: Any Hz, 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" label or with nobody assigned, any [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer) cards in the "To-Do" column.
To contribute, look at the active [issues](https://github.com/BeamMP/BeamMP-Server/issues) and at the [trello](https://trello.com/b/Kw75j3zZ/beamngdrive-multiplayer). Any issues that have the "help wanted" label or don't have anyone assigned and any trello cards that aren't assigned or in the "In-Progress" section are good tasks to take on. You can either contribute by programming or by testing and adding more info and ideas.
Fork this repository, make a new branch for your feature, implement your feature or fix, and then create a pull-request here. Even incomplete features and fixes can be pull-requested.
If you need support with understanding the codebase, please write us in the discord. You'll need to be proficient in modern C++.
## About Building from Source
We only allow building unmodified (original) source code for public use. `master` is considered **unstable** and we will not provide technical support if such a build doesn't work, so always build from a tag. You can checkout a tag with `git checkout tags/TAGNAME`, where `TAGNAME` is the tag, for example `v1.20`.
## Supported Operating Systems
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we usually only distribute windows binaries and sometimes linux. For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support any big-endian architectures.
Recommended compilers: MSVC, GCC, CLANG.
You can find precompiled binaries under [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
## Build Instructions
**__Do not compile from `master`. Always build from a release tag, i.e. `tags/v2.0`!__**
Currently only linux and windows are supported (generally). See [Releases](https://github.com/BeamMP/BeamMP-Server/releases/) for official binary releases. On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
### Prerequisites
#### Windows
Please use the prepackaged binaries in [Releases](https://github.com/BeamMP/BeamMP-Server/releases/).
Dependencies for windows can be installed with `vcpkg`, in which case the current dependencies are the `x64-windows-static` versions of `lua`, `zlib`, `rapidjson`, `boost-beast`, `boost-asio` and `openssl`.
#### Linux / \*nix
These package names are in the debian / ubuntu style. Feel free to PR your own guide for a different distro.
- `git`
- `make`
- `cmake`
- `g++`
Must support ISO C++17. If your distro's `g++` doesn't support C++17, chances are that it has a `g++-8` or `g++-10` package that does. If this is the case. you just need to run CMake with `-DCMAKE_CXX_COMPILER=g++-10` (replace `g++-10` with your compiler's name).
- `liblua5.3-dev`
Any 5.x version should work, but 5.3 is what we officially use. Any other version might break in the future.
You can also use any version of `libluajit`, but the same applies regarding the version.
- `libz-dev`
- `rapidjson-dev`
- `libopenssl-dev` or `libssl-dev`
**If** you're building it from source, you'll need `libboost1.70-all-dev` or `libboost1.71-all-dev` or higher as well.
### How to build
On windows. use git-bash for these commands. On linux, these should work in your shell.
1. Make sure you have all [prerequisites](#prerequisites) installed
2. Clone the repository in a location of your choice with `git clone --recursive https://github.com/BeamMP/BeamMP-Server`. Now change into the cloned directory by running `cd BeamMP-Server`.
3. Checkout the branch of the release you want to compile (`master` is often unstable), for example `git checkout tags/v1.20` for version 1.20. You can find the latest version [here](https://github.com/BeamMP/BeamMP-Server/tags).
4. Run `cmake .` (with `.`)
5. Run `make`
6. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server` (`.\BeamMP-Server.exe` for windows). Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
## 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.

1
asio Submodule

Submodule asio added at 230c0d2ae0

BIN
enet.lib

Binary file not shown.

94
include/Client.h Normal file
View File

@@ -0,0 +1,94 @@
#pragma once
#include <chrono>
#include <memory>
#include <queue>
#include <string>
#include <unordered_set>
#include "Common.h"
#include "Compat.h"
#include "VehicleData.h"
class TServer;
class TClient final {
public:
using TSetOfVehicleData = std::vector<TVehicleData>;
struct TVehicleDataLockPair {
TSetOfVehicleData* VehicleData;
std::unique_lock<std::mutex> Lock;
};
explicit TClient(TServer& Server);
TClient(const TClient&) = delete;
TClient& operator=(const TClient&) = delete;
void AddNewCar(int Ident, const std::string& Data);
void SetCarData(int Ident, const std::string& Data);
TVehicleDataLockPair GetAllCars();
void SetName(const std::string& Name) { mName = Name; }
void SetRoles(const std::string& Role) { mRole = Role; }
void AddIdentifier(const std::string& ID) { mIdentifiers.insert(ID); };
std::string GetCarData(int Ident);
void SetUDPAddr(sockaddr_in Addr) { mUDPAddress = Addr; }
void SetDownSock(SOCKET CSock) { mSocket[1] = CSock; }
void SetTCPSock(SOCKET CSock) { mSocket[0] = CSock; }
void SetStatus(int Status) { mStatus = Status; }
// locks
void DeleteCar(int Ident);
[[nodiscard]] std::set<std::string> GetIdentifiers() const { return mIdentifiers; }
[[nodiscard]] sockaddr_in GetUDPAddr() const { return mUDPAddress; }
[[nodiscard]] SOCKET GetDownSock() const { return mSocket[1]; }
[[nodiscard]] SOCKET GetTCPSock() const { return mSocket[0]; }
[[nodiscard]] std::string GetRoles() const { return mRole; }
[[nodiscard]] std::string GetName() const { return mName; }
void SetUnicycleID(int ID) { mUnicycleID = ID; }
void SetID(int ID) { mID = ID; }
[[nodiscard]] int GetOpenCarID() const;
[[nodiscard]] int GetCarCount() const;
void ClearCars();
[[nodiscard]] int GetStatus() const { return mStatus; }
[[nodiscard]] int GetID() const { return mID; }
[[nodiscard]] int GetUnicycleID() const { return mUnicycleID; }
[[nodiscard]] bool IsConnected() const { return mIsConnected; }
[[nodiscard]] bool IsSynced() const { return mIsSynced; }
[[nodiscard]] bool IsSyncing() const { return mIsSyncing; }
[[nodiscard]] bool IsGuest() const { return mIsGuest; }
void SetIsGuest(bool NewIsGuest) { mIsGuest = NewIsGuest; }
void SetIsSynced(bool NewIsSynced) { mIsSynced = NewIsSynced; }
void SetIsSyncing(bool NewIsSyncing) { mIsSyncing = NewIsSyncing; }
void EnqueuePacket(const std::string& Packet);
[[nodiscard]] std::queue<std::string>& MissedPacketQueue() { return mPacketsSync; }
[[nodiscard]] const std::queue<std::string>& MissedPacketQueue() const { return mPacketsSync; }
[[nodiscard]] size_t MissedPacketQueueSize() const { return mPacketsSync.size(); }
[[nodiscard]] std::mutex& MissedPacketQueueMutex() const { return mMissedPacketsMutex; }
void SetIsConnected(bool NewIsConnected) { mIsConnected = NewIsConnected; }
[[nodiscard]] TServer& Server() const;
void UpdatePingTime();
int SecondsSinceLastPing();
private:
void InsertVehicle(int ID, const std::string& Data);
TServer& mServer;
bool mIsConnected = false;
bool mIsSynced = false;
bool mIsSyncing = false;
mutable std::mutex mMissedPacketsMutex;
std::queue<std::string> mPacketsSync;
std::set<std::string> mIdentifiers;
bool mIsGuest = false;
std::mutex mVehicleDataMutex;
TSetOfVehicleData mVehicleData;
std::string mName = "Unknown Client";
SOCKET mSocket[2] { SOCKET(0), SOCKET(0) };
sockaddr_in mUDPAddress {}; // is this initialization OK? yes it is
int mUnicycleID = -1;
std::string mRole;
std::string mDID;
int mStatus = 0;
int mID = -1;
std::chrono::time_point<std::chrono::high_resolution_clock> mLastPingTime;
};

123
include/Common.h Normal file
View File

@@ -0,0 +1,123 @@
#pragma once
#include <atomic>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include "TConsole.h"
// 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 {
TSettings() noexcept
: ServerName("BeamMP Server")
, ServerDesc("BeamMP Default Description")
, Resource("Resources")
, MapName("/levels/gridmap_v2/info.json")
, MaxPlayers(10)
, Private(false)
, MaxCars(1)
, DebugModeEnabled(false)
, Port(30814) { }
std::string ServerName;
std::string ServerDesc;
std::string Resource;
std::string MapName;
std::string Key;
int MaxPlayers;
bool Private;
int MaxCars;
bool DebugModeEnabled;
int Port;
std::string CustomIP;
[[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 ServerVersion() { return "2.1.4"; }
static std::string ClientVersion() { return "2.0"; }
static std::string PPS() { return mPPS; }
static void SetPPS(std::string NewPPS) { mPPS = NewPPS; }
static inline TSettings Settings {};
static std::string GetBackendUrlForAuth() { return "auth.beammp.com"; }
static std::string GetBackendHostname() { return "backend.beammp.com"; }
static std::string GetBackendUrlForSocketIO() { return "https://backend.beammp.com"; }
private:
static inline std::string mPPS;
static std::unique_ptr<TConsole> mConsole;
static inline std::mutex mShutdownHandlersMutex {};
static inline std::deque<TShutdownHandler> mShutdownHandlers {};
};
std::string ThreadName();
void RegisterThread(const std::string str);
#define RegisterThreadAuto() RegisterThread(__func__)
#define KB 1024
#define MB (KB * 1024)
#define _file_basename std::filesystem::path(__FILE__).filename().string()
#define _line std::to_string(__LINE__)
#define _in_lambda (std::string(__func__) == "operator()")
// 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
#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
#else // !defined(DEBUG)
#define _this_location (ThreadName())
#endif // defined(DEBUG)
#define warn(x) Application::Console().Write(_this_location + std::string("[WARN] ") + (x))
#define info(x) Application::Console().Write(_this_location + std::string("[INFO] ") + (x))
#define error(x) Application::Console().Write(_this_location + std::string("[ERROR] ") + (x))
#define luaprint(x) Application::Console().Write(_this_location + std::string("[LUA] ") + (x))
#define debug(x) \
do { \
if (Application::Settings.DebugModeEnabled) { \
Application::Console().Write(_this_location + std::string("[DEBUG] ") + (x)); \
} \
} while (false)
#define Biggest 30000
std::string Comp(std::string Data);
std::string DeComp(std::string Compressed);

36
include/Compat.h Normal file
View File

@@ -0,0 +1,36 @@
#pragma once
// ======================= UNIX ========================
#ifdef __unix
#include <arpa/inet.h>
#include <sys/socket.h>
#include <termios.h>
#include <unistd.h>
using SOCKET = int;
using DWORD = unsigned long;
using PDWORD = unsigned long*;
using LPDWORD = unsigned long*;
char _getch();
inline void CloseSocketProper(int socket) {
shutdown(socket, SHUT_RDWR);
close(socket);
}
#endif // unix
// ======================= WIN32 =======================
#ifdef WIN32
#include <conio.h>
#include <winsock2.h>
inline void CloseSocketProper(SOCKET socket) {
shutdown(socket, SD_BOTH);
closesocket(socket);
}
#endif // WIN32
// ======================= OTHER =======================
#if !defined(WIN32) && !defined(__unix)
#error "OS not supported"
#endif

68
include/CustomAssert.h Normal file
View File

@@ -0,0 +1,68 @@
// 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";
#if 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 Assert(cond) _assert(__FILE__, __func__, __LINE__, #cond, (cond))
#define AssertNotReachable() _assert(__FILE__, __func__, __LINE__, "reached unreachable code", false)
#else
// In release build, these macros turn into NOPs. The compiler will optimize these out.
#define Assert(x) \
do { \
} while (false)
#define AssertNotReachable() \
do { \
} while (false)
#endif // DEBUG

9
include/Http.h Normal file
View File

@@ -0,0 +1,9 @@
#pragma once
#include <string>
#include <unordered_map>
namespace Http {
std::string GET(const std::string& host, int port, const std::string& target);
std::string POST(const std::string& host, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, bool json);
}

19
include/IThreaded.h Normal file
View File

@@ -0,0 +1,19 @@
#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 void Start() final {
mThread = std::thread([this] { (*this)(); });
}
virtual void operator()() = 0;
protected:
std::thread mThread;
};

9
include/Json.h Normal file
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"

20
include/RWMutex.h Normal file
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>;

69
include/SocketIO.h Normal file
View File

@@ -0,0 +1,69 @@
#pragma once
#include <atomic>
#include <deque>
#include <mutex>
#include <sio_client.h>
#include <thread>
#include <memory>
/*
* We send relevant server events over socket.io to the backend.
*
* We send all events to `backend.beammp.com`, to the room `/key`
* where `key` is the currently active auth-key.
*/
enum class SocketIOEvent {
ConsoleOut,
CPUUsage,
MemoryUsage,
NetworkUsage,
PlayerList,
};
enum class SocketIORoom {
None,
Stats,
Player,
Info,
Console,
};
class SocketIO final {
private:
struct Event;
public:
enum class EventType {
};
// Singleton pattern
static SocketIO& Get();
void Emit(SocketIOEvent Event, const std::string& Data);
~SocketIO();
void SetAuthenticated(bool auth) { mAuthenticated = auth; }
private:
SocketIO() noexcept;
void ThreadMain();
struct Event {
std::string Name;
std::string Data;
};
bool mAuthenticated { false };
sio::client mClient;
std::thread mThread;
std::atomic_bool mCloseThread { false };
std::mutex mQueueMutex;
std::deque<Event> mQueue;
friend std::unique_ptr<SocketIO> std::make_unique<SocketIO>();
};

21
include/TConfig.h Normal file
View File

@@ -0,0 +1,21 @@
#pragma once
#include "Common.h"
#include <atomic>
class TConfig {
public:
explicit TConfig();
bool Failed() const { return mFailed; }
private:
void CreateConfigFile(std::string_view name);
void ParseFromFile(std::string_view name);
void PrintDebug();
void ParseOldFormat();
bool mFailed { false };
};

19
include/TConsole.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include "commandline/commandline.h"
#include "TLuaFile.h"
#include <atomic>
#include <fstream>
class TConsole {
public:
TConsole();
void Write(const std::string& str);
void WriteRaw(const std::string& str);
void InitializeLuaConsole(TLuaEngine& Engine);
private:
std::unique_ptr<TLuaFile> mLuaConsole { nullptr };
Commandline mCommandline;
};

View File

@@ -0,0 +1,21 @@
#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();
bool mShutdown = false;
TResourceManager& mResourceManager;
TServer& mServer;
};

38
include/TLuaEngine.h Normal file
View File

@@ -0,0 +1,38 @@
#pragma once
#include "Common.h"
#include "IThreaded.h"
#include "TLuaFile.h"
#include "TServer.h"
#include <lua.hpp>
#include <memory>
#include <optional>
#include <set>
class TLuaEngine : public IThreaded {
public:
explicit TLuaEngine(TServer& Server, TNetwork& Network);
using TSetOfLuaFile = std::set<std::unique_ptr<TLuaFile>>;
void operator()() override;
[[nodiscard]] const TSetOfLuaFile& LuaFiles() const { return mLuaFiles; }
[[nodiscard]] TServer& Server() { return mServer; }
[[nodiscard]] const TServer& Server() const { return mServer; }
[[nodiscard]] TNetwork& Network() { return mNetwork; }
[[nodiscard]] const TNetwork& Network() const { return mNetwork; }
std::optional<std::reference_wrapper<TLuaFile>> GetScript(lua_State* L);
private:
void FolderList(const std::string& Path, bool HotSwap);
void RegisterFiles(const std::string& Path, bool HotSwap);
bool NewFile(const std::string& Path);
TNetwork& mNetwork;
TServer& mServer;
std::string mPath;
bool mShutdown { false };
TSetOfLuaFile mLuaFiles;
};

61
include/TLuaFile.h Normal file
View File

@@ -0,0 +1,61 @@
#ifndef TLUAFILE_H
#define TLUAFILE_H
#include <any>
#include <filesystem>
#include <lua.hpp>
#include <mutex>
#include <set>
#include <string>
#include <vector>
namespace fs = std::filesystem;
struct TLuaArg {
std::vector<std::any> args;
void PushArgs(lua_State* State);
};
class TLuaEngine;
class TLuaFile {
public:
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
void UnRegisterEvent(const std::string& Event);
void SetLastWrite(fs::file_time_type time);
bool IsRegistered(const std::string& Event);
void SetPluginName(const std::string& Name);
void Execute(const std::string& Command);
void SetFileName(const std::string& Name);
fs::file_time_type GetLastWrite();
lua_State* GetState();
std::string GetOrigin();
std::mutex Lock;
void Reload();
void Init(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote);
explicit TLuaFile(TLuaEngine& Engine, bool Console = false);
~TLuaFile();
void SetStopThread(bool StopThread) { mStopThread = StopThread; }
TLuaEngine& Engine() { return mEngine; }
[[nodiscard]] std::string GetPluginName() const;
[[nodiscard]] std::string GetFileName() const;
[[nodiscard]] const lua_State* GetState() const;
[[nodiscard]] bool GetStopThread() const { return mStopThread; }
[[nodiscard]] const TLuaEngine& Engine() const { return mEngine; }
[[nodiscard]] std::string GetRegistered(const std::string& Event) const;
private:
TLuaEngine& mEngine;
std::set<std::pair<std::string, std::string>> mRegisteredEvents;
lua_State* mLuaState { nullptr };
fs::file_time_type mLastWrote;
std::string mPluginName {};
std::string mFileName {};
bool mStopThread = false;
bool mConsole = false;
void Load();
};
std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
#endif // TLUAFILE_H

49
include/TNetwork.h Normal file
View File

@@ -0,0 +1,49 @@
#pragma once
#include "Compat.h"
#include "TResourceManager.h"
#include "TServer.h"
class TNetwork {
public:
TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager);
[[nodiscard]] bool TCPSend(TClient& c, const std::string& Data, bool IsSync = false);
[[nodiscard]] bool SendLarge(TClient& c, std::string Data, bool isSync = false);
[[nodiscard]] bool Respond(TClient& c, const std::string& MSG, bool Rel, bool isSync = false);
std::shared_ptr<TClient> CreateClient(SOCKET TCPSock);
std::string TCPRcv(TClient& c);
void ClientKick(TClient& c, const std::string& R);
[[nodiscard]] bool SyncClient(const std::weak_ptr<TClient>& c);
void Identify(SOCKET TCPSock);
void Authentication(SOCKET TCPSock);
[[nodiscard]] bool CheckBytes(TClient& c, int32_t BytesRcv);
void SyncResources(TClient& c);
[[nodiscard]] bool UDPSend(TClient& Client, std::string Data) const;
void SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel);
void UpdatePlayer(TClient& Client);
private:
void UDPServerMain();
void TCPServerMain();
TServer& mServer;
TPPSMonitor& mPPSMonitor;
SOCKET mUDPSock {};
bool mShutdown { false };
TResourceManager& mResourceManager;
std::thread mUDPThread;
std::thread mTCPThread;
std::string UDPRcvFromClient(sockaddr_in& client) const;
void HandleDownload(SOCKET TCPSock);
void OnConnect(const std::weak_ptr<TClient>& c);
void TCPClient(const std::weak_ptr<TClient>& c);
void Looper(const std::weak_ptr<TClient>& c);
int OpenID();
void OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked);
void Parse(TClient& c, const std::string& Packet);
void SendFile(TClient& c, const std::string& Name);
static bool TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size);
static void SplitLoad(TClient& c, size_t Sent, size_t Size, bool D, const std::string& Name);
};

27
include/TPPSMonitor.h Normal file
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);
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 };
bool mShutdown { false };
int mInternalPPS { 0 };
};

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;
};

37
include/TServer.h Normal file
View File

@@ -0,0 +1,37 @@
#pragma once
#include "IThreaded.h"
#include "RWMutex.h"
#include <functional>
#include <memory>
#include <mutex>
#include <unordered_set>
class TClient;
class TNetwork;
class TPPSMonitor;
class TServer final {
public:
using TClientSet = std::unordered_set<std::shared_ptr<TClient>>;
TServer(int argc, char** argv);
void InsertClient(const std::shared_ptr<TClient>& Ptr);
std::weak_ptr<TClient> InsertNewClient();
void RemoveClient(const std::weak_ptr<TClient>&);
// in Fn, return true to continue, return false to break
void ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn);
size_t ClientCount() const;
static void GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network);
static void HandleEvent(TClient& c, const std::string& Data);
RWMutex& GetClientMutex() const { return mClientsMutex; }
private:
TClientSet mClients;
mutable RWMutex mClientsMutex;
static void ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network);
static bool ShouldSpawn(TClient& c, const std::string& CarJson, int ID);
static bool IsUnicycle(TClient& c, const std::string& CarJson);
static void Apply(TClient& c, int VID, const std::string& pckt);
};

35
include/VehicleData.h Normal file
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();
}
};
}

1
include/commandline Submodule

Submodule include/commandline added at c34703df11

1
include/tomlplusplus Submodule

Submodule include/tomlplusplus added at bc6891e1fb

Binary file not shown.

Binary file not shown.

1
rapidjson Submodule

Submodule rapidjson added at 13dfc96c9c

1
socket.io-client-cpp Submodule

Submodule socket.io-client-cpp added at b196fa7537

102
src/Client.cpp Normal file
View File

@@ -0,0 +1,102 @@
#include "Client.h"
#include "CustomAssert.h"
#include <memory>
// FIXME: add debug prints
void TClient::DeleteCar(int Ident) {
std::unique_lock lock(mVehicleDataMutex);
auto iter = std::find_if(mVehicleData.begin(), mVehicleData.end(), [&](auto& elem) {
return Ident == elem.ID();
});
if (iter != mVehicleData.end()) {
mVehicleData.erase(iter);
} else {
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;
do {
found = true;
for (auto& v : mVehicleData) {
if (v.ID() == OpenID) {
OpenID++;
found = false;
}
}
} while (!found);
return OpenID;
}
void TClient::AddNewCar(int Ident, const std::string& Data) {
std::unique_lock lock(mVehicleDataMutex);
mVehicleData.emplace_back(Ident, Data);
}
TClient::TVehicleDataLockPair TClient::GetAllCars() {
return { &mVehicleData, std::unique_lock(mVehicleDataMutex) };
}
std::string TClient::GetCarData(int Ident) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
return v.Data();
}
}
} // unlock
DeleteCar(Ident);
return "";
}
void TClient::SetCarData(int Ident, const std::string& Data) {
{ // lock
std::unique_lock lock(mVehicleDataMutex);
for (auto& v : mVehicleData) {
if (v.ID() == Ident) {
v.SetData(Data);
return;
}
}
} // unlock
DeleteCar(Ident);
}
int TClient::GetCarCount() const {
return int(mVehicleData.size());
}
TServer& TClient::Server() const {
return mServer;
}
void TClient::EnqueuePacket(const std::string& Packet) {
std::unique_lock Lock(mMissedPacketsMutex);
mPacketsSync.push(Packet);
}
TClient::TClient(TServer& Server)
: mServer(Server)
, mLastPingTime(std::chrono::high_resolution_clock::now()) {
}
void TClient::UpdatePingTime() {
mLastPingTime = std::chrono::high_resolution_clock::now();
//debug(GetName() + ": " + std::string("ping time updated!: ") + ((SecondsSinceLastPing() == 0) ? "OK" : "ERR"));
}
int TClient::SecondsSinceLastPing() {
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::high_resolution_clock::now() - mLastPingTime)
.count();
return int(seconds);
}

88
src/Common.cpp Normal file
View File

@@ -0,0 +1,88 @@
#include "Common.h"
#include "TConsole.h"
#include <array>
#include <iostream>
#include <map>
#include <thread>
#include <zlib.h>
std::unique_ptr<TConsole> Application::mConsole = std::make_unique<TConsole>();
void Application::RegisterShutdownHandler(const TShutdownHandler& Handler) {
std::unique_lock Lock(mShutdownHandlersMutex);
if (Handler) {
mShutdownHandlers.push_front(Handler);
}
}
void Application::GracefullyShutdown() {
info("please wait while all subsystems are shutting down...");
std::unique_lock Lock(mShutdownHandlersMutex);
for (auto& Handler : mShutdownHandlers) {
Handler();
}
}
std::string Comp(std::string Data) {
std::array<char, Biggest> C {};
// obsolete
C.fill(0);
z_stream defstream;
defstream.zalloc = Z_NULL;
defstream.zfree = Z_NULL;
defstream.opaque = Z_NULL;
defstream.avail_in = (uInt)Data.length();
defstream.next_in = (Bytef*)&Data[0];
defstream.avail_out = Biggest;
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
deflateInit(&defstream, Z_BEST_COMPRESSION);
deflate(&defstream, Z_SYNC_FLUSH);
deflate(&defstream, Z_FINISH);
deflateEnd(&defstream);
size_t TO = defstream.total_out;
std::string Ret(TO, 0);
std::copy_n(C.begin(), TO, Ret.begin());
return Ret;
}
std::string DeComp(std::string Compressed) {
std::array<char, Biggest> C {};
// not needed
C.fill(0);
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = Biggest;
infstream.next_in = (Bytef*)(&Compressed[0]);
infstream.avail_out = Biggest;
infstream.next_out = (Bytef*)(C.data());
inflateInit(&infstream);
inflate(&infstream, Z_SYNC_FLUSH);
inflate(&infstream, Z_FINISH);
inflateEnd(&infstream);
size_t TO = infstream.total_out;
std::string Ret(TO, 0);
std::copy_n(C.begin(), TO, Ret.begin());
return Ret;
}
// thread name stuff
std::map<std::thread::id, std::string> threadNameMap;
std::string ThreadName() {
if (Application::Settings.DebugModeEnabled) {
auto id = std::this_thread::get_id();
if (threadNameMap.find(id) != threadNameMap.end()) {
// found
return threadNameMap.at(id) + " ";
}
}
return "";
}
void RegisterThread(const std::string str) {
threadNameMap[std::this_thread::get_id()] = str;
}

35
src/Compat.cpp Normal file
View File

@@ -0,0 +1,35 @@
#include "Compat.h"
#ifndef WIN32
static struct termios old, current;
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 */
}
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
char getch_(int echo) {
char ch;
initTermios(echo);
read(STDIN_FILENO, &ch, 1);
resetTermios();
return ch;
}
char _getch(void) {
return getch_(0);
}
#endif // !WIN32

145
src/Http.cpp Normal file
View File

@@ -0,0 +1,145 @@
#include "Http.h"
#include "Common.h"
#undef error
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace ssl = net::ssl; // from <boost/asio/ssl.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
std::string Http::GET(const std::string& host, int port, const std::string& target) {
// FIXME: doesn't support https
// if it causes issues, yell at me and I'll fix it asap. - Lion
try {
net::io_context io;
tcp::resolver resolver(io);
beast::tcp_stream stream(io);
auto const results = resolver.resolve(host, std::to_string(port));
stream.connect(results);
http::request<http::string_body> req { http::verb::get, target, 11 /* http 1.1 */ };
req.set(http::field::host, host);
// tell the server what we are (boost beast)
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(stream, req);
// used for reading
beast::flat_buffer buffer;
http::response<http::string_body> response;
http::read(stream, buffer, response);
std::string result(response.body());
beast::error_code ec;
stream.socket().shutdown(tcp::socket::shutdown_both, ec);
if (ec && ec != beast::errc::not_connected) {
throw beast::system_error { ec }; // goes down to `return "-1"` anyways
}
return result;
} catch (const std::exception& e) {
Application::Console().Write(e.what());
return "-1";
}
}
std::string Http::POST(const std::string& host, const std::string& target, const std::unordered_map<std::string, std::string>& fields, const std::string& body, bool json) {
try {
net::io_context io;
// The SSL context is required, and holds certificates
ssl::context ctx(ssl::context::tlsv13);
ctx.set_verify_mode(ssl::verify_none);
tcp::resolver resolver(io);
beast::ssl_stream<beast::tcp_stream> stream(io, ctx);
decltype(resolver)::results_type results;
auto try_connect_with_protocol = [&](tcp protocol) {
try {
results = resolver.resolve(protocol, host, std::to_string(443));
if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) {
boost::system::error_code ec { static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
// FIXME: we could throw and crash, if we like
// throw boost::system::system_error { ec };
//debug("POST " + host + target + " failed.");
return false;
}
beast::get_lowest_layer(stream).connect(results);
} catch (const boost::system::system_error&) {
return false;
}
return true;
};
//bool ok = try_connect_with_protocol(tcp::v6());
//if (!ok) {
//debug("IPv6 connect failed, trying IPv4");
bool ok = try_connect_with_protocol(tcp::v4());
if (!ok) {
//error("failed to resolve or connect in POST " + host + target);
return "-1";
}
//}
stream.handshake(ssl::stream_base::client);
http::request<http::string_body> req { http::verb::post, target, 11 /* http 1.1 */ };
req.set(http::field::host, host);
if (!body.empty()) {
if (json) {
// FIXME: json is untested.
req.set(http::field::content_type, "application/json");
} else {
req.set(http::field::content_type, "application/x-www-form-urlencoded");
}
req.set(http::field::content_length, std::to_string(body.size()));
req.body() = body;
// info("body is " + body + " (" + req.body() + ")");
// info("content size is " + std::to_string(body.size()) + " (" + boost::lexical_cast<std::string>(body.size()) + ")");
}
for (const auto& pair : fields) {
// info("setting " + pair.first + " to " + pair.second);
req.set(pair.first, pair.second);
}
std::stringstream oss;
oss << req;
beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(5));
http::write(stream, req);
// used for reading
beast::flat_buffer buffer;
http::response<http::string_body> response;
http::read(stream, buffer, response);
std::stringstream result;
result << response;
beast::error_code ec;
stream.shutdown(ec);
// IGNORING ec
// info(result.str());
std::string debug_response_str;
std::getline(result, debug_response_str);
//debug("POST " + host + target + ": " + debug_response_str);
return std::string(response.body());
} catch (const std::exception& e) {
Application::Console().Write(e.what());
return "-1";
}
}

98
src/SocketIO.cpp Normal file
View File

@@ -0,0 +1,98 @@
#include "SocketIO.h"
#include "Common.h"
#include <iostream>
//TODO Default disabled with config option
static std::unique_ptr<SocketIO> SocketIOInstance = std::make_unique<SocketIO>();
SocketIO& SocketIO::Get() {
return *SocketIOInstance;
}
SocketIO::SocketIO() noexcept
: mThread([this] { ThreadMain(); }) {
mClient.socket()->on("network", [&](sio::event&e) {
if(e.get_message()->get_string() == "Welcome"){
info("SocketIO Authenticated!");
mAuthenticated = true;
}
});
mClient.socket()->on("welcome", [&](sio::event&) {
info("Got welcome from backend! Authenticating SocketIO...");
mClient.socket()->emit("onInitConnection", Application::Settings.Key);
});
mClient.set_logs_quiet();
mClient.set_reconnect_delay(10000);
mClient.connect(Application::GetBackendUrlForSocketIO());
}
SocketIO::~SocketIO() {
mCloseThread.store(true);
mThread.join();
}
static constexpr auto EventNameFromEnum(SocketIOEvent Event) {
switch (Event) {
case SocketIOEvent::CPUUsage:
return "cpu usage";
case SocketIOEvent::MemoryUsage:
return "memory usage";
case SocketIOEvent::ConsoleOut:
return "console out";
case SocketIOEvent::NetworkUsage:
return "network usage";
case SocketIOEvent::PlayerList:
return "player list";
default:
error("unreachable code reached (developer error)");
abort();
}
}
void SocketIO::Emit(SocketIOEvent Event, const std::string& Data) {
if (!mAuthenticated) {
debug("trying to emit a socket.io event when not yet authenticated");
return;
}
std::string EventName = EventNameFromEnum(Event);
debug("emitting event \"" + EventName + "\" with data: \"" + Data);
std::unique_lock Lock(mQueueMutex);
mQueue.push_back({EventName, Data });
debug("queue now has " + std::to_string(mQueue.size()) + " events");
}
void SocketIO::ThreadMain() {
while (!mCloseThread.load()) {
bool empty;
{ // queue lock scope
std::unique_lock Lock(mQueueMutex);
empty = mQueue.empty();
} // end queue lock scope
if (empty || !mClient.opened()) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
} else {
Event TheEvent;
{ // queue lock scope
std::unique_lock Lock(mQueueMutex);
TheEvent = mQueue.front();
mQueue.pop_front();
} // end queue lock scope
debug("sending \"" + TheEvent.Name + "\" event");
mClient.socket()->emit(TheEvent.Name, TheEvent.Data);
debug("sent \"" + TheEvent.Name + "\" event");
}
}
// using std::cout as this happens during static destruction and the logger might be dead already
std::cout << "closing " + std::string(__func__) << std::endl;
mClient.sync_close();
mClient.clear_con_listeners();
std::cout << "closed" << std::endl;
}

213
src/TConfig.cpp Normal file
View File

@@ -0,0 +1,213 @@
#include <toml.hpp> // header-only version of TOML++
#include "TConfig.h"
#include <fstream>
#include <iostream>
#include <istream>
#include <sstream>
static const char* ConfigFileName = static_cast<const char*>("ServerConfig.toml");
static constexpr std::string_view StrDebug = "Debug";
static constexpr std::string_view StrPrivate = "Private";
static constexpr std::string_view StrPort = "Port";
static constexpr std::string_view StrMaxCars = "MaxCars";
static constexpr std::string_view StrMaxPlayers = "MaxPlayers";
static constexpr std::string_view StrMap = "Map";
static constexpr std::string_view StrName = "Name";
static constexpr std::string_view StrDescription = "Description";
static constexpr std::string_view StrResourceFolder = "ResourceFolder";
static constexpr std::string_view StrAuthKey = "AuthKey";
TConfig::TConfig() {
if (!fs::exists(ConfigFileName) || !fs::is_regular_file(ConfigFileName)) {
info("No config file found! Generating one...");
CreateConfigFile(ConfigFileName);
}
if (!mFailed) {
if (fs::exists("Server.cfg")) {
warn("An old \"Server.cfg\" file still exists. Please note that this is no longer used. Instead, \"" + std::string(ConfigFileName) + "\" is used. You can safely delete the \"Server.cfg\".");
}
ParseFromFile(ConfigFileName);
}
}
void TConfig::CreateConfigFile(std::string_view name) {
// 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) {
error("an error occurred and was ignored during config transfer: " + std::string(e.what()));
}
toml::table tbl { {
{ "General",
toml::table { {
{ StrDebug, Application::Settings.DebugModeEnabled },
{ StrPrivate, Application::Settings.Private },
{ StrPort, Application::Settings.Port },
{ StrMaxCars, Application::Settings.MaxCars },
{ StrMaxPlayers, Application::Settings.MaxPlayers },
{ StrMap, Application::Settings.MapName },
{ StrName, Application::Settings.ServerName },
{ StrDescription, Application::Settings.ServerDesc },
{ StrResourceFolder, Application::Settings.Resource },
{ StrAuthKey, Application::Settings.Key },
} } },
} };
std::ofstream ofs { std::string(name) };
if (ofs.good()) {
ofs << "# 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://beammp.com/k/dashboard` on the left under \"Keys\"\n"
<< '\n';
ofs << tbl << '\n';
error("There was no \"" + std::string(ConfigFileName) + "\" file (this is normal for the first time running the server), so one was generated for you. It was automatically filled with the settings from your Server.cfg, if you have one. Please open ServerConfig.toml and ensure your AuthKey and other settings are filled in and correct, then restart the server. The old Server.cfg file will no longer be used and causes a warning if it exists from now on.");
mFailed = true;
} else {
error("Couldn't create " + std::string(name) + ". Check permissions, try again, and contact support if it continues not to work.");
mFailed = true;
}
}
void TConfig::ParseFromFile(std::string_view name) {
try {
toml::table FullTable = toml::parse_file(name);
toml::table GeneralTable = *FullTable["General"].as_table();
if (auto val = GeneralTable[StrDebug].value<bool>(); val.has_value()) {
Application::Settings.DebugModeEnabled = val.value();
} else {
throw std::runtime_error(std::string(StrDebug));
}
if (auto val = GeneralTable[StrPrivate].value<bool>(); val.has_value()) {
Application::Settings.Private = val.value();
} else {
throw std::runtime_error(std::string(StrPrivate));
}
if (auto val = GeneralTable[StrPort].value<int>(); val.has_value()) {
Application::Settings.Port = val.value();
} else {
throw std::runtime_error(std::string(StrPort));
}
if (auto val = GeneralTable[StrMaxCars].value<int>(); val.has_value()) {
Application::Settings.MaxCars = val.value();
} else {
throw std::runtime_error(std::string(StrMaxCars));
}
if (auto val = GeneralTable[StrMaxPlayers].value<int>(); val.has_value()) {
Application::Settings.MaxPlayers = val.value();
} else {
throw std::runtime_error(std::string(StrMaxPlayers));
}
if (auto val = GeneralTable[StrMap].value<std::string>(); val.has_value()) {
Application::Settings.MapName = val.value();
} else {
throw std::runtime_error(std::string(StrMap));
}
if (auto val = GeneralTable[StrName].value<std::string>(); val.has_value()) {
Application::Settings.ServerName = val.value();
} else {
throw std::runtime_error(std::string(StrName));
}
if (auto val = GeneralTable[StrDescription].value<std::string>(); val.has_value()) {
Application::Settings.ServerDesc = val.value();
} else {
throw std::runtime_error(std::string(StrDescription));
}
if (auto val = GeneralTable[StrResourceFolder].value<std::string>(); val.has_value()) {
Application::Settings.Resource = val.value();
} else {
throw std::runtime_error(std::string(StrResourceFolder));
}
if (auto val = GeneralTable[StrAuthKey].value<std::string>(); val.has_value()) {
Application::Settings.Key = val.value();
} else {
throw std::runtime_error(std::string(StrAuthKey));
}
} catch (const std::exception& err) {
error("Error parsing config file value: " + std::string(err.what()));
mFailed = true;
return;
}
PrintDebug();
// all good so far, let's check if there's a key
if (Application::Settings.Key.empty()) {
error("No AuthKey specified in the \"" + std::string(ConfigFileName) + "\" file. Please get an AuthKey, enter it into the config file, and restart this server.");
mFailed = true;
}
}
void TConfig::PrintDebug() {
debug(std::string(StrDebug) + ": " + std::string(Application::Settings.DebugModeEnabled ? "true" : "false"));
debug(std::string(StrPrivate) + ": " + std::string(Application::Settings.Private ? "true" : "false"));
debug(std::string(StrPort) + ": " + std::to_string(Application::Settings.Port));
debug(std::string(StrMaxCars) + ": " + std::to_string(Application::Settings.MaxCars));
debug(std::string(StrMaxPlayers) + ": " + std::to_string(Application::Settings.MaxPlayers));
debug(std::string(StrMap) + ": \"" + Application::Settings.MapName + "\"");
debug(std::string(StrName) + ": \"" + Application::Settings.ServerName + "\"");
debug(std::string(StrDescription) + ": \"" + Application::Settings.ServerDesc + "\"");
debug(std::string(StrResourceFolder) + ": \"" + Application::Settings.Resource + "\"");
// special!
debug("Key Length: " + std::to_string(Application::Settings.Key.length()) + "");
}
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 {
warn("unknown key in old auth file (ignored): " + Key);
}
Str >> std::ws;
}
}

78
src/TConsole.cpp Normal file
View File

@@ -0,0 +1,78 @@
#include "TConsole.h"
#include "Common.h"
#include "Compat.h"
#include <ctime>
#include <sstream>
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);
tm local_tm {};
#ifdef WIN32
localtime_s(&local_tm, &tt);
#else // unix
localtime_r(&tt, &local_tm);
#endif // WIN32
std::stringstream date;
int S = local_tm.tm_sec;
int M = local_tm.tm_min;
int H = local_tm.tm_hour;
std::string Secs = (S > 9 ? std::to_string(S) : "0" + std::to_string(S));
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
date
<< "["
<< local_tm.tm_mday << "/"
<< local_tm.tm_mon + 1 << "/"
<< local_tm.tm_year + 1900 << " "
<< Hour << ":"
<< Min << ":"
<< Secs
<< "] ";
/* TODO
if (Debug) {
date << ThreadName()
<< " ";
}
*/
return date.str();
}
TConsole::TConsole() {
mCommandline.enable_history();
mCommandline.set_history_limit(20);
mCommandline.set_prompt("> ");
bool success = mCommandline.enable_write_to_file("Server.log");
if (!success) {
error("unable to open file for writing: \"Server.log\"");
}
mCommandline.on_command = [this](Commandline& c) {
auto cmd = c.get_command();
mCommandline.write("> " + cmd);
if (cmd == "exit") {
info("gracefully shutting down");
Application::GracefullyShutdown();
} else if (cmd == "clear" || cmd == "cls") {
// TODO: clear screen
} else {
if (mLuaConsole) {
mLuaConsole->Execute(cmd);
} else {
error("Lua subsystem not yet initialized, please wait a few seconds and try again");
}
}
};
}
void TConsole::Write(const std::string& str) {
auto ToWrite = GetDate() + str;
mCommandline.write(ToWrite);
// TODO write to logfile, too
}
void TConsole::InitializeLuaConsole(TLuaEngine& Engine) {
mLuaConsole = std::make_unique<TLuaFile>(Engine, true);
}
void TConsole::WriteRaw(const std::string& str) {
mCommandline.write(str);
}

109
src/THeartbeatThread.cpp Normal file
View File

@@ -0,0 +1,109 @@
#include "THeartbeatThread.h"
#include "Client.h"
#include "Http.h"
//#include "SocketIO.h"
#include <sstream>
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;
while (!mShutdown) {
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;
}
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;
Body += "&pps=" + Application::PPS();
T = Http::POST(Application::GetBackendHostname(), "/heartbeat", {}, Body, false);
if (T.substr(0, 2) != "20") {
//Backend system refused server startup!
std::this_thread::sleep_for(std::chrono::milliseconds(500));
T = Http::POST(Application::GetBackendHostname(), "/heartbeat", {}, Body, false);
// TODO backup2 + HTTP flag (no TSL)
if (T.substr(0, 2) != "20") {
warn("Backend system refused server! Server might not show in the public list");
debug("server returned \"" + T + "\"");
isAuth = false;
}
}
if (!isAuth) {
if (T == "2000") {
info(("Authenticated!"));
isAuth = true;
} else if (T == "200") {
info(("Resumed authenticated session!"));
isAuth = true;
}
}
//SocketIO::Get().SetAuthenticated(isAuth);
}
}
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::ServerVersion()
<< "&clientversion=" << Application::ClientVersion()
<< "&name=" << Application::Settings.ServerName
<< "&modlist=" << mResourceManager.TrimmedList()
<< "&modstotalsize=" << mResourceManager.MaxModSize()
<< "&modstotal=" << mResourceManager.ModsLoaded()
<< "&playerslist=" << GetPlayers()
<< "&desc=" << Application::Settings.ServerDesc;
return Ret.str();
}
THeartbeatThread::THeartbeatThread(TResourceManager& ResourceManager, TServer& Server)
: mResourceManager(ResourceManager)
, mServer(Server) {
Application::RegisterShutdownHandler([&] {
if (mThread.joinable()) {
debug("shutting down Heartbeat");
mShutdown = true;
mThread.join();
debug("shut down Heartbeat");
}
});
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() {
}*/

103
src/TLuaEngine.cpp Normal file
View File

@@ -0,0 +1,103 @@
#include "TLuaEngine.h"
#include "TLuaFile.h"
#include <filesystem>
#include <sys/stat.h>
namespace fs = std::filesystem;
// necessary as lua relies on global state
TLuaEngine* TheEngine;
TLuaEngine::TLuaEngine(TServer& Server, TNetwork& Network)
: mNetwork(Network)
, mServer(Server) {
TheEngine = this;
if (!fs::exists(Application::Settings.Resource)) {
fs::create_directory(Application::Settings.Resource);
}
std::string Path = Application::Settings.Resource + ("/Server");
if (!fs::exists(Path)) {
fs::create_directory(Path);
}
FolderList(Path, false);
mPath = Path;
Application::RegisterShutdownHandler([&] {if (mThread.joinable()) {
debug("shutting down LuaEngine");
mShutdown = true;
mThread.join();
debug("shut down LuaEngine");
} });
Start();
}
void TLuaEngine::operator()() {
RegisterThread("LuaEngine");
info("Lua system online");
while (!mShutdown) {
if (!mLuaFiles.empty()) {
for (auto& Script : mLuaFiles) {
struct stat Info { };
if (stat(Script->GetFileName().c_str(), &Info) != 0) {
Script->SetStopThread(true);
mLuaFiles.erase(Script);
info(("[HOTSWAP] Removed removed script due to delete"));
break;
}
if (Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())) {
Script->SetStopThread(true);
info(("[HOTSWAP] Updated Scripts due to edit"));
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
Script->Reload();
}
}
}
FolderList(mPath, true);
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
std::optional<std::reference_wrapper<TLuaFile>> TLuaEngine::GetScript(lua_State* L) {
for (auto& Script : mLuaFiles) {
if (Script->GetState() == L)
return *Script;
}
return std::nullopt;
}
void TLuaEngine::FolderList(const std::string& Path, bool HotSwap) {
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().filename().string().find('.');
if (pos == std::string::npos) {
RegisterFiles(entry.path().string(), HotSwap);
}
}
}
void TLuaEngine::RegisterFiles(const std::string& Path, bool HotSwap) {
std::string Name = Path.substr(Path.find_last_of('\\') + 1);
if (!HotSwap)
info(("Loading plugin : ") + Name);
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().string().find((".lua"));
if (pos != std::string::npos && entry.path().string().length() - pos == 4) {
if (!HotSwap || NewFile(entry.path().string())) {
auto FileName = entry.path().string();
std::unique_ptr<TLuaFile> ScriptToInsert(new TLuaFile(*this));
auto& Script = *ScriptToInsert;
mLuaFiles.insert(std::move(ScriptToInsert));
Script.Init(Name, FileName, fs::last_write_time(FileName));
if (HotSwap)
info(("[HOTSWAP] Added : ") + Script.GetFileName().substr(Script.GetFileName().find('\\')));
}
}
}
}
bool TLuaEngine::NewFile(const std::string& Path) {
for (auto& Script : mLuaFiles) {
if (Path == Script->GetFileName())
return false;
}
return true;
}

823
src/TLuaFile.cpp Normal file
View File

@@ -0,0 +1,823 @@
#include "TLuaFile.h"
#include "Client.h"
#include "Common.h"
#include "CustomAssert.h"
#include "TLuaEngine.h"
#include "TNetwork.h"
#include "TServer.h"
#include <future>
#include <thread>
// TODO: REWRITE
void SendError(TLuaEngine& Engine, lua_State* L, const std::string& msg);
std::any CallFunction(TLuaFile* lua, const std::string& FuncName, std::shared_ptr<TLuaArg> Arg);
std::any TriggerLuaEvent(TLuaEngine& Engine, const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait);
extern TLuaEngine* TheEngine;
static TLuaEngine& Engine() {
Assert(TheEngine);
return *TheEngine;
}
std::shared_ptr<TLuaArg> CreateArg(lua_State* L, int T, int S) {
if (S > T)
return nullptr;
std::shared_ptr<TLuaArg> temp(new TLuaArg);
for (int C = S; C <= T; C++) {
if (lua_isstring(L, C)) {
temp->args.emplace_back(std::string(lua_tostring(L, C)));
} else if (lua_isinteger(L, C)) {
temp->args.emplace_back(int(lua_tointeger(L, C)));
} else if (lua_isboolean(L, C)) {
temp->args.emplace_back(bool(lua_toboolean(L, C)));
} else if (lua_isnumber(L, C)) {
temp->args.emplace_back(float(lua_tonumber(L, C)));
}
}
return temp;
}
void ClearStack(lua_State* L) {
lua_settop(L, 0);
}
std::any Trigger(TLuaFile* lua, const std::string& R, std::shared_ptr<TLuaArg> arg) {
RegisterThread(lua->GetFileName());
std::lock_guard<std::mutex> lockGuard(lua->Lock);
std::packaged_task<std::any(std::shared_ptr<TLuaArg>)> task([lua, R](std::shared_ptr<TLuaArg> arg) { return CallFunction(lua, R, arg); });
std::future<std::any> f1 = task.get_future();
std::thread t(std::move(task), arg);
t.detach();
auto status = f1.wait_for(std::chrono::seconds(5));
if (status != std::future_status::timeout)
return f1.get();
SendError(lua->Engine(), lua->GetState(), R + " took too long to respond");
return 0;
}
std::any FutureWait(TLuaFile* lua, const std::string& R, std::shared_ptr<TLuaArg> arg, bool Wait) {
Assert(lua);
std::packaged_task<std::any(std::shared_ptr<TLuaArg>)> task([lua, R](std::shared_ptr<TLuaArg> arg) { return Trigger(lua, R, arg); });
std::future<std::any> f1 = task.get_future();
std::thread t(std::move(task), arg);
t.detach();
int T = 0;
if (Wait)
T = 6;
auto status = f1.wait_for(std::chrono::seconds(T));
if (status != std::future_status::timeout)
return f1.get();
return 0;
}
std::any TriggerLuaEvent(const std::string& Event, bool local, TLuaFile* Caller, std::shared_ptr<TLuaArg> arg, bool Wait) {
std::any R;
int Ret = 0;
for (auto& Script : Engine().LuaFiles()) {
if (Script->IsRegistered(Event)) {
if (local) {
if (Script->GetPluginName() == Caller->GetPluginName()) {
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
if (R.type() == typeid(int)) {
if (std::any_cast<int>(R))
Ret++;
} else if (Event == "onPlayerAuth")
return R;
}
} else {
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
if (R.type() == typeid(int)) {
if (std::any_cast<int>(R))
Ret++;
} else if (Event == "onPlayerAuth")
return R;
}
}
}
return Ret;
}
bool ConsoleCheck(lua_State* L, int r) {
if (r != LUA_OK) {
std::string msg = lua_tostring(L, -1);
warn(("_Console | ") + msg);
return false;
}
return true;
}
bool CheckLua(lua_State* L, int r) {
if (r != LUA_OK) {
std::string msg = lua_tostring(L, -1);
auto MaybeS = Engine().GetScript(L);
if (MaybeS.has_value()) {
TLuaFile& S = MaybeS.value();
std::string a = fs::path(S.GetFileName()).filename().string();
warn(a + " | " + msg);
return false;
}
// What the fuck, what do we do?!
AssertNotReachable();
}
return true;
}
int lua_RegisterEvent(lua_State* L) {
int Args = lua_gettop(L);
auto MaybeScript = Engine().GetScript(L);
Assert(MaybeScript.has_value());
TLuaFile& Script = MaybeScript.value();
if (Args == 2 && lua_isstring(L, 1) && lua_isstring(L, 2)) {
Script.RegisterEvent(lua_tostring(L, 1), lua_tostring(L, 2));
} else
SendError(Engine(), L, "RegisterEvent invalid argument count expected 2 got " + std::to_string(Args));
return 0;
}
int lua_TriggerEventL(lua_State* L) {
int Args = lua_gettop(L);
auto MaybeScript = Engine().GetScript(L);
Assert(MaybeScript.has_value());
TLuaFile& Script = MaybeScript.value();
if (Args > 0) {
if (lua_isstring(L, 1)) {
TriggerLuaEvent(lua_tostring(L, 1), true, &Script, CreateArg(L, Args, 2), false);
} else
SendError(Engine(), L, ("TriggerLocalEvent wrong argument [1] need string"));
} else {
SendError(Engine(), L, ("TriggerLocalEvent not enough arguments expected 1 got 0"));
}
return 0;
}
int lua_TriggerEventG(lua_State* L) {
int Args = lua_gettop(L);
auto MaybeScript = Engine().GetScript(L);
Assert(MaybeScript.has_value());
TLuaFile& Script = MaybeScript.value();
if (Args > 0) {
if (lua_isstring(L, 1)) {
TriggerLuaEvent(lua_tostring(L, 1), false, &Script, CreateArg(L, Args, 2), false);
} else
SendError(Engine(), L, ("TriggerGlobalEvent wrong argument [1] need string"));
} else
SendError(Engine(), L, ("TriggerGlobalEvent not enough arguments"));
return 0;
}
void SafeExecution(TLuaFile* lua, const std::string& FuncName) {
lua_State* luaState = lua->GetState();
lua_getglobal(luaState, FuncName.c_str());
if (lua_isfunction(luaState, -1)) {
int R = lua_pcall(luaState, 0, 0, 0);
CheckLua(luaState, R);
}
ClearStack(luaState);
}
void ExecuteAsync(TLuaFile* lua, const std::string& FuncName) {
std::lock_guard<std::mutex> lockGuard(lua->Lock);
SafeExecution(lua, FuncName);
}
void CallAsync(TLuaFile* lua, const std::string& Func, int U) {
RegisterThread(lua->GetFileName());
lua->SetStopThread(false);
int D = 1000 / U;
while (!lua->GetStopThread()) {
ExecuteAsync(lua, Func);
std::this_thread::sleep_for(std::chrono::milliseconds(D));
}
}
int lua_StopThread(lua_State* L) {
auto MaybeScript = Engine().GetScript(L);
Assert(MaybeScript.has_value());
// ugly, but whatever, this is safe as fuck
MaybeScript.value().get().SetStopThread(true);
return 0;
}
int lua_CreateThread(lua_State* L) {
int Args = lua_gettop(L);
if (Args > 1) {
if (lua_isstring(L, 1)) {
std::string STR = lua_tostring(L, 1);
if (lua_isinteger(L, 2) || lua_isnumber(L, 2)) {
int U = int(lua_tointeger(L, 2));
if (U > 0 && U < 501) {
auto MaybeScript = Engine().GetScript(L);
Assert(MaybeScript.has_value());
TLuaFile& Script = MaybeScript.value();
std::thread t1(CallAsync, &Script, STR, U);
t1.detach();
} else
SendError(Engine(), L, ("CreateThread wrong argument [2] number must be between 1 and 500"));
} else
SendError(Engine(), L, ("CreateThread wrong argument [2] need number"));
} else
SendError(Engine(), L, ("CreateThread wrong argument [1] need string"));
} else
SendError(Engine(), L, ("CreateThread not enough arguments"));
return 0;
}
int lua_Sleep(lua_State* L) {
if (lua_isnumber(L, 1)) {
int t = int(lua_tonumber(L, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(t));
} else {
SendError(Engine(), L, ("Sleep not enough arguments"));
return 0;
}
return 1;
}
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;
}
int lua_isConnected(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (MaybeClient && !MaybeClient.value().expired())
lua_pushboolean(L, MaybeClient.value().lock()->IsConnected());
else
return 0;
} else {
SendError(Engine(), L, ("isConnected not enough arguments"));
return 0;
}
return 1;
}
int lua_GetPlayerName(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (MaybeClient && !MaybeClient.value().expired())
lua_pushstring(L, MaybeClient.value().lock()->GetName().c_str());
else
return 0;
} else {
SendError(Engine(), L, ("GetPlayerName not enough arguments"));
return 0;
}
return 1;
}
int lua_GetPlayerCount(lua_State* L) {
lua_pushinteger(L, Engine().Server().ClientCount());
return 1;
}
int lua_GetGuest(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (MaybeClient && !MaybeClient.value().expired())
lua_pushboolean(L, MaybeClient.value().lock()->IsGuest());
else
return 0;
} else {
SendError(Engine(), L, "GetGuest not enough arguments");
return 0;
}
return 1;
}
int lua_GetAllPlayers(lua_State* L) {
lua_newtable(L);
Engine().Server().ForEachClient([&](const std::weak_ptr<TClient>& ClientPtr) -> bool {
std::shared_ptr<TClient> Client;
{
ReadLock Lock(Engine().Server().GetClientMutex());
if (ClientPtr.expired())
return true;
Client = ClientPtr.lock();
}
lua_pushinteger(L, Client->GetID());
lua_pushstring(L, Client->GetName().c_str());
lua_settable(L, -3);
return true;
});
if (Engine().Server().ClientCount() == 0)
return 0;
return 1;
}
int lua_GetIdentifiers(lua_State* L) {
if (lua_isnumber(L, 1)) {
auto MaybeClient = GetClient(Engine().Server(), int(lua_tonumber(L, 1)));
if (MaybeClient && !MaybeClient.value().expired()) {
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
if (IDs.empty())
return 0;
lua_newtable(L);
for (const std::string& ID : IDs) {
lua_pushstring(L, ID.substr(0, ID.find(':')).c_str());
lua_pushstring(L, ID.c_str());
lua_settable(L, -3);
}
} else
return 0;
} else {
SendError(Engine(), L, "lua_GetIdentifiers wrong arguments");
return 0;
}
return 1;
}
int lua_GetCars(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value().lock();
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (VehicleData.empty())
return 0;
lua_newtable(L);
for (const auto& v : VehicleData) {
lua_pushinteger(L, v.ID());
lua_pushstring(L, v.Data().substr(3).c_str());
lua_settable(L, -3);
}
} else
return 0;
} else {
SendError(Engine(), L, ("GetPlayerVehicles wrong arguments"));
return 0;
}
return 1;
}
int lua_dropPlayer(lua_State* L) {
int Args = lua_gettop(L);
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (!MaybeClient || MaybeClient.value().expired())
return 0;
std::string Reason;
if (Args > 1 && lua_isstring(L, 2)) {
Reason = std::string((" Reason : ")) + lua_tostring(L, 2);
}
auto c = MaybeClient.value().lock();
Engine().Network().Respond(*c, "C:Server:You have been Kicked from the server! " + Reason, true);
c->SetStatus(-2);
info(("Closing socket due to kick"));
CloseSocketProper(c->GetTCPSock());
} else
SendError(Engine(), L, ("DropPlayer not enough arguments"));
return 0;
}
int lua_sendChat(lua_State* L) {
if (lua_isinteger(L, 1) || lua_isnumber(L, 1)) {
if (lua_isstring(L, 2)) {
int ID = int(lua_tointeger(L, 1));
if (ID == -1) {
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
Engine().Network().SendToAll(nullptr, Packet, true, true);
} else {
auto MaybeClient = GetClient(Engine().Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto c = MaybeClient.value().lock();
if (!c->IsSynced())
return 0;
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
Engine().Network().Respond(*c, Packet, true);
} else
SendError(Engine(), L, ("SendChatMessage invalid argument [1] invalid ID"));
}
} else
SendError(Engine(), L, ("SendChatMessage invalid argument [2] expected string"));
} else
SendError(Engine(), L, ("SendChatMessage invalid argument [1] expected number"));
return 0;
}
int lua_RemoveVehicle(lua_State* L) {
int Args = lua_gettop(L);
if (Args != 2) {
SendError(Engine(), L, ("RemoveVehicle invalid argument count expected 2 got ") + std::to_string(Args));
return 0;
}
if ((lua_isinteger(L, 1) || lua_isnumber(L, 1)) && (lua_isinteger(L, 2) || lua_isnumber(L, 2))) {
int PID = int(lua_tointeger(L, 1));
int VID = int(lua_tointeger(L, 2));
auto MaybeClient = GetClient(Engine().Server(), PID);
if (!MaybeClient || MaybeClient.value().expired()) {
SendError(Engine(), L, ("RemoveVehicle invalid Player ID"));
return 0;
}
auto c = MaybeClient.value().lock();
if (!c->GetCarData(VID).empty()) {
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
Engine().Network().SendToAll(nullptr, Destroy, true, true);
c->DeleteCar(VID);
}
} else
SendError(Engine(), L, ("RemoveVehicle invalid argument expected number"));
return 0;
}
int lua_HWID(lua_State* L) {
lua_pushinteger(L, -1);
return 1;
}
int lua_RemoteEvent(lua_State* L) {
int Args = lua_gettop(L);
if (Args != 3) {
SendError(Engine(), L, ("TriggerClientEvent invalid argument count expected 3 got ") + std::to_string(Args));
return 0;
}
if (!lua_isnumber(L, 1)) {
SendError(Engine(), L, ("TriggerClientEvent invalid argument [1] expected number"));
return 0;
}
if (!lua_isstring(L, 2)) {
SendError(Engine(), L, ("TriggerClientEvent invalid argument [2] expected string"));
return 0;
}
if (!lua_isstring(L, 3)) {
SendError(Engine(), L, ("TriggerClientEvent invalid argument [3] expected string"));
return 0;
}
int ID = int(lua_tointeger(L, 1));
std::string Packet = "E:" + std::string(lua_tostring(L, 2)) + ":" + std::string(lua_tostring(L, 3));
if (ID == -1)
Engine().Network().SendToAll(nullptr, Packet, true, true);
else {
auto MaybeClient = GetClient(Engine().Server(), ID);
if (!MaybeClient || MaybeClient.value().expired()) {
SendError(Engine(), L, ("TriggerClientEvent invalid Player ID"));
return 0;
}
auto c = MaybeClient.value().lock();
Engine().Network().Respond(*c, Packet, true);
}
return 0;
}
int lua_ServerExit(lua_State*) {
Application::GracefullyShutdown();
return 0;
}
int lua_Set(lua_State* L) {
int Args = lua_gettop(L);
if (Args != 2) {
SendError(Engine(), L, ("set invalid argument count expected 2 got ") + std::to_string(Args));
return 0;
}
if (!lua_isnumber(L, 1)) {
SendError(Engine(), L, ("set invalid argument [1] expected number"));
return 0;
}
auto MaybeSrc = Engine().GetScript(L);
std::string Name;
if (!MaybeSrc.has_value()) {
Name = ("_Console");
} else {
Name = MaybeSrc.value().get().GetPluginName();
}
int C = int(lua_tointeger(L, 1));
switch (C) {
case 0: //debug
if (lua_isboolean(L, 2)) {
Application::Settings.DebugModeEnabled = lua_toboolean(L, 2);
info(Name + (" | Debug -> ") + (Application::Settings.DebugModeEnabled ? "true" : "false"));
} else
SendError(Engine(), L, ("set invalid argument [2] expected boolean for ID : 0"));
break;
case 1: //private
if (lua_isboolean(L, 2)) {
Application::Settings.Private = lua_toboolean(L, 2);
info(Name + (" | Private -> ") + (Application::Settings.Private ? "true" : "false"));
} else
SendError(Engine(), L, ("set invalid argument [2] expected boolean for ID : 1"));
break;
case 2: //max cars
if (lua_isnumber(L, 2)) {
Application::Settings.MaxCars = int(lua_tointeger(L, 2));
info(Name + (" | MaxCars -> ") + std::to_string(Application::Settings.MaxCars));
} else
SendError(Engine(), L, ("set invalid argument [2] expected number for ID : 2"));
break;
case 3: //max players
if (lua_isnumber(L, 2)) {
Application::Settings.MaxPlayers = int(lua_tointeger(L, 2));
info(Name + (" | MaxPlayers -> ") + std::to_string(Application::Settings.MaxPlayers));
} else
SendError(Engine(), L, ("set invalid argument [2] expected number for ID : 3"));
break;
case 4: //Map
if (lua_isstring(L, 2)) {
Application::Settings.MapName = lua_tostring(L, 2);
info(Name + (" | MapName -> ") + Application::Settings.MapName);
} else
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 4"));
break;
case 5: //Name
if (lua_isstring(L, 2)) {
Application::Settings.ServerName = lua_tostring(L, 2);
info(Name + (" | ServerName -> ") + Application::Settings.ServerName);
} else
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 5"));
break;
case 6: //Desc
if (lua_isstring(L, 2)) {
Application::Settings.ServerDesc = lua_tostring(L, 2);
info(Name + (" | ServerDesc -> ") + Application::Settings.ServerDesc);
} else
SendError(Engine(), L, ("set invalid argument [2] expected string for ID : 6"));
break;
default:
warn(("Invalid config ID : ") + std::to_string(C));
break;
}
return 0;
}
extern "C" {
int lua_Print(lua_State* L) {
int Arg = lua_gettop(L);
std::string to_print;
for (int i = 1; i <= Arg; i++) {
if (lua_isstring(L, i)) {
to_print += lua_tostring(L, i);
} else if (lua_isinteger(L, i)) {
to_print += std::to_string(lua_tointeger(L, 1));
} else if (lua_isnumber(L, i)) {
to_print += std::to_string(lua_tonumber(L, 1));
} else if (lua_isboolean(L, i)) {
to_print += lua_toboolean(L, i) ? "true" : "false";
} else if (lua_isfunction(L, i)) {
std::stringstream ss;
ss << std::hex << reinterpret_cast<const void*>(lua_tocfunction(L, i));
to_print += "function: " + ss.str();
} else if (lua_istable(L, i)) {
std::stringstream ss;
ss << std::hex << reinterpret_cast<const void*>(lua_topointer(L, i));
to_print += "table: " + ss.str();
} else if (lua_isnoneornil(L, i)) {
to_print += "nil";
} else if (lua_isthread(L, i)) {
std::stringstream ss;
ss << std::hex << reinterpret_cast<const void*>(lua_tothread(L, i));
to_print += "thread: " + ss.str();
} else {
to_print += "(unknown)";
}
if (i + 1 <= Arg) {
to_print += "\t";
}
}
luaprint(to_print);
return 0;
}
}
int lua_TempFix(lua_State* L);
void TLuaFile::Init(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote) {
// set global engine for lua_* functions
if (!TheEngine) {
TheEngine = &mEngine;
}
Assert(mLuaState);
if (!PluginName.empty()) {
SetPluginName(PluginName);
}
if (!FileName.empty()) {
SetFileName(FileName);
}
SetLastWrite(LastWrote);
Load();
}
TLuaFile::TLuaFile(TLuaEngine& Engine, bool Console)
: mEngine(Engine)
, mLuaState(luaL_newstate()) {
if (Console) {
mConsole = Console;
Load();
}
}
void TLuaFile::Execute(const std::string& Command) {
if (ConsoleCheck(mLuaState, luaL_dostring(mLuaState, Command.c_str()))) {
lua_settop(mLuaState, 0);
}
}
void TLuaFile::Reload() {
if (CheckLua(mLuaState, luaL_dofile(mLuaState, mFileName.c_str()))) {
CallFunction(this, ("onInit"), nullptr);
}
}
std::string TLuaFile::GetOrigin() {
return fs::path(GetFileName()).filename().string();
}
std::any CallFunction(TLuaFile* lua, const std::string& FuncName, std::shared_ptr<TLuaArg> Arg) {
RegisterThread(lua->GetFileName());
lua_State* luaState = lua->GetState();
lua_getglobal(luaState, FuncName.c_str());
if (lua_isfunction(luaState, -1)) {
int Size = 0;
if (Arg != nullptr) {
Size = int(Arg->args.size());
Arg->PushArgs(luaState);
}
int R = lua_pcall(luaState, Size, 1, 0);
if (CheckLua(luaState, R)) {
if (lua_isnumber(luaState, -1)) {
auto ret = int(lua_tointeger(luaState, -1));
ClearStack(luaState);
return ret;
} else if (lua_isstring(luaState, -1)) {
auto ret = std::string(lua_tostring(luaState, -1));
ClearStack(luaState);
return ret;
}
}
}
ClearStack(luaState);
return 0;
}
void TLuaFile::SetPluginName(const std::string& Name) {
mPluginName = Name;
}
void TLuaFile::SetFileName(const std::string& Name) {
mFileName = Name;
}
void TLuaFile::Load() {
Assert(mLuaState);
luaL_openlibs(mLuaState);
lua_register(mLuaState, "GetPlayerIdentifiers", lua_GetIdentifiers);
lua_register(mLuaState, "TriggerGlobalEvent", lua_TriggerEventG);
lua_register(mLuaState, "TriggerLocalEvent", lua_TriggerEventL);
lua_register(mLuaState, "TriggerClientEvent", lua_RemoteEvent);
lua_register(mLuaState, "GetPlayerCount", lua_GetPlayerCount);
lua_register(mLuaState, "isPlayerConnected", lua_isConnected);
lua_register(mLuaState, "RegisterEvent", lua_RegisterEvent);
lua_register(mLuaState, "GetPlayerName", lua_GetPlayerName);
lua_register(mLuaState, "RemoveVehicle", lua_RemoveVehicle);
lua_register(mLuaState, "GetPlayerDiscordID", lua_TempFix);
lua_register(mLuaState, "CreateThread", lua_CreateThread);
lua_register(mLuaState, "GetPlayerVehicles", lua_GetCars);
lua_register(mLuaState, "SendChatMessage", lua_sendChat);
lua_register(mLuaState, "GetPlayers", lua_GetAllPlayers);
lua_register(mLuaState, "GetPlayerGuest", lua_GetGuest);
lua_register(mLuaState, "StopThread", lua_StopThread);
lua_register(mLuaState, "DropPlayer", lua_dropPlayer);
lua_register(mLuaState, "GetPlayerHWID", lua_HWID);
lua_register(mLuaState, "exit", lua_ServerExit);
lua_register(mLuaState, "Sleep", lua_Sleep);
lua_register(mLuaState, "print", lua_Print);
lua_register(mLuaState, "Set", lua_Set);
if (!mConsole)
Reload();
}
void TLuaFile::RegisterEvent(const std::string& Event, const std::string& FunctionName) {
mRegisteredEvents.insert(std::make_pair(Event, FunctionName));
}
void TLuaFile::UnRegisterEvent(const std::string& Event) {
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
if (a.first == Event) {
mRegisteredEvents.erase(a);
break;
}
}
}
bool TLuaFile::IsRegistered(const std::string& Event) {
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
if (a.first == Event)
return true;
}
return false;
}
std::string TLuaFile::GetRegistered(const std::string& Event) const {
for (const std::pair<std::string, std::string>& a : mRegisteredEvents) {
if (a.first == Event)
return a.second;
}
return "";
}
std::string TLuaFile::GetFileName() const {
return mFileName;
}
std::string TLuaFile::GetPluginName() const {
return mPluginName;
}
lua_State* TLuaFile::GetState() {
return mLuaState;
}
const lua_State* TLuaFile::GetState() const {
return mLuaState;
}
void TLuaFile::SetLastWrite(fs::file_time_type time) {
mLastWrote = time;
}
fs::file_time_type TLuaFile::GetLastWrite() {
return mLastWrote;
}
TLuaFile::~TLuaFile() {
info("closing lua state");
lua_close(mLuaState);
}
void SendError(TLuaEngine& Engine, lua_State* L, const std::string& msg) {
Assert(L);
auto MaybeS = Engine.GetScript(L);
std::string a;
if (!MaybeS.has_value()) {
a = ("_Console");
} else {
TLuaFile& S = MaybeS.value();
a = fs::path(S.GetFileName()).filename().string();
}
warn(a + (" | Incorrect Call of ") + msg);
}
int lua_TempFix(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
auto MaybeClient = GetClient(Engine().Server(), ID);
if (!MaybeClient || MaybeClient.value().expired())
return 0;
std::string Ret;
auto c = MaybeClient.value().lock();
if (c->IsGuest()) {
Ret = "Guest-" + c->GetName();
} else
Ret = c->GetName();
lua_pushstring(L, Ret.c_str());
} else
SendError(Engine(), L, "GetDID not enough arguments");
return 1;
}
void TLuaArg::PushArgs(lua_State* State) {
for (std::any arg : args) {
if (!arg.has_value()) {
error("arg didn't have a value, this is not expected, bad");
return;
}
const auto& Type = arg.type();
if (Type == typeid(bool)) {
lua_pushboolean(State, std::any_cast<bool>(arg));
} else if (Type == typeid(std::string)) {
lua_pushstring(State, std::any_cast<std::string>(arg).c_str());
} else if (Type == typeid(const char*)) {
lua_pushstring(State, std::any_cast<const char*>(arg));
} else if (Type == typeid(int)) {
lua_pushinteger(State, std::any_cast<int>(arg));
} else if (Type == typeid(float)) {
lua_pushnumber(State, std::any_cast<float>(arg));
} else if (Type == typeid(double)) {
lua_pushnumber(State, std::any_cast<double>(arg));
} else {
// if this happens, implement a sane behavior for that value
error("what in the hell is " + std::string(arg.type().name()));
}
}
}

994
src/TNetwork.cpp Normal file
View File

@@ -0,0 +1,994 @@
#include "TNetwork.h"
#include "Client.h"
#include <CustomAssert.h>
#include <Http.h>
#include <array>
#include <cstring>
TNetwork::TNetwork(TServer& Server, TPPSMonitor& PPSMonitor, TResourceManager& ResourceManager)
: mServer(Server)
, mPPSMonitor(PPSMonitor)
, mResourceManager(ResourceManager) {
Application::RegisterShutdownHandler([&] {
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([&] {
if (mUDPThread.joinable()) {
debug("shutting down TCPServer");
mShutdown = true;
mUDPThread.detach();
debug("shut down TCPServer");
}
});
Application::RegisterShutdownHandler([&] {
if (mTCPThread.joinable()) {
debug("shutting down TCPServer");
mShutdown = true;
mTCPThread.detach();
debug("shut down TCPServer");
}
});
mTCPThread = std::thread(&TNetwork::TCPServerMain, this);
mUDPThread = std::thread(&TNetwork::UDPServerMain, this);
}
void TNetwork::UDPServerMain() {
RegisterThread("UDPServer");
#ifdef WIN32
WSADATA data;
if (WSAStartup(514, &data)) {
error(("Can't start Winsock!"));
//return;
}
mUDPSock = socket(AF_INET, SOCK_DGRAM, 0);
// Create a server hint structure for the server
sockaddr_in serverAddr {};
serverAddr.sin_addr.S_un.S_addr = ADDR_ANY; //Any Local
serverAddr.sin_family = AF_INET; // Address format is IPv4
serverAddr.sin_port = htons(Application::Settings.Port); // Convert from little to big endian
// Try and bind the socket to the IP and port
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
error(("Can't bind socket!") + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
//return;
}
#else // unix
mUDPSock = socket(AF_INET, SOCK_DGRAM, 0);
// Create a server hint structure for the server
sockaddr_in serverAddr {};
serverAddr.sin_addr.s_addr = INADDR_ANY; //Any Local
serverAddr.sin_family = AF_INET; // Address format is IPv4
serverAddr.sin_port = htons(uint16_t(Application::Settings.Port)); // Convert from little to big endian
// Try and bind the socket to the IP and port
if (bind(mUDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
error(("Can't bind socket!") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
//return;
}
#endif
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 (!mShutdown) {
try {
sockaddr_in client {};
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
size_t Pos = Data.find(':');
if (Data.empty() || Pos > 2)
continue;
/*char clientIp[256];
ZeroMemory(clientIp, 256); ///Code to get IP we don't need that yet
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);*/
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);
TServer::GlobalParser(ClientPtr, Data.substr(2), mPPSMonitor, *this);
}
return true;
});
} catch (const std::exception& e) {
error(("fatal: ") + std::string(e.what()));
}
}
}
void TNetwork::TCPServerMain() {
RegisterThread("TCPServer");
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(514, &wsaData)) {
error("Can't start Winsock!");
return;
}
SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in addr {};
addr.sin_addr.S_un.S_addr = ADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(Application::Settings.Port);
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
error("Can't bind socket! " + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
}
if (Listener == -1) {
error("Invalid listening socket");
return;
}
if (listen(Listener, SOMAXCONN)) {
error("listener failed " + std::to_string(GetLastError()));
//TODO Fix me leak for Listener socket
return;
}
info("Vehicle event network online");
do {
try {
client = accept(Listener, nullptr, nullptr);
if (client == -1) {
warn("Got an invalid client socket on connect! Skipping...");
continue;
}
std::thread ID(&TNetwork::Identify, this, client);
ID.detach();
} catch (const std::exception& e) {
error("fatal: " + std::string(e.what()));
}
} while (client);
CloseSocketProper(client);
WSACleanup();
#else // unix
// wondering why we need slightly different implementations of this?
// ask ms.
SOCKET client = -1;
SOCKET Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int optval = 1;
setsockopt(Listener, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
// TODO: check optval or return value idk
sockaddr_in addr {};
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(uint16_t(Application::Settings.Port));
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
error(("Can't bind socket! ") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(-1);
}
if (Listener == -1) {
error(("Invalid listening socket"));
return;
}
if (listen(Listener, SOMAXCONN)) {
error(("listener failed ") + std::string(strerror(errno)));
//TODO fix me leak Listener
return;
}
info(("Vehicle event network online"));
do {
try {
if (mShutdown) {
debug("shutdown during TCP wait for accept loop");
break;
}
client = accept(Listener, nullptr, nullptr);
if (client == -1) {
warn(("Got an invalid client socket on connect! Skipping..."));
continue;
}
std::thread ID(&TNetwork::Identify, this, client);
ID.detach(); // TODO: Add to a queue and attempt to join periodically
} catch (const std::exception& e) {
error(("fatal: ") + std::string(e.what()));
}
} while (client);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
CloseSocketProper(client);
#endif
}
#undef GetObject //Fixes Windows
#include "Json.h"
namespace json = rapidjson;
void TNetwork::Identify(SOCKET TCPSock) {
RegisterThreadAuto();
char Code;
if (recv(TCPSock, &Code, 1, 0) != 1) {
CloseSocketProper(TCPSock);
return;
}
if (Code == 'C') {
Authentication(TCPSock);
} else if (Code == 'D') {
HandleDownload(TCPSock);
} else {
CloseSocketProper(TCPSock);
}
}
void TNetwork::HandleDownload(SOCKET TCPSock) {
char D;
if (recv(TCPSock, &D, 1, 0) != 1) {
CloseSocketProper(TCPSock);
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(TCPSock);
}
}
return true;
});
}
void TNetwork::Authentication(SOCKET TCPSock) {
auto Client = CreateClient(TCPSock);
std::string Rc;
info("Identifying new client...");
Rc = TCPRcv(*Client);
if (Rc.size() > 3 && Rc.substr(0, 2) == "VC") {
Rc = Rc.substr(2);
if (Rc.length() > 4 || Rc != Application::ClientVersion()) {
ClientKick(*Client, "Outdated Version!");
return;
}
} else {
ClientKick(*Client, "Invalid version header!");
return;
}
if (!TCPSend(*Client, "S")) {
// TODO: handle
}
Rc = TCPRcv(*Client);
if (Rc.size() > 50) {
ClientKick(*Client, "Invalid Key!");
return;
}
if (!Rc.empty()) {
Rc = Http::POST(Application::GetBackendUrlForAuth(), "/pkToUser", {}, R"({"key":")" + Rc + "\"}", true);
}
json::Document AuthResponse;
AuthResponse.Parse(Rc.c_str());
if (Rc == "-1" || AuthResponse.HasParseError()) {
ClientKick(*Client, "Invalid key! Please restart your game.");
return;
}
if (!AuthResponse.IsObject()) {
ClientKick(*Client, "Backend returned invalid auth response format.");
error("Backend returned invalid auth response format. This should never happen.");
return;
}
if (AuthResponse["username"].IsString() && AuthResponse["roles"].IsString()
&& AuthResponse["guest"].IsBool() && AuthResponse["identifiers"].IsArray()) {
Client->SetName(AuthResponse["username"].GetString());
Client->SetRoles(AuthResponse["roles"].GetString());
Client->SetIsGuest(AuthResponse["guest"].GetBool());
for (const auto& ID : AuthResponse["identifiers"].GetArray()) {
Client->AddIdentifier(ID.GetString());
}
} else {
ClientKick(*Client, "Invalid authentication data!");
return;
}
debug("Name -> " + Client->GetName() + ", Guest -> " + std::to_string(Client->IsGuest()) + ", Roles -> " + Client->GetRoles());
debug("There are " + std::to_string(mServer.ClientCount()) + " known clients");
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;
}
info("Client Iteration: Name -> " + Cl->GetName() + ", Guest -> " + std::to_string(Cl->IsGuest()) + ", Roles -> " + Cl->GetRoles());
if (Cl->GetName() == Client->GetName() && Cl->IsGuest() == Client->IsGuest()) {
info("New client matched with current iteration");
info("Old client (" + Cl->GetName() + ") kicked: Reconnecting");
CloseSocketProper(Cl->GetTCPSock());
Cl->SetStatus(-2);
return false;
}
return true;
});
auto arg = std::make_unique<TLuaArg>(TLuaArg { { Client->GetName(), Client->GetRoles(), Client->IsGuest() } });
std::any Res = TriggerLuaEvent("onPlayerAuth", false, nullptr, std::move(arg), true);
if (Res.type() == typeid(int) && std::any_cast<int>(Res)) {
ClientKick(*Client, "you are not allowed on the server!");
return;
} else if (Res.type() == typeid(std::string)) {
ClientKick(*Client, std::any_cast<std::string>(Res));
return;
}
if (mServer.ClientCount() < size_t(Application::Settings.MaxPlayers)) {
info("Identification success");
mServer.InsertClient(Client);
TCPClient(Client);
} else
ClientKick(*Client, "Server full!");
}
std::shared_ptr<TClient> TNetwork::CreateClient(SOCKET TCPSock) {
auto c = std::make_shared<TClient>(mServer);
c->SetTCPSock(TCPSock);
return c;
}
bool TNetwork::TCPSend(TClient& c, const std::string& 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;
}
}
int32_t Size, Sent;
std::string Send(4, 0);
Size = int32_t(Data.size());
memcpy(&Send[0], &Size, sizeof(Size));
Send += Data;
Sent = 0;
Size += 4;
do {
#ifdef WIN32
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, 0);
#else //WIN32
int32_t Temp = send(c.GetTCPSock(), &Send[Sent], Size - Sent, MSG_NOSIGNAL);
#endif //WIN32
if (Temp == 0) {
debug("send() == 0: " + std::string(std::strerror(errno)));
if (c.GetStatus() > -1)
c.SetStatus(-1);
return false;
} else if (Temp < 0) {
debug("send() < 0: " + std::string(std::strerror(errno))); //TODO fix it was spamming yet everyone stayed on the server
if (c.GetStatus() > -1)
c.SetStatus(-1);
CloseSocketProper(c.GetTCPSock());
return false;
}
Sent += Temp;
c.UpdatePingTime();
} while (Sent < Size);
return true;
}
bool TNetwork::CheckBytes(TClient& c, int32_t BytesRcv) {
if (BytesRcv == 0) {
debug("(TCP) Connection closing...");
if (c.GetStatus() > -1)
c.SetStatus(-1);
return false;
} else if (BytesRcv < 0) {
#ifdef WIN32
debug(("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
#else // unix
debug(("(TCP) recv failed with error: ") + std::string(strerror(errno)));
#endif // WIN32
if (c.GetStatus() > -1)
c.SetStatus(-1);
info(("Closing socket in CheckBytes, BytesRcv < 0"));
CloseSocketProper(c.GetTCPSock());
return false;
}
return true;
}
std::string TNetwork::TCPRcv(TClient& c) {
int32_t Header, BytesRcv = 0, Temp;
if (c.GetStatus() < 0)
return "";
std::vector<char> Data(sizeof(Header));
do {
Temp = recv(c.GetTCPSock(), &Data[BytesRcv], 4 - BytesRcv, 0);
if (!CheckBytes(c, Temp)) {
#ifdef DEBUG
error(std::string(__func__) + (": failed on CheckBytes in while(BytesRcv < 4)"));
#endif // DEBUG
return "";
}
BytesRcv += Temp;
} while (size_t(BytesRcv) < sizeof(Header));
memcpy(&Header, &Data[0], sizeof(Header));
#ifdef DEBUG
//debug(std::string(__func__) + (": expecting ") + std::to_string(Header) + (" bytes."));
#endif // DEBUG
if (!CheckBytes(c, BytesRcv)) {
#ifdef DEBUG
error(std::string(__func__) + (": failed on CheckBytes"));
#endif // DEBUG
return "";
}
if (Header < 100 * MB) {
Data.resize(Header);
} else {
ClientKick(c, "Header size limit exceeded");
warn("Client " + c.GetName() + " (" + std::to_string(c.GetID()) + ") sent header of >100MB - assuming malicious intent and disconnecting the client.");
return "";
}
BytesRcv = 0;
do {
Temp = recv(c.GetTCPSock(), &Data[BytesRcv], Header - BytesRcv, 0);
if (!CheckBytes(c, Temp)) {
#ifdef DEBUG
error(std::string(__func__) + (": failed on CheckBytes in while(BytesRcv < Header)"));
#endif // DEBUG
return "";
}
#ifdef DEBUG
//debug(std::string(__func__) + (": Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG
BytesRcv += Temp;
} while (BytesRcv < Header);
#ifdef DEBUG
//debug(std::string(__func__) + (": finished recv with Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG
std::string Ret(Data.data(), Header);
if (Ret.substr(0, 4) == "ABG:") {
Ret = DeComp(Ret.substr(4));
}
#ifdef DEBUG
//debug("Parsing from " + c->GetName() + " -> " +std::to_string(Ret.size()));
#endif
return Ret;
}
void TNetwork::ClientKick(TClient& c, const std::string& R) {
info("Client kicked: " + R);
if (!TCPSend(c, "E" + R)) {
// TODO handle
}
c.SetStatus(-2);
if (c.GetTCPSock())
CloseSocketProper(c.GetTCPSock());
if (c.GetDownSock())
CloseSocketProper(c.GetDownSock());
}
void TNetwork::Looper(const std::weak_ptr<TClient>& c) {
while (!c.expired()) {
auto Client = c.lock();
if (Client->GetStatus() < 0) {
debug("client status < 0, 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::string QData {};
{ // locked context
std::unique_lock lock(Client->MissedPacketQueueMutex());
if (Client->MissedPacketQueueSize() <= 0) {
break;
}
QData = Client->MissedPacketQueue().front();
Client->MissedPacketQueue().pop();
} // end locked context
// debug("sending a missed packet: " + QData);
if (!TCPSend(*Client, QData, true)) {
if (Client->GetStatus() > -1)
Client->SetStatus(-1);
{
std::unique_lock lock(Client->MissedPacketQueueMutex());
while (!Client->MissedPacketQueue().empty()) {
Client->MissedPacketQueue().pop();
}
}
CloseSocketProper(Client->GetTCPSock());
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() == -1) {
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->GetStatus() < 0) {
debug("client status < 0, breaking client loop");
break;
}
auto res = TCPRcv(*Client);
if (res == "") {
debug("TCPRcv error, break client loop");
break;
}
TServer::GlobalParser(c, res, mPPSMonitor, *this);
}
if (QueueSync.joinable())
QueueSync.join();
if (!c.expired()) {
auto Client = c.lock();
OnDisconnect(c, Client->GetStatus() == -2);
} else {
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(Packet);
//(void)Respond(Client, Packet, true);
}
void TNetwork::OnDisconnect(const std::weak_ptr<TClient>& ClientPtr, bool kicked) {
Assert(!ClientPtr.expired());
auto LockedClientPtr = ClientPtr.lock();
TClient& c = *LockedClientPtr;
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, Packet, false, true);
}
if (kicked)
Packet = ("L") + c.GetName() + (" was kicked!");
else
Packet = ("L") + c.GetName() + (" left the server!");
SendToAll(&c, Packet, false, true);
Packet.clear();
TriggerLuaEvent(("onPlayerDisconnect"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID() } }), false);
if (c.GetTCPSock())
CloseSocketProper(c.GetTCPSock());
if (c.GetDownSock())
CloseSocketProper(c.GetDownSock());
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) {
Assert(!c.expired());
info("Client connected");
auto LockedClient = c.lock();
LockedClient->SetID(OpenID());
info("Assigned ID " + std::to_string(LockedClient->GetID()) + " to " + LockedClient->GetName());
TriggerLuaEvent("onPlayerConnecting", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
SyncResources(*LockedClient);
if (LockedClient->GetStatus() < 0)
return;
(void)Respond(*LockedClient, "M" + Application::Settings.MapName, true); //Send the Map on connect
info(LockedClient->GetName() + " : Connected");
TriggerLuaEvent("onPlayerJoining", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
}
void TNetwork::SyncResources(TClient& c) {
#ifndef DEBUG
try {
#endif
if (!TCPSend(c, "P" + std::to_string(c.GetID()))) {
// TODO handle
}
std::string Data;
while (c.GetStatus() > -1) {
Data = TCPRcv(c);
if (Data == "Done")
break;
Parse(c, Data);
}
#ifndef DEBUG
} catch (std::exception& e) {
error("Exception! : " + std::string(e.what()));
c.SetStatus(-1);
}
#endif
}
void TNetwork::Parse(TClient& c, const std::string& Packet) {
if (Packet.empty())
return;
char Code = Packet.at(0), SubCode = 0;
if (Packet.length() > 1)
SubCode = Packet.at(1);
switch (Code) {
case 'f':
SendFile(c, Packet.substr(1));
return;
case 'S':
if (SubCode == 'R') {
debug("Sending Mod Info");
std::string ToSend = mResourceManager.FileList() + mResourceManager.FileSizes();
if (ToSend.empty())
ToSend = "-";
if (!TCPSend(c, ToSend)) {
// TODO: error
}
}
return;
default:
return;
}
}
void TNetwork::SendFile(TClient& c, const std::string& Name) {
info(c.GetName() + " requesting : " + Name.substr(Name.find_last_of('/')));
if (!std::filesystem::exists(Name)) {
if (!TCPSend(c, "CO")) {
// TODO: handle
}
warn("File " + Name + " could not be accessed!");
return;
} else {
if (!TCPSend(c, "AG")) {
// TODO: handle
}
}
///Wait for connections
int T = 0;
while (c.GetDownSock() < 1 && T < 50) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
T++;
}
if (c.GetDownSock() < 1) {
error("Client doesn't have a download socket!");
if (c.GetStatus() > -1)
c.SetStatus(-1);
return;
}
size_t Size = size_t(std::filesystem::file_size(Name)), MSize = Size / 2;
std::thread SplitThreads[2] {
std::thread([&] {
SplitLoad(c, 0, MSize, false, Name);
}),
std::thread([&] {
SplitLoad(c, MSize, Size, true, Name);
})
};
for (auto& SplitThread : SplitThreads) {
if (SplitThread.joinable()) {
SplitThread.join();
}
}
}
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 = 0x7735940; //125MB
char* Data;
if (Size > Split)
Data = new char[Split];
else
Data = new char[Size];
SOCKET TCPSock;
if (D)
TCPSock = c.GetDownSock();
else
TCPSock = c.GetTCPSock();
info("Split load Socket " + std::to_string(TCPSock));
while (c.GetStatus() > -1 && Sent < Size) {
size_t Diff = Size - Sent;
if (Diff > Split) {
f.seekg(Sent, std::ios_base::beg);
f.read(Data, Split);
if (!TCPSendRaw(c, TCPSock, Data, Split)) {
if (c.GetStatus() > -1)
c.SetStatus(-1);
break;
}
Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(Data, Diff);
if (!TCPSendRaw(c, TCPSock, Data, int32_t(Diff))) {
if (c.GetStatus() > -1)
c.SetStatus(-1);
break;
}
Sent += Diff;
}
}
delete[] Data;
f.close();
}
bool TNetwork::TCPSendRaw(TClient& C, SOCKET socket, char* Data, int32_t Size) {
intmax_t Sent = 0;
do {
intmax_t Temp = send(socket, &Data[Sent], int(Size - Sent), 0);
if (Temp < 1) {
info("Socket Closed! " + std::to_string(socket));
CloseSocketProper(socket);
return false;
}
Sent += Temp;
C.UpdatePingTime();
} while (Sent < Size);
return true;
}
bool TNetwork::SendLarge(TClient& c, std::string Data, bool isSync) {
if (Data.length() > 400) {
std::string CMP(Comp(Data));
Data = "ABG:" + CMP;
}
return TCPSend(c, Data, isSync);
}
bool TNetwork::Respond(TClient& c, const std::string& 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.length() > 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, ("Sn") + LockedClient->GetName(), true)) {
return false;
}
// ignore error
(void)SendToAll(LockedClient.get(), ("JWelcome ") + LockedClient->GetName() + "!", false, true);
TriggerLuaEvent(("onPlayerJoin"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID() } }), false);
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->GetStatus() < 0) {
Return = true;
res = false;
return false;
}
res = Respond(*LockedClient, v.Data(), true, true);
}
}
return true;
});
LockedClient->SetIsSyncing(false);
if (Return) {
return res;
}
LockedClient->SetIsSynced(true);
info(LockedClient->GetName() + (" is now synced!"));
return true;
}
void TNetwork::SendToAll(TClient* c, const std::string& Data, bool Self, bool Rel) {
if (!Self)
Assert(c);
char C = Data.at(0);
bool ret = true;
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 (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.length() > 1000) {
if (Data.length() > 400) {
std::string CMP(Comp(Data));
Client->EnqueuePacket("ABG:" + CMP);
} 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::string Data) const {
if (!Client.IsConnected() || Client.GetStatus() < 0) {
// 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;
}
sockaddr_in Addr = Client.GetUDPAddr();
auto AddrSize = sizeof(Client.GetUDPAddr());
if (Data.length() > 400) {
std::string CMP(Comp(Data));
Data = "ABG:" + CMP;
}
#ifdef WIN32
int sendOk;
int len = static_cast<int>(Data.size());
#else
int64_t sendOk;
size_t len = Data.size();
#endif // WIN32
sendOk = sendto(mUDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, int(AddrSize));
#ifdef WIN32
if (sendOk == -1) {
debug(("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
if (Client.GetStatus() > -1)
Client.SetStatus(-1);
return false;
} else if (sendOk == 0) {
debug(("(UDP) sendto returned 0"));
if (Client.GetStatus() > -1)
Client.SetStatus(-1);
return false;
}
#else // unix
if (sendOk == -1) {
debug(("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
if (Client.GetStatus() > -1)
Client.SetStatus(-1);
return false;
} else if (sendOk == 0) {
debug(("(UDP) sendto returned 0"));
if (Client.GetStatus() > -1)
Client.SetStatus(-1);
return false;
}
#endif // WIN32
return true;
}
std::string TNetwork::UDPRcvFromClient(sockaddr_in& client) const {
size_t clientLength = sizeof(client);
std::array<char, 1024> Ret {};
#ifdef WIN32
auto Rcv = recvfrom(mUDPSock, Ret.data(), int(Ret.size()), 0, (sockaddr*)&client, (int*)&clientLength);
#else // unix
int64_t Rcv = recvfrom(mUDPSock, Ret.data(), Ret.size(), 0, (sockaddr*)&client, (socklen_t*)&clientLength);
#endif // WIN32
if (Rcv == -1) {
#ifdef WIN32
error(("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
#else // unix
error(("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
#endif // WIN32
return "";
}
return std::string(Ret.begin(), Ret.begin() + Rcv);
}

66
src/TPPSMonitor.cpp Normal file
View File

@@ -0,0 +1,66 @@
#include "TPPSMonitor.h"
#include "Client.h"
#include "TNetwork.h"
TPPSMonitor::TPPSMonitor(TServer& Server)
: mServer(Server) {
Application::SetPPS("-");
Application::RegisterShutdownHandler([&] {
if (mThread.joinable()) {
debug("shutting down PPSMonitor");
mShutdown = true;
mThread.join();
debug("shut down PPSMonitor");
}
});
Start();
}
void TPPSMonitor::operator()() {
RegisterThread("PPSMonitor");
while (!mNetwork) {
// hard spi
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
info("PPSMonitor starting");
std::vector<std::shared_ptr<TClient>> TimedOutClients;
while (!mShutdown) {
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() > (5 * 60)) {
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 >5 min)");
}
TimedOutClients.clear();
if (C == 0 || mInternalPPS == 0) {
Application::SetPPS("-");
} else {
int R = (mInternalPPS / C) / V;
Application::SetPPS(std::to_string(R));
}
mInternalPPS = 0;
}
}

32
src/TResourceManager.cpp Normal file
View File

@@ -0,0 +1,32 @@
#include "TResourceManager.h"
#include <algorithm>
#include <filesystem>
namespace fs = std::filesystem;
TResourceManager::TResourceManager() {
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 += File + ';';
mFileSizes += std::to_string(size_t(fs::file_size(entry.path()))) + ';';
mMaxModSize += size_t(fs::file_size(entry.path()));
mModsLoaded++;
}
}
}
if (mModsLoaded)
info("Loaded " + std::to_string(mModsLoaded) + " Mods");
}

365
src/TServer.cpp Normal file
View File

@@ -0,0 +1,365 @@
#include "TServer.h"
#include "Client.h"
#include "Common.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include <TLuaFile.h>
#include <any>
#include <sstream>
#undef GetObject //Fixes Windows
#include "Json.h"
namespace json = rapidjson;
TServer::TServer(int argc, char** argv) {
info("BeamMP Server v" + Application::ServerVersion());
if (argc > 1) {
Application::Settings.CustomIP = argv[1];
size_t n = std::count(Application::Settings.CustomIP.begin(), Application::Settings.CustomIP.end(), '.');
auto p = Application::Settings.CustomIP.find_first_not_of(".0123456789");
if (p != std::string::npos || n != 3 || Application::Settings.CustomIP.substr(0, 3) == "127") {
Application::Settings.CustomIP.clear();
warn("IP Specified is invalid! Ignoring");
} else {
info("server started with custom IP");
}
}
}
void TServer::RemoveClient(const std::weak_ptr<TClient>& WeakClientPtr) {
if (!WeakClientPtr.expired()) {
TClient& Client = *WeakClientPtr.lock();
debug("removing client " + Client.GetName() + " (" + std::to_string(ClientCount()) + ")");
Client.ClearCars();
WriteLock Lock(mClientsMutex);
mClients.erase(WeakClientPtr.lock());
}
}
std::weak_ptr<TClient> TServer::InsertNewClient() {
debug("inserting new client (" + std::to_string(ClientCount()) + ")");
WriteLock Lock(mClientsMutex);
auto [Iter, Replaced] = mClients.insert(std::make_shared<TClient>(*this));
return *Iter;
}
void TServer::ForEachClient(const std::function<bool(std::weak_ptr<TClient>)>& Fn) {
decltype(mClients) Clients;
{
ReadLock lock(mClientsMutex);
Clients = mClients;
}
for (auto& Client : Clients) {
if (!Fn(Client)) {
break;
}
}
}
size_t TServer::ClientCount() const {
ReadLock Lock(mClientsMutex);
return mClients.size();
}
void TServer::GlobalParser(const std::weak_ptr<TClient>& Client, std::string Packet, TPPSMonitor& PPSMonitor, TNetwork& Network) {
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
abort();
}
if (Packet.substr(0, 4) == "ABG:") {
Packet = DeComp(Packet.substr(4));
}
if (Packet.empty()) {
return;
}
if (Client.expired()) {
return;
}
auto LockedClient = Client.lock();
std::any Res;
char Code = Packet.at(0);
//V to Z
if (Code <= 90 && Code >= 86) {
PPSMonitor.IncrementInternalPPS();
Network.SendToAll(LockedClient.get(), Packet, false, false);
return;
}
switch (Code) {
case 'H': // initial connection
#ifdef DEBUG
debug(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
#endif
if (!Network.SyncClient(Client)) {
// TODO handle
}
return;
case 'p':
if (!Network.Respond(*LockedClient, ("p"), false)) {
// failed to send
if (LockedClient->GetStatus() > -1) {
LockedClient->SetStatus(-1);
}
} else {
Network.UpdatePlayer(*LockedClient);
}
return;
case 'O':
if (Packet.length() > 1000) {
debug(("Received data from: ") + LockedClient->GetName() + (" Size: ") + std::to_string(Packet.length()));
}
ParseVehicle(*LockedClient, Packet, Network);
return;
case 'J':
#ifdef DEBUG
debug(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
Network.SendToAll(LockedClient.get(), Packet, false, true);
return;
case 'C':
#ifdef DEBUG
debug(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break;
Res = TriggerLuaEvent("onChatMessage", false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { LockedClient->GetID(), LockedClient->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }), true);
if (std::any_cast<int>(Res))
break;
Network.SendToAll(nullptr, Packet, true, true);
return;
case 'E':
#ifdef DEBUG
debug(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
HandleEvent(*LockedClient, Packet);
return;
case 'N':
debug("got 'N' packet (" + std::to_string(Packet.size()) + ")");
Network.SendToAll(LockedClient.get(), Packet, false, true);
default:
return;
}
}
void TServer::HandleEvent(TClient& c, const std::string& Data) {
std::stringstream ss(Data);
std::string t, Name;
int a = 0;
while (std::getline(ss, t, ':')) {
switch (a) {
case 1:
Name = t;
break;
case 2:
TriggerLuaEvent(Name, false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), t } }), false);
break;
default:
break;
}
if (a == 2)
break;
a++;
}
}
bool TServer::IsUnicycle(TClient& c, const std::string& CarJson) {
rapidjson::Document Car;
Car.Parse(CarJson.c_str(), CarJson.size());
if (Car.HasParseError()) {
error("Failed to parse vehicle data -> " + CarJson);
} else if (Car["jbm"].IsString() && std::string(Car["jbm"].GetString()) == "unicycle") {
return true;
}
return false;
}
bool TServer::ShouldSpawn(TClient& c, const std::string& CarJson, int ID) {
if (c.GetUnicycleID() > -1 && (c.GetCarCount() - 1) < Application::Settings.MaxCars) {
return true;
}
if (IsUnicycle(c, CarJson)) {
c.SetUnicycleID(ID);
return true;
}
return Application::Settings.MaxCars > c.GetCarCount();
}
void TServer::ParseVehicle(TClient& c, const std::string& Pckt, TNetwork& Network) {
if (Pckt.length() < 4)
return;
std::string Packet = Pckt;
char Code = Packet.at(1);
int PID = -1;
int VID = -1, Pos;
std::string Data = Packet.substr(3), pid, vid;
switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
case 's':
#ifdef DEBUG
debug(std::string(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
if (Data.at(0) == '0') {
int CarID = c.GetOpenCarID();
debug(c.GetName() + (" created a car with ID ") + std::to_string(CarID));
std::string CarJson = Packet.substr(5);
Packet = "Os:" + c.GetRoles() + ":" + c.GetName() + ":" + std::to_string(c.GetID()) + "-" + std::to_string(CarID) + ":" + CarJson;
auto Res = TriggerLuaEvent(("onVehicleSpawn"), false, nullptr, std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), CarID, Packet.substr(3) } }), true);
if (ShouldSpawn(c, CarJson, CarID) && std::any_cast<int>(Res) == 0) {
c.AddNewCar(CarID, Packet);
Network.SendToAll(nullptr, Packet, true, true);
} else {
if (!Network.Respond(c, Packet, true)) {
// TODO: handle
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(CarID);
if (!Network.Respond(c, Destroy, true)) {
// TODO: handle
}
debug(c.GetName() + (" (force : car limit/lua) removed ID ") + std::to_string(CarID));
}
}
return;
case 'c':
#ifdef DEBUG
debug(std::string(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid);
VID = stoi(vid);
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
auto Res = TriggerLuaEvent(("onVehicleEdited"), false, nullptr,
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Packet.substr(3) } }),
true);
auto FoundPos = Packet.find('{');
FoundPos = FoundPos == std::string::npos ? 0 : FoundPos; // attempt at sanitizing this
if ((c.GetUnicycleID() != VID || IsUnicycle(c, Packet.substr(FoundPos)))
&& std::any_cast<int>(Res) == 0) {
Network.SendToAll(&c, Packet, false, true);
Apply(c, VID, Packet);
} else {
if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1);
}
std::string Destroy = "Od:" + std::to_string(c.GetID()) + "-" + std::to_string(VID);
if (!Network.Respond(c, Destroy, true)) {
// TODO: handle
}
c.DeleteCar(VID);
}
}
return;
case 'd':
#ifdef DEBUG
debug(std::string(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid);
VID = stoi(vid);
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
if (c.GetUnicycleID() == VID) {
c.SetUnicycleID(-1);
}
Network.SendToAll(nullptr, Packet, true, true);
TriggerLuaEvent(("onVehicleDeleted"), false, nullptr,
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID } }), false);
c.DeleteCar(VID);
debug(c.GetName() + (" deleted car with ID ") + std::to_string(VID));
}
return;
case 'r':
#ifdef DEBUG
debug(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
Pos = int(Data.find('-'));
pid = Data.substr(0, Pos++);
vid = Data.substr(Pos, Data.find(':') - Pos);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid);
VID = stoi(vid);
}
if (PID != -1 && VID != -1 && PID == c.GetID()) {
Data = Data.substr(Data.find('{'));
TriggerLuaEvent("onVehicleReset", false, nullptr,
std::make_unique<TLuaArg>(TLuaArg { { c.GetID(), VID, Data } }),
false);
Network.SendToAll(&c, Packet, false, true);
}
return;
case 't':
#ifdef DEBUG
debug(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
Network.SendToAll(&c, Packet, false, true);
return;
default:
#ifdef DEBUG
warn(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
#endif // DEBUG
return;
}
}
void TServer::Apply(TClient& c, int VID, const std::string& pckt) {
auto FoundPos = pckt.find('{');
if (FoundPos == std::string::npos) {
error("Malformed packet received, no '{' found");
return;
}
std::string Packet = pckt.substr(FoundPos);
std::string VD = c.GetCarData(VID);
if (VD.empty()) {
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) {
error("Malformed packet received, no '{' found");
return;
}
VD = VD.substr(FoundPos);
rapidjson::Document Veh, Pack;
Veh.Parse(VD.c_str());
if (Veh.HasParseError()) {
error("Could not get vehicle config!");
return;
}
Pack.Parse(Packet.c_str());
if (Pack.HasParseError() || Pack.IsNull()) {
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) {
debug("inserting client (" + std::to_string(ClientCount()) + ")");
WriteLock Lock(mClientsMutex); //TODO why is there 30+ threads locked here
(void)mClients.insert(NewClient);
}

18
src/VehicleData.cpp Normal file
View File

@@ -0,0 +1,18 @@
#include "VehicleData.h"
#include <utility>
#include "Common.h"
TVehicleData::TVehicleData(int ID, std::string Data)
: mID(ID)
, mData(std::move(Data)) {
#ifdef DEBUG
debug("vehicle " + std::to_string(mID) + " constructed");
#endif
}
TVehicleData::~TVehicleData() {
#ifdef DEBUG
debug("vehicle " + std::to_string(mID) + " destroyed");
#endif
}

View File

@@ -1,119 +0,0 @@
//
// Created by Anonymous275 on 1/28/2020.
//
#include "main.h"
#include <iostream>
#include <fstream>
#include <string>
#include "logger.h"
using namespace std; //nameSpace STD
void GenerateConfig();
string RemoveComments(string Line);
string convertToString(char* a, int size);
void SetValues(string Line, int Index);
void SetMainValues(bool D,int P,string Name,string serverName);
bool D;
int P;
string M;
string S;
//Generates or Reads Config
void ParseConfig(){
ifstream InFileStream;
InFileStream.open("Server.cfg");
if(InFileStream.good()){ //Checks if Config Exists
info("Config Found Updating Values");
string line;
int index = 1;
while (getline(InFileStream, line)) {
if(line.rfind('#', 0) != 0){ //Checks if it starts as Comment
string CleanLine = RemoveComments(line); //Cleans it from the Comments
SetValues(CleanLine,index); //sets the values
index++;
}
}
SetMainValues(D,P,M,S); //gives the values to Main
}else{
info("Config Not Found Generating A new One");
GenerateConfig();
}
InFileStream.close();
}
void SetValues(string Line, int Index) {
int i = 0, state = 0;
char Data[50] = "";
bool Switch = false;
if (Index > 2) { Switch = true; }
for (char &c : Line) {
if (Switch) {
if (c == '\"') { state++; }
if (state > 0 && state < 2) {
Data[i] = c;
i++;
}
} else {
if (c == ' ') { state++; }
if (state > 1) {
Data[i] = c;
i++;
}
}
}
for (int C = 1; C <= i; C++){
Data[C-1] = Data[C];
}
string::size_type sz;
bool Boolean = (convertToString(Data,i-1).find("true") != string::npos);//searches for "true"
switch (Index){
case 1 :
if(Boolean){D = true;}else{D = false;}//checks and sets the Debug Value
break;
case 2 : P = stoi(Data, &sz);//sets the Port
break;
case 3 : M = Data; //Map
break;
case 4 : S = Data; //Name
}
}
//generates default Config
void GenerateConfig(){
ofstream FileStream;
FileStream.open ("Server.cfg");
FileStream << "# This is the BeamNG-MP Server Configuration File\n"
"Debug = false # true or false to enable debug console output\n"
"Port = 30813 # Port to run the server on\n"
"Map = \"levels/gridmap/level.json\"\n"
"Name = \"BeamNG-MP FTW\"";
FileStream.close();
}
string RemoveComments(string Line){
int i = 0;
char Data[50] = "";
for(char& c : Line) {
if(c == '#'){break;} //when it finds the # it will stop
Data[i] = c;
i++;
}
return convertToString(Data,i); //Converts it from a char array to string and returns it
}
//Converts a char array or pointer to string
string convertToString(char* a, int size)
{
int i;
string s = "";
for (i = 0; i < size; i++) {
s = s + a[i];
}
return s;
}

View File

@@ -1,27 +0,0 @@
/**
@file callbacks.h
@brief ENet callbacks
*/
#ifndef __ENET_CALLBACKS_H__
#define __ENET_CALLBACKS_H__
#include <stdlib.h>
typedef struct _ENetCallbacks
{
void * (ENET_CALLBACK * malloc) (size_t size);
void (ENET_CALLBACK * free) (void * memory);
void (ENET_CALLBACK * no_memory) (void);
} ENetCallbacks;
/** @defgroup callbacks ENet internal callbacks
@{
@ingroup private
*/
extern void * enet_malloc (size_t);
extern void enet_free (void *);
/** @} */
#endif /* __ENET_CALLBACKS_H__ */

View File

@@ -1,607 +0,0 @@
/**
@file enet.h
@brief ENet public header file
*/
#ifndef __ENET_ENET_H__
#define __ENET_ENET_H__
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdlib.h>
#ifdef _WIN32
#include "enet/win32.h"
#else
#include "enet/unix.h"
#endif
#include "enet/types.h"
#include "enet/protocol.h"
#include "enet/list.h"
#include "enet/callbacks.h"
#define ENET_VERSION_MAJOR 1
#define ENET_VERSION_MINOR 3
#define ENET_VERSION_PATCH 14
#define ENET_VERSION_CREATE(major, minor, patch) (((major)<<16) | ((minor)<<8) | (patch))
#define ENET_VERSION_GET_MAJOR(version) (((version)>>16)&0xFF)
#define ENET_VERSION_GET_MINOR(version) (((version)>>8)&0xFF)
#define ENET_VERSION_GET_PATCH(version) ((version)&0xFF)
#define ENET_VERSION ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH)
typedef enet_uint32 ENetVersion;
struct _ENetHost;
struct _ENetEvent;
struct _ENetPacket;
typedef enum _ENetSocketType
{
ENET_SOCKET_TYPE_STREAM = 1,
ENET_SOCKET_TYPE_DATAGRAM = 2
} ENetSocketType;
typedef enum _ENetSocketWait
{
ENET_SOCKET_WAIT_NONE = 0,
ENET_SOCKET_WAIT_SEND = (1 << 0),
ENET_SOCKET_WAIT_RECEIVE = (1 << 1),
ENET_SOCKET_WAIT_INTERRUPT = (1 << 2)
} ENetSocketWait;
typedef enum _ENetSocketOption
{
ENET_SOCKOPT_NONBLOCK = 1,
ENET_SOCKOPT_BROADCAST = 2,
ENET_SOCKOPT_RCVBUF = 3,
ENET_SOCKOPT_SNDBUF = 4,
ENET_SOCKOPT_REUSEADDR = 5,
ENET_SOCKOPT_RCVTIMEO = 6,
ENET_SOCKOPT_SNDTIMEO = 7,
ENET_SOCKOPT_ERROR = 8,
ENET_SOCKOPT_NODELAY = 9
} ENetSocketOption;
typedef enum _ENetSocketShutdown
{
ENET_SOCKET_SHUTDOWN_READ = 0,
ENET_SOCKET_SHUTDOWN_WRITE = 1,
ENET_SOCKET_SHUTDOWN_READ_WRITE = 2
} ENetSocketShutdown;
#define ENET_HOST_ANY 0
#define ENET_HOST_BROADCAST 0xFFFFFFFFU
#define ENET_PORT_ANY 0
/**
* Portable internet address structure.
*
* The host must be specified in network byte-order, and the port must be in host
* byte-order. The constant ENET_HOST_ANY may be used to specify the default
* server host. The constant ENET_HOST_BROADCAST may be used to specify the
* broadcast address (255.255.255.255). This makes sense for enet_host_connect,
* but not for enet_host_create. Once a server responds to a broadcast, the
* address is updated from ENET_HOST_BROADCAST to the server's actual IP address.
*/
typedef struct _ENetAddress
{
enet_uint32 host;
enet_uint16 port;
} ENetAddress;
/**
* Packet flag bit constants.
*
* The host must be specified in network byte-order, and the port must be in
* host byte-order. The constant ENET_HOST_ANY may be used to specify the
* default server host.
@sa ENetPacket
*/
typedef enum _ENetPacketFlag
{
/** packet must be received by the target peer and resend attempts should be
* made until the packet is delivered */
ENET_PACKET_FLAG_RELIABLE = (1 << 0),
/** packet will not be sequenced with other packets
* not supported for reliable packets
*/
ENET_PACKET_FLAG_UNSEQUENCED = (1 << 1),
/** packet will not allocate data, and user must supply it instead */
ENET_PACKET_FLAG_NO_ALLOCATE = (1 << 2),
/** packet will be fragmented using unreliable (instead of reliable) sends
* if it exceeds the MTU */
ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = (1 << 3),
/** whether the packet has been sent from all queues it has been entered into */
ENET_PACKET_FLAG_SENT = (1<<8)
} ENetPacketFlag;
typedef void (ENET_CALLBACK * ENetPacketFreeCallback) (struct _ENetPacket *);
/**
* ENet packet structure.
*
* An ENet data packet that may be sent to or received from a peer. The shown
* fields should only be read and never modified. The data field contains the
* allocated data for the packet. The dataLength fields specifies the length
* of the allocated data. The flags field is either 0 (specifying no flags),
* or a bitwise-or of any combination of the following flags:
*
* ENET_PACKET_FLAG_RELIABLE - packet must be received by the target peer
* and resend attempts should be made until the packet is delivered
*
* ENET_PACKET_FLAG_UNSEQUENCED - packet will not be sequenced with other packets
* (not supported for reliable packets)
*
* ENET_PACKET_FLAG_NO_ALLOCATE - packet will not allocate data, and user must supply it instead
*
* ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT - packet will be fragmented using unreliable
* (instead of reliable) sends if it exceeds the MTU
*
* ENET_PACKET_FLAG_SENT - whether the packet has been sent from all queues it has been entered into
@sa ENetPacketFlag
*/
typedef struct _ENetPacket
{
size_t referenceCount; /**< internal use only */
enet_uint32 flags; /**< bitwise-or of ENetPacketFlag constants */
enet_uint8 * data; /**< allocated data for packet */
size_t dataLength; /**< length of data */
ENetPacketFreeCallback freeCallback; /**< function to be called when the packet is no longer in use */
void * userData; /**< application private data, may be freely modified */
} ENetPacket;
typedef struct _ENetAcknowledgement
{
ENetListNode acknowledgementList;
enet_uint32 sentTime;
ENetProtocol command;
} ENetAcknowledgement;
typedef struct _ENetOutgoingCommand
{
ENetListNode outgoingCommandList;
enet_uint16 reliableSequenceNumber;
enet_uint16 unreliableSequenceNumber;
enet_uint32 sentTime;
enet_uint32 roundTripTimeout;
enet_uint32 roundTripTimeoutLimit;
enet_uint32 fragmentOffset;
enet_uint16 fragmentLength;
enet_uint16 sendAttempts;
ENetProtocol command;
ENetPacket * packet;
} ENetOutgoingCommand;
typedef struct _ENetIncomingCommand
{
ENetListNode incomingCommandList;
enet_uint16 reliableSequenceNumber;
enet_uint16 unreliableSequenceNumber;
ENetProtocol command;
enet_uint32 fragmentCount;
enet_uint32 fragmentsRemaining;
enet_uint32 * fragments;
ENetPacket * packet;
} ENetIncomingCommand;
typedef enum _ENetPeerState
{
ENET_PEER_STATE_DISCONNECTED = 0,
ENET_PEER_STATE_CONNECTING = 1,
ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2,
ENET_PEER_STATE_CONNECTION_PENDING = 3,
ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4,
ENET_PEER_STATE_CONNECTED = 5,
ENET_PEER_STATE_DISCONNECT_LATER = 6,
ENET_PEER_STATE_DISCONNECTING = 7,
ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8,
ENET_PEER_STATE_ZOMBIE = 9
} ENetPeerState;
#ifndef ENET_BUFFER_MAXIMUM
#define ENET_BUFFER_MAXIMUM (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS)
#endif
enum
{
ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024,
ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024,
ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000,
ENET_HOST_DEFAULT_MTU = 1400,
ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024,
ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024,
ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500,
ENET_PEER_DEFAULT_PACKET_THROTTLE = 32,
ENET_PEER_PACKET_THROTTLE_SCALE = 32,
ENET_PEER_PACKET_THROTTLE_COUNTER = 7,
ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2,
ENET_PEER_PACKET_THROTTLE_DECELERATION = 2,
ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000,
ENET_PEER_PACKET_LOSS_SCALE = (1 << 16),
ENET_PEER_PACKET_LOSS_INTERVAL = 10000,
ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024,
ENET_PEER_TIMEOUT_LIMIT = 32,
ENET_PEER_TIMEOUT_MINIMUM = 5000,
ENET_PEER_TIMEOUT_MAXIMUM = 30000,
ENET_PEER_PING_INTERVAL = 500,
ENET_PEER_UNSEQUENCED_WINDOWS = 64,
ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024,
ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32,
ENET_PEER_RELIABLE_WINDOWS = 16,
ENET_PEER_RELIABLE_WINDOW_SIZE = 0x1000,
ENET_PEER_FREE_RELIABLE_WINDOWS = 8
};
typedef struct _ENetChannel
{
enet_uint16 outgoingReliableSequenceNumber;
enet_uint16 outgoingUnreliableSequenceNumber;
enet_uint16 usedReliableWindows;
enet_uint16 reliableWindows [ENET_PEER_RELIABLE_WINDOWS];
enet_uint16 incomingReliableSequenceNumber;
enet_uint16 incomingUnreliableSequenceNumber;
ENetList incomingReliableCommands;
ENetList incomingUnreliableCommands;
} ENetChannel;
/**
* An ENet peer which data packets may be sent or received from.
*
* No fields should be modified unless otherwise specified.
*/
typedef struct _ENetPeer
{
ENetListNode dispatchList;
struct _ENetHost * host;
enet_uint16 outgoingPeerID;
enet_uint16 incomingPeerID;
enet_uint32 connectID;
enet_uint8 outgoingSessionID;
enet_uint8 incomingSessionID;
ENetAddress address; /**< Internet address of the peer */
void * data; /**< Application private data, may be freely modified */
ENetPeerState state;
ENetChannel * channels;
size_t channelCount; /**< Number of channels allocated for communication with peer */
enet_uint32 incomingBandwidth; /**< Downstream bandwidth of the client in bytes/second */
enet_uint32 outgoingBandwidth; /**< Upstream bandwidth of the client in bytes/second */
enet_uint32 incomingBandwidthThrottleEpoch;
enet_uint32 outgoingBandwidthThrottleEpoch;
enet_uint32 incomingDataTotal;
enet_uint32 outgoingDataTotal;
enet_uint32 lastSendTime;
enet_uint32 lastReceiveTime;
enet_uint32 nextTimeout;
enet_uint32 earliestTimeout;
enet_uint32 packetLossEpoch;
enet_uint32 packetsSent;
enet_uint32 packetsLost;
enet_uint32 packetLoss; /**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE */
enet_uint32 packetLossVariance;
enet_uint32 packetThrottle;
enet_uint32 packetThrottleLimit;
enet_uint32 packetThrottleCounter;
enet_uint32 packetThrottleEpoch;
enet_uint32 packetThrottleAcceleration;
enet_uint32 packetThrottleDeceleration;
enet_uint32 packetThrottleInterval;
enet_uint32 pingInterval;
enet_uint32 timeoutLimit;
enet_uint32 timeoutMinimum;
enet_uint32 timeoutMaximum;
enet_uint32 lastRoundTripTime;
enet_uint32 lowestRoundTripTime;
enet_uint32 lastRoundTripTimeVariance;
enet_uint32 highestRoundTripTimeVariance;
enet_uint32 roundTripTime; /**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgement */
enet_uint32 roundTripTimeVariance;
enet_uint32 mtu;
enet_uint32 windowSize;
enet_uint32 reliableDataInTransit;
enet_uint16 outgoingReliableSequenceNumber;
ENetList acknowledgements;
ENetList sentReliableCommands;
ENetList sentUnreliableCommands;
ENetList outgoingReliableCommands;
ENetList outgoingUnreliableCommands;
ENetList dispatchedCommands;
int needsDispatch;
enet_uint16 incomingUnsequencedGroup;
enet_uint16 outgoingUnsequencedGroup;
enet_uint32 unsequencedWindow [ENET_PEER_UNSEQUENCED_WINDOW_SIZE / 32];
enet_uint32 eventData;
size_t totalWaitingData;
} ENetPeer;
/** An ENet packet compressor for compressing UDP packets before socket sends or receives.
*/
typedef struct _ENetCompressor
{
/** Context data for the compressor. Must be non-NULL. */
void * context;
/** Compresses from inBuffers[0:inBufferCount-1], containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */
size_t (ENET_CALLBACK * compress) (void * context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit);
/** Decompresses from inData, containing inLimit bytes, to outData, outputting at most outLimit bytes. Should return 0 on failure. */
size_t (ENET_CALLBACK * decompress) (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit);
/** Destroys the context when compression is disabled or the host is destroyed. May be NULL. */
void (ENET_CALLBACK * destroy) (void * context);
} ENetCompressor;
/** Callback that computes the checksum of the data held in buffers[0:bufferCount-1] */
typedef enet_uint32 (ENET_CALLBACK * ENetChecksumCallback) (const ENetBuffer * buffers, size_t bufferCount);
/** Callback for intercepting received raw UDP packets. Should return 1 to intercept, 0 to ignore, or -1 to propagate an error. */
typedef int (ENET_CALLBACK * ENetInterceptCallback) (struct _ENetHost * host, struct _ENetEvent * event);
/** An ENet host for communicating with peers.
*
* No fields should be modified unless otherwise stated.
@sa enet_host_create()
@sa enet_host_destroy()
@sa enet_host_connect()
@sa enet_host_service()
@sa enet_host_flush()
@sa enet_host_broadcast()
@sa enet_host_compress()
@sa enet_host_compress_with_range_coder()
@sa enet_host_channel_limit()
@sa enet_host_bandwidth_limit()
@sa enet_host_bandwidth_throttle()
*/
typedef struct _ENetHost
{
ENetSocket socket;
ENetAddress address; /**< Internet address of the host */
enet_uint32 incomingBandwidth; /**< downstream bandwidth of the host */
enet_uint32 outgoingBandwidth; /**< upstream bandwidth of the host */
enet_uint32 bandwidthThrottleEpoch;
enet_uint32 mtu;
enet_uint32 randomSeed;
int recalculateBandwidthLimits;
ENetPeer * peers; /**< array of peers allocated for this host */
size_t peerCount; /**< number of peers allocated for this host */
size_t channelLimit; /**< maximum number of channels allowed for connected peers */
enet_uint32 serviceTime;
ENetList dispatchQueue;
int continueSending;
size_t packetSize;
enet_uint16 headerFlags;
ENetProtocol commands [ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS];
size_t commandCount;
ENetBuffer buffers [ENET_BUFFER_MAXIMUM];
size_t bufferCount;
ENetChecksumCallback checksum; /**< callback the user can set to enable packet checksums for this host */
ENetCompressor compressor;
enet_uint8 packetData [2][ENET_PROTOCOL_MAXIMUM_MTU];
ENetAddress receivedAddress;
enet_uint8 * receivedData;
size_t receivedDataLength;
enet_uint32 totalSentData; /**< total data sent, user should reset to 0 as needed to prevent overflow */
enet_uint32 totalSentPackets; /**< total UDP packets sent, user should reset to 0 as needed to prevent overflow */
enet_uint32 totalReceivedData; /**< total data received, user should reset to 0 as needed to prevent overflow */
enet_uint32 totalReceivedPackets; /**< total UDP packets received, user should reset to 0 as needed to prevent overflow */
ENetInterceptCallback intercept; /**< callback the user can set to intercept received raw UDP packets */
size_t connectedPeers;
size_t bandwidthLimitedPeers;
size_t duplicatePeers; /**< optional number of allowed peers from duplicate IPs, defaults to ENET_PROTOCOL_MAXIMUM_PEER_ID */
size_t maximumPacketSize; /**< the maximum allowable packet size that may be sent or received on a peer */
size_t maximumWaitingData; /**< the maximum aggregate amount of buffer space a peer may use waiting for packets to be delivered */
} ENetHost;
/**
* An ENet event type, as specified in @ref ENetEvent.
*/
typedef enum _ENetEventType
{
/** no event occurred within the specified time limit */
ENET_EVENT_TYPE_NONE = 0,
/** a connection request initiated by enet_host_connect has completed.
* The peer field contains the peer which successfully connected.
*/
ENET_EVENT_TYPE_CONNECT = 1,
/** a peer has disconnected. This event is generated on a successful
* completion of a disconnect initiated by enet_peer_disconnect, if
* a peer has timed out, or if a connection request intialized by
* enet_host_connect has timed out. The peer field contains the peer
* which disconnected. The data field contains user supplied data
* describing the disconnection, or 0, if none is available.
*/
ENET_EVENT_TYPE_DISCONNECT = 2,
/** a packet has been received from a peer. The peer field specifies the
* peer which sent the packet. The channelID field specifies the channel
* number upon which the packet was received. The packet field contains
* the packet that was received; this packet must be destroyed with
* enet_packet_destroy after use.
*/
ENET_EVENT_TYPE_RECEIVE = 3
} ENetEventType;
/**
* An ENet event as returned by enet_host_service().
@sa enet_host_service
*/
typedef struct _ENetEvent
{
ENetEventType type; /**< type of the event */
ENetPeer * peer; /**< peer that generated a connect, disconnect or receive event */
enet_uint8 channelID; /**< channel on the peer that generated the event, if appropriate */
enet_uint32 data; /**< data associated with the event, if appropriate */
ENetPacket * packet; /**< packet associated with the event, if appropriate */
} ENetEvent;
/** @defgroup global ENet global functions
@{
*/
/**
Initializes ENet globally. Must be called prior to using any functions in
ENet.
@returns 0 on success, < 0 on failure
*/
ENET_API int enet_initialize (void);
/**
Initializes ENet globally and supplies user-overridden callbacks. Must be called prior to using any functions in ENet. Do not use enet_initialize() if you use this variant. Make sure the ENetCallbacks structure is zeroed out so that any additional callbacks added in future versions will be properly ignored.
@param version the constant ENET_VERSION should be supplied so ENet knows which version of ENetCallbacks struct to use
@param inits user-overridden callbacks where any NULL callbacks will use ENet's defaults
@returns 0 on success, < 0 on failure
*/
ENET_API int enet_initialize_with_callbacks (ENetVersion version, const ENetCallbacks * inits);
/**
Shuts down ENet globally. Should be called when a program that has
initialized ENet exits.
*/
ENET_API void enet_deinitialize (void);
/**
Gives the linked version of the ENet library.
@returns the version number
*/
ENET_API ENetVersion enet_linked_version (void);
/** @} */
/** @defgroup private ENet private implementation functions */
/**
Returns the wall-time in milliseconds. Its initial value is unspecified
unless otherwise set.
*/
ENET_API enet_uint32 enet_time_get (void);
/**
Sets the current wall-time in milliseconds.
*/
ENET_API void enet_time_set (enet_uint32);
/** @defgroup socket ENet socket functions
@{
*/
ENET_API ENetSocket enet_socket_create (ENetSocketType);
ENET_API int enet_socket_bind (ENetSocket, const ENetAddress *);
ENET_API int enet_socket_get_address (ENetSocket, ENetAddress *);
ENET_API int enet_socket_listen (ENetSocket, int);
ENET_API ENetSocket enet_socket_accept (ENetSocket, ENetAddress *);
ENET_API int enet_socket_connect (ENetSocket, const ENetAddress *);
ENET_API int enet_socket_send (ENetSocket, const ENetAddress *, const ENetBuffer *, size_t);
ENET_API int enet_socket_receive (ENetSocket, ENetAddress *, ENetBuffer *, size_t);
ENET_API int enet_socket_wait (ENetSocket, enet_uint32 *, enet_uint32);
ENET_API int enet_socket_set_option (ENetSocket, ENetSocketOption, int);
ENET_API int enet_socket_get_option (ENetSocket, ENetSocketOption, int *);
ENET_API int enet_socket_shutdown (ENetSocket, ENetSocketShutdown);
ENET_API void enet_socket_destroy (ENetSocket);
ENET_API int enet_socketset_select (ENetSocket, ENetSocketSet *, ENetSocketSet *, enet_uint32);
/** @} */
/** @defgroup Address ENet address functions
@{
*/
/** Attempts to parse the printable form of the IP address in the parameter hostName
and sets the host field in the address parameter if successful.
@param address destination to store the parsed IP address
@param hostName IP address to parse
@retval 0 on success
@retval < 0 on failure
@returns the address of the given hostName in address on success
*/
ENET_API int enet_address_set_host_ip (ENetAddress * address, const char * hostName);
/** Attempts to resolve the host named by the parameter hostName and sets
the host field in the address parameter if successful.
@param address destination to store resolved address
@param hostName host name to lookup
@retval 0 on success
@retval < 0 on failure
@returns the address of the given hostName in address on success
*/
ENET_API int enet_address_set_host (ENetAddress * address, const char * hostName);
/** Gives the printable form of the IP address specified in the address parameter.
@param address address printed
@param hostName destination for name, must not be NULL
@param nameLength maximum length of hostName.
@returns the null-terminated name of the host in hostName on success
@retval 0 on success
@retval < 0 on failure
*/
ENET_API int enet_address_get_host_ip (const ENetAddress * address, char * hostName, size_t nameLength);
/** Attempts to do a reverse lookup of the host field in the address parameter.
@param address address used for reverse lookup
@param hostName destination for name, must not be NULL
@param nameLength maximum length of hostName.
@returns the null-terminated name of the host in hostName on success
@retval 0 on success
@retval < 0 on failure
*/
ENET_API int enet_address_get_host (const ENetAddress * address, char * hostName, size_t nameLength);
/** @} */
ENET_API ENetPacket * enet_packet_create (const void *, size_t, enet_uint32);
ENET_API void enet_packet_destroy (ENetPacket *);
ENET_API int enet_packet_resize (ENetPacket *, size_t);
ENET_API enet_uint32 enet_crc32 (const ENetBuffer *, size_t);
ENET_API ENetHost * enet_host_create (const ENetAddress *, size_t, size_t, enet_uint32, enet_uint32);
ENET_API void enet_host_destroy (ENetHost *);
ENET_API ENetPeer * enet_host_connect (ENetHost *, const ENetAddress *, size_t, enet_uint32);
ENET_API int enet_host_check_events (ENetHost *, ENetEvent *);
ENET_API int enet_host_service (ENetHost *, ENetEvent *, enet_uint32);
ENET_API void enet_host_flush (ENetHost *);
ENET_API void enet_host_broadcast (ENetHost *, enet_uint8, ENetPacket *);
ENET_API void enet_host_compress (ENetHost *, const ENetCompressor *);
ENET_API int enet_host_compress_with_range_coder (ENetHost * host);
ENET_API void enet_host_channel_limit (ENetHost *, size_t);
ENET_API void enet_host_bandwidth_limit (ENetHost *, enet_uint32, enet_uint32);
extern void enet_host_bandwidth_throttle (ENetHost *);
extern enet_uint32 enet_host_random_seed (void);
ENET_API int enet_peer_send (ENetPeer *, enet_uint8, ENetPacket *);
ENET_API ENetPacket * enet_peer_receive (ENetPeer *, enet_uint8 * channelID);
ENET_API void enet_peer_ping (ENetPeer *);
ENET_API void enet_peer_ping_interval (ENetPeer *, enet_uint32);
ENET_API void enet_peer_timeout (ENetPeer *, enet_uint32, enet_uint32, enet_uint32);
ENET_API void enet_peer_reset (ENetPeer *);
ENET_API void enet_peer_disconnect (ENetPeer *, enet_uint32);
ENET_API void enet_peer_disconnect_now (ENetPeer *, enet_uint32);
ENET_API void enet_peer_disconnect_later (ENetPeer *, enet_uint32);
ENET_API void enet_peer_throttle_configure (ENetPeer *, enet_uint32, enet_uint32, enet_uint32);
extern int enet_peer_throttle (ENetPeer *, enet_uint32);
extern void enet_peer_reset_queues (ENetPeer *);
extern void enet_peer_setup_outgoing_command (ENetPeer *, ENetOutgoingCommand *);
extern ENetOutgoingCommand * enet_peer_queue_outgoing_command (ENetPeer *, const ENetProtocol *, ENetPacket *, enet_uint32, enet_uint16);
extern ENetIncomingCommand * enet_peer_queue_incoming_command (ENetPeer *, const ENetProtocol *, const void *, size_t, enet_uint32, enet_uint32);
extern ENetAcknowledgement * enet_peer_queue_acknowledgement (ENetPeer *, const ENetProtocol *, enet_uint16);
extern void enet_peer_dispatch_incoming_unreliable_commands (ENetPeer *, ENetChannel *);
extern void enet_peer_dispatch_incoming_reliable_commands (ENetPeer *, ENetChannel *);
extern void enet_peer_on_connect (ENetPeer *);
extern void enet_peer_on_disconnect (ENetPeer *);
ENET_API void * enet_range_coder_create (void);
ENET_API void enet_range_coder_destroy (void *);
ENET_API size_t enet_range_coder_compress (void *, const ENetBuffer *, size_t, size_t, enet_uint8 *, size_t);
ENET_API size_t enet_range_coder_decompress (void *, const enet_uint8 *, size_t, enet_uint8 *, size_t);
extern size_t enet_protocol_command_size (enet_uint8);
#ifdef __cplusplus
}
#endif
#endif /* __ENET_ENET_H__ */

View File

@@ -1,43 +0,0 @@
/**
@file list.h
@brief ENet list management
*/
#ifndef __ENET_LIST_H__
#define __ENET_LIST_H__
#include <stdlib.h>
typedef struct _ENetListNode
{
struct _ENetListNode * next;
struct _ENetListNode * previous;
} ENetListNode;
typedef ENetListNode * ENetListIterator;
typedef struct _ENetList
{
ENetListNode sentinel;
} ENetList;
extern void enet_list_clear (ENetList *);
extern ENetListIterator enet_list_insert (ENetListIterator, void *);
extern void * enet_list_remove (ENetListIterator);
extern ENetListIterator enet_list_move (ENetListIterator, void *, void *);
extern size_t enet_list_size (ENetList *);
#define enet_list_begin(list) ((list) -> sentinel.next)
#define enet_list_end(list) (& (list) -> sentinel)
#define enet_list_empty(list) (enet_list_begin (list) == enet_list_end (list))
#define enet_list_next(iterator) ((iterator) -> next)
#define enet_list_previous(iterator) ((iterator) -> previous)
#define enet_list_front(list) ((void *) (list) -> sentinel.next)
#define enet_list_back(list) ((void *) (list) -> sentinel.previous)
#endif /* __ENET_LIST_H__ */

View File

@@ -1,198 +0,0 @@
/**
@file protocol.h
@brief ENet protocol
*/
#ifndef __ENET_PROTOCOL_H__
#define __ENET_PROTOCOL_H__
#include "enet/types.h"
enum
{
ENET_PROTOCOL_MINIMUM_MTU = 576,
ENET_PROTOCOL_MAXIMUM_MTU = 4096,
ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32,
ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096,
ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536,
ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1,
ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255,
ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xFFF,
ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024
};
typedef enum _ENetProtocolCommand
{
ENET_PROTOCOL_COMMAND_NONE = 0,
ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1,
ENET_PROTOCOL_COMMAND_CONNECT = 2,
ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3,
ENET_PROTOCOL_COMMAND_DISCONNECT = 4,
ENET_PROTOCOL_COMMAND_PING = 5,
ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6,
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7,
ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8,
ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9,
ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10,
ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11,
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12,
ENET_PROTOCOL_COMMAND_COUNT = 13,
ENET_PROTOCOL_COMMAND_MASK = 0x0F
} ENetProtocolCommand;
typedef enum _ENetProtocolFlag
{
ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 << 7),
ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 << 6),
ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 << 14),
ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 << 15),
ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED | ENET_PROTOCOL_HEADER_FLAG_SENT_TIME,
ENET_PROTOCOL_HEADER_SESSION_MASK = (3 << 12),
ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12
} ENetProtocolFlag;
#ifdef _MSC_VER
#pragma pack(push, 1)
#define ENET_PACKED
#elif defined(__GNUC__) || defined(__clang__)
#define ENET_PACKED __attribute__ ((packed))
#else
#define ENET_PACKED
#endif
typedef struct _ENetProtocolHeader
{
enet_uint16 peerID;
enet_uint16 sentTime;
} ENET_PACKED ENetProtocolHeader;
typedef struct _ENetProtocolCommandHeader
{
enet_uint8 command;
enet_uint8 channelID;
enet_uint16 reliableSequenceNumber;
} ENET_PACKED ENetProtocolCommandHeader;
typedef struct _ENetProtocolAcknowledge
{
ENetProtocolCommandHeader header;
enet_uint16 receivedReliableSequenceNumber;
enet_uint16 receivedSentTime;
} ENET_PACKED ENetProtocolAcknowledge;
typedef struct _ENetProtocolConnect
{
ENetProtocolCommandHeader header;
enet_uint16 outgoingPeerID;
enet_uint8 incomingSessionID;
enet_uint8 outgoingSessionID;
enet_uint32 mtu;
enet_uint32 windowSize;
enet_uint32 channelCount;
enet_uint32 incomingBandwidth;
enet_uint32 outgoingBandwidth;
enet_uint32 packetThrottleInterval;
enet_uint32 packetThrottleAcceleration;
enet_uint32 packetThrottleDeceleration;
enet_uint32 connectID;
enet_uint32 data;
} ENET_PACKED ENetProtocolConnect;
typedef struct _ENetProtocolVerifyConnect
{
ENetProtocolCommandHeader header;
enet_uint16 outgoingPeerID;
enet_uint8 incomingSessionID;
enet_uint8 outgoingSessionID;
enet_uint32 mtu;
enet_uint32 windowSize;
enet_uint32 channelCount;
enet_uint32 incomingBandwidth;
enet_uint32 outgoingBandwidth;
enet_uint32 packetThrottleInterval;
enet_uint32 packetThrottleAcceleration;
enet_uint32 packetThrottleDeceleration;
enet_uint32 connectID;
} ENET_PACKED ENetProtocolVerifyConnect;
typedef struct _ENetProtocolBandwidthLimit
{
ENetProtocolCommandHeader header;
enet_uint32 incomingBandwidth;
enet_uint32 outgoingBandwidth;
} ENET_PACKED ENetProtocolBandwidthLimit;
typedef struct _ENetProtocolThrottleConfigure
{
ENetProtocolCommandHeader header;
enet_uint32 packetThrottleInterval;
enet_uint32 packetThrottleAcceleration;
enet_uint32 packetThrottleDeceleration;
} ENET_PACKED ENetProtocolThrottleConfigure;
typedef struct _ENetProtocolDisconnect
{
ENetProtocolCommandHeader header;
enet_uint32 data;
} ENET_PACKED ENetProtocolDisconnect;
typedef struct _ENetProtocolPing
{
ENetProtocolCommandHeader header;
} ENET_PACKED ENetProtocolPing;
typedef struct _ENetProtocolSendReliable
{
ENetProtocolCommandHeader header;
enet_uint16 dataLength;
} ENET_PACKED ENetProtocolSendReliable;
typedef struct _ENetProtocolSendUnreliable
{
ENetProtocolCommandHeader header;
enet_uint16 unreliableSequenceNumber;
enet_uint16 dataLength;
} ENET_PACKED ENetProtocolSendUnreliable;
typedef struct _ENetProtocolSendUnsequenced
{
ENetProtocolCommandHeader header;
enet_uint16 unsequencedGroup;
enet_uint16 dataLength;
} ENET_PACKED ENetProtocolSendUnsequenced;
typedef struct _ENetProtocolSendFragment
{
ENetProtocolCommandHeader header;
enet_uint16 startSequenceNumber;
enet_uint16 dataLength;
enet_uint32 fragmentCount;
enet_uint32 fragmentNumber;
enet_uint32 totalLength;
enet_uint32 fragmentOffset;
} ENET_PACKED ENetProtocolSendFragment;
typedef union _ENetProtocol
{
ENetProtocolCommandHeader header;
ENetProtocolAcknowledge acknowledge;
ENetProtocolConnect connect;
ENetProtocolVerifyConnect verifyConnect;
ENetProtocolDisconnect disconnect;
ENetProtocolPing ping;
ENetProtocolSendReliable sendReliable;
ENetProtocolSendUnreliable sendUnreliable;
ENetProtocolSendUnsequenced sendUnsequenced;
ENetProtocolSendFragment sendFragment;
ENetProtocolBandwidthLimit bandwidthLimit;
ENetProtocolThrottleConfigure throttleConfigure;
} ENET_PACKED ENetProtocol;
#ifdef _MSC_VER
#pragma pack(pop)
#endif
#endif /* __ENET_PROTOCOL_H__ */

View File

@@ -1,18 +0,0 @@
/**
@file time.h
@brief ENet time constants and macros
*/
#ifndef __ENET_TIME_H__
#define __ENET_TIME_H__
#define ENET_TIME_OVERFLOW 86400000
#define ENET_TIME_LESS(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW)
#define ENET_TIME_GREATER(a, b) ((b) - (a) >= ENET_TIME_OVERFLOW)
#define ENET_TIME_LESS_EQUAL(a, b) (! ENET_TIME_GREATER (a, b))
#define ENET_TIME_GREATER_EQUAL(a, b) (! ENET_TIME_LESS (a, b))
#define ENET_TIME_DIFFERENCE(a, b) ((a) - (b) >= ENET_TIME_OVERFLOW ? (b) - (a) : (a) - (b))
#endif /* __ENET_TIME_H__ */

View File

@@ -1,13 +0,0 @@
/**
@file types.h
@brief type definitions for ENet
*/
#ifndef __ENET_TYPES_H__
#define __ENET_TYPES_H__
typedef unsigned char enet_uint8; /**< unsigned 8-bit type */
typedef unsigned short enet_uint16; /**< unsigned 16-bit type */
typedef unsigned int enet_uint32; /**< unsigned 32-bit type */
#endif /* __ENET_TYPES_H__ */

View File

@@ -1,48 +0,0 @@
/**
@file unix.h
@brief ENet Unix header
*/
#ifndef __ENET_UNIX_H__
#define __ENET_UNIX_H__
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#ifdef MSG_MAXIOVLEN
#define ENET_BUFFER_MAXIMUM MSG_MAXIOVLEN
#endif
typedef int ENetSocket;
#define ENET_SOCKET_NULL -1
#define ENET_HOST_TO_NET_16(value) (htons (value)) /**< macro that converts host to net byte-order of a 16-bit value */
#define ENET_HOST_TO_NET_32(value) (htonl (value)) /**< macro that converts host to net byte-order of a 32-bit value */
#define ENET_NET_TO_HOST_16(value) (ntohs (value)) /**< macro that converts net to host byte-order of a 16-bit value */
#define ENET_NET_TO_HOST_32(value) (ntohl (value)) /**< macro that converts net to host byte-order of a 32-bit value */
typedef struct
{
void * data;
size_t dataLength;
} ENetBuffer;
#define ENET_CALLBACK
#define ENET_API extern
typedef fd_set ENetSocketSet;
#define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO (& (sockset))
#define ENET_SOCKETSET_ADD(sockset, socket) FD_SET (socket, & (sockset))
#define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLR (socket, & (sockset))
#define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET (socket, & (sockset))
#endif /* __ENET_UNIX_H__ */

View File

@@ -1,12 +0,0 @@
/**
@file utility.h
@brief ENet utility header
*/
#ifndef __ENET_UTILITY_H__
#define __ENET_UTILITY_H__
#define ENET_MAX(x, y) ((x) > (y) ? (x) : (y))
#define ENET_MIN(x, y) ((x) < (y) ? (x) : (y))
#endif /* __ENET_UTILITY_H__ */

View File

@@ -1,57 +0,0 @@
/**
@file win32.h
@brief ENet Win32 header
*/
#ifndef __ENET_WIN32_H__
#define __ENET_WIN32_H__
#ifdef _MSC_VER
#ifdef ENET_BUILDING_LIB
#pragma warning (disable: 4267) // size_t to int conversion
#pragma warning (disable: 4244) // 64bit to 32bit int
#pragma warning (disable: 4018) // signed/unsigned mismatch
#pragma warning (disable: 4146) // unary minus operator applied to unsigned type
#endif
#endif
#include <stdlib.h>
#include <winsock2.h>
typedef SOCKET ENetSocket;
#define ENET_SOCKET_NULL INVALID_SOCKET
#define ENET_HOST_TO_NET_16(value) (htons (value))
#define ENET_HOST_TO_NET_32(value) (htonl (value))
#define ENET_NET_TO_HOST_16(value) (ntohs (value))
#define ENET_NET_TO_HOST_32(value) (ntohl (value))
typedef struct
{
size_t dataLength;
void * data;
} ENetBuffer;
#define ENET_CALLBACK __cdecl
#ifdef ENET_DLL
#ifdef ENET_BUILDING_LIB
#define ENET_API __declspec( dllexport )
#else
#define ENET_API __declspec( dllimport )
#endif /* ENET_BUILDING_LIB */
#else /* !ENET_DLL */
#define ENET_API extern
#endif /* ENET_DLL */
typedef fd_set ENetSocketSet;
#define ENET_SOCKETSET_EMPTY(sockset) FD_ZERO (& (sockset))
#define ENET_SOCKETSET_ADD(sockset, socket) FD_SET (socket, & (sockset))
#define ENET_SOCKETSET_REMOVE(sockset, socket) FD_CLR (socket, & (sockset))
#define ENET_SOCKETSET_CHECK(sockset, socket) FD_ISSET (socket, & (sockset))
#endif /* __ENET_WIN32_H__ */

View File

@@ -1,94 +0,0 @@
//
// Created by jojos38 on 28.01.2020.
//
#include "logger.h"
using namespace std;
int loggerlevel;
void setLoggerLevel(char level_string[]) {
if (!strcmp(level_string, "ALL"))
loggerlevel = 0;
if (!strcmp(level_string, "DEBUG"))
loggerlevel = 1;
if (!strcmp(level_string, "INFO"))
loggerlevel = 2;
if (!strcmp(level_string, "WARN"))
loggerlevel = 3;
if (!strcmp(level_string, "ERROR"))
loggerlevel = 4;
if (!strcmp(level_string, "OFF"))
loggerlevel = 5;
}
stringstream getDate() {
// current date/time based on current system
time_t now = time(0);
tm* ltm = localtime(&now);
int month = 1 + ltm->tm_mon;
int day = ltm->tm_mday;
int hours = 1 + ltm->tm_hour;
int minutes = 1 + ltm->tm_min;
int seconds = 1 + ltm->tm_sec;
string month_string;
if (month < 10) month_string = "0" + to_string(month);
else month_string = to_string(month);
string day_string;
if (day < 10) day_string = "0" + to_string(day);
else day_string = to_string(day);
string hours_string;
if (hours < 10) hours_string = "0" + to_string(hours);
else hours_string = to_string(hours);
string minutes_string;
if (minutes < 10) minutes_string = "0" + to_string(minutes);
else minutes_string = to_string(minutes);
string seconds_string;
if (seconds < 10) seconds_string = "0" + to_string(seconds);
else seconds_string = to_string(seconds);
std::stringstream date;
date
<< "["
<< day_string << "/"
<< month_string << "/"
<< 1900 + ltm->tm_year << " "
<< hours_string << ":"
<< minutes_string << ":"
<< seconds_string
<< "] ";
return date;
}
/*
void info(char obj[]) {
if (level <= 2)
cout << getDate().str() << "\u001b[36m" << "[INFO]" << "\u001b[0m" << " " << obj << endl;
}
void error(char obj[]) {
if (level <= 4)
cout << getDate().str() << "\x1B[31m" << "[ERRO]" << "\u001b[0m" << " " << obj << endl;
}
void warn(char obj[]) {
if (level <= 3)
cout << getDate().str() << "\u001b[33m" << "[WARN]" << "\u001b[0m" << " " << obj << endl;
}
void debug(char obj[]) {
if (level <= 1)
cout << getDate().str() << "\u001b[35m" << "[DBUG]" << "\u001b[0m" << " " << obj << endl;
}*/

View File

@@ -1,41 +0,0 @@
//
// Created by jojos38 on 28.01.2020.
//
#ifndef LOGGER_H
#define LOGGER_H
#include <iostream>
#include <ctime>
#include <sstream>
#include <string.h>
using namespace std;
extern int loggerlevel;
stringstream getDate();
void setLoggerLevel(char level_string[]);
template<typename T>
void info(const T& toPrint) {
if (loggerlevel <= 2)
cout << getDate().str() << "[INFO] " << toPrint << endl;
}
template<typename T>
void error(const T& toPrint) {
if (loggerlevel <= 4)
cout << getDate().str() "[ERRO] " << toPrint << endl;
}
template<typename T>
void warn(const T& toPrint) {
if (loggerlevel <= 3)
cout << getDate().str() << "[WARN] " << toPrint << endl;
}
template<typename T>
void debug(const T& toPrint) {
if (loggerlevel <= 1)
cout << getDate().str() << "[DBUG] " << toPrint << endl;
}
#endif // LOGGER_H

View File

@@ -1,46 +1,74 @@
//
// Created by Anonymous275 on 28.01.2020.
//
#include "main.h"
#include <iostream>
#include <string>
#include "enet/enet.h"
#include "network.h"
#include "logger.h"
using namespace std; //nameSpace STD
void DebugData();
void ParseConfig();
bool Debug = false;
int Port = 30813;
string MapName = "levels/gridmap/level.json";
string ServerName = "BeamNG-MP FTW";
//Entry
int main() {
ParseConfig();
if(Debug){ //checks if debug is on
DebugData(); //Prints Debug Data
}
setLoggerLevel("ALL");
startRUDP("localhost", 30814);
}
void DebugData(){
cout << "Debug : true" << "\n";
cout << "Port : " << Port << "\n";
cout << "MapName : " << MapName << "\n";
cout << "ServerName : " << ServerName << "\n";
}
void SetMainValues(bool D, int P,string Name,string serverName){
Debug = D;
Port = P;
MapName = Name;
ServerName = serverName;
}
#include "Common.h"
#include "Http.h"
#include "TConfig.h"
#include "THeartbeatThread.h"
#include "TLuaEngine.h"
#include "TNetwork.h"
#include "TPPSMonitor.h"
#include "TResourceManager.h"
#include "TServer.h"
#include <thread>
#ifdef __unix
#include <csignal>
void UnixSignalHandler(int sig) {
switch (sig) {
case SIGPIPE:
warn("ignoring SIGPIPE");
break;
case SIGTERM:
info("gracefully shutting down via SIGTERM");
Application::GracefullyShutdown();
break;
case SIGINT:
info("gracefully shutting down via SIGINT");
Application::GracefullyShutdown();
break;
default:
debug("unhandled signal: " + std::to_string(sig));
break;
}
}
#endif // __unix
int main(int argc, char** argv) {
#ifdef __unix
#if DEBUG
info("registering handlers for SIGINT, SIGTERM, SIGPIPE");
#endif // DEBUG
signal(SIGPIPE, UnixSignalHandler);
signal(SIGTERM, UnixSignalHandler);
#ifndef DEBUG
signal(SIGINT, UnixSignalHandler);
#endif // DEBUG
#endif // __unix
setlocale(LC_ALL, "C");
bool Shutdown = false;
Application::RegisterShutdownHandler([&Shutdown] { Shutdown = true; });
TServer Server(argc, argv);
TConfig Config;
if (Config.Failed()) {
info("Closing in 10 seconds");
std::this_thread::sleep_for(std::chrono::seconds(10));
return 1;
}
RegisterThread("Main");
TResourceManager ResourceManager;
TPPSMonitor PPSMonitor(Server);
THeartbeatThread Heartbeat(ResourceManager, Server);
TNetwork Network(Server, PPSMonitor, ResourceManager);
TLuaEngine LuaEngine(Server, Network);
PPSMonitor.SetNetwork(Network);
Application::Console().InitializeLuaConsole(LuaEngine);
// TODO: replace
while (!Shutdown) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}

View File

@@ -1,12 +0,0 @@
//
// Created by Антон on 28.01.2020.
//
#ifndef BEAMNG_MP_SERVER_MAIN_H
#define BEAMNG_MP_SERVER_MAIN_H
class main {
};
#endif //BEAMNG_MP_SERVER_MAIN_H

View File

@@ -1,68 +0,0 @@
//
// Created by jojos38 on 28.01.2020.
//
#include <iostream>
#include "network.h"
#include "logger.h"
using namespace std;
#define EXIT_SUCCESS /*implementation defined*/
#define EXIT_FAILURE /*implementation defined*/
void listen();
ENetAddress address;
ENetHost* server;
ENetEvent event;
void startRUDP(char host[], int port) {
// ---------- Initializing ENet ---------- //
if (enet_initialize() != 0) {
fprintf(stderr, "An error occurred while initializing ENet.\n");
return EXIT_FAILURE;
}
atexit(enet_deinitialize);
info("ENet initialized");
// ---------- Starting server ---------- //
enet_address_set_host(&address, host); // Set host
address.port = port; // Set port
server = enet_host_create(
&address /* the address to bind the server host to */,
32 /* allow up to 32 clients and/or outgoing connections */,
2 /* allow up to 2 channels to be used, 0 and 1 */,
0 /* assume any amount of incoming bandwidth */,
0 /* assume any amount of outgoing bandwidth */);
if (server == NULL) {
fprintf(stderr, "An error occurred while trying to create an ENet server host.\n");
return EXIT_FAILURE;
}
info("Server started");
listen();
}
void listen() {
info("Listening for packets...");
while (true) {
switch (event.type) {
case ENET_EVENT_TYPE_CONNECT:
printf("A new client connected from %x:%u.\n", event.peer->address.host, event.peer->address.port);
/* Store any relevant client information here. */
event.peer->data = "Client information";
break;
case ENET_EVENT_TYPE_RECEIVE:
printf("A packet of length %u containing %s was received from %s on channel %u.\n",
event.packet->dataLength,
event.packet->data,
event.peer->data,
event.channelID);
/* Clean up the packet now that we're done using it. */
enet_packet_destroy(event.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
printf("%s disconnected.\n", event.peer->data);
/* Reset the peer's client information. */
event.peer->data = NULL;
}
}
}

View File

@@ -1,15 +0,0 @@
//
// Created by jojos38 on 28.01.2020.
//
#ifndef NETWORK_H
#define NETWORK_H
#include "enet/enet.h"
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"winmm.lib")
#pragma comment(lib,"enet.lib")
void startRUDP(char host[], int port);
#endif // NETWORK_H