mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-07-14 02:34:12 +00:00
Compare commits
111 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e58a241b28 | |||
| bf4c2d120e | |||
| 8b88127e20 | |||
| 6e7b2e0525 | |||
| 1e6c2ea680 | |||
| 140b43a18c | |||
| b8211166ad | |||
| 8e1d235dee | |||
| dc61d4649c | |||
| 03ac847683 | |||
| 3dde6a76cb | |||
| 87a0d46b00 | |||
| 452a4c5e16 | |||
| adfda5a8cb | |||
| 14097b6c68 | |||
| 7a21751750 | |||
| e68582871d | |||
| 3df71e96c5 | |||
| 6a1baa249a | |||
| 56cd0eca11 | |||
| 04e058dc0d | |||
| f359c0cdca | |||
| 9a45efef57 | |||
| b06d2fe151 | |||
| 145b74aefc | |||
| 1515fc2675 | |||
| 0f802e4021 | |||
| 213c1c7b6b | |||
| 787f59ba46 | |||
| 72bec02e21 | |||
| 46e42b88da | |||
| 39028ba4d7 | |||
| 9cd4609cad | |||
| 3b61da9edd | |||
| 09c4bb8b33 | |||
| f0a5fa48b8 | |||
| cfea87251b | |||
| 04c1b76402 | |||
| e15833084a | |||
| 13207a8ddf | |||
| d5aef2525f | |||
| efbd2a4bb8 | |||
| 478bf48a5a | |||
| 1e7cccd9a9 | |||
| 5fdfc10f79 | |||
| 7eaa382f6c | |||
| b66251d375 | |||
| e6f316a6c2 | |||
| 49a8e84161 | |||
| 3376eb7482 | |||
| de398c0208 | |||
| cde157fdfe | |||
| 3b0da388fb | |||
| ad49713e13 | |||
| 191264e732 | |||
| 88181cf44c | |||
| 03ea9513b9 | |||
| 6ed714b863 | |||
| 669e061fdf | |||
| 9b78fc76db | |||
| dfcf820824 | |||
| 259f3de774 | |||
| d9e0761e07 | |||
| 67cec26979 | |||
| 260fd03a1f | |||
| 2323c07d8e | |||
| a61554187e | |||
| 6c2b131d72 | |||
| 5a42fe87fd | |||
| 4551a2da60 | |||
| 223c9a5064 | |||
| 5097244c76 | |||
| 4e985bc0e0 | |||
| 7d0941dee8 | |||
| 0e75a35c83 | |||
| 7598261aff | |||
| 8280b06253 | |||
| 81816da44d | |||
| 7c82f474bb | |||
| 4bf4727cc3 | |||
| 0335d22809 | |||
| 0f5d61c89b | |||
| 37d7a289eb | |||
| 596a7234ed | |||
| 8735824495 | |||
| 51c5ee0638 | |||
| 4f57680a67 | |||
| 1c21298351 | |||
| e781bbac8e | |||
| a0db8aa8be | |||
| f2b9384447 | |||
| b5c6f2c3c7 | |||
| 6dee028a88 | |||
| 4f52e30545 | |||
| 01fb538129 | |||
| a23b5a43c0 | |||
| 8ee6ba16f2 | |||
| 0b6ad43fbb | |||
| 5d8c9cd792 | |||
| c5ce152a30 | |||
| 6c60f220eb | |||
| ff5a5204c9 | |||
| ad85317f60 | |||
| efad9ec03e | |||
| 5011ae280c | |||
| ebc0dba4ef | |||
| ad15846625 | |||
| e1b9f2b969 | |||
| 3fedcf5bd5 | |||
| 190cc8f238 | |||
| 38aaf29fe8 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
BasedOnStyle: WebKit
|
||||
BreakBeforeBraces: Attach
|
||||
|
||||
...
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
+4
-464
@@ -1,464 +1,4 @@
|
||||
boost_*
|
||||
Resources
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
#VS Files
|
||||
out/
|
||||
|
||||
#Clion Files
|
||||
cmake-build-debug/CMakeFiles/
|
||||
cmake-build-release/CMakeFiles/
|
||||
cmake-build-debug/Resources/
|
||||
cmake-build-release/Resources/
|
||||
cmake-build-debug/*.*
|
||||
cmake-build-release/*.*
|
||||
cmake-build-debug/Makefile
|
||||
cmake-build-release/Makefile
|
||||
!cmake-build-debug/*.lib
|
||||
!cmake-build-release/*.lib
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
out/build/x86-Debug/VSInheritEnvironments.txt
|
||||
out/build/x86-Debug/rules.ninja
|
||||
out/build/x86-Debug/CMakeFiles/untitled.dir/manifest.res
|
||||
out/build/x86-Debug/CMakeFiles/untitled.dir/manifest.rc
|
||||
out/build/x86-Debug/CMakeFiles/untitled.dir/intermediate.manifest
|
||||
out/build/x86-Debug/CMakeFiles/untitled.dir/embed.manifest
|
||||
out/build/x86-Debug/CMakeFiles/TargetDirectories.txt
|
||||
out/build/x86-Debug/CMakeFiles/ShowIncludes/main.c
|
||||
out/build/x86-Debug/CMakeFiles/ShowIncludes/foo.h
|
||||
out/build/x86-Debug/CMakeFiles/cmake.check_cache
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.exe
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.cpp
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.exe
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.c
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeSystem.cmake
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeRCCompiler.cmake
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_CXX.bin
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_C.bin
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCXXCompiler.cmake
|
||||
out/build/x86-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCCompiler.cmake
|
||||
out/build/x86-Debug/CMakeCache.txt
|
||||
out/build/x86-Debug/cmake_install.cmake
|
||||
out/build/x86-Debug/build.ninja
|
||||
out/build/x86-Debug/.ninja_log
|
||||
out/build/x86-Debug/.ninja_deps
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-untitled-Debug-03f16c5921ae0bd48990.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-27T23-42-34-0718.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-2b93246ca751d7a49cd1.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/cmakeFiles-v1-d93b224eb363971ee2c4.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/cache-v2-43521627501184045d13.json
|
||||
out/build/x86-Debug/.cmake/api/v1/query/client-MicrosoftVS/query.json
|
||||
out/build/x64-Debug/VSInheritEnvironments.txt
|
||||
out/build/x64-Debug/rules.ninja
|
||||
out/build/x64-Debug/CMakeFiles/untitled.dir/manifest.res
|
||||
out/build/x64-Debug/CMakeFiles/untitled.dir/manifest.rc
|
||||
out/build/x64-Debug/CMakeFiles/untitled.dir/intermediate.manifest
|
||||
out/build/x64-Debug/CMakeFiles/untitled.dir/embed.manifest
|
||||
out/build/x64-Debug/CMakeFiles/TargetDirectories.txt
|
||||
out/build/x64-Debug/CMakeFiles/ShowIncludes/main.c
|
||||
out/build/x64-Debug/CMakeFiles/ShowIncludes/foo.h
|
||||
out/build/x64-Debug/CMakeFiles/cmake.check_cache
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.exe
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdCXX/CMakeCXXCompilerId.cpp
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.exe
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CompilerIdC/CMakeCCompilerId.c
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeSystem.cmake
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeRCCompiler.cmake
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_CXX.bin
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeDetermineCompilerABI_C.bin
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCXXCompiler.cmake
|
||||
out/build/x64-Debug/CMakeFiles/3.15.19101501-MSVC_2/CMakeCCompiler.cmake
|
||||
out/build/x64-Debug/CMakeCache.txt
|
||||
out/build/x64-Debug/cmake_install.cmake
|
||||
out/build/x64-Debug/build.ninja
|
||||
out/build/x64-Debug/.ninja_log
|
||||
out/build/x64-Debug/.ninja_deps
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/target-untitled-Debug-8918286eee207fe0275b.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-27T23-42-03-0431.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/codemodel-v2-ee254da00ecbf4b22928.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/cmakeFiles-v1-ee926bd040d82c324cbe.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/cache-v2-6f7cb0917968b934d35c.json
|
||||
out/build/x64-Debug/.cmake/api/v1/query/client-MicrosoftVS/query.json
|
||||
CMakeSettings.json
|
||||
cmake-build-debug/Resource1.resx
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T10-34-19-0746.json
|
||||
out/build/x64-Debug/untitled.exe
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T11-19-41-0061.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/cmakeFiles-v1-52c1d9386071c1490278.json
|
||||
out/build/x86-Debug/CMakeFiles/cmake-main.dir/manifest.res
|
||||
out/build/x86-Debug/CMakeFiles/cmake-main.dir/manifest.rc
|
||||
out/build/x86-Debug/CMakeFiles/cmake-main.dir/intermediate.manifest
|
||||
out/build/x86-Debug/CMakeFiles/cmake-main.dir/embed.manifest
|
||||
out/build/x86-Debug/cmake-main.exe
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-1cc90e5d191bd520f961.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-0c9bd3464adc40e447af.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T11-21-26-0362.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-1850e17888d5bab56568.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/cmakeFiles-v1-7c376457f6b736ad28ac.json
|
||||
out/build/x64-Debug/CMakeFiles/cmake-main.dir/manifest.res
|
||||
out/build/x64-Debug/CMakeFiles/cmake-main.dir/manifest.rc
|
||||
out/build/x64-Debug/CMakeFiles/cmake-main.dir/intermediate.manifest
|
||||
out/build/x64-Debug/CMakeFiles/cmake-main.dir/embed.manifest
|
||||
out/build/x64-Debug/cmake-main.exe
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/target-enet-Debug-645fd45f5bd4fab53aa9.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-b124668c8fb6ca5df286.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/index-2020-01-28T11-21-06-0706.json
|
||||
out/build/x64-Debug/.cmake/api/v1/reply/codemodel-v2-63a6ab1789a1732f4563.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-d301abed48f6c38bdcfb.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T12-30-44-0946.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-3eaabe43603befc605b1.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-70eff68e1e381b42992e.json
|
||||
*.xml
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-enet-Debug-48db38ae5d08e27876b8.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/target-cmake-main-Debug-540e487569703b71c785.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/index-2020-01-28T17-35-38-0764.json
|
||||
out/build/x86-Debug/.cmake/api/v1/reply/codemodel-v2-6a61e390ef8eaf17e9f8.json
|
||||
out/build/x86-Debug/Server.cfg
|
||||
*Server.cfg*
|
||||
/target
|
||||
/.idea
|
||||
ServerConfig.toml
|
||||
beammp_rust_server.iml
|
||||
Generated
-2
@@ -1,2 +0,0 @@
|
||||
# Default ignored files
|
||||
/workspace.xml
|
||||
Generated
-1
@@ -1 +0,0 @@
|
||||
Server
|
||||
Generated
-2
@@ -1,2 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module classpath="CMake" type="CPP_MODULE" version="4" />
|
||||
Generated
-7
@@ -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>
|
||||
Generated
-8
@@ -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>
|
||||
Generated
-6
@@ -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>
|
||||
@@ -0,0 +1,82 @@
|
||||
# BeamMP Protocol Documentation
|
||||
WIP of course, but hope it helps others
|
||||
|
||||
## TCP
|
||||
### Basic message format
|
||||
All messages are sent as strings (?).
|
||||
Every packet starts with a 4 byte header, denoting how many bytes the packet data is.
|
||||
This means that you first must read 4 bytes from your socket, to get the header data, and afterwards read the data ready for reading.
|
||||
|
||||
### Communication flow
|
||||
Upon client connection:
|
||||
1. Authentication
|
||||
2. Sync with client?
|
||||
|
||||
#### Authentication
|
||||
1. C->S - Client sends the server a single byte. The BeamMP source checks for 3 letters, but I only saw C
|
||||
2. C->S - Client sends a packet containing the client version
|
||||
3. S->C - Server sends the server a regular packet containing only 1 byte: `S` (the ascii character)
|
||||
4. C->S - Client sends the server its public key
|
||||
5. S->C - Server sends the client their assigned server ID
|
||||
|
||||
#### Syncing resources
|
||||
1. C->S - Client sends the server a packet with the code `SR`
|
||||
2. S->C - Server sends the client a packet containing a filelist containing the name and size of files to download, or "-" if it's empty
|
||||
|
||||
### Packets
|
||||
All packets start with a single character, denoted as "Packet Code" or simply "Code" down below.
|
||||
The data mentioned is merely example data, to show the data format. This includes the code!
|
||||
Example:
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `C` | C->S | Client version | VC2.0 |
|
||||
|
||||
#### Uncategorized
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `J` | S->C | Show a message in the top left on the clients screen | JWelcome Luuk! |
|
||||
|
||||
#### Authentication
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `C` | C->S | Client version | VC2.0 |
|
||||
| `S` | S->C | Confirmation? | None |
|
||||
| `D` | C->S | Start download phase? Seems unused from testing | None |
|
||||
| `P` | S->C | Send client their assigned ID | P123 |
|
||||
|
||||
#### Syncing resources
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `SR` | C->S | Client requests a list containing all mods, containing their name and file size | None |
|
||||
| `f` | C->S | Client requests file with name | fcool_mod.zip |
|
||||
| `-` | S->C | Technically not a packet, see [Syncing Resources](https://github.com/Lucky4Luuk/beammp_rust_server/blob/master/BEAMMP_PROTOCOL_DOCS.md#syncing-resources), step 2. | * |
|
||||
|
||||
#### Syncing client state
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `H` | C->S | Client requests a full sync with the server state | None |
|
||||
|
||||
### Vehicle packets
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `Os` | C->S | Client informs server they are spawning a car | Os:C_ID:{car_json} |
|
||||
| `Os` | S->C | Server sends this packet to all clients, informing them a client has spawned a car | Os:C_ROLES:C_NAME:C_ID-CAR_ID:CAR_JSON |
|
||||
| `Or` | C->S | Client informs server they are respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
|
||||
| `Or` | S->C | Server informs all other clients that a client is respawning their car | Or:C_ID-CAR_ID:{respawn_json} |
|
||||
| `Od` | C->S | Client informs server they are deleting their car | Od:C_ID-CAR_ID |
|
||||
| `Od` | S->C | Server informs all other clients that a client is deleting their car | Od:C_ID-CAR_ID |
|
||||
| `Oc` | C->S | Client informs server they are editing their car | Oc:?... |
|
||||
| `Oc` | S->C | Server informs all other clients that a client has edited their car | Oc:?... |
|
||||
|
||||
## UDP
|
||||
### Packets
|
||||
#### Uncategorized
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `p` | C->S | Ping! | None |
|
||||
| `p` | S->C | Pong! | None |
|
||||
|
||||
#### Vehicle related
|
||||
| Code | Dir | Explanation | Data |
|
||||
| ---- | --- | ----------- | ---- |
|
||||
| `Zp` | C->S | Positional packet | Zp:C_ID-CAR_ID:{transform_json} |
|
||||
@@ -1,39 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(Server)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
||||
|
||||
if (UNIX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic -static-libstdc++")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Og -g")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -s")
|
||||
elseif (WIN32)
|
||||
# This might cause issues with old windows headers, but it's worth the trouble to keep the code
|
||||
# completely cross platform. For fixes to common issues arising from /permissive- visit:
|
||||
# https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance
|
||||
message(${CMAKE_CXX_FLAGS_RELEASE})
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W3 /permissive-")
|
||||
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
|
||||
endif ()
|
||||
|
||||
find_package(Boost 1.70.0 REQUIRED COMPONENTS system thread)
|
||||
|
||||
file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "include/*.h" "include/*/*.h" "include/*.hpp" "include/*/*.hpp")
|
||||
add_executable(BeamMP-Server ${source_files})
|
||||
|
||||
target_include_directories(BeamMP-Server SYSTEM PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
|
||||
find_package(Lua 5.3 REQUIRED)
|
||||
target_include_directories(BeamMP-Server SYSTEM PUBLIC ${LUA_INCLUDE_DIR} ${Boost_INCLUDE_DIRS})
|
||||
|
||||
if (UNIX)
|
||||
target_link_libraries(BeamMP-Server z pthread stdc++fs ${Boost_LINK_DIRS} lua curl dl)
|
||||
elseif (WIN32)
|
||||
include(FindLua)
|
||||
find_package(CURL CONFIG REQUIRED)
|
||||
find_package(ZLIB REQUIRED)
|
||||
target_link_libraries(BeamMP-Server PRIVATE urlmon ws2_32 CURL::libcurl ZLIB::ZLIB ${Boost_LINK_DIRS} ${LUA_LIBRARIES})
|
||||
endif ()
|
||||
Generated
+1801
File diff suppressed because it is too large
Load Diff
+36
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "beammp_rust_server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
pretty_env_logger = "0.4.0"
|
||||
|
||||
argh = "0.1.12"
|
||||
|
||||
lazy_static = "1"
|
||||
|
||||
anyhow = "1.0.66"
|
||||
glam = "0.24.2"
|
||||
num_enum = "0.5.7"
|
||||
|
||||
async-trait = "0.1.58"
|
||||
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "net", "io-util", "sync"] }
|
||||
futures = "0.3.29"
|
||||
|
||||
reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde-aux = "4.2.0"
|
||||
serde_json = "*"
|
||||
|
||||
toml = "0.5"
|
||||
flate2 = "1.0"
|
||||
|
||||
mlua = { version = "0.9.1", features = ["lua54", "vendored", "send"] }
|
||||
|
||||
ratatui = "0.24.0"
|
||||
crossterm = "0.27.0"
|
||||
uuid = "1.6.1"
|
||||
@@ -0,0 +1,37 @@
|
||||
# This is the BeamMP-Server config file.
|
||||
# Help & Documentation: `https://wiki.beammp.com/en/home/server-maintenance`
|
||||
# IMPORTANT: Fill in the AuthKey with the key you got from `https://beammp.com/k/dashboard` on the left under "Keys"
|
||||
|
||||
[General]
|
||||
Name = "bepis big gaming"
|
||||
Port = 30814
|
||||
# AuthKey has to be filled out in order to run the server
|
||||
AuthKey = "test"
|
||||
# Whether to log chat messages in the console / log
|
||||
LogChat = true
|
||||
Debug = false
|
||||
Private = true
|
||||
MaxCars = 20
|
||||
MaxPlayers = 800000
|
||||
Map = "/levels/west_coast_usa/info.json"
|
||||
Description = "BeamMP Default Description"
|
||||
ResourceFolder = "Resources"
|
||||
|
||||
[Misc]
|
||||
# Hides the periodic update message which notifies you of a new server version. You should really keep this on and always update as soon as possible. For more information visit https://wiki.beammp.com/en/home/server-maintenance#updating-the-server. An update message will always appear at startup regardless.
|
||||
ImScaredOfUpdates = false
|
||||
# If SendErrors is `true`, the server will send helpful info about crashes and other issues back to the BeamMP developers. This info may include your config, who is on your server at the time of the error, and similar general information. This kind of data is vital in helping us diagnose and fix issues faster. This has no impact on server performance. You can opt-out of this system by setting this to `false`
|
||||
SendErrorsShowMessage = true
|
||||
# You can turn on/off the SendErrors message you get on startup here
|
||||
SendErrors = true
|
||||
|
||||
[HTTP]
|
||||
# Which IP to listen on. Pick 0.0.0.0 for a public-facing server with no specific IP, and 127.0.0.1 or 'localhost' for a local server.
|
||||
HTTPServerIP = "127.0.0.1"
|
||||
SSLKeyPath = "./.ssl/HttpServer/key.pem"
|
||||
SSLCertPath = "./.ssl/HttpServer/cert.pem"
|
||||
HTTPServerPort = 8080
|
||||
# Recommended to have enabled for servers which face the internet. With SSL the server will serve https and requires valid key and cert files
|
||||
UseSSL = false
|
||||
# Enables the internal HTTP server
|
||||
HTTPServerEnabled = false
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
BeamMP Server implemented in Rust
|
||||
Copyright (C) 2023 - Luuk van Oijen
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -1,36 +1,5 @@
|
||||
# BeamNG-MP-Server
|
||||
# BeamMP Server
|
||||
A BeamMP server implementation in Rust, meant to (hopefully) replace the official server implementation one day.
|
||||
|
||||
## Unix specific build instructions
|
||||
|
||||
1. You need boost >= 1.70.0
|
||||
|
||||
Check with your ditro's package manager whether it provides this. If it does, you should use that.
|
||||
|
||||
|
||||
If it doesnt provide it or you want to link it statically (like we do with our releases), then you have to do this:
|
||||
|
||||
download the latest boost source code.
|
||||
Then, go to the downloaded directory and run
|
||||
```sh
|
||||
b2 link=static runtime-link=static threading=multi
|
||||
```
|
||||
And then either symlink, edit CMakeLists to find it, or simply run
|
||||
```sh
|
||||
b2 link=static runtime-link=static threading=multi install
|
||||
```
|
||||
(warning: installs boost into your system, you might not want this).
|
||||
|
||||
Then on invocation of cmake, ensure that you define `Boost_USE_STATIC_RUNTIME=ON`.
|
||||
|
||||
|
||||
2. Building
|
||||
|
||||
Run cmake, and then make.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
~/src/Server $ cmake -S . -B bin -DCMAKE_BUILD_TYPE=Release
|
||||
...
|
||||
~/src/Server $ make -C bin -j 5
|
||||
```
|
||||
## Features
|
||||
TODO
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,61 @@
|
||||
print("test from lua")
|
||||
print("Player count: " .. MP.GetPlayerCount())
|
||||
|
||||
function onPluginLoaded()
|
||||
print("HI!")
|
||||
end
|
||||
|
||||
function onShutdown()
|
||||
print("BYE!")
|
||||
end
|
||||
|
||||
function onPlayerAuthenticated(joined_name, role, is_guest, identifiers)
|
||||
print("hi welcome mista " .. joined_name)
|
||||
print("u a guest? " .. tostring(is_guest))
|
||||
|
||||
print("current players:")
|
||||
for id, name in pairs(MP.GetPlayers()) do
|
||||
print("- [" .. id .. "]" .. name)
|
||||
end
|
||||
print("yipee")
|
||||
|
||||
print("Player count: " .. MP.GetPlayerCount())
|
||||
|
||||
for key, value in pairs(identifiers) do
|
||||
print(key .. ": " .. value)
|
||||
end
|
||||
|
||||
-- print("now trying with getting it ourself")
|
||||
-- for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
|
||||
-- print(key .. ": " .. value)
|
||||
-- end
|
||||
|
||||
return 0 -- 0 = do not cancel
|
||||
end
|
||||
|
||||
function onPlayerDisconnect(pid, name, identifiers)
|
||||
-- Player is already gone here, so for now, player data is no longer
|
||||
-- requestable for player with the id `pid`
|
||||
print("Player " .. name .. " (" .. pid .. ") has left!")
|
||||
end
|
||||
|
||||
function onChatMessage(pid, name, message)
|
||||
MP.SendChatMessage(-1, "i hate this " .. name .. " guy!")
|
||||
MP.SendChatMessage(pid, "hiii babe i didnt mean it :3")
|
||||
print("" .. name .. " (" .. pid .. "): " .. message)
|
||||
|
||||
print("identifiers:")
|
||||
for key, value in pairs(MP.GetPlayerIdentifiers(pid)) do
|
||||
print(key .. ": " .. value)
|
||||
end
|
||||
|
||||
print("unknown identifiers (nil): " .. tostring(MP.GetPlayerIdentifiers(100)))
|
||||
|
||||
return message .. " (edited by lua!!!)"
|
||||
end
|
||||
|
||||
MP.RegisterEventHandler("onInit", "onPluginLoaded")
|
||||
MP.RegisterEventHandler("onShutdown", "onShutdown")
|
||||
MP.RegisterEventHandler("onPlayerAuth", "onPlayerAuthenticated")
|
||||
MP.RegisterEventHandler("onPlayerDisconnect", "onPlayerDisconnect")
|
||||
MP.RegisterEventHandler("onChatMessage", "onChatMessage")
|
||||
Binary file not shown.
@@ -1,85 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#pragma once
|
||||
#ifdef WIN32
|
||||
#include <WS2tcpip.h>
|
||||
#else
|
||||
#include <arpa/inet.h>
|
||||
#define SOCKET int
|
||||
#endif
|
||||
#include "CustomAssert.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
#include <algorithm>
|
||||
|
||||
struct VData{
|
||||
int ID = -1;
|
||||
std::string Data;
|
||||
};
|
||||
|
||||
class Client {
|
||||
private:
|
||||
std::set<std::unique_ptr<VData>> VehicleData; //ID and Data;
|
||||
std::string Name = Sec("Unknown Client");
|
||||
sockaddr_in UDPADDR;
|
||||
std::string Role;
|
||||
std::string DID;
|
||||
SOCKET TCPSOCK;
|
||||
int Status = 0;
|
||||
int ID = -1;
|
||||
public:
|
||||
void AddNewCar(int ident,const std::string& Data);
|
||||
void SetCarData(int ident,const std::string&Data);
|
||||
void SetName(const std::string& name);
|
||||
void SetRole(const std::string& role);
|
||||
void SetDID(const std::string& did);
|
||||
std::string GetCarData(int ident);
|
||||
void SetUDPAddr(sockaddr_in Addr);
|
||||
std::set<std::unique_ptr<VData>>& GetAllCars();
|
||||
const std::set<std::unique_ptr<VData>>& GetAllCars() const;
|
||||
void SetTCPSock(SOCKET CSock);
|
||||
void SetStatus(int status);
|
||||
void DeleteCar(int ident);
|
||||
sockaddr_in GetUDPAddr();
|
||||
bool isConnected = false;
|
||||
std::string GetRole();
|
||||
std::string GetName();
|
||||
bool isSynced = false;
|
||||
std::string GetDID();
|
||||
SOCKET GetTCPSock();
|
||||
void SetID(int ID);
|
||||
int GetOpenCarID();
|
||||
int GetCarCount();
|
||||
void ClearCars();
|
||||
int GetStatus();
|
||||
int GetID();
|
||||
};
|
||||
struct ClientInterface{
|
||||
std::set<std::unique_ptr<Client>> Clients;
|
||||
void RemoveClient(Client*& c){
|
||||
Assert(c);
|
||||
c->ClearCars();
|
||||
auto Iter = std::find_if(Clients.begin(), Clients.end(), [&](auto& ptr) {
|
||||
return c == ptr.get();
|
||||
});
|
||||
Assert(Iter != Clients.end());
|
||||
if (Iter == Clients.end()) {
|
||||
return;
|
||||
}
|
||||
Clients.erase(Iter);
|
||||
c = nullptr;
|
||||
}
|
||||
void AddClient(Client*&& c){
|
||||
Assert(c);
|
||||
Clients.insert(std::move(std::unique_ptr<Client>(c)));
|
||||
}
|
||||
int Size(){
|
||||
return int(Clients.size());
|
||||
}
|
||||
};
|
||||
|
||||
extern std::unique_ptr<ClientInterface> CI;
|
||||
@@ -1,7 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/24/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
std::string Comp(std::string Data);
|
||||
std::string DeComp(std::string Compressed);
|
||||
@@ -1,7 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
std::string HttpRequest(const std::string& IP, int port);
|
||||
std::string PostHTTP(const std::string& IP, const std::string& Fields);
|
||||
@@ -1,67 +0,0 @@
|
||||
// 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 "Logger.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
|
||||
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
|
||||
@@ -1,18 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 4/2/2020.
|
||||
///
|
||||
#pragma once
|
||||
#include "Security/Xor.h"
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
void InitLog();
|
||||
#define DebugPrintTID() DebugPrintTIDInternal(__func__, false)
|
||||
void DebugPrintTIDInternal(const std::string& func, bool overwrite = true); // prints the current thread id in debug mode, to make tracing of crashes and asserts easier
|
||||
void ConsoleOut(const std::string& msg);
|
||||
void QueueAbort();
|
||||
void except(const std::string& toPrint);
|
||||
void debug(const std::string& toPrint);
|
||||
void error(const std::string& toPrint);
|
||||
void info(const std::string& toPrint);
|
||||
void warn(const std::string& toPrint);
|
||||
@@ -1,77 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/20/2020
|
||||
///
|
||||
|
||||
#pragma once
|
||||
#include <any>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <lua.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
struct LuaArg {
|
||||
std::vector<std::any> args;
|
||||
void PushArgs(lua_State* State) {
|
||||
for (std::any arg : args) {
|
||||
if (!arg.has_value())
|
||||
return;
|
||||
std::string Type = arg.type().name();
|
||||
if (Type.find("bool") != std::string::npos) {
|
||||
lua_pushboolean(State, std::any_cast<bool>(arg));
|
||||
}
|
||||
if (Type.find("basic_string") != std::string::npos || Type.find("char") != std::string::npos) {
|
||||
lua_pushstring(State, std::any_cast<std::string>(arg).c_str());
|
||||
}
|
||||
if (Type.find("int") != std::string::npos) {
|
||||
lua_pushinteger(State, std::any_cast<int>(arg));
|
||||
}
|
||||
if (Type.find("float") != std::string::npos) {
|
||||
lua_pushnumber(State, std::any_cast<float>(arg));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class Lua {
|
||||
private:
|
||||
std::set<std::pair<std::string, std::string>> _RegisteredEvents;
|
||||
lua_State* luaState { nullptr };
|
||||
fs::file_time_type _LastWrote;
|
||||
std::string _PluginName {};
|
||||
std::string _FileName {};
|
||||
bool _StopThread = false;
|
||||
bool _Console = false;
|
||||
|
||||
public:
|
||||
void Init();
|
||||
void RegisterEvent(const std::string& Event, const std::string& FunctionName);
|
||||
std::string GetRegistered(const std::string& Event) const;
|
||||
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();
|
||||
std::string GetPluginName() const;
|
||||
std::string GetFileName() const;
|
||||
lua_State* GetState();
|
||||
const lua_State* GetState() const;
|
||||
std::string GetOrigin();
|
||||
std::mutex Lock;
|
||||
void Reload();
|
||||
Lua(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote, bool Console = false);
|
||||
Lua(bool Console = false);
|
||||
~Lua();
|
||||
void SetStopThread(bool StopThread) { _StopThread = StopThread; }
|
||||
bool GetStopThread() const { return _StopThread; }
|
||||
};
|
||||
int CallFunction(Lua* lua, const std::string& FuncName, std::shared_ptr<LuaArg> args);
|
||||
int TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait);
|
||||
extern std::set<std::unique_ptr<Lua>> PluginEngine;
|
||||
@@ -1,19 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/31/2020
|
||||
///
|
||||
#pragma once
|
||||
#include "Client.hpp"
|
||||
#include <string>
|
||||
void TCPServerMain();
|
||||
void UpdatePlayers();
|
||||
void OnConnect(Client* c);
|
||||
void InitClient(Client* c);
|
||||
void SyncResources(Client* c);
|
||||
[[noreturn]] void UDPServerMain();
|
||||
void OnDisconnect(Client* c, bool kicked);
|
||||
void UDPSend(Client* c, std::string Data);
|
||||
void TCPSend(Client* c, const std::string& Data);
|
||||
void SendLarge(Client* c, std::string Data);
|
||||
void GParser(Client* c, const std::string& Packet);
|
||||
void Respond(Client* c, const std::string& MSG, bool Rel);
|
||||
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel);
|
||||
@@ -1,19 +0,0 @@
|
||||
// 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>
|
||||
|
||||
// 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>;
|
||||
@@ -1,21 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
#ifdef __linux
|
||||
#define EXCEPTION_POINTERS void
|
||||
#else
|
||||
#include <WS2tcpip.h>
|
||||
#endif
|
||||
#include "Xor.h"
|
||||
#include <string>
|
||||
struct RSA {
|
||||
int n = 0;
|
||||
int e = 0;
|
||||
int d = 0;
|
||||
};
|
||||
std::string RSA_E(const std::string& Data, int e, int n);
|
||||
std::string RSA_E(const std::string& Data, RSA* k);
|
||||
std::string RSA_D(const std::string& Data, RSA* k);
|
||||
int Handle(EXCEPTION_POINTERS* ep, char* Origin);
|
||||
RSA* GenKey();
|
||||
@@ -1,132 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/11/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <array>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
#define BEGIN_NAMESPACE(x) namespace x {
|
||||
#define END_NAMESPACE }
|
||||
|
||||
BEGIN_NAMESPACE(XorCompileTime)
|
||||
|
||||
constexpr auto time = __TIME__;
|
||||
constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast<int>(time[1]) * 3600 + static_cast<int>(time[0]) * 36000;
|
||||
|
||||
// 1988, Stephen Park and Keith Miller
|
||||
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
|
||||
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
|
||||
// with 32-bit math and without division
|
||||
|
||||
template <int N>
|
||||
struct RandomGenerator {
|
||||
private:
|
||||
static constexpr unsigned a = 16807; // 7^5
|
||||
static constexpr unsigned m = 2147483647; // 2^31 - 1
|
||||
|
||||
static constexpr unsigned s = RandomGenerator<N - 1>::value;
|
||||
static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807
|
||||
static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807
|
||||
static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits
|
||||
static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi
|
||||
static constexpr unsigned lo3 = lo2 + hi;
|
||||
|
||||
public:
|
||||
static constexpr unsigned max = m;
|
||||
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct RandomGenerator<0> {
|
||||
static constexpr unsigned value = seed;
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct RandomInt {
|
||||
static constexpr auto value = RandomGenerator<N + 1>::value % M;
|
||||
};
|
||||
|
||||
template <int N>
|
||||
struct RandomChar {
|
||||
static const char value = static_cast<char>(1 + RandomInt<N, 0x7F - 1>::value);
|
||||
};
|
||||
|
||||
template <size_t N, int K, typename Char>
|
||||
struct XorString {
|
||||
private:
|
||||
const char _key;
|
||||
std::array<Char, N + 1> _encrypted;
|
||||
|
||||
constexpr Char enc(Char c) const {
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
Char dec(Char c) const {
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
public:
|
||||
template <size_t... Is>
|
||||
constexpr inline XorString(const Char* str, std::index_sequence<Is...>)
|
||||
: _key(RandomChar<K>::value)
|
||||
, _encrypted { enc(str[Is])... } { }
|
||||
|
||||
inline decltype(auto) decrypt() {
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
_encrypted[i] = dec(_encrypted[i]);
|
||||
}
|
||||
_encrypted[N] = '\0';
|
||||
return _encrypted.data();
|
||||
}
|
||||
};
|
||||
|
||||
static auto w_printf = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_printf_s = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
/*static auto w_sprintf = [](char* buf, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
};*/
|
||||
|
||||
/*static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
|
||||
int ret;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
ret = vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
};*/
|
||||
|
||||
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsnprintf(buf, buf_size, fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
||||
int ret;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
ret = vsnprintf(buf, buf_size, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
};
|
||||
#define Sec(s) [] { constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
|
||||
#define SecW(s) [] { constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
|
||||
END_NAMESPACE
|
||||
@@ -1,24 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
extern std::string ServerName;
|
||||
extern std::string ServerDesc;
|
||||
extern std::string StatReport;
|
||||
extern std::string FileSizes;
|
||||
extern std::string Resource;
|
||||
extern std::string FileList;
|
||||
extern std::string CustomIP;
|
||||
extern std::string MapName;
|
||||
extern uint64_t MaxModSize;
|
||||
extern std::string Key;
|
||||
std::string GetSVer();
|
||||
std::string GetCVer();
|
||||
extern int MaxPlayers;
|
||||
extern int ModsLoaded;
|
||||
extern bool Private;
|
||||
extern int MaxCars;
|
||||
extern bool Debug;
|
||||
extern int Port;
|
||||
extern int PPS;
|
||||
@@ -1,12 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#pragma once
|
||||
void InitServer(int argc, char* argv[]);
|
||||
void ConsoleInit();
|
||||
void InitConfig();
|
||||
void InitLua();
|
||||
void InitRes();
|
||||
void HBInit();
|
||||
void StatInit();
|
||||
void NetMain();
|
||||
@@ -1,38 +0,0 @@
|
||||
// Author: lionkor
|
||||
|
||||
#pragma once
|
||||
|
||||
// This header defines unix equivalents of common win32 functions.
|
||||
|
||||
#ifndef WIN32
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include <cstring>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// ZeroMemory is just a {0} or a memset(addr, 0, len), and it's a macro on MSVC
|
||||
inline void ZeroMemory(void* dst, size_t len) {
|
||||
Assert(std::memset(dst, 0, len) != nullptr);
|
||||
}
|
||||
// provides unix equivalent of closesocket call in win32
|
||||
inline void CloseSocketProper(int socket) {
|
||||
shutdown(socket, SHUT_RDWR);
|
||||
close(socket);
|
||||
}
|
||||
|
||||
#ifndef __try
|
||||
#define __try
|
||||
#endif
|
||||
|
||||
#ifndef __except
|
||||
#define __except (x) /**/
|
||||
#endif
|
||||
|
||||
#else // win32
|
||||
|
||||
inline void CloseSocketProper(uint64_t socket) {
|
||||
shutdown(socket, SD_BOTH);
|
||||
closesocket(socket);
|
||||
}
|
||||
#endif // WIN32
|
||||
@@ -1,52 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/15/2020
|
||||
///
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <zlib.h>
|
||||
|
||||
#define Biggest 30000
|
||||
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;
|
||||
}
|
||||
-244
@@ -1,244 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 10/29/2020
|
||||
///
|
||||
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#ifdef WIN32
|
||||
#include <conio.h>
|
||||
#include <windows.h>
|
||||
#else // *nix
|
||||
typedef unsigned long DWORD, *PDWORD, *LPDWORD;
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
#endif // WIN32
|
||||
#include "Logger.h"
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
std::vector<std::string> QConsoleOut;
|
||||
std::string CInputBuff;
|
||||
std::mutex MLock;
|
||||
std::unique_ptr<Lua> LuaConsole;
|
||||
void HandleInput(const std::string& cmd) {
|
||||
std::cout << std::endl;
|
||||
if (cmd == Sec("exit")) {
|
||||
_Exit(0);
|
||||
} else if (cmd == Sec("clear") || cmd == Sec("cls")) {
|
||||
// 2J is clearscreen, H is reset position to top-left
|
||||
ConsoleOut(Sec("\x1b[2J\x1b[H"));
|
||||
} else {
|
||||
LuaConsole->Execute(cmd);
|
||||
}
|
||||
}
|
||||
|
||||
void ProcessOut() {
|
||||
static size_t len = 2;
|
||||
if (QConsoleOut.empty() && len == CInputBuff.length())
|
||||
return;
|
||||
printf("%c[2K\r", 27);
|
||||
for (const std::string& msg : QConsoleOut)
|
||||
if (!msg.empty())
|
||||
std::cout << msg;
|
||||
MLock.lock();
|
||||
QConsoleOut.clear();
|
||||
MLock.unlock();
|
||||
std::cout << "> " << CInputBuff << std::flush;
|
||||
len = CInputBuff.length();
|
||||
}
|
||||
|
||||
void ConsoleOut(const std::string& msg) {
|
||||
MLock.lock();
|
||||
QConsoleOut.emplace_back(msg);
|
||||
MLock.unlock();
|
||||
}
|
||||
|
||||
[[noreturn]] void OutputRefresh() {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
ProcessOut();
|
||||
}
|
||||
}
|
||||
|
||||
#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
|
||||
|
||||
void SetupConsole() {
|
||||
#if defined(WIN32)
|
||||
DWORD outMode = 0;
|
||||
HANDLE stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
if (stdoutHandle == INVALID_HANDLE_VALUE) {
|
||||
error("Invalid console handle! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
if (!GetConsoleMode(stdoutHandle, &outMode)) {
|
||||
error("Invalid console mode! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
// Enable ANSI escape codes
|
||||
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
|
||||
if (!SetConsoleMode(stdoutHandle, outMode)) {
|
||||
error("failed to set console mode! Inputs will not work properly");
|
||||
return;
|
||||
}
|
||||
#else
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
static std::vector<std::string> ConsoleHistory {};
|
||||
static size_t ConsoleHistoryReadIndex { 0 };
|
||||
|
||||
static inline void ConsoleHistoryAdd(const std::string& cmd) {
|
||||
ConsoleHistory.push_back(cmd);
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size();
|
||||
}
|
||||
static std::string CompositeInput;
|
||||
static bool CompositeInputExpected { false };
|
||||
|
||||
static void ProcessCompositeInput() {
|
||||
#ifdef WIN32
|
||||
if (CompositeInput.size() == 1 && memcmp(CompositeInput.data(), std::array<char, 1> { 72 }.data(), 1) == 0) {
|
||||
#else // unix
|
||||
if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 65 }.data(), 2) == 0) {
|
||||
#endif // WIN32
|
||||
|
||||
// UP ARROW
|
||||
// info(std::to_string(ConsoleHistoryReadIndex));
|
||||
if (!ConsoleHistory.empty()) {
|
||||
if (ConsoleHistoryReadIndex != 0) {
|
||||
ConsoleHistoryReadIndex -= 1;
|
||||
}
|
||||
CInputBuff = ConsoleHistory.at(ConsoleHistoryReadIndex);
|
||||
}
|
||||
#ifdef WIN32
|
||||
} else if (CompositeInput.size() == 1 && memcmp(CompositeInput.data(), std::array<char, 1> { 80 }.data(), 1) == 0) {
|
||||
#else // unix
|
||||
} else if (CompositeInput.size() == 2 && memcmp(CompositeInput.data(), std::array<char, 2> { 91, 66 }.data(), 2) == 0) {
|
||||
#endif // WIN32
|
||||
|
||||
// DOWN ARROW
|
||||
if (!ConsoleHistory.empty()) {
|
||||
if (ConsoleHistoryReadIndex != ConsoleHistory.size() - 1) {
|
||||
ConsoleHistoryReadIndex += 1;
|
||||
CInputBuff = ConsoleHistory.at(ConsoleHistoryReadIndex);
|
||||
} else {
|
||||
CInputBuff = "";
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// not composite input, we made a mistake, so lets just add it to the buffer like usual
|
||||
CInputBuff += CompositeInput;
|
||||
}
|
||||
// ensure history doesnt grow too far beyond a max
|
||||
static constexpr size_t MaxHistory = 10;
|
||||
if (ConsoleHistory.size() > 2 * MaxHistory) {
|
||||
std::vector<std::string> NewHistory(ConsoleHistory.begin() + ConsoleHistory.size() - MaxHistory, ConsoleHistory.end());
|
||||
ConsoleHistory = std::move(NewHistory);
|
||||
ConsoleHistoryReadIndex = ConsoleHistory.size();
|
||||
}
|
||||
}
|
||||
|
||||
void ReadCin() {
|
||||
DebugPrintTID();
|
||||
size_t null_byte_counter = 0;
|
||||
while (true) {
|
||||
int In = _getch();
|
||||
//info(std::to_string(In));
|
||||
if (In == 0) {
|
||||
++null_byte_counter;
|
||||
if (null_byte_counter > 50) {
|
||||
info(Sec("too many null bytes in input, this is now assumed to be a background thread - console input is now disabled"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (CompositeInputExpected) {
|
||||
CompositeInput += char(In);
|
||||
#ifdef WIN32
|
||||
if (CompositeInput.size() == 1) {
|
||||
#else // unix
|
||||
if (CompositeInput.size() == 2) {
|
||||
#endif // WIN32
|
||||
CompositeInputExpected = false;
|
||||
ProcessCompositeInput();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (In == 13 || In == '\n') {
|
||||
if (!CInputBuff.empty()) {
|
||||
HandleInput(CInputBuff);
|
||||
ConsoleHistoryAdd(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
}
|
||||
} else if (In == 8 || In == 127) {
|
||||
if (!CInputBuff.empty())
|
||||
CInputBuff.pop_back();
|
||||
} else if (In == 4) {
|
||||
CInputBuff = "exit";
|
||||
HandleInput(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
} else if (In == 12) {
|
||||
CInputBuff = "clear";
|
||||
HandleInput(CInputBuff);
|
||||
CInputBuff.clear();
|
||||
#ifdef WIN32
|
||||
} else if (In == 224) {
|
||||
#else // unix
|
||||
} else if (In == 27) {
|
||||
#endif // WIN32
|
||||
|
||||
// escape char, assume stuff follows
|
||||
CompositeInputExpected = true;
|
||||
CompositeInput.clear();
|
||||
} else if (!isprint(In)) {
|
||||
// ignore
|
||||
} else {
|
||||
CInputBuff += char(In);
|
||||
}
|
||||
}
|
||||
}
|
||||
void ConsoleInit() {
|
||||
SetupConsole();
|
||||
LuaConsole = std::make_unique<Lua>(true);
|
||||
LuaConsole->Init();
|
||||
printf("> ");
|
||||
std::thread In(ReadCin);
|
||||
In.detach();
|
||||
std::thread Out(OutputRefresh);
|
||||
Out.detach();
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include "CustomAssert.h"
|
||||
#include "Settings.h"
|
||||
//#include <windows.h>
|
||||
#include "Logger.h"
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
int Rand() {
|
||||
std::random_device r;
|
||||
std::default_random_engine e1(r());
|
||||
std::uniform_int_distribution<int> uniform_dist(1, 5000);
|
||||
return uniform_dist(e1);
|
||||
}
|
||||
|
||||
int log_power(int n, unsigned int p, int mod) {
|
||||
int result = 1;
|
||||
for (; p; p >>= 1u) {
|
||||
if (p & 1u)
|
||||
result = int((1LL * result * n) % mod);
|
||||
n = int((1LL * n * n) % mod);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
bool rabin_miller(int n) {
|
||||
bool ok = true;
|
||||
for (int i = 1; i <= 5 && ok; i++) {
|
||||
int a = Rand() + 1;
|
||||
int result = log_power(a, n - 1, n);
|
||||
ok &= (result == 1);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
int generate_prime() {
|
||||
int generated = Rand();
|
||||
while (!rabin_miller(generated))
|
||||
generated = Rand();
|
||||
return generated;
|
||||
}
|
||||
int gcd(int a, int b) {
|
||||
while (b) {
|
||||
int r = a % b;
|
||||
a = b;
|
||||
b = r;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
int generate_coprime(int n) {
|
||||
int generated = Rand();
|
||||
while (gcd(n, generated) != 1)
|
||||
generated = Rand();
|
||||
return generated;
|
||||
}
|
||||
|
||||
std::pair<int, int> euclid_extended(int a, int b) {
|
||||
if (!b)
|
||||
return { 1, 0 };
|
||||
auto result = euclid_extended(b, a % b);
|
||||
return { result.second, result.first - (a / b) * result.second };
|
||||
}
|
||||
|
||||
int modular_inverse(int n, int mod) {
|
||||
int inverse = euclid_extended(n, mod).first;
|
||||
while (inverse < 0)
|
||||
inverse += mod;
|
||||
return inverse;
|
||||
}
|
||||
|
||||
RSA* GenKey() {
|
||||
int p, q;
|
||||
p = generate_prime();
|
||||
q = generate_prime();
|
||||
int n = p * q;
|
||||
int phi = (p - 1) * (q - 1);
|
||||
int e = generate_coprime(phi);
|
||||
int d = modular_inverse(e, phi);
|
||||
return new RSA { n, e, d };
|
||||
}
|
||||
|
||||
int Enc(int value, int e, int n) {
|
||||
return log_power(value, e, n);
|
||||
}
|
||||
|
||||
int Dec(int value, int d, int n) {
|
||||
return log_power(value, d, n);
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
int Handle(EXCEPTION_POINTERS* ep, char* Origin) {
|
||||
//Assert(false);
|
||||
std::stringstream R;
|
||||
R << Sec("Code : ") << std::hex
|
||||
<< ep->ExceptionRecord->ExceptionCode
|
||||
<< std::dec << Sec(" Origin : ") << Origin;
|
||||
except(R.str());
|
||||
return 1;
|
||||
}
|
||||
#else
|
||||
// stub
|
||||
int Handle(EXCEPTION_POINTERS*, char*) { return 1; }
|
||||
#endif // WIN32
|
||||
|
||||
std::string RSA_E(const std::string& Data, RSA* k) {
|
||||
std::stringstream stream;
|
||||
for (const char& c : Data) {
|
||||
stream << std::hex << Enc(uint8_t(c), k->e, k->n) << "g";
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
std::string RSA_E(const std::string& Data, int e, int n) {
|
||||
std::stringstream stream;
|
||||
for (const char& c : Data) {
|
||||
stream << std::hex << Enc(uint8_t(c), e, n) << "g";
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
std::string RSA_D(const std::string& Data, RSA* k) {
|
||||
std::stringstream ss(Data);
|
||||
std::string token, ret;
|
||||
while (std::getline(ss, token, 'g')) {
|
||||
if (token.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)
|
||||
return "";
|
||||
int c = std::stoi(token, nullptr, 16);
|
||||
ret += char(Dec(c, k->d, k->n));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "CustomAssert.h"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
std::string ServerName;
|
||||
std::string ServerDesc;
|
||||
std::string Resource;
|
||||
std::string MapName;
|
||||
std::string Key;
|
||||
int MaxPlayers;
|
||||
bool Private;
|
||||
int MaxCars;
|
||||
bool Debug;
|
||||
int Port;
|
||||
|
||||
void SetValues(const std::string& Line, int Index) {
|
||||
int state = 0;
|
||||
std::string Data;
|
||||
bool Switch = false;
|
||||
if (Index > 5)
|
||||
Switch = true;
|
||||
for (char c : Line) {
|
||||
if (Switch) {
|
||||
if (c == '\"')
|
||||
state++;
|
||||
if (state > 0 && state < 2)
|
||||
Data += c;
|
||||
} else {
|
||||
if (c == ' ')
|
||||
state++;
|
||||
if (state > 1)
|
||||
Data += c;
|
||||
}
|
||||
}
|
||||
Data = Data.substr(1);
|
||||
std::string::size_type sz;
|
||||
bool FoundTrue = std::string(Data).find("true") != std::string::npos; //searches for "true"
|
||||
switch (Index) {
|
||||
case 1:
|
||||
Debug = FoundTrue; //checks and sets the Debug Value
|
||||
break;
|
||||
case 2:
|
||||
Private = FoundTrue; //checks and sets the Private Value
|
||||
break;
|
||||
case 3:
|
||||
Port = std::stoi(Data, &sz); //sets the Port
|
||||
break;
|
||||
case 4:
|
||||
MaxCars = std::stoi(Data, &sz); //sets the Max Car amount
|
||||
break;
|
||||
case 5:
|
||||
MaxPlayers = std::stoi(Data, &sz); //sets the Max Amount of player
|
||||
break;
|
||||
case 6:
|
||||
MapName = Data; //Map
|
||||
break;
|
||||
case 7:
|
||||
ServerName = Data; //Name
|
||||
break;
|
||||
case 8:
|
||||
ServerDesc = Data; //desc
|
||||
break;
|
||||
case 9:
|
||||
Resource = Data; //File name
|
||||
break;
|
||||
case 10:
|
||||
Key = Data; //File name
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::string RemoveComments(const std::string& Line) {
|
||||
std::string Return;
|
||||
for (char c : Line) {
|
||||
if (c == '#')
|
||||
break;
|
||||
Return += c;
|
||||
}
|
||||
return Return;
|
||||
}
|
||||
void LoadConfig(std::ifstream& IFS) {
|
||||
Assert(IFS.is_open());
|
||||
std::string line;
|
||||
int index = 1;
|
||||
while (getline(IFS, line)) {
|
||||
index++;
|
||||
}
|
||||
if (index - 1 < 11) {
|
||||
error(Sec("Outdated/Incorrect config please remove it server will close in 5 secs"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
IFS.close();
|
||||
IFS.open(Sec("Server.cfg"));
|
||||
info(Sec("Config found updating values"));
|
||||
index = 1;
|
||||
while (getline(IFS, line)) {
|
||||
if (line.rfind('#', 0) != 0 && line.rfind(' ', 0) != 0) { //Checks if it starts as Comment
|
||||
std::string CleanLine = RemoveComments(line); //Cleans it from the Comments
|
||||
SetValues(CleanLine, index); //sets the values
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
void GenerateConfig() {
|
||||
std::ofstream FileStream;
|
||||
FileStream.open(Sec("Server.cfg"));
|
||||
FileStream << Sec("# This is the BeamMP Server Configuration File v0.60\n"
|
||||
"Debug = false # true or false to enable debug console output\n"
|
||||
"Private = true # Private?\n"
|
||||
"Port = 30814 # Port to run the server on UDP and TCP\n"
|
||||
"Cars = 1 # Max cars for every player\n"
|
||||
"MaxPlayers = 10 # Maximum Amount of Clients\n"
|
||||
"Map = \"/levels/gridmap/info.json\" # Default Map\n"
|
||||
"Name = \"BeamMP New Server\" # Server Name\n"
|
||||
"Desc = \"BeamMP Default Description\" # Server Description\n"
|
||||
"use = \"Resources\" # Resource file name\n"
|
||||
"AuthKey = \"\" # Auth Key");
|
||||
FileStream.close();
|
||||
}
|
||||
void Default() {
|
||||
info(Sec("Config not found generating default"));
|
||||
GenerateConfig();
|
||||
error(Sec("You are required to input the AuthKey"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
void DebugData() {
|
||||
debug(std::string(Sec("Debug : ")) + (Debug ? "true" : "false"));
|
||||
debug(std::string(Sec("Private : ")) + (Private ? "true" : "false"));
|
||||
debug(Sec("Port : ") + std::to_string(Port));
|
||||
debug(Sec("Max Cars : ") + std::to_string(MaxCars));
|
||||
debug(Sec("MaxPlayers : ") + std::to_string(MaxPlayers));
|
||||
debug(Sec("MapName : ") + MapName);
|
||||
debug(Sec("ServerName : ") + ServerName);
|
||||
debug(Sec("ServerDesc : ") + ServerDesc);
|
||||
debug(Sec("File : ") + Resource);
|
||||
debug(Sec("Key length: ") + std::to_string(Key.length()));
|
||||
}
|
||||
void InitConfig() {
|
||||
std::ifstream IFS;
|
||||
IFS.open(Sec("Server.cfg"));
|
||||
if (IFS.good())
|
||||
LoadConfig(IFS);
|
||||
else
|
||||
Default();
|
||||
if (IFS.is_open())
|
||||
IFS.close();
|
||||
if (Key.empty()) {
|
||||
error(Sec("No AuthKey was found"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
if (Debug)
|
||||
DebugData();
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Curl/Http.h"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
void WebsocketInit();
|
||||
std::string GetPlayers() {
|
||||
std::string Return;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
Return += c->GetName() + ";";
|
||||
}
|
||||
}
|
||||
return Return;
|
||||
}
|
||||
std::string GenerateCall() {
|
||||
std::stringstream Ret;
|
||||
Ret << "uuid=" << Key << "&players=" << CI->Size()
|
||||
<< "&maxplayers=" << MaxPlayers << "&port=" << Port
|
||||
<< "&map=" << MapName << "&private=" << (Private ? "true" : "false")
|
||||
<< "&version=" << GetSVer() << "&clientversion=" << GetCVer()
|
||||
<< "&name=" << ServerName << "&pps=" << StatReport
|
||||
<< "&modlist=" << FileList << "&modstotalsize=" << MaxModSize
|
||||
<< "&modstotal=" << ModsLoaded << "&playerslist=" << GetPlayers()
|
||||
<< "&desc=" << ServerDesc;
|
||||
return Ret.str();
|
||||
}
|
||||
std::string RunPromise(const std::string& IP, const std::string& R) {
|
||||
std::packaged_task<std::string()> task([&] { return PostHTTP(IP, R); });
|
||||
std::future<std::string> f1 = task.get_future();
|
||||
std::thread t(std::move(task));
|
||||
t.detach();
|
||||
auto status = f1.wait_for(std::chrono::seconds(10));
|
||||
if (status != std::future_status::timeout)
|
||||
return f1.get();
|
||||
error(Sec("Backend system Timeout please try again later"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}
|
||||
|
||||
void Heartbeat() {
|
||||
DebugPrintTID();
|
||||
std::string R, T;
|
||||
bool isAuth = false;
|
||||
while (true) {
|
||||
R = GenerateCall();
|
||||
if (!CustomIP.empty())
|
||||
R += "&ip=" + CustomIP;
|
||||
std::string link = Sec("https://beammp.com/heartbeatv2");
|
||||
T = RunPromise(link, R);
|
||||
if (T.find_first_not_of(Sec("20")) != std::string::npos) {
|
||||
//Backend system refused server startup!
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
std::string Backup = Sec("https://backup1.beammp.com/heartbeatv2");
|
||||
T = RunPromise(Backup, R);
|
||||
if (T.find_first_not_of(Sec("20")) != std::string::npos) {
|
||||
error(Sec("Backend system refused server! Check your AuthKey"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(-1);
|
||||
}
|
||||
}
|
||||
//Server Authenticated
|
||||
if (T.length() == 4)
|
||||
info(Sec("Server authenticated"));
|
||||
R.clear();
|
||||
T.clear();
|
||||
if (!isAuth) {
|
||||
WebsocketInit();
|
||||
isAuth = true;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
}
|
||||
}
|
||||
void HBInit() {
|
||||
std::thread HB(Heartbeat);
|
||||
HB.detach();
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
uint64_t MaxModSize = 0;
|
||||
std::string FileSizes;
|
||||
std::string FileList;
|
||||
int ModsLoaded = 0;
|
||||
|
||||
void InitRes() {
|
||||
std::string Path = Resource + Sec("/Client");
|
||||
if (!fs::exists(Path))
|
||||
fs::create_directory(Path);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().string().find(Sec(".zip"));
|
||||
if (pos != std::string::npos) {
|
||||
if (entry.path().string().length() - pos == 4) {
|
||||
FileList += entry.path().string() + ";";
|
||||
FileSizes += std::to_string(fs::file_size(entry.path())) + ";";
|
||||
MaxModSize += fs::file_size(entry.path());
|
||||
ModsLoaded++;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::replace(FileList.begin(), FileList.end(), '\\', '/');
|
||||
if (ModsLoaded) {
|
||||
info(Sec("Loaded ") + std::to_string(ModsLoaded) + Sec(" Mods"));
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/28/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
std::string CustomIP;
|
||||
std::string GetSVer() {
|
||||
return std::string(Sec("1.13"));
|
||||
}
|
||||
std::string GetCVer() {
|
||||
return std::string(Sec("1.70"));
|
||||
}
|
||||
void Args(int argc, char* argv[]) {
|
||||
info(Sec("BeamMP Server Running version ") + GetSVer());
|
||||
if (argc > 1) {
|
||||
CustomIP = argv[1];
|
||||
size_t n = std::count(CustomIP.begin(), CustomIP.end(), '.');
|
||||
auto p = CustomIP.find_first_not_of(Sec(".0123456789"));
|
||||
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == Sec("127")) {
|
||||
CustomIP.clear();
|
||||
warn(Sec("IP Specified is invalid! Ignoring"));
|
||||
} else
|
||||
info(Sec("Server started with custom IP"));
|
||||
}
|
||||
}
|
||||
void InitServer(int argc, char* argv[]) {
|
||||
InitLog();
|
||||
Args(argc, argv);
|
||||
CI = std::make_unique<ClientInterface>();
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/20/2020
|
||||
///
|
||||
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <thread>
|
||||
|
||||
#ifdef __linux
|
||||
// we need this for `struct stat`
|
||||
#include <sys/stat.h>
|
||||
#endif // __linux
|
||||
|
||||
std::set<std::unique_ptr<Lua>> PluginEngine;
|
||||
bool NewFile(const std::string& Path) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Path == Script->GetFileName())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void RegisterFiles(const std::string& Path, bool HotSwap) {
|
||||
std::string Name = Path.substr(Path.find_last_of('\\') + 1);
|
||||
if (!HotSwap)
|
||||
info(Sec("Loading plugin : ") + Name);
|
||||
for (const auto& entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().string().find(Sec(".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<Lua> ScriptToInsert(new Lua(Name, FileName, fs::last_write_time(FileName)));
|
||||
auto& Script = *ScriptToInsert;
|
||||
PluginEngine.insert(std::move(ScriptToInsert));
|
||||
Script.Init();
|
||||
if (HotSwap)
|
||||
info(Sec("[HOTSWAP] Added : ") + Script.GetFileName().substr(Script.GetFileName().find('\\')));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
[[noreturn]] void HotSwaps(const std::string& path) {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
if (!PluginEngine.empty()) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
struct stat Info { };
|
||||
if (stat(Script->GetFileName().c_str(), &Info) != 0) {
|
||||
Script->SetStopThread(true);
|
||||
PluginEngine.erase(Script);
|
||||
info(Sec("[HOTSWAP] Removed removed script due to delete"));
|
||||
break;
|
||||
}
|
||||
if (Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())) {
|
||||
Script->SetStopThread(true);
|
||||
info(Sec("[HOTSWAP] Updated Scripts due to edit"));
|
||||
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
|
||||
Script->Reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
FolderList(path, true);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
|
||||
void InitLua() {
|
||||
if (!fs::exists(Resource)) {
|
||||
fs::create_directory(Resource);
|
||||
}
|
||||
std::string Path = Resource + Sec("/Server");
|
||||
if (!fs::exists(Path)) {
|
||||
fs::create_directory(Path);
|
||||
}
|
||||
FolderList(Path, false);
|
||||
std::thread t1(HotSwaps, Path);
|
||||
t1.detach();
|
||||
info(Sec("Lua system online"));
|
||||
}
|
||||
@@ -1,668 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/19/2020
|
||||
///
|
||||
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
std::shared_ptr<LuaArg> CreateArg(lua_State* L, int T, int S) {
|
||||
if (S > T)
|
||||
return nullptr;
|
||||
std::shared_ptr<LuaArg> temp(new LuaArg);
|
||||
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::optional<std::reference_wrapper<Lua>> GetScript(lua_State* L) {
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Script->GetState() == L)
|
||||
return *Script;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
void SendError(lua_State* L, const std::string& msg) {
|
||||
Assert(L);
|
||||
auto MaybeS = GetScript(L);
|
||||
std::string a;
|
||||
if (!MaybeS.has_value()) {
|
||||
a = Sec("_Console");
|
||||
} else {
|
||||
Lua& S = MaybeS.value();
|
||||
a = fs::path(S.GetFileName()).filename().string();
|
||||
}
|
||||
warn(a + Sec(" | Incorrect Call of ") + msg);
|
||||
}
|
||||
int Trigger(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg) {
|
||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
||||
std::packaged_task<int(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return CallFunction(lua, R, arg); });
|
||||
std::future<int> 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->GetState(), R + " took too long to respond");
|
||||
return 0;
|
||||
}
|
||||
int FutureWait(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg, bool Wait) {
|
||||
Assert(lua);
|
||||
std::packaged_task<int(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return Trigger(lua, R, arg); });
|
||||
std::future<int> 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;
|
||||
}
|
||||
int TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait) {
|
||||
int R = 0;
|
||||
for (auto& Script : PluginEngine) {
|
||||
if (Script->IsRegistered(Event)) {
|
||||
if (local) {
|
||||
if (Script->GetPluginName() == Caller->GetPluginName()) {
|
||||
R += FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
||||
}
|
||||
} else
|
||||
R += FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
|
||||
}
|
||||
}
|
||||
return R;
|
||||
}
|
||||
bool ConsoleCheck(lua_State* L, int r) {
|
||||
if (r != LUA_OK) {
|
||||
std::string msg = lua_tostring(L, -1);
|
||||
warn(Sec("_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 = GetScript(L);
|
||||
if (MaybeS.has_value()) {
|
||||
Lua& 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 = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& 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(L, Sec("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 = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& 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(L, Sec("TriggerLocalEvent wrong argument [1] need string"));
|
||||
} else {
|
||||
SendError(L, Sec("TriggerLocalEvent not enough arguments expected 1 got 0"));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lua_TriggerEventG(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
auto MaybeScript = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& 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(L, Sec("TriggerGlobalEvent wrong argument [1] need string"));
|
||||
} else
|
||||
SendError(L, Sec("TriggerGlobalEvent not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
|
||||
char* ThreadOrigin(Lua* lua) {
|
||||
std::string T = "Thread in " + fs::path(lua->GetFileName()).filename().string();
|
||||
char* Data = new char[T.size() + 1];
|
||||
ZeroMemory(Data, T.size() + 1);
|
||||
memcpy(Data, T.c_str(), T.size());
|
||||
return Data;
|
||||
}
|
||||
void SafeExecution(Lua* lua, const std::string& FuncName) {
|
||||
lua_State* luaState = lua->GetState();
|
||||
lua_getglobal(luaState, FuncName.c_str());
|
||||
if (lua_isfunction(luaState, -1)) {
|
||||
char* Origin = ThreadOrigin(lua);
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
int R = lua_pcall(luaState, 0, 0, 0);
|
||||
CheckLua(luaState, R);
|
||||
} __except (Handle(GetExceptionInformation(), Origin)) {
|
||||
}
|
||||
#else // unix
|
||||
int R = lua_pcall(luaState, 0, 0, 0);
|
||||
CheckLua(luaState, R);
|
||||
#endif // WIN32
|
||||
delete[] Origin;
|
||||
}
|
||||
ClearStack(luaState);
|
||||
}
|
||||
|
||||
void ExecuteAsync(Lua* lua, const std::string& FuncName) {
|
||||
std::lock_guard<std::mutex> lockGuard(lua->Lock);
|
||||
SafeExecution(lua, FuncName);
|
||||
}
|
||||
void CallAsync(Lua* lua, const std::string& Func, int U) {
|
||||
DebugPrintTID();
|
||||
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 = 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 = GetScript(L);
|
||||
Assert(MaybeScript.has_value());
|
||||
Lua& Script = MaybeScript.value();
|
||||
std::thread t1(CallAsync, &Script, STR, U);
|
||||
t1.detach();
|
||||
} else
|
||||
SendError(L, Sec("CreateThread wrong argument [2] number must be between 1 and 500"));
|
||||
} else
|
||||
SendError(L, Sec("CreateThread wrong argument [2] need number"));
|
||||
} else
|
||||
SendError(L, Sec("CreateThread wrong argument [1] need string"));
|
||||
} else
|
||||
SendError(L, Sec("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(L, Sec("Sleep not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
Client* GetClient(int ID) {
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
return c.get();
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
int lua_isConnected(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushboolean(L, c->isConnected);
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, Sec("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));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushstring(L, c->GetName().c_str());
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, Sec("GetPlayerName not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_GetPlayerCount(lua_State* L) {
|
||||
lua_pushinteger(L, CI->Size());
|
||||
return 1;
|
||||
}
|
||||
int lua_GetDID(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr)
|
||||
lua_pushstring(L, c->GetDID().c_str());
|
||||
else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, Sec("GetDID not enough arguments"));
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int lua_GetAllPlayers(lua_State* L) {
|
||||
lua_newtable(L);
|
||||
int i = 1;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c == nullptr)
|
||||
continue;
|
||||
lua_pushinteger(L, c->GetID());
|
||||
lua_pushstring(L, c->GetName().c_str());
|
||||
lua_settable(L, -3);
|
||||
i++;
|
||||
}
|
||||
if (CI->Clients.empty())
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
int lua_GetCars(lua_State* L) {
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int ID = int(lua_tonumber(L, 1));
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr) {
|
||||
int i = 1;
|
||||
for (auto& v : c->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
lua_pushinteger(L, v->ID);
|
||||
lua_pushstring(L, v->Data.substr(3).c_str());
|
||||
lua_settable(L, -3);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (c->GetAllCars().empty())
|
||||
return 0;
|
||||
} else
|
||||
return 0;
|
||||
} else {
|
||||
SendError(L, Sec("GetPlayerVehicles not enough 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));
|
||||
Client* c = GetClient(ID);
|
||||
if (c == nullptr)
|
||||
return 0;
|
||||
if (c->GetRole() == Sec("MDEV"))
|
||||
return 0;
|
||||
std::string Reason;
|
||||
if (Args > 1 && lua_isstring(L, 2)) {
|
||||
Reason = std::string(Sec(" Reason : ")) + lua_tostring(L, 2);
|
||||
}
|
||||
Respond(c, "C:Server:You have been Kicked from the server! " + Reason, true);
|
||||
c->SetStatus(-2);
|
||||
info(Sec("Closing socket due to kick"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
|
||||
} else
|
||||
SendError(L, Sec("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));
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
} else {
|
||||
Client* c = GetClient(ID);
|
||||
if (c != nullptr) {
|
||||
if (!c->isSynced)
|
||||
return 0;
|
||||
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
|
||||
Respond(c, Packet, true);
|
||||
} else
|
||||
SendError(L, Sec("SendChatMessage invalid argument [1] invalid ID"));
|
||||
}
|
||||
} else
|
||||
SendError(L, Sec("SendChatMessage invalid argument [2] expected string"));
|
||||
} else
|
||||
SendError(L, Sec("SendChatMessage invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
int lua_RemoveVehicle(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args != 2) {
|
||||
SendError(L, Sec("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));
|
||||
Client* c = GetClient(PID);
|
||||
if (c == nullptr) {
|
||||
SendError(L, Sec("RemoveVehicle invalid Player ID"));
|
||||
return 0;
|
||||
}
|
||||
if (c->GetRole() == "MDEV")
|
||||
return 0;
|
||||
if (!c->GetCarData(VID).empty()) {
|
||||
std::string Destroy = "Od:" + std::to_string(PID) + "-" + std::to_string(VID);
|
||||
SendToAll(nullptr, Destroy, true, true);
|
||||
c->DeleteCar(VID);
|
||||
}
|
||||
} else
|
||||
SendError(L, Sec("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(L, Sec("TriggerClientEvent invalid argument count expected 3 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isnumber(L, 1)) {
|
||||
SendError(L, Sec("TriggerClientEvent invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isstring(L, 2)) {
|
||||
SendError(L, Sec("TriggerClientEvent invalid argument [2] expected string"));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isstring(L, 3)) {
|
||||
SendError(L, Sec("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)
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
else {
|
||||
Client* c = GetClient(ID);
|
||||
if (c == nullptr) {
|
||||
SendError(L, Sec("TriggerClientEvent invalid Player ID"));
|
||||
return 0;
|
||||
}
|
||||
Respond(c, Packet, true);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
int lua_ServerExit(lua_State*) {
|
||||
_Exit(0);
|
||||
}
|
||||
int lua_Set(lua_State* L) {
|
||||
int Args = lua_gettop(L);
|
||||
if (Args != 2) {
|
||||
SendError(L, Sec("set invalid argument count expected 2 got ") + std::to_string(Args));
|
||||
return 0;
|
||||
}
|
||||
if (!lua_isnumber(L, 1)) {
|
||||
SendError(L, Sec("set invalid argument [1] expected number"));
|
||||
return 0;
|
||||
}
|
||||
auto MaybeSrc = GetScript(L);
|
||||
std::string Name;
|
||||
if (!MaybeSrc.has_value()) {
|
||||
Name = Sec("_Console");
|
||||
} else {
|
||||
Name = MaybeSrc.value().get().GetPluginName();
|
||||
}
|
||||
int C = int(lua_tointeger(L, 1));
|
||||
switch (C) {
|
||||
case 0: //debug
|
||||
if (lua_isboolean(L, 2)) {
|
||||
Debug = lua_toboolean(L, 2);
|
||||
info(Name + Sec(" | Debug -> ") + (Debug ? "true" : "false"));
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected boolean for ID : 0"));
|
||||
break;
|
||||
case 1: //private
|
||||
if (lua_isboolean(L, 2)) {
|
||||
Private = lua_toboolean(L, 2);
|
||||
info(Name + Sec(" | Private -> ") + (Private ? "true" : "false"));
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected boolean for ID : 1"));
|
||||
break;
|
||||
case 2: //max cars
|
||||
if (lua_isnumber(L, 2)) {
|
||||
MaxCars = int(lua_tointeger(L, 2));
|
||||
info(Name + Sec(" | MaxCars -> ") + std::to_string(MaxCars));
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected number for ID : 2"));
|
||||
break;
|
||||
case 3: //max players
|
||||
if (lua_isnumber(L, 2)) {
|
||||
MaxPlayers = int(lua_tointeger(L, 2));
|
||||
info(Name + Sec(" | MaxPlayers -> ") + std::to_string(MaxPlayers));
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected number for ID : 3"));
|
||||
break;
|
||||
case 4: //Map
|
||||
if (lua_isstring(L, 2)) {
|
||||
MapName = lua_tostring(L, 2);
|
||||
info(Name + Sec(" | MapName -> ") + MapName);
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected string for ID : 4"));
|
||||
break;
|
||||
case 5: //Name
|
||||
if (lua_isstring(L, 2)) {
|
||||
ServerName = lua_tostring(L, 2);
|
||||
info(Name + Sec(" | ServerName -> ") + ServerName);
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected string for ID : 5"));
|
||||
break;
|
||||
case 6: //Desc
|
||||
if (lua_isstring(L, 2)) {
|
||||
ServerDesc = lua_tostring(L, 2);
|
||||
info(Name + Sec(" | ServerDesc -> ") + ServerDesc);
|
||||
} else
|
||||
SendError(L, Sec("set invalid argument [2] expected string for ID : 6"));
|
||||
break;
|
||||
default:
|
||||
warn(Sec("Invalid config ID : ") + std::to_string(C));
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
extern "C" {
|
||||
int lua_Print(lua_State* L) {
|
||||
int Arg = lua_gettop(L);
|
||||
for (int i = 1; i <= Arg; i++) {
|
||||
auto str = lua_tostring(L, i);
|
||||
if (str != nullptr) {
|
||||
ConsoleOut(str + std::string(Sec("\n")));
|
||||
} else {
|
||||
ConsoleOut(Sec("nil\n"));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Lua::Lua(const std::string& PluginName, const std::string& FileName, fs::file_time_type LastWrote, bool Console)
|
||||
: luaState(luaL_newstate()) {
|
||||
Assert(luaState);
|
||||
if (!PluginName.empty()) {
|
||||
SetPluginName(PluginName);
|
||||
}
|
||||
if (!FileName.empty()) {
|
||||
SetFileName(FileName);
|
||||
}
|
||||
SetLastWrite(LastWrote);
|
||||
_Console = Console;
|
||||
}
|
||||
|
||||
Lua::Lua(bool Console)
|
||||
: luaState(luaL_newstate()) {
|
||||
_Console = Console;
|
||||
}
|
||||
|
||||
void Lua::Execute(const std::string& Command) {
|
||||
if (ConsoleCheck(luaState, luaL_dostring(luaState, Command.c_str()))) {
|
||||
lua_settop(luaState, 0);
|
||||
}
|
||||
}
|
||||
void Lua::Reload() {
|
||||
if (CheckLua(luaState, luaL_dofile(luaState, _FileName.c_str()))) {
|
||||
CallFunction(this, Sec("onInit"), nullptr);
|
||||
}
|
||||
}
|
||||
std::string Lua::GetOrigin() {
|
||||
return fs::path(GetFileName()).filename().string();
|
||||
}
|
||||
|
||||
int CallFunction(Lua* lua, const std::string& FuncName, std::shared_ptr<LuaArg> Arg) {
|
||||
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);
|
||||
}
|
||||
std::string Origin = lua->GetOrigin();
|
||||
int R = lua_pcall(luaState, Size, 1, 0);
|
||||
if (CheckLua(luaState, R)) {
|
||||
if (lua_isnumber(luaState, -1)) {
|
||||
return int(lua_tointeger(luaState, -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
ClearStack(luaState);
|
||||
return 0;
|
||||
}
|
||||
void Lua::SetPluginName(const std::string& Name) {
|
||||
_PluginName = Name;
|
||||
}
|
||||
void Lua::SetFileName(const std::string& Name) {
|
||||
_FileName = Name;
|
||||
}
|
||||
void Lua::Init() {
|
||||
Assert(luaState);
|
||||
luaL_openlibs(luaState);
|
||||
lua_register(luaState, "TriggerGlobalEvent", lua_TriggerEventG);
|
||||
lua_register(luaState, "TriggerLocalEvent", lua_TriggerEventL);
|
||||
lua_register(luaState, "TriggerClientEvent", lua_RemoteEvent);
|
||||
lua_register(luaState, "GetPlayerCount", lua_GetPlayerCount);
|
||||
lua_register(luaState, "isPlayerConnected", lua_isConnected);
|
||||
lua_register(luaState, "RegisterEvent", lua_RegisterEvent);
|
||||
lua_register(luaState, "GetPlayerName", lua_GetPlayerName);
|
||||
lua_register(luaState, "RemoveVehicle", lua_RemoveVehicle);
|
||||
lua_register(luaState, "GetPlayerDiscordID", lua_GetDID);
|
||||
lua_register(luaState, "GetPlayerVehicles", lua_GetCars);
|
||||
lua_register(luaState, "CreateThread", lua_CreateThread);
|
||||
lua_register(luaState, "SendChatMessage", lua_sendChat);
|
||||
lua_register(luaState, "GetPlayers", lua_GetAllPlayers);
|
||||
lua_register(luaState, "StopThread", lua_StopThread);
|
||||
lua_register(luaState, "DropPlayer", lua_dropPlayer);
|
||||
lua_register(luaState, "GetPlayerHWID", lua_HWID);
|
||||
lua_register(luaState, "exit", lua_ServerExit);
|
||||
lua_register(luaState, "Sleep", lua_Sleep);
|
||||
lua_register(luaState, "print", lua_Print);
|
||||
lua_register(luaState, "Set", lua_Set);
|
||||
if (!_Console)
|
||||
Reload();
|
||||
}
|
||||
|
||||
void Lua::RegisterEvent(const std::string& Event, const std::string& FunctionName) {
|
||||
_RegisteredEvents.insert(std::make_pair(Event, FunctionName));
|
||||
}
|
||||
void Lua::UnRegisterEvent(const std::string& Event) {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event) {
|
||||
_RegisteredEvents.erase(a);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool Lua::IsRegistered(const std::string& Event) {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::string Lua::GetRegistered(const std::string& Event) const {
|
||||
for (const std::pair<std::string, std::string>& a : _RegisteredEvents) {
|
||||
if (a.first == Event)
|
||||
return a.second;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
std::string Lua::GetFileName() const {
|
||||
return _FileName;
|
||||
}
|
||||
std::string Lua::GetPluginName() const {
|
||||
return _PluginName;
|
||||
}
|
||||
lua_State* Lua::GetState() {
|
||||
return luaState;
|
||||
}
|
||||
|
||||
const lua_State* Lua::GetState() const {
|
||||
return luaState;
|
||||
}
|
||||
|
||||
void Lua::SetLastWrite(fs::file_time_type time) {
|
||||
_LastWrote = time;
|
||||
}
|
||||
fs::file_time_type Lua::GetLastWrite() {
|
||||
return _LastWrote;
|
||||
}
|
||||
|
||||
Lua::~Lua() {
|
||||
info("closing lua state");
|
||||
lua_close(luaState);
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/31/2020
|
||||
///
|
||||
#include "Curl/Http.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
bool Send(SOCKET TCPSock, std::string Data) {
|
||||
#ifdef WIN32
|
||||
int BytesSent;
|
||||
int len = static_cast<int>(Data.size());
|
||||
#else
|
||||
int64_t BytesSent;
|
||||
size_t len = Data.size();
|
||||
#endif // WIN32
|
||||
BytesSent = send(TCPSock, Data.c_str(), len, 0);
|
||||
Data.clear();
|
||||
if (BytesSent <= 0) {
|
||||
#ifndef WIN32
|
||||
error(__func__ + std::string(" ") + strerror(errno));
|
||||
#else
|
||||
error(__func__ + std::string(" ") + std::to_string(WSAGetLastError()));
|
||||
#endif // WIN32
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
std::string Rcv(SOCKET TCPSock) {
|
||||
uint32_t RealSize;
|
||||
#ifdef WIN32
|
||||
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<char*>(&RealSize), sizeof(RealSize), 0);
|
||||
#else
|
||||
int64_t BytesRcv = recv(TCPSock, reinterpret_cast<void*>(&RealSize), sizeof(RealSize), 0);
|
||||
#endif
|
||||
if (BytesRcv != sizeof(RealSize)) {
|
||||
error(std::string(Sec("invalid packet: expected 4, got ")) + std::to_string(BytesRcv));
|
||||
return "";
|
||||
}
|
||||
// RealSize is big-endian, so we convert it to host endianness
|
||||
RealSize = ntohl(RealSize);
|
||||
debug(std::string("got ") + std::to_string(RealSize) + " as size");
|
||||
if (RealSize > 7000) {
|
||||
error(Sec("Larger than allowed TCP packet received"));
|
||||
return "";
|
||||
}
|
||||
char buf[7000];
|
||||
std::fill_n(buf, 7000, 0);
|
||||
BytesRcv = recv(TCPSock, buf, RealSize, 0);
|
||||
if (BytesRcv != RealSize) {
|
||||
debug("expected " + std::to_string(RealSize) + " bytes, got " + std::to_string(BytesRcv) + " instead");
|
||||
}
|
||||
if (BytesRcv <= 0)
|
||||
return "";
|
||||
return std::string(buf);
|
||||
}
|
||||
std::string GetRole(const std::string& DID) {
|
||||
if (!DID.empty()) {
|
||||
std::string a = HttpRequest(Sec("https://beammp.com/entitlement?did=") + DID, 443);
|
||||
std::string b = HttpRequest(Sec("https://backup1.beammp.com/entitlement?did=") + DID, 443);
|
||||
if (!a.empty() || !b.empty()) {
|
||||
if (a != b)
|
||||
a = b;
|
||||
auto pos = a.find('"');
|
||||
if (pos != std::string::npos) {
|
||||
return a.substr(pos + 1, a.find('"', pos + 1) - 2);
|
||||
} else if (a == "[]")
|
||||
return Sec("Member");
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
void Check(SOCKET TCPSock, std::shared_ptr<std::atomic_bool> ok) {
|
||||
DebugPrintTID();
|
||||
size_t accum = 0;
|
||||
while (!*ok) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
accum += 100;
|
||||
if (accum >= 5000) {
|
||||
error(Sec("Identification timed out (Check accum)"));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
int Max() {
|
||||
int M = MaxPlayers;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
if (c->GetRole() == Sec("MDEV"))
|
||||
M++;
|
||||
}
|
||||
}
|
||||
return M;
|
||||
}
|
||||
void CreateClient(SOCKET TCPSock, const std::string& Name, const std::string& DID, const std::string& Role) {
|
||||
auto* c = new Client;
|
||||
c->SetTCPSock(TCPSock);
|
||||
c->SetName(Name);
|
||||
c->SetRole(Role);
|
||||
c->SetDID(DID);
|
||||
Client& Client = *c;
|
||||
CI->AddClient(std::move(c));
|
||||
InitClient(&Client);
|
||||
}
|
||||
std::pair<int, int> Parse(const std::string& msg) {
|
||||
std::stringstream ss(msg);
|
||||
std::string t;
|
||||
std::pair<int, int> a = { 0, 0 }; //N then E
|
||||
while (std::getline(ss, t, 'g')) {
|
||||
if (t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)
|
||||
return a;
|
||||
if (a.first == 0) {
|
||||
a.first = std::stoi(t, nullptr, 16);
|
||||
} else if (a.second == 0) {
|
||||
a.second = std::stoi(t, nullptr, 16);
|
||||
} else
|
||||
return a;
|
||||
}
|
||||
return { 0, 0 };
|
||||
}
|
||||
std::string GenerateM(RSA* key) {
|
||||
std::stringstream stream;
|
||||
stream << std::hex << key->n << "g" << key->e << "g" << RSA_E(Sec("IDC"), key);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void Identification(SOCKET TCPSock, RSA* Skey) {
|
||||
DebugPrintTID();
|
||||
Assert(Skey);
|
||||
std::shared_ptr<std::atomic_bool> ok = std::make_shared<std::atomic_bool>(false);
|
||||
std::thread Timeout(Check, TCPSock, ok);
|
||||
Timeout.detach();
|
||||
std::string Name, DID, Role;
|
||||
if (!Send(TCPSock, GenerateM(Skey))) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
std::string msg = Rcv(TCPSock);
|
||||
auto Keys = Parse(msg);
|
||||
if (!Send(TCPSock, RSA_E("HC", Keys.second, Keys.first))) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
|
||||
std::string Res = Rcv(TCPSock);
|
||||
std::string Ver = Rcv(TCPSock);
|
||||
*ok = true;
|
||||
Ver = RSA_D(Ver, Skey);
|
||||
if (Ver.size() > 3 && Ver.substr(0, 2) == Sec("VC")) {
|
||||
Ver = Ver.substr(2);
|
||||
if (Ver.length() > 4 || Ver != GetCVer()) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
Res = RSA_D(Res, Skey);
|
||||
if (Res.size() < 3 || Res.substr(0, 2) != Sec("NR")) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
if (Res.find(':') == std::string::npos) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
Name = Res.substr(2, Res.find(':') - 2);
|
||||
DID = Res.substr(Res.find(':') + 1);
|
||||
Role = GetRole(DID);
|
||||
if (Role.empty() || Role.find(Sec("Error")) != std::string::npos) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
return;
|
||||
}
|
||||
// DebugPrintTIDInternal(std::string("Client(") + Name + ")");
|
||||
debug(Sec("Name -> ") + Name + Sec(", Role -> ") + Role + Sec(", ID -> ") + DID);
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
if (c->GetDID() == DID) {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
c->SetStatus(-2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Role == Sec("MDEV") || CI->Size() < Max()) {
|
||||
debug("Identification success");
|
||||
CreateClient(TCPSock, Name, DID, Role);
|
||||
} else {
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
}
|
||||
}
|
||||
void Identify(SOCKET TCPSock) {
|
||||
RSA* Skey = GenKey();
|
||||
// this disgusting ifdef stuff is needed because for some
|
||||
// reason MSVC defines __try and __except and libg++ defines
|
||||
// __try and __catch so its all a big mess if we leave this in or undefine
|
||||
// the macros
|
||||
/*#ifdef WIN32
|
||||
__try{
|
||||
#endif // WIN32*/
|
||||
Identification(TCPSock, Skey);
|
||||
/*#ifdef WIN32
|
||||
}__except(1){
|
||||
if(TCPSock != -1){
|
||||
error("died on " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(TCPSock);
|
||||
}
|
||||
}
|
||||
#endif // WIN32*/
|
||||
|
||||
delete Skey;
|
||||
}
|
||||
|
||||
void TCPServerMain() {
|
||||
DebugPrintTID();
|
||||
#ifdef WIN32
|
||||
WSADATA wsaData;
|
||||
if (WSAStartup(514, &wsaData)) {
|
||||
error(Sec("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(Port);
|
||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
|
||||
error(Sec("Can't bind socket! ") + std::to_string(WSAGetLastError()));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
}
|
||||
if (Listener == -1) {
|
||||
error(Sec("Invalid listening socket"));
|
||||
return;
|
||||
}
|
||||
if (listen(Listener, SOMAXCONN)) {
|
||||
error(Sec("listener failed ") + std::to_string(GetLastError()));
|
||||
return;
|
||||
}
|
||||
info(Sec("Vehicle event network online"));
|
||||
do {
|
||||
try {
|
||||
client = accept(Listener, nullptr, nullptr);
|
||||
if (client == -1) {
|
||||
warn(Sec("Got an invalid client socket on connect! Skipping..."));
|
||||
continue;
|
||||
}
|
||||
std::thread ID(Identify, client);
|
||||
ID.detach();
|
||||
} catch (const std::exception& e) {
|
||||
error(Sec("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, 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(Port));
|
||||
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) != 0) {
|
||||
error(Sec("Can't bind socket! ") + std::string(strerror(errno)));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
}
|
||||
if (Listener == -1) {
|
||||
error(Sec("Invalid listening socket"));
|
||||
return;
|
||||
}
|
||||
if (listen(Listener, SOMAXCONN)) {
|
||||
error(Sec("listener failed ") + std::string(strerror(errno)));
|
||||
return;
|
||||
}
|
||||
info(Sec("Vehicle event network online"));
|
||||
do {
|
||||
try {
|
||||
client = accept(Listener, nullptr, nullptr);
|
||||
if (client == -1) {
|
||||
warn(Sec("Got an invalid client socket on connect! Skipping..."));
|
||||
continue;
|
||||
}
|
||||
std::thread ID(Identify, client);
|
||||
ID.detach();
|
||||
} catch (const std::exception& e) {
|
||||
error(Sec("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
} while (client);
|
||||
|
||||
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
|
||||
CloseSocketProper(client);
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
|
||||
std::string Client::GetName() {
|
||||
return Name;
|
||||
}
|
||||
void Client::SetName(const std::string& name) {
|
||||
Name = name;
|
||||
}
|
||||
void Client::SetDID(const std::string& did) {
|
||||
DID = did;
|
||||
}
|
||||
std::string Client::GetDID() {
|
||||
return DID;
|
||||
}
|
||||
void Client::SetRole(const std::string& role) {
|
||||
Role = role;
|
||||
}
|
||||
std::string Client::GetRole() {
|
||||
return Role;
|
||||
}
|
||||
int Client::GetID() {
|
||||
return ID;
|
||||
}
|
||||
void Client::SetID(int id) {
|
||||
ID = id;
|
||||
}
|
||||
void Client::SetStatus(int state) {
|
||||
Status = state;
|
||||
}
|
||||
int Client::GetStatus() {
|
||||
return Status;
|
||||
}
|
||||
void Client::SetUDPAddr(sockaddr_in Addr) {
|
||||
UDPADDR = Addr;
|
||||
}
|
||||
sockaddr_in Client::GetUDPAddr() {
|
||||
return UDPADDR;
|
||||
}
|
||||
void Client::SetTCPSock(SOCKET CSock) {
|
||||
TCPSOCK = CSock;
|
||||
}
|
||||
SOCKET Client::GetTCPSock() {
|
||||
return TCPSOCK;
|
||||
}
|
||||
void Client::DeleteCar(int ident) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
VehicleData.erase(v);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
void Client::ClearCars() {
|
||||
VehicleData.clear();
|
||||
}
|
||||
int Client::GetOpenCarID() {
|
||||
int OpenID = 0;
|
||||
bool found;
|
||||
do {
|
||||
found = true;
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == OpenID) {
|
||||
OpenID++;
|
||||
found = false;
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return OpenID;
|
||||
}
|
||||
void Client::AddNewCar(int ident, const std::string& Data) {
|
||||
VehicleData.insert(std::unique_ptr<VData>(new VData { ident, Data }));
|
||||
}
|
||||
|
||||
std::set<std::unique_ptr<VData>>& Client::GetAllCars() {
|
||||
return VehicleData;
|
||||
}
|
||||
|
||||
const std::set<std::unique_ptr<VData>>& Client::GetAllCars() const {
|
||||
return VehicleData;
|
||||
}
|
||||
|
||||
std::string Client::GetCarData(int ident) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
return v->Data;
|
||||
}
|
||||
}
|
||||
DeleteCar(ident);
|
||||
return "";
|
||||
}
|
||||
void Client::SetCarData(int ident, const std::string& Data) {
|
||||
for (auto& v : VehicleData) {
|
||||
if (v != nullptr && v->ID == ident) {
|
||||
v->Data = Data;
|
||||
return;
|
||||
}
|
||||
}
|
||||
DeleteCar(ident);
|
||||
}
|
||||
int Client::GetCarCount() {
|
||||
return int(VehicleData.size());
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
int FC(const std::string& s, const std::string& p, int n) {
|
||||
auto i = s.find(p);
|
||||
int j;
|
||||
for (j = 1; j < n && i != std::string::npos; ++j) {
|
||||
i = s.find(p, i + 1);
|
||||
}
|
||||
if (j == n)
|
||||
return int(i);
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
void Apply(Client* c, int VID, const std::string& pckt) {
|
||||
Assert(c);
|
||||
std::string Packet = pckt;
|
||||
std::string VD = c->GetCarData(VID);
|
||||
Packet = Packet.substr(FC(Packet, ",", 2) + 1);
|
||||
Packet = VD.substr(0, FC(VD, ",", 2) + 1) + Packet.substr(0, Packet.find_last_of('"') + 1) + VD.substr(FC(VD, ",\"", 7));
|
||||
c->SetCarData(VID, Packet);
|
||||
}
|
||||
|
||||
void VehicleParser(Client* c, const std::string& Pckt) {
|
||||
Assert(c);
|
||||
if (c == nullptr || Pckt.length() < 4)
|
||||
return;
|
||||
std::string Packet = Pckt;
|
||||
char Code = Packet.at(1);
|
||||
int PID = -1;
|
||||
int VID = -1;
|
||||
std::string Data = Packet.substr(3), pid, vid;
|
||||
switch (Code) { //Spawned Destroyed Switched/Moved NotFound Reset
|
||||
case 's':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'Os' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
if (Data.at(0) == '0') {
|
||||
int CarID = c->GetOpenCarID();
|
||||
debug(c->GetName() + Sec(" created a car with ID ") + std::to_string(CarID));
|
||||
Packet = "Os:" + c->GetRole() + ":" + c->GetName() + ":" + std::to_string(c->GetID()) + "-" + std::to_string(CarID) + Packet.substr(4);
|
||||
if (c->GetCarCount() >= MaxCars || TriggerLuaEvent(Sec("onVehicleSpawn"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), CarID, Packet.substr(3) } }), true)) {
|
||||
Respond(c, Packet, true);
|
||||
std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(CarID);
|
||||
Respond(c, Destroy, true);
|
||||
debug(c->GetName() + Sec(" (force : car limit/lua) removed ID ") + std::to_string(CarID));
|
||||
} else {
|
||||
c->AddNewCar(CarID, Packet);
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'c':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'Oc' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#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()) {
|
||||
if (!TriggerLuaEvent(Sec("onVehicleEdited"), false, nullptr,
|
||||
std::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), VID, Packet.substr(3) } }),
|
||||
true)) {
|
||||
SendToAll(c, Packet, false, true);
|
||||
Apply(c, VID, Packet);
|
||||
} else {
|
||||
std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(VID);
|
||||
Respond(c, Destroy, true);
|
||||
c->DeleteCar(VID);
|
||||
}
|
||||
}
|
||||
return;
|
||||
case 'd':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'Od' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#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()) {
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
TriggerLuaEvent(Sec("onVehicleDeleted"), false, nullptr,
|
||||
std::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), VID } }), false);
|
||||
c->DeleteCar(VID);
|
||||
debug(c->GetName() + Sec(" deleted car with ID ") + std::to_string(VID));
|
||||
}
|
||||
return;
|
||||
case 'r':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'Or' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
case 't':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'Ot' packet: '")) + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
default:
|
||||
#ifdef DEBUG
|
||||
warn(std::string(Sec("possibly not implemented: '") + Packet + Sec("' (") + std::to_string(Packet.size()) + Sec(")")));
|
||||
#endif // DEBUG
|
||||
return;
|
||||
}
|
||||
}
|
||||
void SyncClient(Client* c) {
|
||||
Assert(c);
|
||||
if (c->isSynced)
|
||||
return;
|
||||
c->isSynced = true;
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
Respond(c, Sec("Sn") + c->GetName(), true);
|
||||
SendToAll(c, Sec("JWelcome ") + c->GetName() + "!", false, true);
|
||||
TriggerLuaEvent(Sec("onPlayerJoin"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
|
||||
for (auto& client : CI->Clients) {
|
||||
if (client != nullptr) {
|
||||
if (client.get() != c) {
|
||||
for (auto& v : client->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
if(c->GetStatus() < 0)return;
|
||||
Respond(c, v->Data, true);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info(c->GetName() + Sec(" is now synced!"));
|
||||
}
|
||||
void ParseVeh(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
VehicleParser(c, Packet);
|
||||
} __except (Handle(GetExceptionInformation(), Sec("Vehicle Handler"))) { }
|
||||
#else // unix
|
||||
VehicleParser(c, Packet);
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
void HandleEvent(Client* c, const std::string& Data) {
|
||||
Assert(c);
|
||||
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::unique_ptr<LuaArg>(new LuaArg { { c->GetID(), t } }), false);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (a == 2)
|
||||
break;
|
||||
a++;
|
||||
}
|
||||
}
|
||||
|
||||
void GlobalParser(Client* c, const std::string& Pack) {
|
||||
Assert(c);
|
||||
if (Pack.empty() || c == nullptr)
|
||||
return;
|
||||
std::string Packet = Pack.substr(0, strlen(Pack.c_str()));
|
||||
std::string pct;
|
||||
char Code = Packet.at(0);
|
||||
|
||||
//V to Z
|
||||
if (Code <= 90 && Code >= 86) {
|
||||
PPS++;
|
||||
SendToAll(c, Packet, false, false);
|
||||
return;
|
||||
}
|
||||
switch (Code) {
|
||||
case 'P': // initial connection
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'P' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
Respond(c, Sec("P") + std::to_string(c->GetID()), true);
|
||||
SyncClient(c);
|
||||
return;
|
||||
case 'p':
|
||||
Respond(c, Sec("p"), false);
|
||||
UpdatePlayers();
|
||||
return;
|
||||
case 'O':
|
||||
if (Packet.length() > 1000) {
|
||||
debug(Sec("Received data from: ") + c->GetName() + Sec(" Size: ") + std::to_string(Packet.length()));
|
||||
}
|
||||
ParseVeh(c, Packet);
|
||||
return;
|
||||
case 'J':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'J' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
SendToAll(c, Packet, false, true);
|
||||
return;
|
||||
case 'C':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'C' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
|
||||
break;
|
||||
if (TriggerLuaEvent(Sec("onChatMessage"), false, nullptr,
|
||||
std::unique_ptr<LuaArg>(new LuaArg {
|
||||
{ c->GetID(), c->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }),
|
||||
true))
|
||||
break;
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
return;
|
||||
case 'E':
|
||||
#ifdef DEBUG
|
||||
debug(std::string(Sec("got 'E' packet: '")) + Pack + Sec("' (") + std::to_string(Packet.size()) + Sec(")"));
|
||||
#endif
|
||||
HandleEvent(c, Packet);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void GParser(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||
abort();
|
||||
}
|
||||
#ifdef WIN32
|
||||
__try {
|
||||
GlobalParser(c, Packet);
|
||||
} __except (Handle(GetExceptionInformation(), Sec("Global Handler"))) { }
|
||||
#else
|
||||
GlobalParser(c, Packet);
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 4/9/2020
|
||||
///
|
||||
|
||||
#include "CustomAssert.h"
|
||||
#include <curl/curl.h>
|
||||
#include <iostream>
|
||||
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
|
||||
((std::string*)userp)->append((char*)contents, size * nmemb);
|
||||
return size * nmemb;
|
||||
}
|
||||
std::string HttpRequest(const std::string& IP, int port) {
|
||||
CURL* curl;
|
||||
CURLcode res;
|
||||
std::string readBuffer;
|
||||
curl = curl_easy_init();
|
||||
Assert(curl);
|
||||
if (curl) {
|
||||
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_PORT, port);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
||||
res = curl_easy_perform(curl);
|
||||
curl_easy_cleanup(curl);
|
||||
if (res != CURLE_OK)
|
||||
return "-1";
|
||||
}
|
||||
return readBuffer;
|
||||
}
|
||||
|
||||
std::string PostHTTP(const std::string& IP, const std::string& Fields) {
|
||||
CURL* curl;
|
||||
CURLcode res;
|
||||
std::string readBuffer;
|
||||
curl = curl_easy_init();
|
||||
Assert(curl);
|
||||
if (curl) {
|
||||
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
|
||||
/*curl_easy_setopt(curl, CURLOPT_URL, "https://95.216.35.232/heartbeatv2");
|
||||
curl_easy_setopt(curl, CURLOPT_PORT, 3600);*/
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, Fields.size());
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Fields.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
||||
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
|
||||
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
|
||||
res = curl_easy_perform(curl);
|
||||
curl_easy_cleanup(curl);
|
||||
if (res != CURLE_OK)
|
||||
return "-1";
|
||||
}
|
||||
return readBuffer;
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Lua/LuaSystem.hpp"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
int OpenID() {
|
||||
int ID = 0;
|
||||
bool found;
|
||||
do {
|
||||
found = true;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr) {
|
||||
if (c->GetID() == ID) {
|
||||
found = false;
|
||||
ID++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (!found);
|
||||
return ID;
|
||||
}
|
||||
void Respond(Client* c, const std::string& MSG, bool Rel) {
|
||||
Assert(c);
|
||||
char C = MSG.at(0);
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || MSG.length() > 1000) {
|
||||
SendLarge(c, MSG);
|
||||
} else {
|
||||
TCPSend(c, MSG);
|
||||
}
|
||||
} else {
|
||||
UDPSend(c, MSG);
|
||||
}
|
||||
}
|
||||
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel) {
|
||||
if (!Self)
|
||||
Assert(c);
|
||||
char C = Data.at(0);
|
||||
for (auto& client : CI->Clients) {
|
||||
if (client != nullptr) {
|
||||
if (Self || client.get() != c) {
|
||||
if (client->isSynced) {
|
||||
if (Rel || C == 'W' || C == 'Y' || C == 'V' || C == 'E') {
|
||||
if (C == 'O' || C == 'T' || Data.length() > 1000)
|
||||
SendLarge(client.get(), Data);
|
||||
else
|
||||
TCPSend(client.get(), Data);
|
||||
} else
|
||||
UDPSend(client.get(), Data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void UpdatePlayers() {
|
||||
std::string Packet = Sec("Ss") + std::to_string(CI->Size()) + "/" + std::to_string(MaxPlayers) + ":";
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr)
|
||||
Packet += c->GetName() + ",";
|
||||
}
|
||||
Packet = Packet.substr(0, Packet.length() - 1);
|
||||
SendToAll(nullptr, Packet, true, true);
|
||||
}
|
||||
void OnDisconnect(Client* c, bool kicked) {
|
||||
|
||||
Assert(c);
|
||||
info(c->GetName() + Sec(" Connection Terminated"));
|
||||
if (c == nullptr)
|
||||
return;
|
||||
std::string Packet;
|
||||
for (auto& v : c->GetAllCars()) {
|
||||
if (v != nullptr) {
|
||||
Packet = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(v->ID);
|
||||
SendToAll(c, Packet, false, true);
|
||||
}
|
||||
}
|
||||
if (kicked)
|
||||
Packet = Sec("L") + c->GetName() + Sec(" was kicked!");
|
||||
Packet = Sec("L") + c->GetName() + Sec(" Left the server!");
|
||||
SendToAll(c, Packet, false, true);
|
||||
Packet.clear();
|
||||
TriggerLuaEvent(Sec("onPlayerDisconnect"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
|
||||
CI->RemoveClient(c); ///Removes the Client from existence
|
||||
}
|
||||
void OnConnect(Client* c) {
|
||||
Assert(c);
|
||||
info(Sec("Client connected"));
|
||||
c->SetID(OpenID());
|
||||
info(Sec("Assigned ID ") + std::to_string(c->GetID()) + Sec(" to ") + c->GetName());
|
||||
TriggerLuaEvent(Sec("onPlayerConnecting"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
|
||||
SyncResources(c);
|
||||
if (c->GetStatus() < 0)
|
||||
return;
|
||||
Respond(c, "M" + MapName, true); //Send the Map on connect
|
||||
info(c->GetName() + Sec(" : Connected"));
|
||||
TriggerLuaEvent(Sec("onPlayerJoining"), false, nullptr, std::unique_ptr<LuaArg>(new LuaArg { { c->GetID() } }), false);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include "Network.h"
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
std::unique_ptr<ClientInterface> CI;
|
||||
void NetMain() {
|
||||
std::thread TCP(TCPServerMain);
|
||||
TCP.detach();
|
||||
UDPServerMain();
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 6/18/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Security/Enc.h"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
std::string StatReport;
|
||||
int PPS = 0;
|
||||
void Monitor() {
|
||||
int R, C = 0, V = 0;
|
||||
if (CI->Clients.empty()) {
|
||||
StatReport = "-";
|
||||
return;
|
||||
}
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetCarCount() > 0) {
|
||||
C++;
|
||||
V += c->GetCarCount();
|
||||
}
|
||||
}
|
||||
if (C == 0 || PPS == 0) {
|
||||
StatReport = "-";
|
||||
} else {
|
||||
R = (PPS / C) / V;
|
||||
StatReport = std::to_string(R);
|
||||
}
|
||||
PPS = 0;
|
||||
}
|
||||
|
||||
[[noreturn]] void Stat() {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
Monitor();
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
|
||||
void StatInit() {
|
||||
StatReport = "-";
|
||||
std::thread Init(Stat);
|
||||
Init.detach();
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Client.hpp"
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <fstream>
|
||||
|
||||
#ifdef __linux
|
||||
// we need this for `struct stat`
|
||||
#include <sys/stat.h>
|
||||
#endif // __linux
|
||||
|
||||
void STCPSend(Client* c, std::string Data) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
#ifdef WIN32
|
||||
int BytesSent;
|
||||
int len = static_cast<int>(Data.size());
|
||||
#else
|
||||
int64_t BytesSent;
|
||||
size_t len = Data.size();
|
||||
#endif // WIN32
|
||||
BytesSent = send(c->GetTCPSock(), Data.c_str(), len, 0);
|
||||
Data.clear();
|
||||
if (BytesSent == 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
} else if (BytesSent < 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
info(Sec("Closing socket, BytesSent < 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
}
|
||||
}
|
||||
void SendFile(Client* c, const std::string& Name) {
|
||||
Assert(c);
|
||||
info(c->GetName() + Sec(" requesting : ") + Name.substr(Name.find_last_of('/')));
|
||||
struct stat Info { };
|
||||
if (stat(Name.c_str(), &Info) != 0) {
|
||||
STCPSend(c, Sec("Cannot Open"));
|
||||
return;
|
||||
}
|
||||
std::ifstream f(Name.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
size_t Size = size_t(fileSize);
|
||||
size_t Sent = 0;
|
||||
size_t Diff;
|
||||
int64_t Split = 64000;
|
||||
while (c->GetStatus() > -1 && Sent < Size) {
|
||||
Diff = Size - Sent;
|
||||
if (Diff > size_t(Split)) {
|
||||
std::string Data(size_t(Split), 0);
|
||||
f.seekg(int64_t(Sent), std::ios_base::beg);
|
||||
f.read(&Data[0], Split);
|
||||
STCPSend(c, Data);
|
||||
Sent += size_t(Split);
|
||||
} else {
|
||||
std::string Data(Diff, 0);
|
||||
f.seekg(int64_t(Sent), std::ios_base::beg);
|
||||
f.read(&Data[0], int64_t(Diff));
|
||||
STCPSend(c, Data);
|
||||
Sent += Diff;
|
||||
}
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
|
||||
void Parse(Client* c, const std::string& Packet) {
|
||||
Assert(c);
|
||||
if (c == nullptr || 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(Sec("Sending Mod Info"));
|
||||
std::string ToSend = FileList + FileSizes;
|
||||
if (ToSend.empty())
|
||||
ToSend = "-";
|
||||
STCPSend(c, ToSend);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
bool STCPRecv(Client* c) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return false;
|
||||
#define len 200
|
||||
char buf[len];
|
||||
ZeroMemory(buf, len);
|
||||
int64_t BytesRcv = recv(c->GetTCPSock(), buf, len, 0);
|
||||
#undef len
|
||||
if (BytesRcv == 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
info(Sec("Closing socket in STCP receive, BytesRcv == 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return false;
|
||||
} else if (BytesRcv < 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
info(Sec("Closing socket in STCP receive, BytesRcv < 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return false;
|
||||
}
|
||||
if (strcmp(buf, "Done") == 0)
|
||||
return false;
|
||||
std::string Ret(buf, size_t(BytesRcv));
|
||||
Parse(c, Ret);
|
||||
return true;
|
||||
}
|
||||
|
||||
void SyncResources(Client* c) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
try {
|
||||
STCPSend(c, Sec("WS"));
|
||||
while (c->GetStatus() > -1 && STCPRecv(c))
|
||||
;
|
||||
} catch (std::exception& e) {
|
||||
except(Sec("Exception! : ") + std::string(e.what()));
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/1/2020
|
||||
///
|
||||
#include "Compressor.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <thread>
|
||||
|
||||
void TCPSend(Client* c, const std::string& Data) {
|
||||
Assert(c);
|
||||
if (c == nullptr)
|
||||
return;
|
||||
// Size is BIG ENDIAN now, use only for header!
|
||||
//auto Size = htonl(int32_t(Data.size()));
|
||||
///TODO : BIG ENDIAN for other OS
|
||||
int32_t Size, Sent, Temp;
|
||||
std::string Send(4, 0);
|
||||
Size = int32_t(Data.size());
|
||||
memcpy(&Send[0], &Size, sizeof(Size));
|
||||
Send += Data;
|
||||
Sent = 0;
|
||||
Size += 4;
|
||||
do {
|
||||
Temp = send(c->GetTCPSock(), &Send[Sent], Size - Sent, 0);
|
||||
if (Temp == 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
return;
|
||||
} else if (Temp < 0) {
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
// info(Sec("Closing socket, Temp < 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return;
|
||||
}
|
||||
Sent += Temp;
|
||||
} while (Sent < Size);
|
||||
}
|
||||
|
||||
bool CheckBytes(Client* c, int32_t BytesRcv) {
|
||||
Assert(c);
|
||||
if (BytesRcv == 0) {
|
||||
debug(Sec("(TCP) Connection closing..."));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
return false;
|
||||
} else if (BytesRcv < 0) {
|
||||
#ifdef WIN32
|
||||
debug(Sec("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
#else // unix
|
||||
debug(Sec("(TCP) recv failed with error: ") + std::string(strerror(errno)));
|
||||
#endif // WIN32
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
info(Sec("Closing socket in CheckBytes, BytesRcv < 0"));
|
||||
CloseSocketProper(c->GetTCPSock());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void TCPRcv(Client* c) {
|
||||
Assert(c);
|
||||
int32_t Header, BytesRcv = 0, Temp;
|
||||
if (c == nullptr || 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__) + Sec(": 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__) + Sec(": expecting ") + std::to_string(Header) + Sec(" bytes."));
|
||||
#endif // DEBUG
|
||||
if (!CheckBytes(c, BytesRcv)) {
|
||||
#ifdef DEBUG
|
||||
error(std::string(__func__) + Sec(": failed on CheckBytes"));
|
||||
#endif // DEBUG
|
||||
return;
|
||||
}
|
||||
Data.resize(Header);
|
||||
BytesRcv = 0;
|
||||
do {
|
||||
Temp = recv(c->GetTCPSock(), &Data[BytesRcv], Header - BytesRcv, 0);
|
||||
if (!CheckBytes(c, Temp)) {
|
||||
#ifdef DEBUG
|
||||
error(std::string(__func__) + Sec(": failed on CheckBytes in while(BytesRcv < Header)"));
|
||||
#endif // DEBUG
|
||||
|
||||
return;
|
||||
}
|
||||
#ifdef DEBUG
|
||||
//debug(std::string(__func__) + Sec(": Temp: ") + std::to_string(Temp) + Sec(", BytesRcv: ") + std::to_string(BytesRcv));
|
||||
#endif // DEBUG
|
||||
BytesRcv += Temp;
|
||||
} while (BytesRcv < Header);
|
||||
#ifdef DEBUG
|
||||
//debug(std::string(__func__) + Sec(": finished recv with Temp: ") + std::to_string(Temp) + Sec(", 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
|
||||
GParser(c, Ret);
|
||||
}
|
||||
|
||||
void TCPClient(Client* c) {
|
||||
DebugPrintTIDInternal(Sec("Client(") + c->GetName() + Sec(")"), true);
|
||||
Assert(c);
|
||||
if (c->GetTCPSock() == -1) {
|
||||
CI->RemoveClient(c);
|
||||
return;
|
||||
}
|
||||
OnConnect(c);
|
||||
while (c->GetStatus() > -1)
|
||||
TCPRcv(c);
|
||||
OnDisconnect(c, c->GetStatus() == -2);
|
||||
}
|
||||
void InitClient(Client* c) {
|
||||
std::thread NewClient(TCPClient, c);
|
||||
NewClient.detach();
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
///UDP
|
||||
#include "Client.hpp"
|
||||
#include "Compressor.h"
|
||||
#include "Logger.h"
|
||||
#include "Network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include "UnixCompat.h"
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
int FC(const std::string& s, const std::string& p, int n);
|
||||
struct PacketData {
|
||||
int ID;
|
||||
::Client* Client;
|
||||
std::string Data;
|
||||
int Tries;
|
||||
};
|
||||
struct SplitData {
|
||||
int Total {};
|
||||
int ID {};
|
||||
std::set<std::pair<int, std::string>> Fragments;
|
||||
};
|
||||
|
||||
SOCKET UDPSock;
|
||||
std::set<PacketData*> DataAcks;
|
||||
std::set<SplitData*> SplitPackets;
|
||||
void UDPSend(Client* c, std::string Data) {
|
||||
Assert(c);
|
||||
if (c == nullptr || !c->isConnected || c->GetStatus() < 0)
|
||||
return;
|
||||
sockaddr_in Addr = c->GetUDPAddr();
|
||||
socklen_t AddrSize = sizeof(c->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(UDPSock, Data.c_str(), len, 0, (sockaddr*)&Addr, AddrSize);
|
||||
#ifdef WIN32
|
||||
if (sendOk == -1) {
|
||||
debug(Sec("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
} else if (sendOk == 0) {
|
||||
debug(Sec("(UDP) sendto returned 0"));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
#else // unix
|
||||
if (sendOk == -1) {
|
||||
debug(Sec("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
} else if (sendOk == 0) {
|
||||
debug(Sec("(UDP) sendto returned 0"));
|
||||
if (c->GetStatus() > -1)
|
||||
c->SetStatus(-1);
|
||||
}
|
||||
#endif // WIN32
|
||||
}
|
||||
|
||||
void AckID(int ID) {
|
||||
for (PacketData* p : DataAcks) {
|
||||
if (p != nullptr && p->ID == ID) {
|
||||
DataAcks.erase(p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
int PacktID() {
|
||||
static int ID = -1;
|
||||
if (ID > 999999)
|
||||
ID = 0;
|
||||
else
|
||||
ID++;
|
||||
return ID;
|
||||
}
|
||||
int SplitID() {
|
||||
static int SID = -1;
|
||||
if (SID > 999999)
|
||||
SID = 0;
|
||||
else
|
||||
SID++;
|
||||
return SID;
|
||||
}
|
||||
void SendLarge(Client* c, std::string Data) {
|
||||
Assert(c);
|
||||
if (Data.length() > 400) {
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
TCPSend(c, Data);
|
||||
}
|
||||
struct HandledC {
|
||||
size_t Pos = 0;
|
||||
Client* c = nullptr;
|
||||
std::array<int, 100> HandledIDs = { -1 };
|
||||
};
|
||||
std::set<HandledC*> HandledIDs;
|
||||
void ResetIDs(HandledC* H) {
|
||||
for (size_t C = 0; C < 100; C++) {
|
||||
H->HandledIDs.at(C) = -1;
|
||||
}
|
||||
}
|
||||
HandledC* GetHandled(Client* c) {
|
||||
Assert(c);
|
||||
for (HandledC* h : HandledIDs) {
|
||||
if (h->c == c) {
|
||||
return h;
|
||||
}
|
||||
}
|
||||
return new HandledC();
|
||||
}
|
||||
bool Handled(Client* c, int ID) {
|
||||
Assert(c);
|
||||
bool handle = false;
|
||||
for (HandledC* h : HandledIDs) {
|
||||
if (h->c == c) {
|
||||
for (int id : h->HandledIDs) {
|
||||
if (id == ID)
|
||||
return true;
|
||||
}
|
||||
if (h->Pos > 99)
|
||||
h->Pos = 0;
|
||||
h->HandledIDs.at(h->Pos) = ID;
|
||||
h->Pos++;
|
||||
handle = true;
|
||||
}
|
||||
}
|
||||
for (HandledC* h : HandledIDs) {
|
||||
if (h->c == nullptr || !h->c->isConnected) {
|
||||
HandledIDs.erase(h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!handle) {
|
||||
HandledC* h = GetHandled(c);
|
||||
ResetIDs(h);
|
||||
if (h->Pos > 99)
|
||||
h->Pos = 0;
|
||||
h->HandledIDs.at(h->Pos) = ID;
|
||||
h->Pos++;
|
||||
h->c = c;
|
||||
HandledIDs.insert(h);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::string UDPRcvFromClient(sockaddr_in& client) {
|
||||
size_t clientLength = sizeof(client);
|
||||
ZeroMemory(&client, clientLength);
|
||||
std::string Ret(10240, 0);
|
||||
int64_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&client, (socklen_t*)&clientLength);
|
||||
if (Rcv == -1) {
|
||||
#ifdef WIN32
|
||||
error(Sec("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
|
||||
#else // unix
|
||||
error(Sec("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
|
||||
#endif // WIN32
|
||||
return "";
|
||||
}
|
||||
return Ret.substr(0, Rcv);
|
||||
}
|
||||
|
||||
SplitData* GetSplit(int SplitID) {
|
||||
for (SplitData* a : SplitPackets) {
|
||||
if (a->ID == SplitID)
|
||||
return a;
|
||||
}
|
||||
auto* SP = new SplitData();
|
||||
SplitPackets.insert(SP);
|
||||
return SP;
|
||||
}
|
||||
void HandleChunk(Client* c, const std::string& Data) {
|
||||
Assert(c);
|
||||
int pos = FC(Data, "|", 5);
|
||||
if (pos == -1)
|
||||
return;
|
||||
std::stringstream ss(Data.substr(0, size_t(pos++)));
|
||||
std::string t;
|
||||
int I = -1;
|
||||
//Current Max ID SID
|
||||
std::vector<int> Num(4, 0);
|
||||
while (std::getline(ss, t, '|')) {
|
||||
if (I >= 0)
|
||||
Num.at(size_t(I)) = std::stoi(t);
|
||||
I++;
|
||||
}
|
||||
std::string ack = "TRG:" + std::to_string(Num.at(2));
|
||||
UDPSend(c, ack);
|
||||
if (Handled(c, Num.at(2))) {
|
||||
return;
|
||||
}
|
||||
std::string Packet = Data.substr(size_t(pos));
|
||||
SplitData* SData = GetSplit(Num.at(3));
|
||||
SData->Total = Num.at(1);
|
||||
SData->ID = Num.at(3);
|
||||
SData->Fragments.insert(std::make_pair(Num.at(0), Packet));
|
||||
if (SData->Fragments.size() == size_t(SData->Total)) {
|
||||
std::string ToHandle;
|
||||
for (const std::pair<int, std::string>& a : SData->Fragments) {
|
||||
ToHandle += a.second;
|
||||
}
|
||||
GParser(c, ToHandle);
|
||||
SplitPackets.erase(SData);
|
||||
delete SData;
|
||||
SData = nullptr;
|
||||
}
|
||||
}
|
||||
void UDPParser(Client* c, std::string Packet) {
|
||||
if (Packet.find("Zp") != std::string::npos && Packet.size() > 500) {
|
||||
abort();
|
||||
}
|
||||
Assert(c);
|
||||
if (Packet.substr(0, 4) == "ABG:") {
|
||||
Packet = DeComp(Packet.substr(4));
|
||||
}
|
||||
if (Packet.substr(0, 4) == "TRG:") {
|
||||
std::string pkt = Packet.substr(4);
|
||||
if (Packet.find_first_not_of("0123456789") == std::string::npos) {
|
||||
AckID(stoi(Packet));
|
||||
}
|
||||
return;
|
||||
} else if (Packet.substr(0, 3) == "BD:") {
|
||||
auto pos = Packet.find(':', 4);
|
||||
int ID = stoi(Packet.substr(3, pos - 3));
|
||||
std::string pkt = "TRG:" + std::to_string(ID);
|
||||
UDPSend(c, pkt);
|
||||
if (!Handled(c, ID)) {
|
||||
pkt = Packet.substr(pos + 1);
|
||||
GParser(c, pkt);
|
||||
}
|
||||
return;
|
||||
} else if (Packet.substr(0, 2) == "SC") {
|
||||
HandleChunk(c, Packet);
|
||||
return;
|
||||
}
|
||||
GParser(c, Packet);
|
||||
}
|
||||
void LOOP() {
|
||||
DebugPrintTID();
|
||||
while (UDPSock != -1) {
|
||||
if (!DataAcks.empty()) {
|
||||
for (PacketData* p : DataAcks) {
|
||||
if (p != nullptr) {
|
||||
if (p->Client == nullptr || p->Client->GetTCPSock() == -1) {
|
||||
DataAcks.erase(p);
|
||||
break;
|
||||
}
|
||||
if (p->Tries < 15) {
|
||||
UDPSend(p->Client, p->Data);
|
||||
p->Tries++;
|
||||
} else {
|
||||
DataAcks.erase(p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
}
|
||||
}
|
||||
[[noreturn]] void UDPServerMain() {
|
||||
#ifdef WIN32
|
||||
WSADATA data;
|
||||
if (WSAStartup(514, &data)) {
|
||||
error(Sec("Can't start Winsock!"));
|
||||
//return;
|
||||
}
|
||||
|
||||
UDPSock = 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(Port); // Convert from little to big endian
|
||||
|
||||
// Try and bind the socket to the IP and port
|
||||
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
error(Sec("Can't bind socket!") + std::to_string(WSAGetLastError()));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
//return;
|
||||
}
|
||||
|
||||
DataAcks.clear();
|
||||
std::thread Ack(LOOP);
|
||||
Ack.detach();
|
||||
|
||||
info(Sec("Vehicle data network online on port ") + std::to_string(Port) + Sec(" with a Max of ") + std::to_string(MaxPlayers) + Sec(" Clients"));
|
||||
while (true) {
|
||||
try {
|
||||
sockaddr_in client {};
|
||||
std::string Data = UDPRcvFromClient(client); //Receives any data from Socket
|
||||
auto Pos = Data.find(':');
|
||||
if (Data.empty() || Pos < 0 || 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 = Data.at(0) - 1;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
c->SetUDPAddr(client);
|
||||
c->isConnected = true;
|
||||
UDPParser(c.get(), Data.substr(2));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
error(Sec("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
/*CloseSocketProper(UDPSock);
|
||||
WSACleanup();
|
||||
return;*/
|
||||
#else // unix
|
||||
UDPSock = 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(Port)); // Convert from little to big endian
|
||||
|
||||
// Try and bind the socket to the IP and port
|
||||
if (bind(UDPSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) != 0) {
|
||||
error(Sec("Can't bind socket!") + std::string(strerror(errno)));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
_Exit(-1);
|
||||
//return;
|
||||
}
|
||||
|
||||
DataAcks.clear();
|
||||
std::thread Ack(LOOP);
|
||||
Ack.detach();
|
||||
|
||||
info(Sec("Vehicle data network online on port ") + std::to_string(Port) + Sec(" with a Max of ") + std::to_string(MaxPlayers) + Sec(" Clients"));
|
||||
while (true) {
|
||||
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;
|
||||
for (auto& c : CI->Clients) {
|
||||
if (c != nullptr && c->GetID() == ID) {
|
||||
c->SetUDPAddr(client);
|
||||
c->isConnected = true;
|
||||
UDPParser(c.get(), Data.substr(2));
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
error(Sec("fatal: ") + std::string(e.what()));
|
||||
}
|
||||
}
|
||||
/*CloseSocketProper(UDPSock); // TODO: Why not this? We did this in TCPServerMain?
|
||||
return;
|
||||
*/
|
||||
#endif // WIN32
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 11/6/2020
|
||||
///
|
||||
/*#include <boost/beast/core.hpp>
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <boost/asio/connect.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>*/
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
/*namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace net = boost::asio;
|
||||
using tcp = boost::asio::ip::tcp;
|
||||
|
||||
std::string GetRes(const beast::flat_buffer& buff) {
|
||||
return (char*)buff.data().data();
|
||||
}*/
|
||||
|
||||
void SyncData() {
|
||||
/*DebugPrintTID();
|
||||
try {
|
||||
std::string const host = Sec("95.216.35.232");
|
||||
|
||||
net::io_context ioc;
|
||||
tcp::resolver r(ioc);
|
||||
|
||||
websocket::stream<tcp::socket> ws(ioc);
|
||||
auto const results = r.resolve(host, Sec("3600"));
|
||||
net::connect(ws.next_layer(), results.begin(), results.end());
|
||||
|
||||
|
||||
ws.handshake(host, "/");
|
||||
beast::flat_buffer buffer;
|
||||
ws.write(boost::asio::buffer("Hello, world!"));
|
||||
ws.read(buffer);
|
||||
|
||||
std::cout << GetRes(buffer) << std::endl;
|
||||
|
||||
ws.close(websocket::close_code::normal);
|
||||
|
||||
}catch(std::exception const& e){
|
||||
error(e.what());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
_Exit(0);
|
||||
}*/
|
||||
}
|
||||
|
||||
void WebsocketInit() {
|
||||
/*std::thread t1(SyncData);
|
||||
t1.detach();*/
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
use crate::fs_util;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(skip)] // Skipping uses Default::default, which makes a new vector for us :)
|
||||
pub mods: Vec<(String, usize)>,
|
||||
|
||||
#[serde(rename = "General")]
|
||||
pub general: GeneralSettings,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GeneralSettings {
|
||||
#[serde(rename = "Port")]
|
||||
pub port: Option<u16>,
|
||||
|
||||
#[serde(rename = "Name")]
|
||||
pub name: String,
|
||||
|
||||
#[serde(rename = "Description")]
|
||||
pub description: String,
|
||||
|
||||
#[serde(rename = "AuthKey")]
|
||||
pub auth_key: Option<String>,
|
||||
|
||||
#[serde(rename = "MaxCars")]
|
||||
pub max_cars: Option<u8>,
|
||||
|
||||
#[serde(rename = "MaxPlayers")]
|
||||
pub max_players: usize,
|
||||
|
||||
#[serde(rename = "Private")]
|
||||
pub private: bool,
|
||||
|
||||
#[serde(rename = "Map")]
|
||||
pub map: String,
|
||||
|
||||
#[serde(rename = "ResourceFolder")]
|
||||
pub resource_folder: String,
|
||||
|
||||
#[serde(rename = "Debug")]
|
||||
pub debug: bool,
|
||||
|
||||
// Options below are not yet supported
|
||||
#[serde(rename = "LogChat")]
|
||||
pub log_chat: bool,
|
||||
}
|
||||
|
||||
impl GeneralSettings {
|
||||
pub fn is_auth_key_valid(&self) -> bool {
|
||||
if let Some(auth_key) = &self.auth_key {
|
||||
Uuid::parse_str(auth_key.as_str()).is_ok()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the client resource path, and ensures it exists.
|
||||
/// Default is Resources/Client.
|
||||
pub fn get_client_resource_folder(&self) -> anyhow::Result<String> {
|
||||
let res_client_path = Path::new(self.resource_folder.as_str()).join("Client");
|
||||
fs_util::ensure_path_exists(&res_client_path)?;
|
||||
Ok(fs_util::path_to_string(res_client_path))
|
||||
}
|
||||
|
||||
/// Returns the server resource path, and ensures it exists.
|
||||
/// Default is Resources/Server.
|
||||
pub fn get_server_resource_folder(&self) -> anyhow::Result<String> {
|
||||
let res_server_path = Path::new(self.resource_folder.as_str()).join("Server");
|
||||
fs_util::ensure_path_exists(&res_server_path)?;
|
||||
Ok(fs_util::path_to_string(res_server_path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Ensures the given path exists by creating it if it doesn't.
|
||||
pub fn ensure_path_exists(path: &PathBuf) -> anyhow::Result<()> {
|
||||
if !path.exists() {
|
||||
debug!("Path {:?} doesn't exist, creating it", path);
|
||||
std::fs::create_dir_all(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Joins a parent folder and a sub-path, resolving the subpath beforehand to ensure that
|
||||
/// the resulting path is still within the parent folder, regardless of ".." in the sub-path.
|
||||
pub fn join_path_secure(parent: &Path, sub: &Path) -> anyhow::Result<PathBuf> {
|
||||
Ok(parent.join(sub.file_name().unwrap_or("".as_ref())))
|
||||
}
|
||||
|
||||
/// Converts a PathBuf into a String in a lossy way. This is generally the way we want to do it
|
||||
/// in the server.
|
||||
pub fn path_to_string(path: PathBuf) -> String {
|
||||
path.into_os_string().to_string_lossy().to_string()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use serde::Serialize;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HeartbeatInfo {
|
||||
uuid: String,
|
||||
players: usize,
|
||||
maxplayers: usize,
|
||||
port: u16,
|
||||
map: String,
|
||||
private: String, // Needs to be either "true" or "false"
|
||||
version: String,
|
||||
clientversion: String,
|
||||
name: String,
|
||||
modlist: String,
|
||||
modstotalsize: usize,
|
||||
modstotal: usize,
|
||||
playerslist: String,
|
||||
desc: String,
|
||||
}
|
||||
|
||||
pub async fn backend_heartbeat(config: std::sync::Arc<crate::config::Config>, mut hb_rx: Receiver<crate::server::ServerStatus>) {
|
||||
if !config.general.is_auth_key_valid() {
|
||||
if config.general.private {
|
||||
warn!("AuthKey has invalid format. This is not an error, since your server is private.");
|
||||
} else {
|
||||
error!("AuthKey has invalid format. The server will not appear on the server list.");
|
||||
}
|
||||
// FIXME: The heartbeat should be started if the config is ever changed/reloaded.
|
||||
return;
|
||||
}
|
||||
let mut info = HeartbeatInfo {
|
||||
uuid: config.general.auth_key.clone().unwrap_or(String::from("Unknown name!")),
|
||||
players: 0,
|
||||
maxplayers: config.general.max_players,
|
||||
port: config.general.port.unwrap_or(30814),
|
||||
map: config.general.map.clone(),
|
||||
private: if config.general.private { String::from("true") } else { String::from("false") },
|
||||
version: String::from("3.3.0"), // TODO: Don't hardcode this
|
||||
clientversion: String::from("2.0"), // TODO: What? I think for now I can fill in 2.0
|
||||
name: config.general.name.clone(),
|
||||
modlist: String::from("-"), // TODO: Implement this
|
||||
modstotalsize: 0, // TODO: Implement this
|
||||
modstotal: 0, // TODO: Implement this
|
||||
playerslist: String::new(),
|
||||
desc: config.general.description.clone(),
|
||||
};
|
||||
|
||||
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
|
||||
tokio::select! {
|
||||
_ = heartbeat_post(&info) => {}
|
||||
status = hb_rx.recv() => {
|
||||
if let Some(status) = status {
|
||||
trace!("status update: {:?}", status);
|
||||
info.players = status.player_count;
|
||||
info.playerslist = status.player_list.iter().map(|(_id, name)| format!("{};", name)).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn heartbeat_post(heartbeat_info: &HeartbeatInfo) {
|
||||
match reqwest::Client::builder()
|
||||
.local_address("0.0.0.0".parse::<std::net::IpAddr>().unwrap())
|
||||
.build().unwrap()
|
||||
.post("https://backend.beammp.com/heartbeat")
|
||||
.form(heartbeat_info)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(resp) => {
|
||||
trace!("heartbeat response:\n{:?}", resp.text().await);
|
||||
},
|
||||
Err(e) => error!("Heartbeat error occured: {e}"),
|
||||
}
|
||||
}
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/17/2020
|
||||
///
|
||||
#include "Logger.h"
|
||||
#include "RWMutex.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Settings.h"
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
static RWMutex ThreadNameMapMutex;
|
||||
static std::unordered_map<std::thread::id, std::string> ThreadNameMap;
|
||||
|
||||
std::string ThreadName() {
|
||||
ReadLock lock(ThreadNameMapMutex);
|
||||
std::string Name;
|
||||
if (ThreadNameMap.find(std::this_thread::get_id()) != ThreadNameMap.end()) {
|
||||
Name = ThreadNameMap.at(std::this_thread::get_id());
|
||||
} else {
|
||||
std::stringstream ss;
|
||||
ss << std::this_thread::get_id();
|
||||
Name = ss.str();
|
||||
}
|
||||
return Name;
|
||||
}
|
||||
|
||||
void SetThreadName(const std::string& Name, bool overwrite) {
|
||||
WriteLock lock(ThreadNameMapMutex);
|
||||
if (overwrite || ThreadNameMap.find(std::this_thread::get_id()) == ThreadNameMap.end()) {
|
||||
ThreadNameMap[std::this_thread::get_id()] = Name;
|
||||
}
|
||||
}
|
||||
|
||||
std::string getDate() {
|
||||
typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>::type> days;
|
||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||
std::chrono::system_clock::duration tp = now.time_since_epoch();
|
||||
days d = std::chrono::duration_cast<days>(tp);
|
||||
tp -= d;
|
||||
auto h = std::chrono::duration_cast<std::chrono::hours>(tp);
|
||||
tp -= h;
|
||||
auto m = std::chrono::duration_cast<std::chrono::minutes>(tp);
|
||||
tp -= m;
|
||||
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp);
|
||||
tp -= s;
|
||||
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
|
||||
<< "] ";
|
||||
if (Debug) {
|
||||
date << ThreadName()
|
||||
<< " ";
|
||||
}
|
||||
return date.str();
|
||||
}
|
||||
|
||||
void InitLog() {
|
||||
std::ofstream LFS;
|
||||
LFS.open(Sec("Server.log"));
|
||||
if (!LFS.is_open()) {
|
||||
error(Sec("logger file init failed!"));
|
||||
} else
|
||||
LFS.close();
|
||||
}
|
||||
std::mutex LogLock;
|
||||
|
||||
void DebugPrintTIDInternal(const std::string& func, bool overwrite) {
|
||||
// we need to print to cout here as we might crash before all console output is handled,
|
||||
// due to segfaults or asserts.
|
||||
SetThreadName(func, overwrite);
|
||||
#ifdef DEBUG
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::stringstream Print;
|
||||
Print << "(debug build) Thread '" << std::this_thread::get_id() << "' is " << func << "\n";
|
||||
ConsoleOut(Print.str());
|
||||
#endif // DEBUG
|
||||
}
|
||||
|
||||
void addToLog(const std::string& Line) {
|
||||
std::ofstream LFS;
|
||||
LFS.open(Sec("Server.log"), std::ios_base::app);
|
||||
LFS << Line.c_str();
|
||||
LFS.close();
|
||||
}
|
||||
void info(const std::string& toPrint) {
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::string Print = getDate() + Sec("[INFO] ") + toPrint + "\n";
|
||||
ConsoleOut(Print);
|
||||
addToLog(Print);
|
||||
}
|
||||
void debug(const std::string& toPrint) {
|
||||
if (!Debug)
|
||||
return;
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::string Print = getDate() + Sec("[DEBUG] ") + toPrint + "\n";
|
||||
ConsoleOut(Print);
|
||||
addToLog(Print);
|
||||
}
|
||||
void warn(const std::string& toPrint) {
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::string Print = getDate() + Sec("[WARN] ") + toPrint + "\n";
|
||||
ConsoleOut(Print);
|
||||
addToLog(Print);
|
||||
}
|
||||
void error(const std::string& toPrint) {
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::string Print = getDate() + Sec("[ERROR] ") + toPrint + "\n";
|
||||
ConsoleOut(Print);
|
||||
addToLog(Print);
|
||||
}
|
||||
void except(const std::string& toPrint) {
|
||||
std::scoped_lock Guard(LogLock);
|
||||
std::string Print = getDate() + Sec("[EXCEP] ") + toPrint + "\n";
|
||||
ConsoleOut(Print);
|
||||
addToLog(Print);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use log::{Record, Level, Metadata, SetLoggerError, LevelFilter};
|
||||
use std::sync::Mutex;
|
||||
|
||||
lazy_static! {
|
||||
static ref LOG_BUFFER: Mutex<Vec<(Level, String)>> = Mutex::new(Vec::new());
|
||||
}
|
||||
|
||||
struct BufferedLogger;
|
||||
|
||||
impl log::Log for BufferedLogger {
|
||||
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||
let mut enabled = true;
|
||||
if metadata.level() != Level::Error {
|
||||
if metadata.target().starts_with("rustls") {
|
||||
enabled = false;
|
||||
}
|
||||
}
|
||||
enabled
|
||||
}
|
||||
|
||||
fn log(&self, record: &Record) {
|
||||
if self.enabled(record.metadata()) {
|
||||
let msg = format!("{}", record.args());
|
||||
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
|
||||
lock.push((record.level(), msg));
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
static LOGGER: BufferedLogger = BufferedLogger;
|
||||
|
||||
pub fn init(filter: LevelFilter) -> Result<(), SetLoggerError> {
|
||||
log::set_logger(&LOGGER)
|
||||
.map(|()| log::set_max_level(filter))
|
||||
}
|
||||
|
||||
pub async fn drain_log_buffer() -> Vec<(Level, String)> {
|
||||
let mut lock = LOG_BUFFER.lock().expect("Logging lock poisoned!");
|
||||
let v = lock.drain(..).collect();
|
||||
drop(lock);
|
||||
v
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
#include "CustomAssert.h"
|
||||
#include "Security/Xor.h"
|
||||
#include "Startup.h"
|
||||
#include <curl/curl.h>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#ifndef WIN32
|
||||
#include <signal.h>
|
||||
void UnixSignalHandler(int sig) {
|
||||
switch (sig) {
|
||||
case SIGPIPE:
|
||||
warn(Sec("ignored signal SIGPIPE: Pipe broken"));
|
||||
break;
|
||||
default:
|
||||
error(Sec("Signal arrived in handler but was not handled: ") + std::to_string(sig));
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif // WIN32
|
||||
|
||||
[[noreturn]] void loop() {
|
||||
DebugPrintTID();
|
||||
while (true) {
|
||||
std::cout.flush();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(600));
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
#ifndef WIN32
|
||||
// ignore SIGPIPE, the signal that is sent for example when a client
|
||||
// disconnects while data is being sent to him ("broken pipe").
|
||||
signal(SIGPIPE, UnixSignalHandler);
|
||||
#endif // WIN32
|
||||
DebugPrintTID();
|
||||
// curl needs to be initialized to properly deallocate its resources later
|
||||
Assert(curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK);
|
||||
#ifdef DEBUG
|
||||
std::thread t1(loop);
|
||||
t1.detach();
|
||||
#endif
|
||||
ConsoleInit();
|
||||
InitServer(argc, argv);
|
||||
InitConfig();
|
||||
InitLua();
|
||||
InitRes();
|
||||
HBInit();
|
||||
StatInit();
|
||||
NetMain();
|
||||
// clean up curl at the end to be sure
|
||||
curl_global_cleanup();
|
||||
return 0;
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#[macro_use] extern crate log;
|
||||
#[macro_use] extern crate async_trait;
|
||||
#[macro_use] extern crate lazy_static;
|
||||
|
||||
use std::path::Path;
|
||||
use argh::FromArgs;
|
||||
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
mod logger;
|
||||
mod tui;
|
||||
mod server;
|
||||
mod config;
|
||||
mod heartbeat;
|
||||
mod fs_util;
|
||||
|
||||
#[derive(FromArgs)]
|
||||
/// BeamMP Server v3.3.0
|
||||
struct Args {
|
||||
/// disables the TUI and shows a simple console log instead
|
||||
#[argh(switch)]
|
||||
disable_tui: bool,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let args: Args = argh::from_env();
|
||||
|
||||
let mut user_config: config::Config = toml::from_str(
|
||||
&std::fs::read_to_string("ServerConfig.toml")
|
||||
.map_err(|_| error!("Failed to read config file!"))
|
||||
.expect("Failed to read config file!")
|
||||
)
|
||||
.map_err(|_| eprintln!("Failed to parse config file!"))
|
||||
.expect("Failed to parse config file!");
|
||||
|
||||
let level_filter = if user_config.general.debug { log::LevelFilter::max() } else { log::LevelFilter::Info };
|
||||
if !args.disable_tui {
|
||||
logger::init(level_filter).expect("Failed to enable logger!");
|
||||
} else {
|
||||
pretty_env_logger::formatted_timed_builder()
|
||||
.filter_level(level_filter)
|
||||
.filter_module("rustls", log::LevelFilter::Error)
|
||||
.init();
|
||||
}
|
||||
|
||||
let client_resources = user_config.general
|
||||
.get_client_resource_folder()
|
||||
.expect("Failed to create the client resource folder");
|
||||
|
||||
for entry in std::fs::read_dir(client_resources).expect("Failed to read client resource folder!") {
|
||||
if let Ok(entry) = entry {
|
||||
if entry.path().is_file() {
|
||||
if let Ok(metadata) = entry.metadata() {
|
||||
if let Some(filename) = entry.path().file_name().map(|s| s.to_string_lossy()) {
|
||||
let mut name = filename.to_string();
|
||||
if !name.starts_with("/") {
|
||||
name = format!("/{name}");
|
||||
}
|
||||
user_config.mods.push((name, metadata.len() as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("Mods: {:?}", user_config.mods);
|
||||
|
||||
let user_config = Arc::new(user_config);
|
||||
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel(100);
|
||||
let (status_tx, status_rx) = mpsc::channel(100);
|
||||
|
||||
if !args.disable_tui {
|
||||
tokio::spawn(tui::tui_main(user_config.clone(), cmd_tx, status_rx));
|
||||
}
|
||||
|
||||
server_main(user_config, cmd_rx, status_tx).await;
|
||||
}
|
||||
|
||||
async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receiver<Vec<String>>, status_tx: mpsc::Sender<server::ServerStatus>) {
|
||||
let (hb_tx, hb_rx) = mpsc::channel(100);
|
||||
|
||||
tokio::spawn(heartbeat::backend_heartbeat(user_config.clone(), hb_rx));
|
||||
|
||||
let mut server = server::Server::new(user_config)
|
||||
.await
|
||||
.map_err(|e| error!("{:?}", e))
|
||||
.expect("Failed to start server!");
|
||||
|
||||
let mut status = server.get_server_status();
|
||||
hb_tx.send(status.clone()).await;
|
||||
status_tx.send(status.clone()).await;
|
||||
'server: loop {
|
||||
// TODO: Error handling
|
||||
if server.clients.len() > 0 {
|
||||
tokio::select! {
|
||||
ret = server::read_tcp(&mut server.clients) => {
|
||||
match ret {
|
||||
Ok(ret) => if let Some((index, packet)) = ret {
|
||||
server.process_tcp(index, packet).await;
|
||||
},
|
||||
Err(e) => error!("Error: {e}"),
|
||||
}
|
||||
}
|
||||
ret = server::read_udp(&mut server.udp_socket) => {
|
||||
if let Some((addr, packet)) = ret {
|
||||
server.process_udp(addr, packet).await;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(tokio::time::Duration::from_millis(50)) => {}
|
||||
}
|
||||
} else {
|
||||
// TODO: Scuffed?
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
|
||||
}
|
||||
|
||||
if let Err(e) = server.process().await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
|
||||
let new_status = server.get_server_status();
|
||||
|
||||
if status != new_status {
|
||||
status = new_status;
|
||||
hb_tx.send(status.clone()).await;
|
||||
status_tx.send(status.clone()).await;
|
||||
}
|
||||
|
||||
// Process commands
|
||||
match cmd_rx.try_recv() {
|
||||
Ok(cmd) => if cmd.len() > 0 {
|
||||
match cmd[0].as_str() {
|
||||
"exit" => {
|
||||
server.close().await;
|
||||
break 'server;
|
||||
},
|
||||
"players" => {
|
||||
let mut pl = "Players:\n".to_string();
|
||||
for (i, (id, player)) in status.player_list.iter().enumerate() {
|
||||
pl.push_str(&format!("\t[{: >2}] - {player}", id));
|
||||
if i + 1 < status.player_list.len() {
|
||||
pl.push('\n');
|
||||
}
|
||||
}
|
||||
info!("{}", pl);
|
||||
},
|
||||
"say" => {
|
||||
let msg = cmd[1..].iter().map(|s| s.as_str()).collect::<Vec<&str>>().join(" ");
|
||||
server.send_chat_message(&msg, None).await;
|
||||
},
|
||||
_ => info!("Unknown command!"),
|
||||
}
|
||||
} else {
|
||||
// what!
|
||||
},
|
||||
Err(mpsc::error::TryRecvError::Empty) => {},
|
||||
Err(e) => {
|
||||
error!("Error: {e}");
|
||||
break;
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::collections::HashMap;
|
||||
|
||||
static BACKEND_URL: &'static str = "backend.beammp.com";
|
||||
static AUTH_URL: &'static str = "auth.beammp.com";
|
||||
|
||||
pub async fn authentication_request<R: DeserializeOwned>(
|
||||
target: &str,
|
||||
map: HashMap<String, String>,
|
||||
) -> anyhow::Result<R> {
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.post(format!("https://{}/{}", AUTH_URL, target))
|
||||
.json(&map)
|
||||
.send()
|
||||
.await?;
|
||||
// panic!("json: {:?}", resp.text().await);
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use glam::*;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
pub struct Car {
|
||||
pub car_json: String,
|
||||
|
||||
pub pos: DVec3,
|
||||
pub rot: DQuat,
|
||||
pub vel: DVec3,
|
||||
pub rvel: DVec3,
|
||||
pub tim: f64,
|
||||
pub ping: f64,
|
||||
pub last_pos_update: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Car {
|
||||
pub fn new(car_json: String) -> Self {
|
||||
Self {
|
||||
car_json: car_json,
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw_position(&self) -> DVec3 {
|
||||
self.pos
|
||||
}
|
||||
|
||||
pub fn raw_rotation(&self) -> DQuat {
|
||||
self.rot
|
||||
}
|
||||
|
||||
pub fn position(&self) -> DVec3 {
|
||||
self.pos + self.vel * self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
pub fn rotation(&self) -> DQuat {
|
||||
let t = self.last_pos_update.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
|
||||
self.rot + DQuat::from_euler(glam::EulerRot::YXZ, self.rvel.x * t, self.rvel.y * t, self.rvel.z * t)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::ops::DerefMut;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{
|
||||
tcp::{OwnedReadHalf, OwnedWriteHalf},
|
||||
TcpStream,
|
||||
};
|
||||
use tokio::sync::mpsc::{Receiver, Sender};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use serde::Deserialize;
|
||||
use crate::fs_util;
|
||||
|
||||
use super::backend::*;
|
||||
use super::car::*;
|
||||
use super::packet::*;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref TAKEN_PLAYER_IDS: Mutex<Vec<u8>> = Mutex::new(Vec::new());
|
||||
pub static ref CLIENT_MOD_PROGRESS: Mutex<HashMap<u8, isize>> = Mutex::new(HashMap::new());
|
||||
}
|
||||
|
||||
// TODO: Return a proper error?
|
||||
async fn claim_id() -> Result<u8, ()> {
|
||||
let mut lock = TAKEN_PLAYER_IDS.lock().await;
|
||||
for index in 0..=255 {
|
||||
if !lock.contains(&index) {
|
||||
lock.push(index);
|
||||
return Ok(index);
|
||||
}
|
||||
}
|
||||
// requires more then 255 players on the server to error
|
||||
Err(())
|
||||
}
|
||||
|
||||
async fn free_id(id: u8) {
|
||||
let mut lock = TAKEN_PLAYER_IDS.lock().await;
|
||||
*lock = lock.drain(..).filter(|i| *i != id).collect::<Vec<u8>>();
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum ClientState {
|
||||
None,
|
||||
Connecting,
|
||||
SyncingResources,
|
||||
Syncing,
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, PartialEq, Clone)]
|
||||
pub struct UserData {
|
||||
pub uid: String,
|
||||
pub createdAt: String,
|
||||
pub guest: bool,
|
||||
pub roles: String,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
pub id: u8,
|
||||
pub udp_addr: Option<SocketAddr>,
|
||||
|
||||
socket: OwnedReadHalf,
|
||||
write_half: Arc<Mutex<OwnedWriteHalf>>,
|
||||
write_runtime: JoinHandle<()>,
|
||||
write_runtime_sender: Sender<Packet>,
|
||||
|
||||
pub state: ClientState,
|
||||
pub info: Option<UserData>,
|
||||
pub cars: Vec<(u8, Car)>,
|
||||
}
|
||||
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
tokio::spawn(free_id(self.id));
|
||||
self.write_runtime.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub async fn new(socket: TcpStream) -> Self {
|
||||
let id = match claim_id().await {
|
||||
Ok(v) => v,
|
||||
Err(_) => panic!("CRITICAL: Saturated Player ID's"),
|
||||
};
|
||||
trace!("Client with ID #{} created!", id);
|
||||
|
||||
let (read_half, write_half) = socket.into_split();
|
||||
let (tx, mut rx): (Sender<Packet>, Receiver<Packet>) = tokio::sync::mpsc::channel(128);
|
||||
let write_half = Arc::new(Mutex::new(write_half));
|
||||
let write_half_ref = Arc::clone(&write_half);
|
||||
let handle: JoinHandle<()> = tokio::spawn(async move {
|
||||
loop {
|
||||
if let Some(packet) = rx.recv().await {
|
||||
// trace!("Runtime received packet...");
|
||||
let mut lock = write_half_ref.lock().await;
|
||||
// trace!("Runtime sending packet!");
|
||||
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
|
||||
error!("{:?}", e);
|
||||
};
|
||||
// trace!("Runtime sent packet!");
|
||||
drop(lock);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
id: id,
|
||||
udp_addr: None,
|
||||
|
||||
socket: read_half,
|
||||
write_half: write_half,
|
||||
write_runtime: handle,
|
||||
write_runtime_sender: tx,
|
||||
|
||||
state: ClientState::Connecting,
|
||||
info: None,
|
||||
cars: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn authenticate(&mut self, config: &super::Config) -> anyhow::Result<bool> {
|
||||
debug!("Authenticating client {}...", self.id);
|
||||
|
||||
// TODO: Check client version
|
||||
trace!("Client version packet");
|
||||
self.socket.readable().await?;
|
||||
let packet = self.read_packet_waiting().await?;
|
||||
debug!("{:?}", packet);
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_code('S')))
|
||||
.await?;
|
||||
|
||||
self.socket.readable().await?;
|
||||
if let Some(packet) = self.read_packet_waiting().await? {
|
||||
debug!("packet: {:?}", packet);
|
||||
if packet.data.len() > 50 {
|
||||
self.kick("Player key too big!").await;
|
||||
return Err(ClientError::AuthenticateError.into());
|
||||
}
|
||||
let mut json = HashMap::new();
|
||||
let key = packet.data_as_string();
|
||||
debug!("[AUTH] key: {}", key);
|
||||
json.insert("key".to_string(), key);
|
||||
let user_data: UserData =
|
||||
authentication_request("pkToUser", json)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("[AUTH] {:?}", e);
|
||||
e
|
||||
})?;
|
||||
debug!("user_data: {:?}", user_data);
|
||||
self.info = Some(user_data);
|
||||
|
||||
// self.write_packet(Packet::Raw(RawPacket::from_code('S')))
|
||||
// .await?;
|
||||
} else {
|
||||
self.kick(
|
||||
"Client never sent public key! If this error persists, try restarting your game.",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str(&format!("P{}", self.id))))
|
||||
.await?;
|
||||
|
||||
self.state = ClientState::SyncingResources;
|
||||
|
||||
debug!(
|
||||
"Authentication of client {} succesfully completed! Syncing now...",
|
||||
self.id
|
||||
);
|
||||
self.sync(config).await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// TODO: https://github.com/BeamMP/BeamMP-Server/blob/master/src/TNetwork.cpp#L619
|
||||
pub async fn sync(&mut self, config: &super::Config) -> anyhow::Result<()> {
|
||||
'syncing: while self.state == ClientState::SyncingResources {
|
||||
self.socket.readable().await?;
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
if (packet.data.len() == 4 && packet.data == [68, 111, 110, 101]) || packet.data.len() == 0 {
|
||||
{
|
||||
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
|
||||
lock.insert(self.id, -1);
|
||||
}
|
||||
break 'syncing;
|
||||
}
|
||||
match packet.data[0] as char {
|
||||
'S' if packet.data.len() > 1 => match packet.data[1] as char {
|
||||
'R' => {
|
||||
let file_packet = if config.mods.len() == 0 {
|
||||
RawPacket::from_code('-')
|
||||
} else {
|
||||
let mut file_data = String::new();
|
||||
// TODO: Collapse these 2 loops into 1
|
||||
for (name, _size) in &config.mods {
|
||||
let mut mod_name = name.clone();
|
||||
if mod_name.starts_with("/") == false {
|
||||
mod_name = format!("/{mod_name}");
|
||||
}
|
||||
file_data.push_str(&format!("{mod_name};"));
|
||||
}
|
||||
for (_name, size) in &config.mods {
|
||||
file_data.push_str(&format!("{size};"));
|
||||
}
|
||||
RawPacket::from_str(&file_data)
|
||||
};
|
||||
// let file_packet = RawPacket::from_code('-');
|
||||
self.write_packet(Packet::Raw(file_packet))
|
||||
.await?;
|
||||
}
|
||||
_ => error!("Unknown packet! {:?}", packet),
|
||||
}
|
||||
'f' => {
|
||||
// Handle file download
|
||||
let mut mod_name = packet.data_as_string().clone();
|
||||
mod_name.remove(0); // Remove f
|
||||
debug!("Client is requesting file {}", mod_name);
|
||||
|
||||
let client_resources = config.general.get_client_resource_folder()?;
|
||||
let mod_path = fs_util::join_path_secure(Path::new(&client_resources), Path::new(&mod_name))?;
|
||||
|
||||
if !mod_path.exists() || !mod_path.is_file() {
|
||||
error!("Client requested mod which doesn't exist: {:?}. Disconnecting", mod_path);
|
||||
self.kick("Invalid mod request").await;
|
||||
return Ok(()) // client requested mod that doesnt exists within "Resources/Client/*"
|
||||
}
|
||||
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str("AG"))).await?;
|
||||
|
||||
let mut mod_id = 0;
|
||||
for (i, (bmod_name, _bmod_size)) in config.mods.iter().enumerate() {
|
||||
if bmod_name == &mod_name {
|
||||
mod_id = i;
|
||||
}
|
||||
}
|
||||
|
||||
// Send the first half of the file over this socket and the other over the DSocket
|
||||
let file_data = std::fs::read(mod_path)?;
|
||||
{
|
||||
let mut lock = self.write_half.lock().await;
|
||||
lock.writable().await?;
|
||||
trace!("Sending packets!");
|
||||
if let Err(e) = lock.write(&file_data[..(file_data.len()/2)]).await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
trace!("Packets sent!");
|
||||
drop(lock);
|
||||
}
|
||||
|
||||
{
|
||||
let mut lock = CLIENT_MOD_PROGRESS.lock().await;
|
||||
lock.insert(self.id, mod_id as isize);
|
||||
}
|
||||
}
|
||||
_ => error!("Unknown packet! {:?}", packet),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.state = ClientState::None;
|
||||
trace!("Done syncing! Sending map name...");
|
||||
self.write_packet(Packet::Raw(RawPacket::from_str(&format!(
|
||||
"M{}",
|
||||
config.general.map
|
||||
))))
|
||||
.await?;
|
||||
trace!("Map name sent!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This function should never block. It should simply check if there's a
|
||||
/// packet, and then and only then should it read it. If this were to block, the server
|
||||
/// would come to a halt until this function unblocks.
|
||||
pub async fn process(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub async fn process_blocking(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
if let Some(packet) = self.read_packet_waiting().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self) {
|
||||
self.state = ClientState::Disconnect;
|
||||
}
|
||||
|
||||
pub async fn kick(&mut self, msg: &str) {
|
||||
// let _ = self.socket.writable().await;
|
||||
// let _ = self.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg)))).await;
|
||||
// self.disconnect();
|
||||
let _ = self
|
||||
.write_packet(Packet::Raw(RawPacket::from_str(&format!("K{}", msg))))
|
||||
.await;
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
pub fn get_userdata(&self) -> UserData {
|
||||
self.info.as_ref().unwrap().clone()
|
||||
}
|
||||
|
||||
// Panics when userdata is not set!
|
||||
pub fn get_name(&self) -> &str {
|
||||
&self.info.as_ref().unwrap().username
|
||||
}
|
||||
|
||||
pub fn get_id(&self) -> u8 {
|
||||
self.id
|
||||
}
|
||||
|
||||
// Panics when userdata is not set!
|
||||
pub fn get_roles(&self) -> &str {
|
||||
&self.info.as_ref().unwrap().roles
|
||||
}
|
||||
|
||||
pub fn register_car(&mut self, car: Car) -> u8 {
|
||||
let mut free_num = 0;
|
||||
for (num, _) in &self.cars {
|
||||
if num == &free_num {
|
||||
free_num += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.cars.push((free_num, car));
|
||||
free_num
|
||||
}
|
||||
|
||||
pub fn unregister_car(&mut self, car_id: u8) {
|
||||
let prev_len = self.cars.len();
|
||||
self.cars.retain(|(id, _)| id != &car_id);
|
||||
if prev_len == self.cars.len() {
|
||||
error!(
|
||||
"Failed to unregister car #{} for client #{}! Ignoring for now...",
|
||||
car_id, self.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_car_mut(&mut self, mut car_id: u8) -> Option<&mut Car> {
|
||||
for (num, car) in &mut self.cars {
|
||||
if num == &mut car_id {
|
||||
return Some(car);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn read_raw(&mut self, count: usize) -> anyhow::Result<Vec<u8>> {
|
||||
let mut b = vec![0u8; count];
|
||||
self.socket.read_exact(&mut b).await?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
async fn read_packet_waiting(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
let start = std::time::Instant::now();
|
||||
'wait: loop {
|
||||
if let Some(packet) = self.read_packet().await? {
|
||||
return Ok(Some(packet));
|
||||
}
|
||||
if start.elapsed().as_secs() >= 5 {
|
||||
break 'wait;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
}
|
||||
Err(ClientError::ConnectionTimeout.into())
|
||||
}
|
||||
|
||||
/// Must be non-blocking
|
||||
async fn read_packet(&mut self) -> anyhow::Result<Option<RawPacket>> {
|
||||
let mut header = [0u8; 4];
|
||||
match self.socket.try_read(&mut header) {
|
||||
Ok(0) => {
|
||||
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
|
||||
self.disconnect();
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(_n) => {}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
|
||||
let expected_size = u32::from_le_bytes(header) as usize;
|
||||
let mut data = Vec::new();
|
||||
let mut tmp_data = vec![0u8; expected_size];
|
||||
let mut data_size = 0;
|
||||
while data_size < expected_size {
|
||||
match self.socket.try_read(&mut tmp_data) {
|
||||
Ok(0) => {
|
||||
error!("Socket is readable, yet has 0 bytes to read! Disconnecting client...");
|
||||
self.disconnect();
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(n) => {
|
||||
data_size += n;
|
||||
data.extend_from_slice(&tmp_data[..n]);
|
||||
},
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
// debug!("Packet appears to be ready, yet can't be read yet!");
|
||||
// self.socket.read(&mut data).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(RawPacket {
|
||||
header: data_size as u32,
|
||||
data: data[..data_size].to_vec(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Blocking write
|
||||
pub async fn write_packet(&mut self, packet: Packet) -> anyhow::Result<()> {
|
||||
let mut lock = self.write_half.lock().await;
|
||||
lock.writable().await?;
|
||||
trace!("Sending packet!");
|
||||
if let Err(e) = tcp_write(lock.deref_mut(), packet).await {
|
||||
error!("{:?}", e);
|
||||
}
|
||||
trace!("Packet sent!");
|
||||
drop(lock);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn queue_packet(&self, packet: Packet) {
|
||||
// TODO: If packet gets lost, put it back at the front of the queue?
|
||||
let _ = self.write_runtime_sender.send(packet).await;
|
||||
}
|
||||
|
||||
pub async fn trigger_client_event<S: Into<String>, D: Into<String>>(&self, event_name: S, data: D) {
|
||||
let event_name = event_name.into();
|
||||
let data = data.into();
|
||||
debug!("Calling client event '{}' with data '{}'", event_name, data);
|
||||
let packet_data = format!("E:{}:{}", event_name, data);
|
||||
self.queue_packet(Packet::Raw(RawPacket::from_str(&packet_data))).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientError {
|
||||
AuthenticateError,
|
||||
ConnectionTimeout,
|
||||
IsDownloader,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClientError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(f, "{:?}", self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ClientError {}
|
||||
|
||||
#[async_trait]
|
||||
trait Writable {
|
||||
async fn writable(&self) -> std::io::Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Writable for TcpStream {
|
||||
async fn writable(&self) -> std::io::Result<()> {
|
||||
self.writable().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Writable for OwnedWriteHalf {
|
||||
async fn writable(&self) -> std::io::Result<()> {
|
||||
self.writable().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn tcp_write<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
mut packet: Packet,
|
||||
) -> anyhow::Result<()> {
|
||||
let compressed = match packet.get_code() {
|
||||
Some('O') => true,
|
||||
Some('T') => true,
|
||||
_ => packet.get_data().len() > 400,
|
||||
};
|
||||
|
||||
if compressed {
|
||||
let mut compressed: Vec<u8> = Vec::with_capacity(100_000);
|
||||
let mut compressor = flate2::Compress::new(flate2::Compression::best(), true);
|
||||
compressor.compress_vec(
|
||||
packet.get_data(),
|
||||
&mut compressed,
|
||||
flate2::FlushCompress::Sync,
|
||||
)?;
|
||||
let mut new_data = "ABG:".as_bytes()[..4].to_vec();
|
||||
new_data.append(&mut compressed);
|
||||
packet.set_header(new_data.len() as u32);
|
||||
packet.set_data(new_data);
|
||||
}
|
||||
|
||||
tcp_write_raw(w, packet).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tcp_write_raw<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
mut packet: Packet,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut raw_data: Vec<u8> = packet.get_header().to_le_bytes().to_vec();
|
||||
raw_data.extend_from_slice(packet.get_data());
|
||||
w.writable().await?;
|
||||
w.write(&raw_data).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tcp_send_file<W: AsyncWriteExt + Writable + std::marker::Unpin>(
|
||||
w: &mut W,
|
||||
file_name: String,
|
||||
) -> anyhow::Result<()> {
|
||||
debug!("Sending file '{}'", file_name);
|
||||
tcp_write(w, Packet::Raw(RawPacket::from_str("KYou have not downloaded the mod manually!"))).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{
|
||||
tcp::{OwnedReadHalf, OwnedWriteHalf},
|
||||
TcpStream,
|
||||
};
|
||||
|
||||
pub async fn handle_http_get(socket: TcpStream) {
|
||||
let (read_half, write_half) = socket.into_split();
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn read_get_request(socket: &mut OwnedReadHalf) {
|
||||
todo!()
|
||||
}
|
||||
+1309
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Packet {
|
||||
Raw(RawPacket),
|
||||
Notification(NotificationPacket),
|
||||
}
|
||||
|
||||
impl Packet {
|
||||
pub fn get_header(&self) -> u32 {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.header,
|
||||
Self::Notification(msg) => self.get_data().len() as u32,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_data(&self) -> &[u8] {
|
||||
match self {
|
||||
Self::Raw(raw) => &raw.data,
|
||||
Self::Notification(p) => p.0.as_bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_code(&self) -> Option<char> {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.data.get(0).map(|c| *c as char),
|
||||
Self::Notification(_) => Some('J'),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_data(&mut self, data: Vec<u8>) {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.data = data,
|
||||
Self::Notification(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_header(&mut self, header: u32) {
|
||||
match self {
|
||||
Self::Raw(raw) => raw.header = header,
|
||||
Self::Notification(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_as_string(&self) -> String {
|
||||
String::from_utf8_lossy(&self.get_data()).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NotificationPacket(String);
|
||||
|
||||
impl NotificationPacket {
|
||||
pub fn new<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("J{}", msg.into()))
|
||||
}
|
||||
pub fn player_welcome<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("JWelcome {}!", msg.into()))
|
||||
}
|
||||
pub fn player_left<S: Into<String>>(msg: S) -> Self {
|
||||
Self(format!("L{} left the server!", msg.into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Protocol:
|
||||
/// Header: 4 bytes, contains data size
|
||||
/// Data: Contains packet data
|
||||
#[derive(Clone)]
|
||||
pub struct RawPacket {
|
||||
pub header: u32,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl RawPacket {
|
||||
pub fn from_code(code: char) -> Self {
|
||||
Self {
|
||||
header: 1,
|
||||
data: vec![code as u8],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_data(data: Vec<u8>) -> Self {
|
||||
Self {
|
||||
header: data.len() as u32,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_str(str_data: &str) -> Self {
|
||||
let data = str_data.as_bytes().to_vec();
|
||||
Self {
|
||||
header: data.len() as u32,
|
||||
data: data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_as_string(&self) -> String {
|
||||
String::from_utf8_lossy(&self.data).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RawPacket {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(
|
||||
f,
|
||||
"Header: `{:?}` - Bytes: `{:?}` - String: `{}`",
|
||||
self.header,
|
||||
self.data,
|
||||
self.data_as_string()
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketData {
|
||||
pub pos: RespawnPacketDataPos,
|
||||
pub rot: RespawnPacketDataRot,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketDataPos {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct RespawnPacketDataRot {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub z: f64,
|
||||
pub w: f64,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct TransformPacket {
|
||||
pub rvel: [f64; 3],
|
||||
pub tim: f64,
|
||||
pub pos: [f64; 3],
|
||||
pub ping: f64,
|
||||
pub rot: [f64; 4],
|
||||
pub vel: [f64; 3],
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
use super::{
|
||||
Backend,
|
||||
ServerBoundPluginEvent,
|
||||
PluginBoundPluginEvent,
|
||||
ScriptEvent,
|
||||
Argument
|
||||
};
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tokio::sync::mpsc::{Sender, Receiver};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use mlua::prelude::*;
|
||||
use mlua::{UserData, UserDataMethods, Value, Function, Variadic};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Context {
|
||||
tx: Arc<Sender<ServerBoundPluginEvent>>,
|
||||
|
||||
handlers: Arc<Mutex<HashMap<String, String>>>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
fn new(tx: Arc<Sender<ServerBoundPluginEvent>>) -> Self {
|
||||
Self {
|
||||
tx,
|
||||
|
||||
handlers: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for Context {
|
||||
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> LuaResult<Self> {
|
||||
match value {
|
||||
Value::UserData(ud) => Ok(ud.borrow::<Self>()?.clone()),
|
||||
_ => unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for Context {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
// Implement all the API functions here
|
||||
|
||||
methods.add_function("RegisterEventHandler", |lua, (event_name, handler_name): (String, String)| {
|
||||
debug!("Event handler registered: {} (EVENT) = {} (LUA)", event_name, handler_name);
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
me.handlers.lock().expect("Lock is poisoned!").insert(event_name, handler_name);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_function("GetServerVersion", |_lua, ()| {
|
||||
Ok((3, 3, 0))
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerCount", |lua, ()| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerCount(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::PlayerCount(player_count) = message {
|
||||
Ok(player_count)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayers", |lua, ()| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayers(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::Players(players) = message {
|
||||
let table = lua.create_table()?;
|
||||
for (id, name) in players {
|
||||
table.set(id, name)?;
|
||||
}
|
||||
Ok(table)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerIdentifiers", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerIdentifiers((id, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
match message {
|
||||
PluginBoundPluginEvent::PlayerIdentifiers(identifiers) => {
|
||||
let table = lua.create_table()?;
|
||||
table.set("id", identifiers.ip)?;
|
||||
table.set("beammp_id", identifiers.beammp_id)?;
|
||||
Ok(Value::Table(table))
|
||||
},
|
||||
PluginBoundPluginEvent::None => Ok(Value::Nil),
|
||||
_ => unreachable!() // This should really never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerName", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
// We can simply request all player names and pick the one we need
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayers(tx)) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::Players(players) = message {
|
||||
let mut name = None;
|
||||
'search: for (pid, pname) in players {
|
||||
if pid == id {
|
||||
name = Some(pname);
|
||||
break 'search;
|
||||
}
|
||||
}
|
||||
Ok(name)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPlayerVehicles", |lua, (id,): (u8,)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPlayerVehicles((id, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
if let PluginBoundPluginEvent::PlayerVehicles(vehicles) = message {
|
||||
let table = lua.create_table()?;
|
||||
for (vid, veh_json) in vehicles {
|
||||
table.set(vid, veh_json)?;
|
||||
}
|
||||
Ok(table)
|
||||
} else {
|
||||
unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("GetPositionRaw", |lua, (pid, vid): (u8, u8)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::RequestPositionRaw((pid, vid, tx))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
let message = rx.blocking_recv();
|
||||
if let Ok(message) = message {
|
||||
match message {
|
||||
PluginBoundPluginEvent::PositionRaw(pos_raw) => {
|
||||
let pos_table = lua.create_table()?;
|
||||
pos_table.set("x", pos_raw.pos[0])?;
|
||||
pos_table.set("y", pos_raw.pos[1])?;
|
||||
pos_table.set("z", pos_raw.pos[2])?;
|
||||
|
||||
let rot_table = lua.create_table()?;
|
||||
pos_table.set("x", pos_raw.rot[0])?;
|
||||
pos_table.set("y", pos_raw.rot[1])?;
|
||||
pos_table.set("z", pos_raw.rot[2])?;
|
||||
pos_table.set("w", pos_raw.rot[3])?;
|
||||
|
||||
let table = lua.create_table()?;
|
||||
table.set("pos", pos_table)?;
|
||||
table.set("rot", rot_table)?;
|
||||
Ok(Value::Table(table))
|
||||
},
|
||||
PluginBoundPluginEvent::None => Ok(Value::Nil),
|
||||
_ => unreachable!() // This really should never be reachable
|
||||
}
|
||||
} else {
|
||||
todo!("Receiving a response from the server failed! How?")
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_function("SendChatMessage", |lua, (id, msg): (isize, String)| {
|
||||
let me: Context = lua.globals().get("MP")?;
|
||||
if let Err(e) = me.tx.blocking_send(ServerBoundPluginEvent::SendChatMessage((id, msg))) {
|
||||
error!("Failed to send packet: {:?}", e);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_function("GetOSName", |lua, ()| {
|
||||
Ok(std::env::consts::OS)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BackendLua {
|
||||
lua: Lua,
|
||||
}
|
||||
|
||||
impl BackendLua {
|
||||
pub fn new() -> Self {
|
||||
let lua = Lua::new();
|
||||
|
||||
Self {
|
||||
lua,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for BackendLua {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()> {
|
||||
self.lua.load(code).exec().map_err(|e| { error!("[LUA] {:?}", e); e })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_api(&mut self, tx: Arc<Sender<ServerBoundPluginEvent>>) -> anyhow::Result<()> {
|
||||
let print_fn = self.lua.create_function(|_lua, (msg,): (String,)| {
|
||||
info!("[LUA] {}", msg);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let api = Context::new(tx);
|
||||
|
||||
let globals = self.lua.globals();
|
||||
globals.set("MP", api)?;
|
||||
globals.set("print", print_fn)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>) {
|
||||
let (event_name, args) = match event {
|
||||
ScriptEvent::OnPluginLoaded => ("onInit", vec![]),
|
||||
ScriptEvent::OnShutdown => ("onShutdown", vec![]),
|
||||
|
||||
ScriptEvent::OnPlayerAuthenticated { name, role, is_guest, identifiers } => ("onPlayerAuth", vec![Argument::String(name), Argument::String(role), Argument::Boolean(is_guest), Argument::Table(identifiers.to_map())]),
|
||||
ScriptEvent::OnPlayerConnecting { pid } => ("onPlayerConnecting", vec![Argument::Integer(pid as i64)]),
|
||||
ScriptEvent::OnPlayerJoining { pid } => ("onPlayerJoining", vec![Argument::Integer(pid as i64)]),
|
||||
|
||||
ScriptEvent::OnPlayerDisconnect { pid, name } => ("onPlayerDisconnect", vec![Argument::Integer(pid as i64), Argument::String(name)]),
|
||||
|
||||
ScriptEvent::OnVehicleSpawn { pid, vid, car_data } => ("onVehicleSpawn", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
ScriptEvent::OnVehicleEdited { pid, vid, car_data } => ("onVehicleEdited", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
ScriptEvent::OnVehicleDeleted { pid, vid } => ("onVehicleDeleted", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64)]),
|
||||
ScriptEvent::OnVehicleReset { pid, vid, car_data } => ("onVehicleReset", vec![Argument::Integer(pid as i64), Argument::Integer(vid as i64), Argument::String(car_data)]),
|
||||
|
||||
ScriptEvent::OnChatMessage { pid, name, message } => ("onChatMessage", vec![Argument::Integer(pid as i64), Argument::String(name), Argument::String(message)]),
|
||||
};
|
||||
|
||||
let mut ret = Value::Number(-1f64);
|
||||
// TODO: Error handling
|
||||
{
|
||||
let ctx: Context = self.lua.globals().get("MP").expect("MP is missing!");
|
||||
let lock = ctx.handlers.lock().expect("Mutex is poisoned!");
|
||||
if let Some(handler_name) = lock.get(event_name) {
|
||||
let func: LuaResult<Function> = self.lua.globals().get(handler_name.clone());
|
||||
if let Ok(func) = func {
|
||||
let mapped_args = args.into_iter().map(|arg| {
|
||||
arg_to_value(&self.lua, arg)
|
||||
}).filter(|v| v.is_some());
|
||||
match func.call::<_, Value>(Variadic::from_iter(mapped_args)) {
|
||||
Ok(res) => { trace!("fn ret: {:?}", res); ret = res; }
|
||||
Err(e) => {
|
||||
error!("[LUA] {}", e);
|
||||
ret = Value::Number(-1f64);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("sending result...");
|
||||
if let Some(resp) = resp {
|
||||
let arg = value_to_arg(ret);
|
||||
resp.send(arg).expect("Failed to send!");
|
||||
}
|
||||
debug!("call_event_handler done");
|
||||
}
|
||||
}
|
||||
|
||||
fn value_to_arg(value: Value) -> Argument {
|
||||
match value {
|
||||
Value::Boolean(b) => Argument::Boolean(b),
|
||||
Value::Integer(i) => Argument::Integer(i),
|
||||
Value::Number(f) => Argument::Number(f as f32),
|
||||
Value::String(s) => Argument::String(s.to_string_lossy().to_string()),
|
||||
_ => Argument::Number(-1f32),
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_to_value(lua: &Lua, arg: Argument) -> Option<Value> {
|
||||
match arg {
|
||||
Argument::String(s) => if let Ok(lua_str) = lua.create_string(&s) { Some(Value::String(lua_str)) } else { None },
|
||||
Argument::Boolean(b) => Some(Value::Boolean(b)),
|
||||
Argument::Number(f) => Some(Value::Number(f as f64)),
|
||||
Argument::Integer(i) => Some(Value::Integer(i as i64)),
|
||||
Argument::Table(t) => {
|
||||
if let Ok(table) = lua.create_table() {
|
||||
for (key, value) in t {
|
||||
if let Some(v) = arg_to_value(lua, value) {
|
||||
if let Err(e) = table.set(key, v) {
|
||||
error!("[LUA] Error occured trying to put data into table: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Value::Table(table))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
pub mod backend_lua;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::HashMap;
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::sync::mpsc::{self, Sender, Receiver};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// NOTE: Send is required as the backend is constructed on the main thread and sent over.
|
||||
/// Even if we construct it inside the runtime however, because of tokio, we would
|
||||
// still have to require Send as the runtime might run on different threads (?)
|
||||
pub trait Backend: Send {
|
||||
fn load(&mut self, code: String) -> anyhow::Result<()>;
|
||||
fn load_api(&mut self, tx: Arc<Sender<ServerBoundPluginEvent>>) -> anyhow::Result<()>;
|
||||
|
||||
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>);
|
||||
}
|
||||
|
||||
// TODO: This is quite focused on Lua right now, perhaps in the future we want to modify this list
|
||||
// to be more versatile?
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Argument {
|
||||
String(String),
|
||||
Boolean(bool),
|
||||
Number(f32),
|
||||
Integer(i64),
|
||||
Table(HashMap<String, Argument>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PlayerIdentifiers {
|
||||
pub ip: String,
|
||||
pub beammp_id: String,
|
||||
}
|
||||
|
||||
impl PlayerIdentifiers {
|
||||
pub fn to_map(&self) -> HashMap<String, Argument> {
|
||||
let mut m = HashMap::new();
|
||||
m.insert(String::from("ip"), Argument::String(self.ip.clone()));
|
||||
m.insert(String::from("beammp"), Argument::String(self.beammp_id.clone()));
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PositionRaw {
|
||||
pub pos: [f32; 3],
|
||||
pub rot: [f32; 4],
|
||||
}
|
||||
|
||||
impl PositionRaw {
|
||||
pub fn to_map(&self) -> HashMap<String, Argument> {
|
||||
let mut pm = HashMap::new();
|
||||
pm.insert(String::from("x"), Argument::Number(self.pos[0]));
|
||||
pm.insert(String::from("y"), Argument::Number(self.pos[1]));
|
||||
pm.insert(String::from("z"), Argument::Number(self.pos[2]));
|
||||
|
||||
let mut rm = HashMap::new();
|
||||
rm.insert(String::from("x"), Argument::Number(self.rot[0]));
|
||||
rm.insert(String::from("y"), Argument::Number(self.rot[1]));
|
||||
rm.insert(String::from("z"), Argument::Number(self.rot[2]));
|
||||
rm.insert(String::from("w"), Argument::Number(self.rot[3]));
|
||||
|
||||
let mut m = HashMap::new();
|
||||
m.insert(String::from("pos"), Argument::Table(pm));
|
||||
m.insert(String::from("rot"), Argument::Table(rm));
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ScriptEvent {
|
||||
OnPluginLoaded,
|
||||
OnShutdown,
|
||||
|
||||
// TODO: Because of limitations in how we accept clients, onPlayerAuth runs after mod downloading and syncing
|
||||
// has already happened. With some reworking, this can be avoided, but it's not easy.
|
||||
// This is quite important however, because otherwise mod downloads will get triggered
|
||||
// constantly even when someone isn't allowed to join!
|
||||
OnPlayerAuthenticated { name: String, role: String, is_guest: bool, identifiers: PlayerIdentifiers },
|
||||
// TODO: See the comment above, this results in these 2 events being useless for now.
|
||||
// I've simply left them in for backwards compatibility for now!
|
||||
OnPlayerConnecting { pid: u8 },
|
||||
OnPlayerJoining { pid: u8 },
|
||||
|
||||
OnPlayerDisconnect { pid: u8, name: String },
|
||||
|
||||
OnVehicleSpawn { pid: u8, vid: u8, car_data: String },
|
||||
OnVehicleEdited { pid: u8, vid: u8, car_data: String },
|
||||
OnVehicleDeleted { pid: u8, vid: u8 },
|
||||
OnVehicleReset { pid: u8, vid: u8, car_data: String },
|
||||
|
||||
OnChatMessage { pid: u8, name: String, message: String },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PluginBoundPluginEvent {
|
||||
None,
|
||||
|
||||
CallEventHandler((ScriptEvent, Option<oneshot::Sender<Argument>>)),
|
||||
|
||||
PlayerCount(usize),
|
||||
Players(HashMap<u8, String>),
|
||||
PlayerIdentifiers(PlayerIdentifiers),
|
||||
|
||||
PlayerVehicles(HashMap<u8, String>),
|
||||
PositionRaw(PositionRaw),
|
||||
}
|
||||
|
||||
// TODO: Perhaps it would be nice to ensure each sender can only sned specifically what it needs to.
|
||||
// Purely to ensure type safety and slightly cleaner code on the backend implementation side.
|
||||
#[derive(Debug)]
|
||||
pub enum ServerBoundPluginEvent {
|
||||
PluginLoaded,
|
||||
|
||||
RequestPlayerCount(oneshot::Sender<PluginBoundPluginEvent>),
|
||||
RequestPlayers(oneshot::Sender<PluginBoundPluginEvent>),
|
||||
RequestPlayerIdentifiers((u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
|
||||
RequestPlayerVehicles((u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
RequestPositionRaw((u8, u8, oneshot::Sender<PluginBoundPluginEvent>)),
|
||||
|
||||
SendChatMessage((isize, String)),
|
||||
}
|
||||
|
||||
pub struct Plugin {
|
||||
runtime: Runtime,
|
||||
tx: Sender<PluginBoundPluginEvent>,
|
||||
rx: Receiver<ServerBoundPluginEvent>,
|
||||
}
|
||||
|
||||
impl Plugin {
|
||||
pub fn new(mut backend: Box<dyn Backend>, src: String) -> anyhow::Result<Self> {
|
||||
let runtime = Runtime::new().expect("Failed to create a tokio Runtime!");
|
||||
let (pb_tx, mut pb_rx) = mpsc::channel(1_000);
|
||||
let (sb_tx, sb_rx) = mpsc::channel(1_000);
|
||||
let sb_tx = Arc::new(sb_tx);
|
||||
runtime.spawn_blocking(move || {
|
||||
if backend.load_api(sb_tx.clone()).is_ok() {
|
||||
if backend.load(src).is_ok() {
|
||||
if sb_tx.blocking_send(ServerBoundPluginEvent::PluginLoaded).is_err() {
|
||||
error!("Plugin communication channels somehow already closed!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Some(message) = pb_rx.blocking_recv() {
|
||||
match message {
|
||||
PluginBoundPluginEvent::CallEventHandler((event, resp)) => {
|
||||
backend.call_event_handler(event, resp);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
} else {
|
||||
error!("Event receiver has closed!"); // TODO: We probably want to display the plugin name here too lol
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
runtime,
|
||||
tx: pb_tx,
|
||||
rx: sb_rx,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn close(mut self) {
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
self.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnShutdown, Some(tx)))).await;
|
||||
let _ = rx.await; // We just wait for it to finish shutting down
|
||||
self.runtime.shutdown_background();
|
||||
}
|
||||
|
||||
// TODO: For performance I think we can turn this into an iterator instead of first allocating
|
||||
// a full vector?
|
||||
pub fn get_events(&mut self) -> Vec<ServerBoundPluginEvent> {
|
||||
let mut events = Vec::new();
|
||||
loop {
|
||||
match self.rx.try_recv() {
|
||||
Ok(event) => events.push(event),
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => break, // TODO: This means the runtime is dead!!! Handle this!!!
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
// TODO: Handle error when connection is closed, as it means the runtime is down
|
||||
pub async fn send_event(&self, event: PluginBoundPluginEvent) {
|
||||
let _ = self.tx.send(event).await;
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
use std::sync::Arc;
|
||||
use std::io::{stdout, Result};
|
||||
use std::collections::VecDeque;
|
||||
use log::Level;
|
||||
|
||||
use crossterm::{
|
||||
event::{self, KeyCode, KeyEventKind, KeyModifiers},
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
ExecutableCommand,
|
||||
};
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
widgets::{Paragraph, Block, Borders},
|
||||
};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::server::ServerStatus;
|
||||
|
||||
pub async fn tui_main(config: Arc<Config>, cmd_tx: mpsc::Sender<Vec<String>>, mut info_rx: mpsc::Receiver<ServerStatus>) {
|
||||
let mut tui = Tui::new().expect("Failed to initialize tui!");
|
||||
|
||||
'app: loop {
|
||||
if tui.update(&cmd_tx, &mut info_rx).await.expect("Failed to run tui.update!") {
|
||||
cmd_tx.send(vec!["exit".to_string()]).await.unwrap();
|
||||
break 'app;
|
||||
}
|
||||
tui.draw().expect("Failed to run tui.draw!");
|
||||
}
|
||||
}
|
||||
|
||||
struct Tui {
|
||||
terminal: Terminal<CrosstermBackend<std::io::Stdout>>,
|
||||
|
||||
log_buffer: VecDeque<(Level, String)>,
|
||||
|
||||
history_scroll: usize,
|
||||
input_history: Vec<String>,
|
||||
input: String,
|
||||
|
||||
server_status: ServerStatus,
|
||||
}
|
||||
|
||||
impl Drop for Tui {
|
||||
fn drop(&mut self) {
|
||||
if let Err(e) = self.cleanup() {
|
||||
eprintln!("Error occured related to the TUI: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
fn new() -> Result<Self> {
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
|
||||
let terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
|
||||
Ok(Self {
|
||||
terminal,
|
||||
|
||||
log_buffer: VecDeque::new(),
|
||||
|
||||
history_scroll: 0,
|
||||
input_history: Vec::new(),
|
||||
input: String::new(),
|
||||
|
||||
server_status: ServerStatus::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> Result<()> {
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
disable_raw_mode()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update(&mut self, cmd_tx: &mpsc::Sender<Vec<String>>, info_rx: &mut mpsc::Receiver<ServerStatus>) -> Result<bool> {
|
||||
for (level, msg) in crate::logger::drain_log_buffer().await {
|
||||
self.log_buffer.push_front((level, msg));
|
||||
if self.log_buffer.len() > 100 {
|
||||
self.log_buffer.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
match info_rx.try_recv() {
|
||||
Ok(status) => self.server_status = status,
|
||||
Err(mpsc::error::TryRecvError::Empty) => {},
|
||||
Err(e) => return Ok(true),
|
||||
}
|
||||
|
||||
if event::poll(std::time::Duration::from_millis(16))? {
|
||||
if let event::Event::Key(key) = event::read()? {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char(c) if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
|
||||
},
|
||||
KeyCode::Char(c) => {
|
||||
let c = if key.modifiers == KeyModifiers::SHIFT { c.to_ascii_uppercase() } else { c };
|
||||
self.input.push(c);
|
||||
self.history_scroll = 0;
|
||||
},
|
||||
KeyCode::Backspace => { self.input.pop(); },
|
||||
KeyCode::Enter => {
|
||||
if self.input.is_empty() == false {
|
||||
let args = self.input.split(" ").map(|s| s.to_string()).collect::<Vec<String>>();
|
||||
if let Err(e) = cmd_tx.send(args.clone()).await {
|
||||
error!("Error occured sending a command to the server! {e}");
|
||||
return Ok(true);
|
||||
}
|
||||
self.input_history.insert(0, self.input.clone());
|
||||
self.input = String::new();
|
||||
if args.get(0) == Some(&"exit".to_string()) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
},
|
||||
KeyCode::Up => {
|
||||
if self.history_scroll < self.input_history.len() {
|
||||
self.history_scroll += 1;
|
||||
self.input = self.input_history[self.history_scroll - 1].clone();
|
||||
}
|
||||
},
|
||||
KeyCode::Down => {
|
||||
if self.history_scroll > 1 {
|
||||
self.history_scroll -= 1;
|
||||
self.input = self.input_history[self.history_scroll - 1].clone();
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn draw(&mut self) -> Result<()> {
|
||||
self.terminal.draw(|frame| {
|
||||
let area = frame.size();
|
||||
|
||||
let vert_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints(vec![
|
||||
Constraint::Length(area.height - 3),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
let horiz_layout = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints(vec![
|
||||
Constraint::Percentage(70),
|
||||
Constraint::Percentage(30),
|
||||
])
|
||||
.split(vert_layout[0]);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for (i, (level, msg)) in self.log_buffer.iter().enumerate() {
|
||||
if i >= (area.height as usize - 5) { break; }
|
||||
let (level_style, spacer) = match level {
|
||||
Level::Info => (Style::default().green(), " "),
|
||||
Level::Warn => (Style::default().yellow(), " "),
|
||||
Level::Error => (Style::default().red(), ""),
|
||||
Level::Debug => (Style::default().gray(), ""),
|
||||
Level::Trace => (Style::default().cyan(), ""),
|
||||
};
|
||||
lines.push(Line::from(vec![
|
||||
Span::styled("[", Style::default()),
|
||||
Span::styled(format!("{}", level), level_style),
|
||||
Span::styled(format!("]{} {}", spacer, msg), Style::default()),
|
||||
]));
|
||||
}
|
||||
lines.reverse();
|
||||
frame.render_widget(
|
||||
// Paragraph::new("[INFO] info!!!\n[DEBUG] debug!!!!").block(Block::new().borders(Borders::ALL)),
|
||||
Paragraph::new(Text::from(lines)).block(Block::new().borders(Borders::ALL).title("Log")),
|
||||
horiz_layout[0],
|
||||
);
|
||||
|
||||
let mut lines = Vec::new();
|
||||
for (id, name) in &self.server_status.player_list {
|
||||
lines.push(Line::from(format!("{id} - {name}")));
|
||||
}
|
||||
frame.render_widget(
|
||||
Paragraph::new(lines).block(Block::new().borders(Borders::ALL).title("Player List")),
|
||||
horiz_layout[1],
|
||||
);
|
||||
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!(" > {}", self.input)).block(Block::new().borders(Borders::ALL).title("Input")),
|
||||
vert_layout[1],
|
||||
);
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user