mirror of
https://github.com/SantaSpeen/BeamMP-Server.git
synced 2026-02-16 18:10:39 +00:00
Compare commits
480 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a1ca8e0576 | ||
|
|
b22f21a6b2 | ||
|
|
531a901431 | ||
|
|
46f778bd01 | ||
|
|
f3b6eea418 | ||
|
|
bceb3aefe4 | ||
|
|
6c72432992 | ||
|
|
17d3f303ca | ||
|
|
2cbcf96282 | ||
|
|
7d4fd44dbf | ||
|
|
71c2af1224 | ||
|
|
2e112fc5f1 | ||
|
|
96c93a6aa6 | ||
|
|
9dbb91fd84 | ||
|
|
26c33ae2fb | ||
|
|
3eb943309e | ||
|
|
3c8e8399cb | ||
|
|
5b500a3da5 | ||
|
|
ade19123b7 | ||
|
|
5ee18e0576 | ||
|
|
77d23caa63 | ||
|
|
79856cde8e | ||
|
|
7bc230974a | ||
|
|
b1ab7e65da | ||
|
|
c82c53e3d1 | ||
|
|
9e861ab993 | ||
|
|
ae11ba5f0d | ||
|
|
1427966d1a | ||
|
|
db92f2867d | ||
|
|
208a41d45f | ||
|
|
f2915f9c2a | ||
|
|
1abf6d5adf | ||
|
|
f626474b4f | ||
|
|
6f3960d2c2 | ||
|
|
6cb19a7991 | ||
|
|
4fe3c50edd | ||
|
|
fe7335fb0e | ||
|
|
40cd203047 | ||
|
|
1fc03500f0 | ||
|
|
73729746ff | ||
|
|
ffdf4dce60 | ||
|
|
bb5d7fdcf4 | ||
|
|
2df2475b59 | ||
|
|
bb32b9cfea | ||
|
|
3f034264f9 | ||
|
|
c67fffed58 | ||
|
|
f50b821733 | ||
|
|
1e5d19bca4 | ||
|
|
1011de1971 | ||
|
|
7336d63f58 | ||
|
|
c5d7369088 | ||
|
|
c3a463552f | ||
|
|
ae9462898e | ||
|
|
529b7e2ae4 | ||
|
|
1bee72a175 | ||
|
|
f1e1b6cc28 | ||
|
|
573bd77bbd | ||
|
|
770e03e3c6 | ||
|
|
11d4522dc7 | ||
|
|
830bc47987 | ||
|
|
bec698fbdc | ||
|
|
60cc835daf | ||
|
|
a85ce18589 | ||
|
|
1228c2fabe | ||
|
|
3da0af37e4 | ||
|
|
baa41dd65a | ||
|
|
534b457f48 | ||
|
|
029cf94e68 | ||
|
|
15f7a6ba85 | ||
|
|
86b5d91579 | ||
|
|
31486bcb56 | ||
|
|
08660d83dc | ||
|
|
6d8f75a577 | ||
|
|
018246cea5 | ||
|
|
a584e25bf3 | ||
|
|
d4d773b769 | ||
|
|
56a02f0215 | ||
|
|
7231c69e10 | ||
|
|
3c68dfaeaf | ||
|
|
69709968fd | ||
|
|
5b9effad85 | ||
|
|
808ab94c68 | ||
|
|
e7ae71513c | ||
|
|
b825e5685b | ||
|
|
e47821416a | ||
|
|
50549f3d1a | ||
|
|
f323d50e34 | ||
|
|
24994d7dde | ||
|
|
77337204e5 | ||
|
|
dad1acbb91 | ||
|
|
8b755e6b7b | ||
|
|
7ccc5a963a | ||
|
|
ca24339c9a | ||
|
|
fc201efa4b | ||
|
|
533c8c80e1 | ||
|
|
78fb81004e | ||
|
|
942b7baa74 | ||
|
|
aa72b2507e | ||
|
|
9860240e24 | ||
|
|
cda8168c58 | ||
|
|
667bd7f7c8 | ||
|
|
b524aa67de | ||
|
|
e35d1b5457 | ||
|
|
1875c8832d | ||
|
|
61726ea3ab | ||
|
|
e4d6c86919 | ||
|
|
eaa6b5322f | ||
|
|
2c06a98e00 | ||
|
|
e73d578797 | ||
|
|
704e25636d | ||
|
|
c7cf0a733e | ||
|
|
24a34d7a97 | ||
|
|
1c98921127 | ||
|
|
2d898f8665 | ||
|
|
229914ac74 | ||
|
|
3258b04dad | ||
|
|
603663ed2c | ||
|
|
44f2fdfa7c | ||
|
|
19abb5b68c | ||
|
|
dd5b0bdd6d | ||
|
|
9c9f503e5c | ||
|
|
b4850f09a9 | ||
|
|
3094d382ff | ||
|
|
940a39ed4e | ||
|
|
23b39bb6c7 | ||
|
|
2cd6e21f8c | ||
|
|
3c6aa741ef | ||
|
|
e79318e49a | ||
|
|
e8938968f2 | ||
|
|
e6f79a8dd1 | ||
|
|
347e72ce90 | ||
|
|
a90c67f47d | ||
|
|
956b2ef5b5 | ||
|
|
31d68249a8 | ||
|
|
6d3e053c71 | ||
|
|
87a1564c0a | ||
|
|
e6109c98bd | ||
|
|
c372e63bd1 | ||
|
|
709ac1dd58 | ||
|
|
6ead6bbb1e | ||
|
|
50fb023eff | ||
|
|
08d043da8d | ||
|
|
c623bdea91 | ||
|
|
b953bae5da | ||
|
|
e039eeaab8 | ||
|
|
15cad02e13 | ||
|
|
67f22c7d76 | ||
|
|
632a5f2801 | ||
|
|
44fa68e6da | ||
|
|
33e0cac4c1 | ||
|
|
a7f1e93ca2 | ||
|
|
f8a9d01749 | ||
|
|
356354d1eb | ||
|
|
40cae31885 | ||
|
|
05c5fb047c | ||
|
|
83145d7466 | ||
|
|
3c48ac6145 | ||
|
|
3fe8d48ada | ||
|
|
f0abfcc0ef | ||
|
|
7410e31230 | ||
|
|
3bc8744b63 | ||
|
|
c076c83edc | ||
|
|
776ddcbbef | ||
|
|
9a74434bbb | ||
|
|
3e2cb3176a | ||
|
|
7cd420a1a5 | ||
|
|
4edd1ac100 | ||
|
|
8e4006fc38 | ||
|
|
ab44ac8c15 | ||
|
|
266303b09d | ||
|
|
b777781c96 | ||
|
|
714d31fb45 | ||
|
|
d481fcd3a7 | ||
|
|
df3269756c | ||
|
|
aadcd1abe5 | ||
|
|
57fc0ea74d | ||
|
|
fe4a1b28b5 | ||
|
|
30916c41c3 | ||
|
|
fab20276ff | ||
|
|
7e6d5ce359 | ||
|
|
6aed93fbf1 | ||
|
|
9b1bf071a8 | ||
|
|
f52308c439 | ||
|
|
0580ad67fd | ||
|
|
218504e674 | ||
|
|
f13523fbe5 | ||
|
|
b81ac35b37 | ||
|
|
8664522d1d | ||
|
|
c15046f8b1 | ||
|
|
c7f8b2b131 | ||
|
|
84252e892e | ||
|
|
32038046d5 | ||
|
|
e04a569e33 | ||
|
|
13f8be5d39 | ||
|
|
bca4b3f140 | ||
|
|
b3256062f7 | ||
|
|
51dbfe0482 | ||
|
|
92a67c7305 | ||
|
|
cc5a878692 | ||
|
|
5759a6f80f | ||
|
|
3dd2e1c278 | ||
|
|
4826fb5fc2 | ||
|
|
8cd35d64e4 | ||
|
|
aec6ad9c14 | ||
|
|
d360403c56 | ||
|
|
bf74b1ae32 | ||
|
|
f19a012509 | ||
|
|
72607583bf | ||
|
|
ef5db013b3 | ||
|
|
4cda6e8bc3 | ||
|
|
459814a6ec | ||
|
|
e5e447c7af | ||
|
|
6a2ce7faab | ||
|
|
ce8661159b | ||
|
|
f5ecc251e7 | ||
|
|
45b3057ed5 | ||
|
|
0476ffa990 | ||
|
|
43690d0833 | ||
|
|
f9cb9af078 | ||
|
|
e4979bb6e2 | ||
|
|
5266ac418b | ||
|
|
ffca27ae6a | ||
|
|
cd1aba7afb | ||
|
|
50b3a9ea19 | ||
|
|
d8f49edb6b | ||
|
|
ec0987e5c1 | ||
|
|
e4fa9a23fa | ||
|
|
0fe4913928 | ||
|
|
bd349556f0 | ||
|
|
dc9c3255de | ||
|
|
d5541ae154 | ||
|
|
467e5a64c3 | ||
|
|
3bb9b17d47 | ||
|
|
51f0b504b7 | ||
|
|
2e48cef647 | ||
|
|
0fe7050166 | ||
|
|
a25cc00093 | ||
|
|
e2e23635bc | ||
|
|
a20f632e3e | ||
|
|
5f3fecb92c | ||
|
|
710bb939ad | ||
|
|
00b7d1ca96 | ||
|
|
7e8b86cf57 | ||
|
|
d47e721b38 | ||
|
|
33a7d0e1a1 | ||
|
|
480c78c9f2 | ||
|
|
d0a7b56e75 | ||
|
|
f6121704df | ||
|
|
c75acbff76 | ||
|
|
d394d7b5a6 | ||
|
|
4e1d2a7ddd | ||
|
|
2571cb1478 | ||
|
|
c387cc3610 | ||
|
|
769c19b811 | ||
|
|
b62676daf4 | ||
|
|
cd19cd343a | ||
|
|
e0b7dd76fd | ||
|
|
fc4bc14ce5 | ||
|
|
61776d6a1b | ||
|
|
0f30706a0a | ||
|
|
cb92833bfd | ||
|
|
a21ca74c58 | ||
|
|
e2611e13e0 | ||
|
|
5fb7c459c6 | ||
|
|
d8e1d389bf | ||
|
|
ae03b5f5ce | ||
|
|
2c6386013d | ||
|
|
3cb4c7cb67 | ||
|
|
229010647c | ||
|
|
03968f34b1 | ||
|
|
941287d22c | ||
|
|
8e4e0c0896 | ||
|
|
c5d1682d5e | ||
|
|
04cf7ca092 | ||
|
|
639c94e0f2 | ||
|
|
623437e864 | ||
|
|
fb420eac1b | ||
|
|
0f33367f6b | ||
|
|
1a2c956d9e | ||
|
|
de859f4762 | ||
|
|
db152e09e9 | ||
|
|
561c0bb381 | ||
|
|
f60a44f65f | ||
|
|
a944565fb9 | ||
|
|
0f4c08c068 | ||
|
|
f0ad3732f4 | ||
|
|
4adfda64c1 | ||
|
|
306fbc5eb4 | ||
|
|
fac1b43b44 | ||
|
|
b22a9566f9 | ||
|
|
6f0c69904c | ||
|
|
e049b1bbf4 | ||
|
|
ef8f8645f7 | ||
|
|
f94252d37b | ||
|
|
8f042a3ee4 | ||
|
|
435c397d02 | ||
|
|
97d8f9506e | ||
|
|
2e7f2cc6bd | ||
|
|
19b7f7f579 | ||
|
|
6a29384b5c | ||
|
|
69da77937d | ||
|
|
5cf97850d7 | ||
|
|
ad844db7fe | ||
|
|
6a8d097dc5 | ||
|
|
e2a45601b3 | ||
|
|
a78f65b274 | ||
|
|
04de729d7c | ||
|
|
667a22b0f8 | ||
|
|
e12b7da27f | ||
|
|
450f6d7139 | ||
|
|
086bcb5ecc | ||
|
|
ac05cb5d0e | ||
|
|
92c44b19c5 | ||
|
|
2a0939891b | ||
|
|
e0b1a5c91f | ||
|
|
5a275580a4 | ||
|
|
03ee46d293 | ||
|
|
fb7ed95d1d | ||
|
|
21c9ac4f53 | ||
|
|
ab5da1d94b | ||
|
|
6710c18168 | ||
|
|
cdd9ef86ae | ||
|
|
85edadb6e4 | ||
|
|
aa29530d92 | ||
|
|
270cca40ac | ||
|
|
c1633b6401 | ||
|
|
fa9bc16038 | ||
|
|
fedca58e8e | ||
|
|
6ecf6c58ac | ||
|
|
954d55c1a6 | ||
|
|
58e65cf43f | ||
|
|
c9f5ee9729 | ||
|
|
583819070b | ||
|
|
9ddab14f01 | ||
|
|
d44aa86ed1 | ||
|
|
7a5861a917 | ||
|
|
5e603c65b6 | ||
|
|
3137f4e9db | ||
|
|
80c5341650 | ||
|
|
cde41f01b2 | ||
|
|
be7e2f1616 | ||
|
|
cdb2624367 | ||
|
|
308500c01f | ||
|
|
8f05cdcc61 | ||
|
|
94f6a81673 | ||
|
|
60c7997c6b | ||
|
|
2d11841a68 | ||
|
|
01e02edf8c | ||
|
|
52bf3cdd21 | ||
|
|
1bbe88b240 | ||
|
|
5fc6c3ddd7 | ||
|
|
d226b36f44 | ||
|
|
7ab37b7fe9 | ||
|
|
747e948339 | ||
|
|
7fce274915 | ||
|
|
b663563f01 | ||
|
|
8e9bf46778 | ||
|
|
c6fbd3dc49 | ||
|
|
b9758ddaea | ||
|
|
e42256dd5f | ||
|
|
0b71d77a48 | ||
|
|
1e5faea1a4 | ||
|
|
4ecd57fed4 | ||
|
|
b8bd939bd7 | ||
|
|
1ef6cf53a2 | ||
|
|
26383d5346 | ||
|
|
96668add6e | ||
|
|
437a654b90 | ||
|
|
a42ab67d2f | ||
|
|
fe6cfd027e | ||
|
|
a08d29a0ae | ||
|
|
2021f0b461 | ||
|
|
5b92cbc0be | ||
|
|
757c63bddb | ||
|
|
77f811b7a8 | ||
|
|
6bebc4c160 | ||
|
|
e5a0d43024 | ||
|
|
b49abe02eb | ||
|
|
3eb2bd0dfc | ||
|
|
775e46788c | ||
|
|
1de29dc5e4 | ||
|
|
e41b3df095 | ||
|
|
24eaa1e079 | ||
|
|
8ba89e491f | ||
|
|
6a3b933df1 | ||
|
|
f0c87341ab | ||
|
|
fbbdc084a4 | ||
|
|
36db73b562 | ||
|
|
f2d87078ae | ||
|
|
5452aeb558 | ||
|
|
2beff2495f | ||
|
|
9bae155439 | ||
|
|
c5c21c43ad | ||
|
|
f144d451c7 | ||
|
|
ddd9c55822 | ||
|
|
801ea3f777 | ||
|
|
e986df0579 | ||
|
|
e9432ac1ca | ||
|
|
aa73a9d16a | ||
|
|
b2166402a2 | ||
|
|
2ec65d5b84 | ||
|
|
69f20bdf41 | ||
|
|
289bb1c1f3 | ||
|
|
eead954bf9 | ||
|
|
13e79e407c | ||
|
|
4d259c9d25 | ||
|
|
953131289d | ||
|
|
8bc35fb82e | ||
|
|
02fbe72eed | ||
|
|
2604308094 | ||
|
|
6787f43889 | ||
|
|
7e917e99a1 | ||
|
|
9adc633c2f | ||
|
|
030944ebc2 | ||
|
|
90458cbf72 | ||
|
|
3bdc75b0c0 | ||
|
|
71a84b4f1b | ||
|
|
31c96cee94 | ||
|
|
232c4d7b28 | ||
|
|
303647a8c3 | ||
|
|
92cc1cb0fd | ||
|
|
c83bc7864a | ||
|
|
83c095ba17 | ||
|
|
69362b2dfd | ||
|
|
e7c1bdd872 | ||
|
|
6c93ea7fb2 | ||
|
|
1b8c7abea5 | ||
|
|
c5e1175f1a | ||
|
|
ed0e35400d | ||
|
|
3d29067cab | ||
|
|
354ff30b90 | ||
|
|
834db5ecc1 | ||
|
|
62928ece9c | ||
|
|
280e3a8daa | ||
|
|
a05acee04f | ||
|
|
ed6b2d236a | ||
|
|
80c3280e4e | ||
|
|
ff2d5d74ae | ||
|
|
375c4a4952 | ||
|
|
49c38a0f00 | ||
|
|
ba47f21898 | ||
|
|
131e64b706 | ||
|
|
b0c6c2bac4 | ||
|
|
2d360610fc | ||
|
|
25a5cd75c6 | ||
|
|
851343eedb | ||
|
|
a85da1e05e | ||
|
|
ce7abdc960 | ||
|
|
60c38ccd1a | ||
|
|
2a3df072d1 | ||
|
|
1636ae3286 | ||
|
|
123cb4f1a2 | ||
|
|
d368b154c2 | ||
|
|
b5dbb70104 | ||
|
|
5cb43950eb | ||
|
|
8d56873335 | ||
|
|
d50f205787 | ||
|
|
9a47f651fc | ||
|
|
e60790e185 | ||
|
|
7410625fce | ||
|
|
29e77b147c | ||
|
|
9bdec9e5f8 | ||
|
|
388cffbe01 | ||
|
|
640a9c2e54 | ||
|
|
3c244c7e7f | ||
|
|
104856938a | ||
|
|
f427cb8d06 | ||
|
|
fef98347e7 | ||
|
|
e2cae1da59 | ||
|
|
4503338378 | ||
|
|
c47e8783e6 | ||
|
|
4e47f36d84 | ||
|
|
3ba8e55e59 | ||
|
|
56bd547823 | ||
|
|
996d96639c | ||
|
|
54319f7cdd | ||
|
|
60a0d13e63 | ||
|
|
9034319685 | ||
|
|
7d5c5a4526 | ||
|
|
1f620f4093 |
5
.clang-format
Normal file
5
.clang-format
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
BasedOnStyle: WebKit
|
||||
BreakBeforeBraces: Attach
|
||||
|
||||
...
|
||||
41
.github/workflows/cmake-linux.yml
vendored
Normal file
41
.github/workflows/cmake-linux.yml
vendored
Normal 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
45
.github/workflows/cmake-windows.yml
vendored
Normal 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
114
.github/workflows/release-build.yml
vendored
Normal 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
33
.gitignore
vendored
@@ -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
15
.gitmodules
vendored
Normal 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
2
.idea/.gitignore
generated
vendored
@@ -1,2 +0,0 @@
|
||||
# Default ignored files
|
||||
/workspace.xml
|
||||
2
.idea/BeamNG-MP-Server.iml
generated
2
.idea/BeamNG-MP-Server.iml
generated
@@ -1,2 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module classpath="CMake" type="CPP_MODULE" version="4" />
|
||||
7
.idea/misc.xml
generated
7
.idea/misc.xml
generated
@@ -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
8
.idea/modules.xml
generated
@@ -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
6
.idea/vcs.xml
generated
@@ -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>
|
||||
@@ -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
2
LICENSE
Normal 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.
|
||||
94
README.md
94
README.md
@@ -1 +1,93 @@
|
||||
# BeamNG-MP-Server
|
||||
# BeamMP-Server
|
||||
|
||||
[](https://github.com/BeamMP/BeamMP-Server/actions?query=workflow%3A%22CMake+Windows+Build%22)
|
||||
[](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
1
asio
Submodule
Submodule asio added at 230c0d2ae0
94
include/Client.h
Normal file
94
include/Client.h
Normal 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
123
include/Common.h
Normal 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
36
include/Compat.h
Normal 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
68
include/CustomAssert.h
Normal 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
9
include/Http.h
Normal 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
19
include/IThreaded.h
Normal 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
9
include/Json.h
Normal 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
20
include/RWMutex.h
Normal 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
69
include/SocketIO.h
Normal 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
21
include/TConfig.h
Normal 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
19
include/TConsole.h
Normal 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;
|
||||
};
|
||||
21
include/THeartbeatThread.h
Normal file
21
include/THeartbeatThread.h
Normal 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
38
include/TLuaEngine.h
Normal 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
61
include/TLuaFile.h
Normal 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
49
include/TNetwork.h
Normal 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
27
include/TPPSMonitor.h
Normal 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 };
|
||||
};
|
||||
21
include/TResourceManager.h
Normal file
21
include/TResourceManager.h
Normal 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
37
include/TServer.h
Normal 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
35
include/VehicleData.h
Normal 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
1
include/commandline
Submodule
Submodule include/commandline added at c34703df11
1
include/tomlplusplus
Submodule
1
include/tomlplusplus
Submodule
Submodule include/tomlplusplus added at bc6891e1fb
Binary file not shown.
Binary file not shown.
1
rapidjson
Submodule
1
rapidjson
Submodule
Submodule rapidjson added at 13dfc96c9c
1
socket.io-client-cpp
Submodule
1
socket.io-client-cpp
Submodule
Submodule socket.io-client-cpp added at b196fa7537
102
src/Client.cpp
Normal file
102
src/Client.cpp
Normal 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
88
src/Common.cpp
Normal 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
35
src/Compat.cpp
Normal 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, ¤t); /* 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
145
src/Http.cpp
Normal 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
98
src/SocketIO.cpp
Normal 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
213
src/TConfig.cpp
Normal 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
78
src/TConsole.cpp
Normal 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
109
src/THeartbeatThread.cpp
Normal 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
103
src/TLuaEngine.cpp
Normal 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
823
src/TLuaFile.cpp
Normal 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
994
src/TNetwork.cpp
Normal 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
66
src/TPPSMonitor.cpp
Normal 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
32
src/TResourceManager.cpp
Normal 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
365
src/TServer.cpp
Normal 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
18
src/VehicleData.cpp
Normal 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
|
||||
}
|
||||
119
src/config.cpp
119
src/config.cpp
@@ -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;
|
||||
}
|
||||
@@ -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__ */
|
||||
|
||||
607
src/enet/enet.h
607
src/enet/enet.h
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
@@ -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__ */
|
||||
|
||||
|
||||
@@ -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;
|
||||
}*/
|
||||
41
src/logger.h
41
src/logger.h
@@ -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
|
||||
120
src/main.cpp
120
src/main.cpp
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
12
src/main.h
12
src/main.h
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user