Compare commits

..

111 Commits

Author SHA1 Message Date
Luuk van Oijen e58a241b28 implement GetOsName 2023-12-06 13:59:54 +01:00
Luuk van Oijen bf4c2d120e wip onvehiclereset implemented 2023-12-05 23:18:52 +01:00
Luuk van Oijen 8b88127e20 support onVehicleDeleted 2023-12-05 14:48:41 +01:00
Luuk van Oijen 6e7b2e0525 Merge branch 'master' of https://github.com/Lucky4Luuk/beammp_rust_server 2023-12-04 16:57:54 +01:00
Luuk van Oijen 1e6c2ea680 Update mod.rs 2023-12-04 16:57:53 +01:00
Luuk van Oijen 140b43a18c wip stuff 2023-12-04 11:16:48 +01:00
Luuk van Oijen b8211166ad mostly finished get position raw stuff 2023-11-30 16:27:23 +01:00
Luuk van Oijen 8e1d235dee switched over to glam and simplified some imports 2023-11-30 15:35:22 +01:00
Luuk van Oijen dc61d4649c wip position raw event 2023-11-30 15:28:35 +01:00
Luuk van Oijen 03ac847683 implemented cancellable vehicle edits 2023-11-30 11:25:17 +01:00
Luuk van Oijen 3dde6a76cb Merge pull request #14 from lionkor/fix-modloading
fix mod loading
2023-11-29 22:47:28 +01:00
Lion Kortlepel 87a0d46b00 fix mod loading
it was using the wrong path because i broke it :)
2023-11-29 22:44:25 +01:00
Luuk van Oijen 452a4c5e16 cancellable vehicle spawns 2023-11-28 19:22:03 +01:00
Luuk van Oijen adfda5a8cb Update backend_lua.rs 2023-11-28 14:05:31 +01:00
Luuk van Oijen 14097b6c68 oops forgot to filter the non-tui logger too 2023-11-28 11:18:47 +01:00
Luuk van Oijen 7a21751750 filtering rustls (except errors) from logs 2023-11-28 10:55:01 +01:00
Luuk van Oijen e68582871d Revert "adding vid to the vehicle spawn data"
This reverts commit 3df71e96c5.
2023-11-27 16:57:04 +01:00
Luuk van Oijen 3df71e96c5 adding vid to the vehicle spawn data 2023-11-27 12:39:15 +01:00
Luuk van Oijen 6a1baa249a wip more lua stuff (events + cleanup/util) 2023-11-26 00:22:28 +01:00
Luuk van Oijen 56cd0eca11 project cleanup, getplayeridentifiers and sendchatmessage implemented
also adds support for the debug flag :)
2023-11-25 19:10:19 +01:00
Luuk van Oijen 04e058dc0d Merge branch 'master' of https://github.com/Lucky4Luuk/beammp_rust_server 2023-11-24 16:05:23 +01:00
Luuk van Oijen f359c0cdca lua chat message stuff 2023-11-24 16:05:21 +01:00
Luuk van Oijen 9a45efef57 Merge pull request #13 from lionkor/add-ci
Create rust.yml to build + test on push and PR
2023-11-24 14:47:17 +01:00
Luuk van Oijen b06d2fe151 say command + playerlist works now 2023-11-24 14:37:07 +01:00
Luuk van Oijen 145b74aefc Merge pull request #12 from lionkor/overhaul-resources-folder-code
Overhaul resources folder code
2023-11-24 09:44:11 +01:00
Luuk van Oijen 1515fc2675 small cleanup 2023-11-24 09:43:13 +01:00
Lion Kortlepel 0f802e4021 fix typo in expect() string 2023-11-23 17:53:28 +01:00
Lion 213c1c7b6b create rust.yml to build + test on push and PR 2023-11-23 17:47:33 +01:00
Lion Kortlepel 787f59ba46 fix server and client resource behavior, canonicalize paths in mod requests 2023-11-23 17:42:10 +01:00
Lion Kortlepel 72bec02e21 add fs_util module with a few useful functions for file/path management 2023-11-23 17:41:42 +01:00
Luuk van Oijen 46e42b88da Merge branch 'master' of https://github.com/Lucky4Luuk/beammp_rust_server 2023-11-23 16:03:44 +01:00
Luuk van Oijen 39028ba4d7 small improvements + players cmd + cleanup 2023-11-23 16:03:31 +01:00
Luuk van Oijen 9cd4609cad Merge pull request #11 from lionkor/fix-uuid-check
Simplify UUID check
2023-11-23 16:00:52 +01:00
Lion Kortlepel 3b61da9edd replace hand-written uuid check with Uuid::parse_str 2023-11-23 15:57:50 +01:00
Lion Kortlepel 09c4bb8b33 add uuid package to validate uuids for the AuthKey 2023-11-23 15:57:32 +01:00
Luuk van Oijen f0a5fa48b8 Update mod.rs 2023-11-23 11:00:15 +01:00
Luuk van Oijen cfea87251b cleanup 2023-11-23 10:59:47 +01:00
Luuk van Oijen 04c1b76402 bunch of changes to prevent deadlocking the server 2023-11-23 10:56:51 +01:00
Luuk van Oijen e15833084a fixed another crash 2023-11-23 10:00:59 +01:00
Luuk van Oijen 13207a8ddf Merge branch 'master' of https://github.com/Lucky4Luuk/beammp_rust_server 2023-11-23 09:47:08 +01:00
Luuk van Oijen d5aef2525f small cleanup 2023-11-23 09:47:01 +01:00
Luuk van Oijen efbd2a4bb8 Merge pull request #9 from OfficialLambdax/welcome/leave-notification
Welcome on full sync- and Leave on disconnect messages
2023-11-23 09:46:51 +01:00
Lambdax 478bf48a5a to broadcast 2023-11-23 09:44:49 +01:00
Luuk van Oijen 1e7cccd9a9 Merge pull request #10 from OfficialLambdax/id-assign-replica
Replicates the player id assigning from the c++ server
2023-11-23 09:41:03 +01:00
Lambdax 5fdfc10f79 assign ids 2023-11-23 09:14:46 +01:00
Lambdax 7eaa382f6c Merge branch 'Lucky4Luuk:master' into welcome/leave-notification 2023-11-22 20:09:38 +01:00
Luuk van Oijen b66251d375 fixed a crash 2023-11-22 19:47:58 +01:00
Lambdax e6f316a6c2 Merge branch 'Lucky4Luuk:master' into welcome/leave-notification 2023-11-22 14:54:45 +01:00
Luuk van Oijen 49a8e84161 Update mod.rs 2023-11-22 14:46:31 +01:00
Lambdax 3376eb7482 formatting 2023-11-22 14:05:06 +01:00
Lambdax de398c0208 welcome & leave 2023-11-22 14:02:23 +01:00
Luuk van Oijen cde157fdfe wip reusing of ids 2023-11-22 13:04:56 +01:00
Luuk van Oijen 3b0da388fb removing a dependency on openssl 2023-11-22 12:44:17 +01:00
Luuk van Oijen ad49713e13 replaced const with cli argument 2023-11-22 12:36:45 +01:00
Luuk van Oijen 191264e732 fixed crash 2023-11-22 12:24:58 +01:00
Luuk van Oijen 88181cf44c Update mod.rs 2023-11-22 12:19:04 +01:00
Luuk van Oijen 03ea9513b9 wip improved return system thingy 2023-11-22 11:14:11 +01:00
Luuk van Oijen 6ed714b863 closing tui no longer crashes + onShutdown event 2023-11-22 11:02:53 +01:00
Luuk van Oijen 669e061fdf Merge pull request #8 from OfficialLambdax/mod-request-check
Mod request check + ui toggle
2023-11-22 10:23:32 +01:00
Lambdax 9b78fc76db request check + ui toggle 2023-11-22 09:54:49 +01:00
Luuk van Oijen dfcf820824 Merge pull request #7 from OfficialLambdax/auth_key-check
Aborts heartbeat if the configured auth_key is invalid
2023-11-22 08:55:37 +01:00
Lambdax 259f3de774 key check 2023-11-22 08:36:17 +01:00
Luuk van Oijen d9e0761e07 wip new console 2023-11-21 17:24:14 +01:00
Luuk van Oijen 67cec26979 Update main.rs 2023-11-21 10:01:54 +01:00
Luuk van Oijen 260fd03a1f small fixes by neverless <3 2023-11-21 10:01:13 +01:00
Luuk van Oijen 2323c07d8e Update main.rs 2023-11-20 18:30:46 +01:00
Luuk van Oijen a61554187e cpu usage finally fixed 2023-11-20 18:30:17 +01:00
Luuk van Oijen 6c2b131d72 kinda works + fixes a crash 2023-11-20 17:02:50 +01:00
Luuk van Oijen 5a42fe87fd wip racing read_tcp and read_udp 2023-11-20 14:49:56 +01:00
Luuk van Oijen 4551a2da60 cleanup 2023-11-20 14:20:12 +01:00
Luuk van Oijen 223c9a5064 cleanup 2023-11-20 13:59:19 +01:00
Luuk van Oijen 5097244c76 heartbeat fixes + guest support 2023-11-20 13:33:07 +01:00
Luuk van Oijen 4e985bc0e0 logging chat 2023-11-20 13:08:04 +01:00
Luuk van Oijen 7d0941dee8 now it updates whenever new data is ready 2023-11-20 12:53:37 +01:00
Luuk van Oijen 0e75a35c83 wip updating of server status 2023-11-20 10:55:31 +01:00
Luuk van Oijen 7598261aff force ipv4? 2023-11-20 10:11:24 +01:00
Luuk van Oijen 8280b06253 small cleanup 2023-11-20 09:47:35 +01:00
Luuk van Oijen 81816da44d heartbeat technically works but needs lots of work 2023-11-20 09:40:16 +01:00
Luuk van Oijen 7c82f474bb wip heartbeat stuff 2023-11-20 09:34:00 +01:00
Luuk van Oijen 4bf4727cc3 wip heartbeat stuff 2023-11-19 22:07:16 +01:00
Luuk van Oijen 0335d22809 wip player identifiers stuff 2023-11-17 14:29:19 +01:00
Luuk van Oijen 0f5d61c89b improvements to many aspects of plugins 2023-11-16 19:47:08 +01:00
Luuk van Oijen 37d7a289eb mod downloads are finally working 2023-11-16 10:42:59 +01:00
Luuk van Oijen 596a7234ed man the download protocol sucks 2023-11-15 21:25:57 +01:00
Luuk van Oijen 8735824495 start of http stuff 2023-11-15 13:38:07 +01:00
Luuk van Oijen 51c5ee0638 whoops small oversight 2023-11-14 21:57:49 +01:00
Luuk van Oijen 4f57680a67 more lua stuff working now + cleanup client code 2023-11-14 14:06:05 +01:00
Luuk van Oijen 1c21298351 more work on the lua stuff 2023-11-14 09:53:46 +01:00
Luuk van Oijen e781bbac8e fixed the event handler registration stuff 2023-11-13 16:57:45 +01:00
Luuk van Oijen a0db8aa8be more steps towards reducing cpu load 2023-11-13 16:37:53 +01:00
Luuk van Oijen f2b9384447 first step towards less cpu usage 2023-11-13 12:33:15 +01:00
Luuk van Oijen b5c6f2c3c7 Update backend_lua.rs 2023-11-12 23:03:59 +01:00
Luuk van Oijen 6dee028a88 Update backend_lua.rs 2023-11-12 22:20:59 +01:00
Luuk van Oijen 4f52e30545 wip lua event stuff 2023-11-12 21:26:23 +01:00
Luuk van Oijen 01fb538129 now its just MP.function instead of MP:function 2023-11-12 16:35:15 +01:00
Luuk van Oijen a23b5a43c0 more lua api stuff 2023-11-12 16:29:22 +01:00
Luuk van Oijen 8ee6ba16f2 very early version of plugin system 2023-11-12 15:31:15 +01:00
Luuk van Oijen 0b6ad43fbb wip small stuff 2023-11-11 00:02:25 +01:00
Luuk van Oijen 5d8c9cd792 interval introduced to avoid massive cpu usage 2023-11-10 10:04:56 +01:00
Luuk van Oijen c5ce152a30 license? 2023-11-09 23:27:39 +01:00
Luuk van Oijen 6c60f220eb comments + todo 2023-11-09 15:53:29 +01:00
Luuk van Oijen ff5a5204c9 bit of cleanup of unused old code 2023-11-09 14:54:45 +01:00
Luuk van Oijen ad85317f60 mod download now gets halfway 2023-11-09 14:15:33 +01:00
Luuk van Oijen efad9ec03e implemented the playerlist and player count 2023-11-09 10:57:34 +01:00
Luuk van Oijen 5011ae280c wip downloading (it doesnt work) 2023-11-08 21:35:13 +01:00
Luuk van Oijen ebc0dba4ef syncing cars when joining works now 2023-11-08 17:00:48 +01:00
Luuk van Oijen ad15846625 wip syncing of vehicles when joining 2023-11-08 13:26:10 +01:00
Luuk van Oijen e1b9f2b969 clients joining should no longer block acception runtime 2023-11-08 12:52:34 +01:00
Luuk van Oijen 3fedcf5bd5 Update mod.rs 2023-11-08 12:04:59 +01:00
Luuk van Oijen 190cc8f238 Update mod.rs 2023-11-08 11:47:23 +01:00
Luuk van Oijen 38aaf29fe8 initial commit 2023-11-07 22:48:41 +01:00
68 changed files with 5887 additions and 4011 deletions
-5
View File
@@ -1,5 +0,0 @@
---
BasedOnStyle: WebKit
BreakBeforeBraces: Attach
...
+21
View File
@@ -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
View File
@@ -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
-2
View File
@@ -1,2 +0,0 @@
# Default ignored files
/workspace.xml
Generated
-1
View File
@@ -1 +0,0 @@
Server
-2
View File
@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />
-7
View File
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
Generated
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+82
View File
@@ -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} |
-43
View File
@@ -1,43 +0,0 @@
cmake_minimum_required(VERSION 3.13)
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 -fno-builtin")
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
#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" "include/*.h" "include/*/*.h" "include/*/*/*.h" "include/*.hpp" "include/*/*.hpp" "src/*/*.cpp")
add_executable(BeamMP-Server ${source_files})
target_include_directories(BeamMP-Server PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
find_package(Lua REQUIRED)
target_include_directories(BeamMP-Server PUBLIC ${LUA_INCLUDE_DIR})
if (UNIX)
target_link_libraries(BeamMP-Server z pthread stdc++fs ${Boost_LINK_DIRS} ${LUA_LIBRARIES} curl dl)
elseif (WIN32)
include(FindLua)
find_package(ZLIB REQUIRED)
find_package(CURL CONFIG REQUIRED)
find_package(RapidJSON CONFIG REQUIRED)
target_include_directories(BeamMP-Server PRIVATE ${RAPIDJSON_INCLUDE_DIRS})
target_link_libraries(BeamMP-Server PRIVATE ws2_32 CURL::libcurl ZLIB::ZLIB ${LUA_LIBRARIES})
#${Boost_LINK_DIRS}
endif ()
Generated
+1801
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -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"
+37
View File
@@ -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
-1
View File
@@ -1 +0,0 @@
Copyright (c) 2019-present Anonymous275. BeamMP Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries, the only permission that has been granted is to use the software in its compiled form as distributed from the BeamMP.com website. Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
+661
View File
@@ -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/>.
+4 -40
View File
@@ -1,41 +1,5 @@
# BeamMP-Server
# BeamMP Server
A BeamMP server implementation in Rust, meant to (hopefully) replace the official server implementation one day.
The Server is the way we link client to each other and handle authentication, compression, and data management. It also allows lua plugins, that system is always being reviewed and improved with detailed instructions on wiki.beammp.com.
## Supported Operating Systems
The code itself supports (latest stable) Linux and Windows. In terms of actual build support, for now we only distribute windows binaries and instructions to build on Debian 10 (stable). For any other distro or OS, you just have to find the same libraries listed in the Linux Build [Prerequisites](#prerequisites) further down the page, and it should build fine. We don't currently support ARM or any big-endian architectures.
Recommended compilers: MSVC, GCC.
## Linux / POSIX specific build instructions
Currently only linux and windows are supported (generally). On systems to which we do not provide binaries (so anything but windows), you are allowed to compile the program and use it. Other restrictions, such as not being allowed to distribute those binaries, still apply (see [copyright notice](#copyright)).
### Prerequisites
All package names are ones found in debian's (debian 10 stable) repositories, but will exist under similar names in other distros. Feel free to PR your own guide for a different distro.
- `git`
- `make`
- `cmake`
- `g++` (must support ISO C++17)
- `liblua5.3`
- `libz-dev`
- `rapidjson-dev`
- `libcurl4-openssl-dev` (or other `libcurl4-*-dev`)
### How to build
1. Make sure you have all [prerequisites](#prerequisites) installed
2. Clone the repository in a location of your choice with `git clone --recursive https://github.com/BeamMP/BeamMP-Server`
3. `cd` into it with `cd BeamMP-Server`
4. Run `cmake .` (with `.`)
5. Run `make`
6. You will now have a `BeamMP-Server` file in your directory, which is executable with `./BeamMP-Server`. Follow the (windows or linux, doesnt matter) instructions on the [wiki](https://wiki.beammp.com/en/home/Server_Mod) for further setup after installation (which we just did), such as port-forwarding and getting a key to actually run the server.
*tip: to run the server in the background, simply (in bash, zsh, etc) run:* `nohup ./BeamMP-Server &`*.*
## Copyright
Copyright (c) 2019-present Anonymous275. BeamMP Server code is not in the public domain and is not free software. One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries, the only permission that has been granted is to use the software in its compiled form as distributed from the BeamMP.com website. Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
## Features
TODO
Binary file not shown.
Binary file not shown.
+61
View File
@@ -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")
-91
View File
@@ -1,91 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 <algorithm>
#include <chrono>
#include <set>
#include <string>
#include <vector>
struct VData {
int ID = -1;
std::string Data;
};
class Client {
private:
std::set<std::unique_ptr<VData>> VehicleData; //ID and Data;
std::string Name = "Unknown Client";
SOCKET SOCK[2] { SOCKET(-1) };
sockaddr_in UDPADDR;
std::string Role;
std::string DID;
int Status = 0;
int ID = -1;
public:
bool isConnected = false;
bool isSynced = false;
bool isGuest = false;
void AddNewCar(int ident, const std::string& Data);
void SetCarData(int ident, const std::string& Data);
std::set<std::unique_ptr<VData>>& GetAllCars();
void SetName(const std::string& name) { Name = name; }
void SetRoles(const std::string& role) { Role = role; }
std::string GetCarData(int ident);
void SetUDPAddr(sockaddr_in Addr) { UDPADDR = Addr; }
void SetDownSock(SOCKET CSock) { SOCK[1] = CSock; }
void SetTCPSock(SOCKET CSock) { SOCK[0] = CSock; }
void SetStatus(int status) { Status = status; }
void DeleteCar(int ident);
sockaddr_in GetUDPAddr() { return UDPADDR; }
std::string GetRoles() { return Role; }
std::string GetName() { return Name; }
SOCKET GetDownSock() { return SOCK[1]; }
SOCKET GetTCPSock() { return SOCK[0]; }
void SetID(int ID) { this->ID = ID; }
int GetOpenCarID();
int GetCarCount();
void ClearCars();
int GetStatus() { return Status; }
int GetID() { return ID; }
};
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::unique_ptr<Client>(c));
}
int Size() {
return int(Clients.size());
}
};
extern std::unique_ptr<ClientInterface> CI;
-11
View File
@@ -1,11 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/24/2020
///
#pragma once
#include <string>
std::string Comp(std::string Data);
std::string DeComp(std::string Compressed);
-11
View File
@@ -1,11 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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, bool json);
-67
View File
@@ -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
-12
View File
@@ -1,12 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 11/27/2020
///
#pragma once
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
namespace json = rapidjson;
-21
View File
@@ -1,21 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 4/2/2020.
///
#pragma once
#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 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);
-81
View File
@@ -1,81 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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; }
};
std::any CallFunction(Lua* lua, const std::string& FuncName, std::shared_ptr<LuaArg> args);
std::any TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait);
extern std::set<std::unique_ptr<Lua>> PluginEngine;
-25
View File
@@ -1,25 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/31/2020
///
#pragma once
#include "Client.hpp"
#include <string>
void TCPServerMain();
void UpdatePlayers();
void OnConnect(Client* c);
void TCPClient(Client* c);
std::string TCPRcv(Client* c);
void SyncResources(Client* c);
[[noreturn]] void UDPServerMain();
void OnDisconnect(Client* c, bool kicked);
void UDPSend(Client* c, std::string Data);
void SendLarge(Client* c, std::string Data);
bool TCPSend(Client* c, const std::string& Data);
void GParser(Client* c, const std::string& Packet);
std::string StaticReason(bool Set, const std::string& R);
void Respond(Client* c, const std::string& MSG, bool Rel);
void SendToAll(Client* c, const std::string& Data, bool Self, bool Rel);
-19
View File
@@ -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>;
-15
View File
@@ -1,15 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/28/2020
///
#pragma once
#ifdef __linux
#define EXCEPTION_POINTERS void
#else
#include <WS2tcpip.h>
#endif
#include <string>
int Handle(EXCEPTION_POINTERS* ep, char* Origin);
-28
View File
@@ -1,28 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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;
-16
View File
@@ -1,16 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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();
-38
View File
@@ -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([[maybe_unused]] void* dst, [[maybe_unused]] size_t len) {
[[maybe_unused]] auto res = std::memset(dst, 0, len);
Assert(res != 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
-56
View File
@@ -1,56 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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;
}
-263
View File
@@ -1,263 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 == ("exit")) {
_Exit(0);
} else if (cmd == ("clear") || cmd == ("cls")) {
// 2J is clearscreen, H is reset position to top-left
ConsoleOut(("\x1b[2J\x1b[H"));
} else {
LuaConsole->Execute(cmd);
}
}
void ProcessOut() {
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;
}
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, &current); /* use these new terminal i/o settings now */
}
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
char getch_(int echo) {
char ch;
initTermios(echo);
read(STDIN_FILENO, &ch, 1);
resetTermios();
return ch;
}
char _getch(void) {
return getch_(0);
}
#endif // WIN32
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 {};
// buffer used to revert back to what we were writing when we go all the way forward in history
static std::string LastInputBuffer {};
static size_t ConsoleHistoryReadIndex { 0 };
static inline void ConsoleHistoryAdd(const std::string& cmd) {
LastInputBuffer.clear();
ConsoleHistory.push_back(cmd);
ConsoleHistoryReadIndex = ConsoleHistory.size();
}
static inline void ConsoleHistoryEnsureBounds() {
if (ConsoleHistoryReadIndex >= ConsoleHistory.size()) {
ConsoleHistoryReadIndex = ConsoleHistory.size() - 1;
}
}
static inline void ConsoleHistoryGoBack() {
if (ConsoleHistoryReadIndex > 0) {
--ConsoleHistoryReadIndex;
ConsoleHistoryEnsureBounds();
}
}
static inline void ConsoleHistoryGoForward() {
++ConsoleHistoryReadIndex;
ConsoleHistoryEnsureBounds();
}
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
if (!ConsoleHistory.empty()) {
ConsoleHistoryGoBack();
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) {
CInputBuff = LastInputBuffer;
} else {
ConsoleHistoryGoForward();
CInputBuff = ConsoleHistory.at(ConsoleHistoryReadIndex);
}
}
} 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) {
decltype(ConsoleHistory) 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(("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);
LastInputBuffer = CInputBuff;
}
}
}
void ConsoleInit() {
SetupConsole();
LuaConsole = std::make_unique<Lua>(true);
LuaConsole->Init();
printf("> ");
std::thread In(ReadCin);
In.detach();
std::thread Out(OutputRefresh);
Out.detach();
}
-27
View File
@@ -1,27 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/28/2020
///
#include "Security/Enc.h"
#include "CustomAssert.h"
#include "Logger.h"
#include <sstream>
#ifdef WIN32
#include <WS2tcpip.h>
int Handle(EXCEPTION_POINTERS* ep, char* Origin) {
Assert(false);
std::stringstream R;
R << ("Code : ") << std::hex
<< ep->ExceptionRecord->ExceptionCode
<< std::dec << (" Origin : ") << Origin;
except(R.str());
return 1;
}
#else
// stub
int Handle(EXCEPTION_POINTERS*, char*) { return 1; }
#endif // WIN32
-167
View File
@@ -1,167 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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(("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(("Server.cfg"));
info(("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(("Server.cfg"));
FileStream << ("# 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(("Config not found generating default"));
GenerateConfig();
error(("You are required to input the AuthKey"));
std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0);
}
void DebugData() {
debug(std::string("Debug : ") + (Debug ? "true" : "false"));
debug(std::string("Private : ") + (Private ? "true" : "false"));
debug("Port : " + std::to_string(Port));
debug("Max Cars : " + std::to_string(MaxCars));
debug("MaxPlayers : " + std::to_string(MaxPlayers));
debug("MapName : " + MapName);
debug("ServerName : " + ServerName);
debug("ServerDesc : " + ServerDesc);
debug("File : " + Resource);
debug("Key length: " + std::to_string(Key.length()));
}
void InitConfig() {
////TODO: Move to json after update 4
std::ifstream IFS;
IFS.open(("Server.cfg"));
if (IFS.good())
LoadConfig(IFS);
else
Default();
if (IFS.is_open())
IFS.close();
if (Key.empty()) {
error(("No AuthKey was found"));
std::this_thread::sleep_for(std::chrono::seconds(3));
_Exit(0);
}
if (Debug)
DebugData();
}
-84
View File
@@ -1,84 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/28/2020
///
#include "Client.hpp"
#include "Curl/Http.h"
#include "Logger.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, false); });
std::future<std::string> f1 = task.get_future();
std::thread t(std::move(task));
t.detach();
auto status = f1.wait_for(std::chrono::seconds(15));
if (status != std::future_status::timeout)
return f1.get();
error("Backend system Timeout please try again later");
return "";
}
[[noreturn]] void Heartbeat() {
DebugPrintTID();
std::string R, T;
bool isAuth = false;
while (true) {
R = GenerateCall();
if (!CustomIP.empty())
R += "&ip=" + CustomIP;
std::string link = "https://beammp.com/heartbeatv2";
T = RunPromise(link, R);
if (T.substr(0, 2) != "20") {
//Backend system refused server startup!
std::this_thread::sleep_for(std::chrono::seconds(10));
std::string Backup = "https://backup1.beammp.com/heartbeatv2";
T = RunPromise(Backup, R);
if (T.substr(0, 2) != "20") {
warn("Backend system refused server! Server might not show in the public list");
}
}
//Server Authenticated
if (!isAuth) {
WebsocketInit();
if (T.length() == 4)info(("Authenticated!"));
else info(("Resumed authenticated session!"));
isAuth = true;
}
//std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
void HBInit() {
std::thread HB(Heartbeat);
HB.detach();
}
-39
View File
@@ -1,39 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 + "/Client";
if (!fs::exists(Path))
fs::create_directory(Path);
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().string().find(".zip");
if (pos != std::string::npos) {
if (entry.path().string().length() - pos == 4) {
FileList += entry.path().string() + ";";
FileSizes += std::to_string(uint64_t(fs::file_size(entry.path()))) + ";";
MaxModSize += uint64_t(fs::file_size(entry.path()));
ModsLoaded++;
}
}
}
std::replace(FileList.begin(), FileList.end(), '\\', '/');
if (ModsLoaded)
info("Loaded " + std::to_string(ModsLoaded) + " Mods");
}
-38
View File
@@ -1,38 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 "1.20";
}
std::string GetCVer() {
return "1.80";
}
void Args(int argc, char* argv[]) {
info("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((".0123456789"));
if (p != std::string::npos || n != 3 || CustomIP.substr(0, 3) == ("127")) {
CustomIP.clear();
warn("IP Specified is invalid! Ignoring");
} else
info("Server started with custom IP");
}
}
void InitServer(int argc, char* argv[]) {
InitLog();
Args(argc, argv);
CI = std::make_unique<ClientInterface>();
}
-92
View File
@@ -1,92 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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(("Loading plugin : ") + Name);
for (const auto& entry : fs::directory_iterator(Path)) {
auto pos = entry.path().string().find((".lua"));
if (pos != std::string::npos && entry.path().string().length() - pos == 4) {
if (!HotSwap || NewFile(entry.path().string())) {
auto FileName = entry.path().string();
std::unique_ptr<Lua> ScriptToInsert(new Lua(Name, FileName, fs::last_write_time(FileName)));
auto& Script = *ScriptToInsert;
PluginEngine.insert(std::move(ScriptToInsert));
Script.Init();
if (HotSwap)
info(("[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(("[HOTSWAP] Removed removed script due to delete"));
break;
}
if (Script->GetLastWrite() != fs::last_write_time(Script->GetFileName())) {
Script->SetStopThread(true);
info(("[HOTSWAP] Updated Scripts due to edit"));
Script->SetLastWrite(fs::last_write_time(Script->GetFileName()));
Script->Reload();
}
}
}
FolderList(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 + ("/Server");
if (!fs::exists(Path)) {
fs::create_directory(Path);
}
FolderList(Path, false);
std::thread t1(HotSwaps, Path);
t1.detach();
info(("Lua system online"));
}
-705
View File
@@ -1,705 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 = ("_Console");
} else {
Lua& S = MaybeS.value();
a = fs::path(S.GetFileName()).filename().string();
}
warn(a + (" | Incorrect Call of ") + msg);
}
std::any Trigger(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg) {
std::lock_guard<std::mutex> lockGuard(lua->Lock);
std::packaged_task<std::any(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return CallFunction(lua, R, arg); });
std::future<std::any> f1 = task.get_future();
std::thread t(std::move(task), arg);
t.detach();
auto status = f1.wait_for(std::chrono::seconds(5));
if (status != std::future_status::timeout)
return f1.get();
SendError(lua->GetState(), R + " took too long to respond");
return 0;
}
std::any FutureWait(Lua* lua, const std::string& R, std::shared_ptr<LuaArg> arg, bool Wait) {
Assert(lua);
std::packaged_task<std::any(std::shared_ptr<LuaArg>)> task([lua, R](std::shared_ptr<LuaArg> arg) { return Trigger(lua, R, arg); });
std::future<std::any> f1 = task.get_future();
std::thread t(std::move(task), arg);
t.detach();
int T = 0;
if (Wait)
T = 6;
auto status = f1.wait_for(std::chrono::seconds(T));
if (status != std::future_status::timeout)
return f1.get();
return 0;
}
std::any TriggerLuaEvent(const std::string& Event, bool local, Lua* Caller, std::shared_ptr<LuaArg> arg, bool Wait) {
std::any R;
std::string Type;
int Ret = 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);
Type = R.type().name();
if (Type.find("int") != std::string::npos) {
if (std::any_cast<int>(R))
Ret++;
} else if (Event == "onPlayerAuth")
return R;
}
} else {
R = FutureWait(Script.get(), Script->GetRegistered(Event), arg, Wait);
Type = R.type().name();
if (Type.find("int") != std::string::npos) {
if (std::any_cast<int>(R))
Ret++;
} else if (Event == "onPlayerAuth")
return R;
}
}
}
return Ret;
}
bool ConsoleCheck(lua_State* L, int r) {
if (r != LUA_OK) {
std::string msg = lua_tostring(L, -1);
warn(("_Console | ") + msg);
return false;
}
return true;
}
bool CheckLua(lua_State* L, int r) {
if (r != LUA_OK) {
std::string msg = lua_tostring(L, -1);
auto MaybeS = 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, ("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, ("TriggerLocalEvent wrong argument [1] need string"));
} else {
SendError(L, ("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, ("TriggerGlobalEvent wrong argument [1] need string"));
} else
SendError(L, ("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, ("CreateThread wrong argument [2] number must be between 1 and 500"));
} else
SendError(L, ("CreateThread wrong argument [2] need number"));
} else
SendError(L, ("CreateThread wrong argument [1] need string"));
} else
SendError(L, ("CreateThread not enough arguments"));
return 0;
}
int lua_Sleep(lua_State* L) {
if (lua_isnumber(L, 1)) {
int t = int(lua_tonumber(L, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(t));
} else {
SendError(L, ("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, ("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, ("GetPlayerName not enough arguments"));
return 0;
}
return 1;
}
int lua_GetPlayerCount(lua_State* L) {
lua_pushinteger(L, CI->Size());
return 1;
}
int lua_GetGuest(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->isGuest);
else
return 0;
} else {
SendError(L, "GetGuest 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, ("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;
std::string Reason;
if (Args > 1 && lua_isstring(L, 2)) {
Reason = std::string((" Reason : ")) + lua_tostring(L, 2);
}
Respond(c, "C:Server:You have been Kicked from the server! " + Reason, true);
c->SetStatus(-2);
info(("Closing socket due to kick"));
CloseSocketProper(c->GetTCPSock());
} else
SendError(L, ("DropPlayer not enough arguments"));
return 0;
}
int lua_sendChat(lua_State* L) {
if (lua_isinteger(L, 1) || lua_isnumber(L, 1)) {
if (lua_isstring(L, 2)) {
int ID = int(lua_tointeger(L, 1));
if (ID == -1) {
std::string Packet = "C:Server: " + std::string(lua_tostring(L, 2));
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, ("SendChatMessage invalid argument [1] invalid ID"));
}
} else
SendError(L, ("SendChatMessage invalid argument [2] expected string"));
} else
SendError(L, ("SendChatMessage invalid argument [1] expected number"));
return 0;
}
int lua_RemoveVehicle(lua_State* L) {
int Args = lua_gettop(L);
if (Args != 2) {
SendError(L, ("RemoveVehicle invalid argument count expected 2 got ") + std::to_string(Args));
return 0;
}
if ((lua_isinteger(L, 1) || lua_isnumber(L, 1)) && (lua_isinteger(L, 2) || lua_isnumber(L, 2))) {
int PID = int(lua_tointeger(L, 1));
int VID = int(lua_tointeger(L, 2));
Client* c = GetClient(PID);
if (c == nullptr) {
SendError(L, ("RemoveVehicle invalid Player ID"));
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, ("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, ("TriggerClientEvent invalid argument count expected 3 got ") + std::to_string(Args));
return 0;
}
if (!lua_isnumber(L, 1)) {
SendError(L, ("TriggerClientEvent invalid argument [1] expected number"));
return 0;
}
if (!lua_isstring(L, 2)) {
SendError(L, ("TriggerClientEvent invalid argument [2] expected string"));
return 0;
}
if (!lua_isstring(L, 3)) {
SendError(L, ("TriggerClientEvent invalid argument [3] expected string"));
return 0;
}
int ID = int(lua_tointeger(L, 1));
std::string Packet = "E:" + std::string(lua_tostring(L, 2)) + ":" + std::string(lua_tostring(L, 3));
if (ID == -1)
SendToAll(nullptr, Packet, true, true);
else {
Client* c = GetClient(ID);
if (c == nullptr) {
SendError(L, ("TriggerClientEvent invalid Player ID"));
return 0;
}
Respond(c, Packet, true);
}
return 0;
}
int lua_ServerExit(lua_State* L) {
if (lua_gettop(L) > 0) {
if (lua_isnumber(L, 1)) {
_Exit(int(lua_tointeger(L, 1)));
}
}
_Exit(0);
}
int lua_Set(lua_State* L) {
int Args = lua_gettop(L);
if (Args != 2) {
SendError(L, ("set invalid argument count expected 2 got ") + std::to_string(Args));
return 0;
}
if (!lua_isnumber(L, 1)) {
SendError(L, ("set invalid argument [1] expected number"));
return 0;
}
auto MaybeSrc = GetScript(L);
std::string Name;
if (!MaybeSrc.has_value()) {
Name = ("_Console");
} else {
Name = MaybeSrc.value().get().GetPluginName();
}
int C = int(lua_tointeger(L, 1));
switch (C) {
case 0: //debug
if (lua_isboolean(L, 2)) {
Debug = lua_toboolean(L, 2);
info(Name + (" | Debug -> ") + (Debug ? "true" : "false"));
} else
SendError(L, ("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 + (" | Private -> ") + (Private ? "true" : "false"));
} else
SendError(L, ("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 + (" | MaxCars -> ") + std::to_string(MaxCars));
} else
SendError(L, ("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 + (" | MaxPlayers -> ") + std::to_string(MaxPlayers));
} else
SendError(L, ("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 + (" | MapName -> ") + MapName);
} else
SendError(L, ("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 + (" | ServerName -> ") + ServerName);
} else
SendError(L, ("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 + (" | ServerDesc -> ") + ServerDesc);
} else
SendError(L, ("set invalid argument [2] expected string for ID : 6"));
break;
default:
warn(("Invalid config ID : ") + std::to_string(C));
break;
}
return 0;
}
extern "C" {
int lua_Print(lua_State* L) {
int Arg = lua_gettop(L);
for (int i = 1; i <= Arg; i++) {
auto str = lua_tostring(L, i);
if (str != nullptr) {
ConsoleOut(str + std::string(("\n")));
} else {
ConsoleOut(("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, ("onInit"), nullptr);
}
}
std::string Lua::GetOrigin() {
return fs::path(GetFileName()).filename().string();
}
std::any 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);
}
int R = lua_pcall(luaState, Size, 1, 0);
if (CheckLua(luaState, R)) {
if (lua_isnumber(luaState, -1)) {
return int(lua_tointeger(luaState, -1));
} else if (lua_isstring(luaState, -1)) {
return std::string(lua_tostring(luaState, -1));
}
}
}
ClearStack(luaState);
return 0;
}
void Lua::SetPluginName(const std::string& Name) {
_PluginName = Name;
}
void Lua::SetFileName(const std::string& Name) {
_FileName = Name;
}
int lua_TempFix(lua_State* L) {
if (lua_isnumber(L, 1)) {
int ID = int(lua_tonumber(L, 1));
Client* c = GetClient(ID);
if (c == nullptr)
return 0;
std::string Ret;
if (c->isGuest) {
Ret = "Guest-" + c->GetName();
} else
Ret = c->GetName();
lua_pushstring(L, Ret.c_str());
} else
SendError(L, "GetDID not enough arguments");
return 1;
}
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_TempFix);
lua_register(luaState, "CreateThread", lua_CreateThread);
lua_register(luaState, "GetPlayerVehicles", lua_GetCars);
lua_register(luaState, "SendChatMessage", lua_sendChat);
lua_register(luaState, "GetPlayers", lua_GetAllPlayers);
lua_register(luaState, "GetPlayerGuest", lua_GetGuest);
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);
}
-228
View File
@@ -1,228 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 7/31/2020
///
#include "Curl/Http.h"
#include "Json.h"
#include "Logger.h"
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <Lua/LuaSystem.hpp>
#include <cstring>
#include <string>
#include <thread>
std::string GetClientInfo(const std::string& PK) {
if (!PK.empty()) {
return PostHTTP("https://auth.beammp.com/pkToUser", R"({"key":")" + PK + "\"}", true);
;
}
return "";
}
Client* CreateClient(SOCKET TCPSock) {
auto* c = new Client;
c->SetTCPSock(TCPSock);
return c;
}
void ClientKick(Client* c, const std::string& R) {
info("Client kicked: " + R);
TCPSend(c, "E" + R);
CloseSocketProper(c->GetTCPSock());
}
void Authentication(SOCKET TCPSock) {
DebugPrintTID();
auto* c = CreateClient(TCPSock);
info("Identifying new client...");
std::string Rc = TCPRcv(c);
if (Rc.size() > 3 && Rc.substr(0, 2) == "VC") {
Rc = Rc.substr(2);
if (Rc.length() > 4 || Rc != GetCVer()) {
ClientKick(c, "Outdated Version!");
return;
}
} else {
ClientKick(c, "Invalid version header!");
return;
}
TCPSend(c, "S");
Rc = TCPRcv(c);
if (Rc.size() > 50) {
ClientKick(c, "Invalid Key!");
return;
}
Rc = GetClientInfo(Rc);
json::Document d;
d.Parse(Rc.c_str());
if (Rc == "-1" || d.HasParseError()) {
ClientKick(c, "Invalid key! Please restart your game.");
return;
}
if (d["username"].IsString() && d["roles"].IsString() && d["guest"].IsBool()) {
c->SetName(d["username"].GetString());
c->SetRoles(d["roles"].GetString());
c->isGuest = d["guest"].GetBool();
} else {
ClientKick(c, "Invalid authentication data!");
return;
}
debug("Name -> " + c->GetName() + ", Guest -> " + std::to_string(c->isGuest) + ", Roles -> " + c->GetRoles());
for (auto& Cl : CI->Clients) {
if (Cl != nullptr) {
if (Cl->GetName() == c->GetName() && Cl->isGuest == c->isGuest) {
info("Old client (" + Cl->GetName() + ") kicked: Reconnecting");
CloseSocketProper(Cl->GetTCPSock());
Cl->SetStatus(-2);
break;
}
}
}
auto arg = std::make_unique<LuaArg>(LuaArg { { c->GetName(), c->GetRoles(), c->isGuest } });
std::any Res = TriggerLuaEvent("onPlayerAuth", false, nullptr, std::move(arg), true);
std::string Type = Res.type().name();
if (Type.find("int") != std::string::npos && std::any_cast<int>(Res)) {
ClientKick(c, "you are not allowed on the server!");
return;
} else if (Type.find("string") != std::string::npos) {
ClientKick(c, std::any_cast<std::string>(Res));
return;
}
if (CI->Size() < MaxPlayers) {
info("Identification success");
Client& Client = *c;
CI->AddClient(std::move(c));
TCPClient(&Client);
} else
ClientKick(c, "Server full!");
}
void HandleDownload(SOCKET TCPSock) {
char D;
if (recv(TCPSock, &D, 1, 0) != 1) {
CloseSocketProper(TCPSock);
return;
}
auto ID = uint8_t(D);
for (auto& c : CI->Clients) {
if (c->GetID() == ID) {
c->SetDownSock(TCPSock);
}
}
}
void Identify(SOCKET TCPSock) {
char Code;
if (recv(TCPSock, &Code, 1, 0) != 1) {
CloseSocketProper(TCPSock);
return;
}
if (Code == 'C') {
Authentication(TCPSock);
} else if (Code == 'D') {
HandleDownload(TCPSock);
} else
CloseSocketProper(TCPSock);
}
void TCPServerMain() {
DebugPrintTID();
#ifdef WIN32
WSADATA wsaData;
if (WSAStartup(514, &wsaData)) {
error("Can't start Winsock!");
return;
}
SOCKET client, Listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in addr {};
addr.sin_addr.S_un.S_addr = ADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(Port);
if (bind(Listener, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
error("Can't bind socket! " + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
}
if (Listener == -1) {
error("Invalid listening socket");
return;
}
if (listen(Listener, SOMAXCONN)) {
error("listener failed " + std::to_string(GetLastError()));
return;
}
info("Vehicle event network online");
do {
try {
client = accept(Listener, nullptr, nullptr);
if (client == -1) {
warn("Got an invalid client socket on connect! Skipping...");
continue;
}
std::thread ID(Identify, client);
ID.detach();
} catch (const std::exception& e) {
error("fatal: " + std::string(e.what()));
}
} while (client);
CloseSocketProper(client);
WSACleanup();
#else // unix
// wondering why we need slightly different implementations of this?
// ask ms.
SOCKET client = -1, 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(("Can't bind socket! ") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
}
if (Listener == -1) {
error(("Invalid listening socket"));
return;
}
if (listen(Listener, SOMAXCONN)) {
error(("listener failed ") + std::string(strerror(errno)));
return;
}
info(("Vehicle event network online"));
do {
try {
client = accept(Listener, nullptr, nullptr);
if (client == -1) {
warn(("Got an invalid client socket on connect! Skipping..."));
continue;
}
std::thread ID(Identify, client);
ID.detach();
} catch (const std::exception& e) {
error(("fatal: ") + std::string(e.what()));
}
} while (client);
debug("all ok, arrived at " + std::string(__func__) + ":" + std::to_string(__LINE__));
CloseSocketProper(client);
#endif // WIN32
}
-66
View File
@@ -1,66 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 5/8/2020
///
#include "Client.hpp"
#include <memory>
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::make_unique<VData>(VData { ident, Data }));
}
std::set<std::unique_ptr<VData>>& Client::GetAllCars() {
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());
}
-268
View File
@@ -1,268 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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"
#undef GetObject //to fix microsoft bs
#include "Json.h"
void Apply(Client* c, int VID, const std::string& pckt) {
Assert(c);
std::string Packet = pckt.substr(pckt.find('{')), VD = c->GetCarData(VID);
std::string Header = VD.substr(0, VD.find('{'));
VD = VD.substr(VD.find('{'));
rapidjson::Document Veh, Pack;
Veh.Parse(VD.c_str());
if (Veh.HasParseError()) {
error("Could not get vehicle config!");
return;
}
Pack.Parse(Packet.c_str());
if (Pack.HasParseError() || Pack.IsNull()) {
error("Could not get active vehicle config!");
return;
}
for (auto& M : Pack.GetObject()) {
if (Veh[M.name].IsNull()) {
Veh.AddMember(M.name, M.value, Veh.GetAllocator());
} else {
Veh[M.name] = Pack[M.name];
}
}
rapidjson::StringBuffer Buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(Buffer);
Veh.Accept(writer);
c->SetCarData(VID, Header + Buffer.GetString());
}
void 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(("got 'Os' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
if (Data.at(0) == '0') {
int CarID = c->GetOpenCarID();
debug(c->GetName() + (" created a car with ID ") + std::to_string(CarID));
Packet = "Os:" + c->GetRoles() + ":" + c->GetName() + ":" + std::to_string(c->GetID()) + "-" + std::to_string(CarID) + Packet.substr(4);
auto Res = TriggerLuaEvent(("onVehicleSpawn"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), CarID, Packet.substr(3) } }), true);
if (c->GetCarCount() >= MaxCars || std::any_cast<int>(Res)) {
Respond(c, Packet, true);
std::string Destroy = "Od:" + std::to_string(c->GetID()) + "-" + std::to_string(CarID);
Respond(c, Destroy, true);
debug(c->GetName() + (" (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(("got 'Oc' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1, Data.find(':', 1) - Data.find('-') - 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid);
VID = stoi(vid);
}
if (PID != -1 && VID != -1 && PID == c->GetID()) {
auto Res = TriggerLuaEvent(("onVehicleEdited"), false, nullptr,
std::make_unique<LuaArg>(LuaArg { { c->GetID(), VID, Packet.substr(3) } }),
true);
if (!std::any_cast<int>(Res)) {
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(("got 'Od' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
pid = Data.substr(0, Data.find('-'));
vid = Data.substr(Data.find('-') + 1);
if (pid.find_first_not_of("0123456789") == std::string::npos && vid.find_first_not_of("0123456789") == std::string::npos) {
PID = stoi(pid);
VID = stoi(vid);
}
if (PID != -1 && VID != -1 && PID == c->GetID()) {
SendToAll(nullptr, Packet, true, true);
TriggerLuaEvent(("onVehicleDeleted"), false, nullptr,
std::make_unique<LuaArg>(LuaArg { { c->GetID(), VID } }), false);
c->DeleteCar(VID);
debug(c->GetName() + (" deleted car with ID ") + std::to_string(VID));
}
return;
case 'r':
#ifdef DEBUG
debug(std::string(("got 'Or' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
SendToAll(c, Packet, false, true);
return;
case 't':
#ifdef DEBUG
debug(std::string(("got 'Ot' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
SendToAll(c, Packet, false, true);
return;
default:
#ifdef DEBUG
warn(std::string(("possibly not implemented: '") + Packet + ("' (") + std::to_string(Packet.size()) + (")")));
#endif // DEBUG
return;
}
}
void SyncClient(Client* c) {
Assert(c);
if (c->isSynced)
return;
c->isSynced = true;
std::this_thread::sleep_for(std::chrono::seconds(1));
Respond(c, ("Sn") + c->GetName(), true);
SendToAll(c, ("JWelcome ") + c->GetName() + "!", false, true);
TriggerLuaEvent(("onPlayerJoin"), false, nullptr, std::make_unique<LuaArg>(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() + (" is now synced!"));
}
void ParseVeh(Client* c, const std::string& Packet) {
Assert(c);
#ifdef WIN32
__try {
VehicleParser(c, Packet);
} __except (Handle(GetExceptionInformation(), ("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::make_unique<LuaArg>(LuaArg { { c->GetID(), t } }), false);
break;
default:
break;
}
if (a == 2)
break;
a++;
}
}
void GlobalParser(Client* c, const std::string& Packet) {
Assert(c);
if (Packet.empty() || c == nullptr)
return;
std::any Res;
char Code = Packet.at(0);
//V to Z
if (Code <= 90 && Code >= 86) {
PPS++;
SendToAll(c, Packet, false, false);
return;
}
switch (Code) {
case 'H': // initial connection
#ifdef DEBUG
debug(std::string("got 'H' packet: '") + Packet + "' (" + std::to_string(Packet.size()) + ")");
#endif
SyncClient(c);
return;
case 'p':
Respond(c, ("p"), false);
UpdatePlayers();
return;
case 'O':
if (Packet.length() > 1000) {
debug(("Received data from: ") + c->GetName() + (" Size: ") + std::to_string(Packet.length()));
}
ParseVeh(c, Packet);
return;
case 'J':
#ifdef DEBUG
debug(std::string(("got 'J' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
SendToAll(c, Packet, false, true);
return;
case 'C':
#ifdef DEBUG
debug(std::string(("got 'C' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#endif
if (Packet.length() < 4 || Packet.find(':', 3) == std::string::npos)
break;
Res = TriggerLuaEvent("onChatMessage", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID(), c->GetName(), Packet.substr(Packet.find(':', 3) + 1) } }), true);
if (std::any_cast<int>(Res))
break;
SendToAll(nullptr, Packet, true, true);
return;
case 'E':
#ifdef DEBUG
debug(std::string(("got 'E' packet: '")) + Packet + ("' (") + std::to_string(Packet.size()) + (")"));
#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(), ("Global Handler"))) { }
#else
GlobalParser(c, Packet);
#endif // WIN32
}
-75
View File
@@ -1,75 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 4/9/2020
///
#include "CustomAssert.h"
#include <curl/curl.h>
#include <iostream>
class CurlManager{
public:
CurlManager(){
curl = curl_easy_init();
}
~CurlManager(){
curl_easy_cleanup(curl);
}
inline CURL* Get(){
return curl;
}
private:
CURL *curl;
};
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) {
static thread_local CurlManager M;
std::string readBuffer;
CURL* curl = M.Get();
CURLcode res;
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);
if (res != CURLE_OK)
return "-1";
}
return readBuffer;
}
std::string PostHTTP(const std::string& IP, const std::string& Fields, bool json) {
auto header = curl_slist { (char*)"Content-Type: application/json" };
static thread_local CurlManager M;
static std::mutex Lock;
std::scoped_lock Guard(Lock);
CURL* curl = M.Get();
CURLcode res;
std::string readBuffer;
Assert(curl);
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
if (json)
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
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);
if (res != CURLE_OK)
return "-1";
}
return readBuffer;
}
-109
View File
@@ -1,109 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 8/1/2020
///
#include "Client.hpp"
#include "Logger.h"
#include "Lua/LuaSystem.hpp"
#include "Network.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <memory>
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 = ("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() + (" Connection Terminated"));
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 = ("L") + c->GetName() + (" was kicked!");
else
Packet = ("L") + c->GetName() + (" left the server!");
SendToAll(c, Packet, false, true);
Packet.clear();
TriggerLuaEvent(("onPlayerDisconnect"), false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
if (c->GetTCPSock())
CloseSocketProper(c->GetTCPSock());
if (c->GetDownSock())
CloseSocketProper(c->GetDownSock());
CI->RemoveClient(c);
}
void OnConnect(Client* c) {
Assert(c);
info("Client connected");
c->SetID(OpenID());
info("Assigned ID " + std::to_string(c->GetID()) + " to " + c->GetName());
TriggerLuaEvent("onPlayerConnecting", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
SyncResources(c);
if (c->GetStatus() < 0)
return;
Respond(c, "M" + MapName, true); //Send the Map on connect
info(c->GetName() + " : Connected");
TriggerLuaEvent("onPlayerJoining", false, nullptr, std::make_unique<LuaArg>(LuaArg { { c->GetID() } }), false);
}
-9
View File
@@ -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();
}
-48
View File
@@ -1,48 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 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 {
int 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();
}
-154
View File
@@ -1,154 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 8/1/2020
///
#include "Client.hpp"
#include "Logger.h"
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <filesystem>
#include <fstream>
bool TCPSendRaw(SOCKET C, char* Data, int32_t Size) {
int64_t Sent = 0;
do {
int64_t Temp = send(C, &Data[Sent], int(Size - Sent), 0);
if (Temp < 1) {
info("Socket Closed! " + std::to_string(C));
CloseSocketProper(C);
return false;
}
Sent += Temp;
} while (Sent < Size);
return true;
}
void SplitLoad(Client* c, int64_t Sent, int64_t Size, bool D, const std::string& Name) {
std::ifstream f(Name.c_str(), std::ios::binary);
int32_t Split = 0x7735940; //125MB
char* Data;
if (Size > Split)
Data = new char[Split];
else
Data = new char[Size];
SOCKET TCPSock;
if (D)
TCPSock = c->GetDownSock();
else
TCPSock = c->GetTCPSock();
info("Split load Socket " + std::to_string(TCPSock));
while (c->GetStatus() > -1 && Sent < Size) {
int64_t Diff = Size - Sent;
if (Diff > Split) {
f.seekg(Sent, std::ios_base::beg);
f.read(Data, Split);
if (!TCPSendRaw(TCPSock, Data, Split)) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
break;
}
Sent += Split;
} else {
f.seekg(Sent, std::ios_base::beg);
f.read(Data, Diff);
if (!TCPSendRaw(TCPSock, Data, int32_t(Diff))) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
break;
}
Sent += Diff;
}
}
delete[] Data;
f.close();
}
void SendFile(Client* c, const std::string& Name) {
Assert(c);
info(c->GetName() + " requesting : " + Name.substr(Name.find_last_of('/')));
if (!std::filesystem::exists(Name)) {
TCPSend(c, "CO");
warn("File " + Name + " could not be accessed!");
return;
} else
TCPSend(c, "AG");
///Wait for connections
int T = 0;
while (c->GetDownSock() < 1 && T < 50) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
T++;
}
if (c->GetDownSock() < 1) {
error("Client doesn't have a download socket!");
if (c->GetStatus() > -1)
c->SetStatus(-1);
return;
}
int64_t Size = std::filesystem::file_size(Name), MSize = Size / 2;
std::thread Dt(SplitLoad, c, 0, MSize, false, Name);
Dt.detach();
SplitLoad(c, MSize, Size, true, Name);
if (Dt.joinable())
Dt.join();
}
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("Sending Mod Info");
std::string ToSend = FileList + FileSizes;
if (ToSend.empty())
ToSend = "-";
TCPSend(c, ToSend);
}
return;
default:
return;
}
}
void SyncResources(Client* c) {
Assert(c);
if (c == nullptr)
return;
#ifndef DEBUG
try {
#endif
TCPSend(c, "P" + std::to_string(c->GetID()));
std::string Data;
while (c->GetStatus() > -1) {
Data = TCPRcv(c);
if (Data == "Done")
break;
Parse(c, Data);
}
#ifndef DEBUG
} catch (std::exception& e) {
except("Exception! : " + std::string(e.what()));
c->SetStatus(-1);
}
#endif
}
-137
View File
@@ -1,137 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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>
bool TCPSend(Client* c, const std::string& Data) {
Assert(c);
if (c == nullptr)
return false;
int32_t Size, Sent;
std::string Send(4, 0);
Size = int32_t(Data.size());
memcpy(&Send[0], &Size, sizeof(Size));
Send += Data;
Sent = 0;
Size += 4;
do {
int32_t Temp = send(c->GetTCPSock(), &Send[Sent], Size - Sent, 0);
if (Temp == 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
return false;
} else if (Temp < 0) {
if (c->GetStatus() > -1)
c->SetStatus(-1);
CloseSocketProper(c->GetTCPSock());
return false;
}
Sent += Temp;
} while (Sent < Size);
return true;
}
bool CheckBytes(Client* c, int32_t BytesRcv) {
Assert(c);
if (BytesRcv == 0) {
debug("(TCP) Connection closing...");
if (c->GetStatus() > -1)
c->SetStatus(-1);
return false;
} else if (BytesRcv < 0) {
#ifdef WIN32
debug(("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
#else // unix
debug(("(TCP) recv failed with error: ") + std::string(strerror(errno)));
#endif // WIN32
if (c->GetStatus() > -1)
c->SetStatus(-1);
info(("Closing socket in CheckBytes, BytesRcv < 0"));
CloseSocketProper(c->GetTCPSock());
return false;
}
return true;
}
std::string 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__) + (": failed on CheckBytes in while(BytesRcv < 4)"));
#endif // DEBUG
return "";
}
BytesRcv += Temp;
} while (size_t(BytesRcv) < sizeof(Header));
memcpy(&Header, &Data[0], sizeof(Header));
#ifdef DEBUG
//debug(std::string(__func__) + (": expecting ") + std::to_string(Header) + (" bytes."));
#endif // DEBUG
if (!CheckBytes(c, BytesRcv)) {
#ifdef DEBUG
error(std::string(__func__) + (": failed on CheckBytes"));
#endif // DEBUG
return "";
}
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__) + (": failed on CheckBytes in while(BytesRcv < Header)"));
#endif // DEBUG
return "";
}
#ifdef DEBUG
//debug(std::string(__func__) + (": Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG
BytesRcv += Temp;
} while (BytesRcv < Header);
#ifdef DEBUG
//debug(std::string(__func__) + (": finished recv with Temp: ") + std::to_string(Temp) + (", BytesRcv: ") + std::to_string(BytesRcv));
#endif // DEBUG
std::string Ret(Data.data(), Header);
if (Ret.substr(0, 4) == "ABG:") {
Ret = DeComp(Ret.substr(4));
}
#ifdef DEBUG
//debug("Parsing from " + c->GetName() + " -> " +std::to_string(Ret.size()));
#endif
return Ret;
}
void TCPClient(Client* c) {
DebugPrintTIDInternal("Client(" + c->GetName() + ")", true);
Assert(c);
if (c->GetTCPSock() == -1) {
CI->RemoveClient(c);
return;
}
OnConnect(c);
while (c->GetStatus() > -1) {
GParser(c, TCPRcv(c));
}
OnDisconnect(c, c->GetStatus() == -2);
}
-193
View File
@@ -1,193 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// Created by Anonymous275 on 5/8/2020
///
#include "Client.hpp"
#include "Compressor.h"
#include "Logger.h"
#include "Network.h"
#include "Security/Enc.h"
#include "Settings.h"
#include "UnixCompat.h"
#include <cmath>
#include <cstring>
#include <sstream>
#include <thread>
#include <vector>
#include <array>
SOCKET UDPSock;
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(("(UDP) Send Failed Code : ") + std::to_string(WSAGetLastError()));
if (c->GetStatus() > -1)
c->SetStatus(-1);
} else if (sendOk == 0) {
debug(("(UDP) sendto returned 0"));
if (c->GetStatus() > -1)
c->SetStatus(-1);
}
#else // unix
if (sendOk == -1) {
debug(("(UDP) Send Failed Code : ") + std::string(strerror(errno)));
if (c->GetStatus() > -1)
c->SetStatus(-1);
} else if (sendOk == 0) {
debug(("(UDP) sendto returned 0"));
if (c->GetStatus() > -1)
c->SetStatus(-1);
}
#endif // WIN32
}
void SendLarge(Client* c, std::string Data) {
Assert(c);
if (Data.length() > 400) {
std::string CMP(Comp(Data));
Data = "ABG:" + CMP;
}
TCPSend(c, Data);
}
std::string UDPRcvFromClient(sockaddr_in& client) {
size_t clientLength = sizeof(client);
std::array<char, 1024> Ret{};
int64_t Rcv = recvfrom(UDPSock, Ret.data(), Ret.size(), 0, (sockaddr*)&client, (socklen_t*)&clientLength);
if (Rcv == -1) {
#ifdef WIN32
error(("(UDP) Error receiving from Client! Code : ") + std::to_string(WSAGetLastError()));
#else // unix
error(("(UDP) Error receiving from Client! Code : ") + std::string(strerror(errno)));
#endif // WIN32
return "";
}
return std::string(Ret.begin(), Ret.begin() + Rcv);
}
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));
}
GParser(c, Packet);
}
[[noreturn]] void UDPServerMain() {
#ifdef WIN32
WSADATA data;
if (WSAStartup(514, &data)) {
error(("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(("Can't bind socket!") + std::to_string(WSAGetLastError()));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
//return;
}
info(("Vehicle data network online on port ") + std::to_string(Port) + (" with a Max of ") + std::to_string(MaxPlayers) + (" 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 == std::string::npos || 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(("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(("Can't bind socket!") + std::string(strerror(errno)));
std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1);
//return;
}
info(("Vehicle data network online on port ") + std::to_string(Port) + (" with a Max of ") + std::to_string(MaxPlayers) + (" 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(("fatal: ") + std::string(e.what()));
}
}
/*CloseSocketProper(UDPSock); // TODO: Why not this? We did this in TCPServerMain?
return;
*/
#endif // WIN32
}
-60
View File
@@ -1,60 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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 = ("95.216.35.232");
net::io_context ioc;
tcp::resolver r(ioc);
websocket::stream<tcp::socket> ws(ioc);
auto const results = r.resolve(host, ("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();*/
}
+76
View File
@@ -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))
}
}
+22
View File
@@ -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()
}
+80
View File
@@ -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}"),
}
}
-133
View File
@@ -1,133 +0,0 @@
// Copyright (c) 2019-present Anonymous275.
// BeamMP Server code is not in the public domain and is not free software.
// One must be granted explicit permission by the copyright holder in order to modify or distribute any part of the source or binaries.
// Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
///
/// 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() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t tt = std::chrono::system_clock::to_time_t(now);
tm local_tm {};
#ifdef WIN32
localtime_s(&local_tm, &tt);
#else // unix
localtime_r(&tt, &local_tm);
#endif // WIN32
std::stringstream date;
int S = local_tm.tm_sec;
int M = local_tm.tm_min;
int H = local_tm.tm_hour;
std::string Secs = (S > 9 ? std::to_string(S) : "0" + std::to_string(S));
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M));
std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
date
<< "["
<< local_tm.tm_mday << "/"
<< local_tm.tm_mon + 1 << "/"
<< local_tm.tm_year + 1900 << " "
<< Hour << ":"
<< Min << ":"
<< Secs
<< "] ";
if (Debug) {
date << ThreadName()
<< " ";
}
return date.str();
}
void InitLog() {
std::ofstream LFS;
LFS.open(("Server.log"));
if (!LFS.is_open()) {
error(("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(("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() + ("[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() + ("[DEBUG] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
}
void warn(const std::string& toPrint) {
std::scoped_lock Guard(LogLock);
std::string Print = getDate() + ("[WARN] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
}
void error(const std::string& toPrint) {
std::scoped_lock Guard(LogLock);
std::string Print = getDate() + ("[ERROR] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
}
void except(const std::string& toPrint) {
std::scoped_lock Guard(LogLock);
std::string Print = getDate() + ("[EXCEP] ") + toPrint + "\n";
ConsoleOut(Print);
addToLog(Print);
}
+44
View File
@@ -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
}
-54
View File
@@ -1,54 +0,0 @@
#include "CustomAssert.h"
#include "Startup.h"
#include <curl/curl.h>
#include <iostream>
#include <thread>
#ifndef WIN32
#include <csignal>
void UnixSignalHandler(int sig) {
switch (sig) {
case SIGPIPE:
warn(("ignored signal SIGPIPE: Pipe broken"));
break;
default:
error(("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
[[maybe_unused]] auto ret = curl_global_init(CURL_GLOBAL_DEFAULT);
Assert(ret == 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
View File
@@ -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;
},
}
}
}
+19
View File
@@ -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?)
}
+43
View File
@@ -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)
}
}
+535
View File
@@ -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(())
}
+14
View File
@@ -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
View File
File diff suppressed because it is too large Load Diff
+144
View File
@@ -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],
}
+334
View File
@@ -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
}
}
}
}
+194
View File
@@ -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
View File
@@ -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(())
}
}