mirror of
https://github.com/BeamMP/BeamMP-Launcher.git
synced 2026-04-03 06:16:15 +00:00
Compare commits
197 Commits
v1.70.0
...
new-protoc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9de3658ed3 | ||
|
|
eb78630547 | ||
|
|
afaa3501a3 | ||
|
|
2d5f95cf4d | ||
|
|
d11262f38d | ||
|
|
e836ad5133 | ||
|
|
72a5e7c5b1 | ||
|
|
5d56d529bc | ||
|
|
4e304f798e | ||
|
|
29b4fa9b81 | ||
|
|
60b6d6f9ac | ||
|
|
120a51e2c7 | ||
|
|
c6e07cd26b | ||
|
|
b9be3990c7 | ||
|
|
fb39318d9d | ||
|
|
061258fb34 | ||
|
|
15691ad915 | ||
|
|
ebdb94f362 | ||
|
|
c0a807194c | ||
|
|
ba82b8990e | ||
|
|
387bce5033 | ||
|
|
342b3c3075 | ||
|
|
c74967e513 | ||
|
|
6c67d07ce3 | ||
|
|
920f682284 | ||
|
|
fe9b2ad0f4 | ||
|
|
e4eb9a6e38 | ||
|
|
874f381d43 | ||
|
|
d141bf346c | ||
|
|
b5f0d9dfdb | ||
|
|
c5a6fc711f | ||
|
|
23cf2483e7 | ||
|
|
c918d8fcd8 | ||
|
|
050261b8a4 | ||
|
|
cd1b2e574f | ||
|
|
ece4a42103 | ||
|
|
6a7bf72df5 | ||
|
|
4dad60bc52 | ||
|
|
0eec0fd4e5 | ||
|
|
1070584ad3 | ||
|
|
265d87b788 | ||
|
|
1ad3736711 | ||
|
|
2d0cbc4500 | ||
|
|
0d70012009 | ||
|
|
c17cb84eb4 | ||
|
|
e2a2b48e73 | ||
|
|
a3a946cee6 | ||
|
|
03dc3e3505 | ||
|
|
8eb8a80d54 | ||
|
|
a4a1e4eca0 | ||
|
|
12ba13d9b4 | ||
|
|
3fc74285e6 | ||
|
|
7e9d4e026b | ||
|
|
9afdfd4d1b | ||
|
|
c2f260a86c | ||
|
|
2781179b4b | ||
|
|
3b479abf64 | ||
|
|
c731718f50 | ||
|
|
0fd0a9fe7e | ||
|
|
302582bfe1 | ||
|
|
839bb48cd6 | ||
|
|
c4ebdda1a4 | ||
|
|
d6b494c6c4 | ||
|
|
a80d4f5147 | ||
|
|
811b04485c | ||
|
|
a64fead653 | ||
|
|
399461d1b1 | ||
|
|
ec5e8ed5b3 | ||
|
|
5655164e60 | ||
|
|
3d9b7c2d67 | ||
|
|
764e3ab5c1 | ||
|
|
3314362faf | ||
|
|
e483f520db | ||
|
|
c92e32c0e1 | ||
|
|
cb872f8a41 | ||
|
|
0aae245054 | ||
|
|
480a7d038f | ||
|
|
f62f44d4c0 | ||
|
|
e316b89fb1 | ||
|
|
3b2dbcac1b | ||
|
|
d881c9faf6 | ||
|
|
11d9375f36 | ||
|
|
4207d7adcf | ||
|
|
832b1d66a0 | ||
|
|
cd829f9f22 | ||
|
|
f7c70eb6df | ||
|
|
01960f6470 | ||
|
|
f6065a1c00 | ||
|
|
ba3b7f0ed0 | ||
|
|
056eadbef2 | ||
|
|
2bb2dc9040 | ||
|
|
17553fd412 | ||
|
|
08c1c0f682 | ||
|
|
84959ae9c9 | ||
|
|
c90c102097 | ||
|
|
5b004426ce | ||
|
|
69c9060dd2 | ||
|
|
49870639ff | ||
|
|
0843862af9 | ||
|
|
71a9a567bc | ||
|
|
a6e3d0fad9 | ||
|
|
411d0786a5 | ||
|
|
acb6b11e24 | ||
|
|
1739393a73 | ||
|
|
298ef33ab7 | ||
|
|
d2433cceca | ||
|
|
705e0ab9c4 | ||
|
|
53c40a2bc3 | ||
|
|
96c60ef05a | ||
|
|
61759b8531 | ||
|
|
691be8cd08 | ||
|
|
082445c295 | ||
|
|
f4bda81be0 | ||
|
|
1ad8e0b8e5 | ||
|
|
6c673e78e5 | ||
|
|
09abe75fbb | ||
|
|
b45e4b40f2 | ||
|
|
15d1539a92 | ||
|
|
14a5f47549 | ||
|
|
584998277d | ||
|
|
fb59b6997c | ||
|
|
a1f5ec9ba5 | ||
|
|
989ac981be | ||
|
|
d425b8035a | ||
|
|
f0540c2df5 | ||
|
|
9df08025ad | ||
|
|
bb732f102f | ||
|
|
ec3bcffe7c | ||
|
|
e70cf0f877 | ||
|
|
b40ab5e36a | ||
|
|
54a27f5c4c | ||
|
|
37cfec9fdc | ||
|
|
16f0769f87 | ||
|
|
9f1e58bb70 | ||
|
|
83b43d782d | ||
|
|
3a0b96da52 | ||
|
|
aa2b07b359 | ||
|
|
289402a9ba | ||
|
|
1afa81e420 | ||
|
|
ae6725ece3 | ||
|
|
fff747afca | ||
|
|
5c1b7b1dbf | ||
|
|
e290910312 | ||
|
|
fb7831d629 | ||
|
|
5b4b930701 | ||
|
|
fe59083257 | ||
|
|
fbc5e28d25 | ||
|
|
d96f968dde | ||
|
|
ba5ba4b8b4 | ||
|
|
263b6c9c0d | ||
|
|
78875c2c9c | ||
|
|
8e55edaa29 | ||
|
|
c77f8742b4 | ||
|
|
0a58001b09 | ||
|
|
075d4a8c4d | ||
|
|
00313e32f9 | ||
|
|
16ea84b4cf | ||
|
|
6b124e89a8 | ||
|
|
543183b852 | ||
|
|
fda7567044 | ||
|
|
6b4211d9cf | ||
|
|
3572a188d1 | ||
|
|
775e44a68f | ||
|
|
eaa8796c02 | ||
|
|
2a03448b3f | ||
|
|
9734a7f3d5 | ||
|
|
e207f2febd | ||
|
|
9f821a01f0 | ||
|
|
9a04665c34 | ||
|
|
ab2a58bf42 | ||
|
|
32bcbac979 | ||
|
|
757ac6303b | ||
|
|
20ba2b9e0a | ||
|
|
99006627a4 | ||
|
|
7cd25fbb22 | ||
|
|
76a1b05056 | ||
|
|
b7ffa153b1 | ||
|
|
5630624757 | ||
|
|
c77b519f59 | ||
|
|
5d996e5bc4 | ||
|
|
b802aa46ef | ||
|
|
62f319a90e | ||
|
|
bb70054293 | ||
|
|
5337d1bf25 | ||
|
|
4b9742553a | ||
|
|
49dd577c36 | ||
|
|
4914d251f1 | ||
|
|
cf459a67d0 | ||
|
|
fa31090143 | ||
|
|
f858c462af | ||
|
|
1579c8bc29 | ||
|
|
6bf7e95321 | ||
|
|
c71b2a8387 | ||
|
|
b5fd281c8d | ||
|
|
c517a48fa6 | ||
|
|
179b46d17b | ||
|
|
5753ebb887 |
5
.clang-format
Normal file
5
.clang-format
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
BasedOnStyle: WebKit
|
||||
BreakBeforeBraces: Attach
|
||||
SpaceAfterTemplateKeyword: false
|
||||
...
|
||||
152
.github/workflows/linux.yml
vendored
Normal file
152
.github/workflows/linux.yml
vendored
Normal file
@@ -0,0 +1,152 @@
|
||||
name: Linux
|
||||
|
||||
on: [push]
|
||||
|
||||
|
||||
env:
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
VCPKG_FORCE_SYSTEM_BINARIES: 1
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
DEBIAN_FRONTEND: "noninteractive"
|
||||
|
||||
jobs:
|
||||
x86_64-matrix:
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- distro: debian
|
||||
version: 11
|
||||
- distro: debian
|
||||
version: 12
|
||||
- distro: ubuntu
|
||||
version: 22.04
|
||||
- distro: ubuntu
|
||||
version: 20.04
|
||||
container:
|
||||
image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
steps:
|
||||
- name: get-cmake
|
||||
uses: lukka/get-cmake@v3.28.1
|
||||
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||
|
||||
- name: Install git
|
||||
run: |
|
||||
apt-get update -y
|
||||
apt-get install -y git
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Git config safe directory
|
||||
shell: bash
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
|
||||
- name: Install Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
|
||||
- name: Create Build Environment
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
|
||||
- name: Build Launcher
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
|
||||
- name: Archive launcher artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Launcher.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
path: ./bin/BeamMP-Launcher
|
||||
|
||||
- name: Archive launcher debug info artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.x86_64
|
||||
path: ./bin/BeamMP-Launcher.debug
|
||||
|
||||
- name: Build Tests
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||
|
||||
- name: Install Runtime Dependencies
|
||||
run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
|
||||
|
||||
- name: Test
|
||||
run: ./bin/BeamMP-Launcher-tests
|
||||
|
||||
# arm64-matrix:
|
||||
# runs-on: [Linux, ARM64]
|
||||
# env:
|
||||
# VCPKG_DEFAULT_TRIPLET: "arm64-linux"
|
||||
# strategy:
|
||||
# matrix:
|
||||
# include:
|
||||
# - distro: debian
|
||||
# version: 11
|
||||
# - distro: debian
|
||||
# version: 12
|
||||
# - distro: ubuntu
|
||||
# version: 22.04
|
||||
# - distro: ubuntu
|
||||
# version: 20.04
|
||||
# container:
|
||||
# image: ${{ matrix.distro }}:${{ matrix.version }}
|
||||
# steps:
|
||||
# - name: get-cmake
|
||||
# uses: lukka/get-cmake@v3.28.1
|
||||
#
|
||||
# - name: Export GitHub Actions cache environment variables
|
||||
# uses: actions/github-script@v6
|
||||
# with:
|
||||
# script: |
|
||||
# core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||
# core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||
#
|
||||
# - name: Install git
|
||||
# run: |
|
||||
# apt-get update -y
|
||||
# apt-get install -y git
|
||||
#
|
||||
# - uses: actions/checkout@v2
|
||||
# with:
|
||||
# submodules: 'recursive'
|
||||
#
|
||||
# - name: Git config safe directory
|
||||
# shell: bash
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1.5-git-safe.sh
|
||||
#
|
||||
# - name: Install Dependencies
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/1-install-deps.sh
|
||||
#
|
||||
# - name: Create Build Environment
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/2-configure.sh '-DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake'
|
||||
#
|
||||
# - name: Build Launcher
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build.sh
|
||||
#
|
||||
# - name: Archive launcher artifact
|
||||
# uses: actions/upload-artifact@v2
|
||||
# with:
|
||||
# name: BeamMP-Launcher.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
# path: ./bin/BeamMP-Launcher
|
||||
#
|
||||
# - name: Archive launcher debug info artifact
|
||||
# uses: actions/upload-artifact@v2
|
||||
# with:
|
||||
# name: debuginfo.${{ matrix.distro }}.${{ matrix.version }}.arm64
|
||||
# path: ./bin/BeamMP-Launcher.debug
|
||||
#
|
||||
# - name: Build Tests
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/3-build-tests.sh
|
||||
#
|
||||
# - name: Install Runtime Dependencies
|
||||
# run: bash ./scripts/${{ matrix.distro }}-${{ matrix.version }}/4-install-runtime-deps.sh
|
||||
#
|
||||
# - name: Test
|
||||
# run: ./bin/BeamMP-Launcher-tests
|
||||
#
|
||||
43
.github/workflows/windows.yml
vendored
Normal file
43
.github/workflows/windows.yml
vendored
Normal file
@@ -0,0 +1,43 @@
|
||||
name: Windows
|
||||
|
||||
on: [push]
|
||||
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-static
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
CMAKE_BUILD_TYPE: "Release"
|
||||
|
||||
jobs:
|
||||
windows-build:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Export GitHub Actions cache environment variables
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
|
||||
core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Setup vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
runVcpkgInstall: true
|
||||
|
||||
- name: Create Build Environment
|
||||
shell: bash
|
||||
run: ./scripts/windows/1-configure.sh
|
||||
|
||||
- name: Build Launcher
|
||||
shell: bash
|
||||
run: bash ./scripts/windows/2-build.sh
|
||||
|
||||
- name: Archive launcher artifact
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: BeamMP-Launcher-windows
|
||||
path: ./bin/Release/BeamMP-Launcher.exe
|
||||
|
||||
20
.gitignore
vendored
20
.gitignore
vendored
@@ -1,13 +1,9 @@
|
||||
cmake-build-debug/CMakeFiles/
|
||||
cmake-build-release/CMakeFiles/
|
||||
cmake-build-debug/BeamNG/
|
||||
cmake-build-release/BeamNG/
|
||||
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
|
||||
cmake-build-debug
|
||||
cmake-build-release
|
||||
/.idea/
|
||||
*.log
|
||||
/*.sh
|
||||
/*.obj
|
||||
/*.exe
|
||||
bin/
|
||||
compile_commands.json
|
||||
|
||||
6
.gitmodules
vendored
Normal file
6
.gitmodules
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
[submodule "deps/BeamMP-Protocol"]
|
||||
path = deps/BeamMP-Protocol
|
||||
url = https://github.com/BeamMP/BeamMP-Protocol
|
||||
[submodule "vcpkg"]
|
||||
path = vcpkg
|
||||
url = https://github.com/Microsoft/vcpkg.git
|
||||
172
CMakeLists.txt
172
CMakeLists.txt
@@ -1,16 +1,162 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(Launcher)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
||||
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
|
||||
|
||||
if (WIN32)
|
||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
|
||||
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
|
||||
set(VCPKG_TARGET_TRIPLET x64-windows-static)
|
||||
endif()
|
||||
file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "src/*/*.hpp" "include/*.h" "include/*/*.h")
|
||||
add_executable(${PROJECT_NAME} ${source_files})
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "BeamMP-Launcher")
|
||||
find_package(CURL CONFIG REQUIRED)
|
||||
|
||||
include(cmake/Vcpkg.cmake) # needs to happen before project()
|
||||
|
||||
project(
|
||||
"BeamMP-Launcher" # replace this
|
||||
VERSION 2.0.100
|
||||
LANGUAGES CXX
|
||||
)
|
||||
|
||||
message(STATUS "MSVC -> forcing use of statically-linked runtime.")
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
|
||||
include(cmake/StandardSettings.cmake)
|
||||
include(cmake/StaticAnalyzers.cmake)
|
||||
include(cmake/Git.cmake)
|
||||
|
||||
add_subdirectory(deps/BeamMP-Protocol)
|
||||
|
||||
# below are options which should be changed
|
||||
|
||||
### SETTINGS ###
|
||||
|
||||
# add all headers (.h, .hpp) to this
|
||||
set(PRJ_HEADERS
|
||||
src/Http.h
|
||||
src/Launcher.h
|
||||
src/Platform.h
|
||||
src/Identity.h
|
||||
src/Version.h
|
||||
src/Hashing.h
|
||||
src/Compression.h
|
||||
src/Config.h
|
||||
src/ServerNetwork.h
|
||||
src/ClientNetwork.h
|
||||
)
|
||||
# add all source files (.cpp) to this, except the one with main()
|
||||
set(PRJ_SOURCES
|
||||
src/Launcher.cpp
|
||||
src/Launcher.cpp
|
||||
src/PlatformWindows.cpp
|
||||
src/PlatformLinux.cpp
|
||||
src/Identity.cpp
|
||||
src/Http.cpp
|
||||
src/Version.cpp
|
||||
src/Hashing.cpp
|
||||
src/Config.cpp
|
||||
src/ServerNetwork.cpp
|
||||
src/ClientNetwork.cpp
|
||||
)
|
||||
# set the source file containing main()
|
||||
set(PRJ_MAIN src/main.cpp)
|
||||
# set the source file containing the test's main
|
||||
set(PRJ_TEST_MAIN tests/test_main.cpp)
|
||||
# set include paths not part of libraries
|
||||
set(PRJ_INCLUDE_DIRS src)
|
||||
# set compile features (e.g. standard version)
|
||||
set(PRJ_COMPILE_FEATURES cxx_std_20)
|
||||
# set #defines (test enable/disable not included here)
|
||||
set(PRJ_DEFINITIONS CPPHTTPLIB_OPENSSL_SUPPORT CPPHTTPLIB_ZLIB_SUPPORT)
|
||||
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||
set(PRJ_LIBRARIES
|
||||
fmt::fmt
|
||||
doctest::doctest
|
||||
Threads::Threads
|
||||
spdlog::spdlog
|
||||
httplib::httplib
|
||||
Boost::system
|
||||
Boost::iostreams
|
||||
Boost::thread
|
||||
Boost::filesystem
|
||||
cryptopp::cryptopp
|
||||
ZLIB::ZLIB
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
protocol
|
||||
zstd::libzstd_static
|
||||
)
|
||||
|
||||
# add dependency find_package calls and similar here
|
||||
find_package(fmt CONFIG REQUIRED)
|
||||
find_package(doctest CONFIG REQUIRED)
|
||||
find_package(spdlog CONFIG REQUIRED)
|
||||
find_package(httplib CONFIG REQUIRED)
|
||||
find_package(Boost REQUIRED COMPONENTS system iostreams thread filesystem)
|
||||
find_package(cryptopp CONFIG REQUIRED)
|
||||
find_package(ZLIB REQUIRED)
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32 rstrtmgr discord-rpc CURL::libcurl ZLIB::ZLIB)
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(zstd CONFIG REQUIRED)
|
||||
|
||||
# to enable multithreading and the Threads::Threads dependency
|
||||
include(FindThreads)
|
||||
|
||||
### END SETTINGS ###
|
||||
|
||||
# DONT change anything beyond this point unless you've read the cmake bible and
|
||||
# swore on it not to bonk up the ci/cd pipelines with your changes.
|
||||
|
||||
####################
|
||||
|
||||
|
||||
# enables compile_commands.json for clang-related tools (such as the clang LS)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# build debug builds by default (if not specified otherwise)
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE "Debug")
|
||||
endif()
|
||||
|
||||
if(UNIX)
|
||||
# this will allow to use same _DEBUG macro available in both Linux as well as Windows - MSCV environment. Easy to put Debug specific code.
|
||||
add_compile_options("$<$<CONFIG:DEBUG>:-D_DEBUG>")
|
||||
endif(UNIX)
|
||||
|
||||
include(cmake/CompilerWarnings.cmake)
|
||||
|
||||
# set MT library for msvc - this is required (says documentation)
|
||||
# linux/mac/etc should simply ignore this by default.
|
||||
|
||||
set(PRJ_DEFINITIONS ${PRJ_DEFINITIONS}
|
||||
PRJ_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||
PRJ_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||
PRJ_VERSION_PATCH=${PROJECT_VERSION_PATCH}
|
||||
PRJ_GIT_HASH="${PRJ_GIT_HASH}"
|
||||
)
|
||||
|
||||
add_executable(${PROJECT_NAME} ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_MAIN})
|
||||
target_link_libraries(${PROJECT_NAME} ${PRJ_LIBRARIES})
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||
target_compile_features(${PROJECT_NAME} PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS}
|
||||
DOCTEST_CONFIG_DISABLE # disables all test code in the final executable
|
||||
)
|
||||
if (WIN32)
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE -DPLATFORM_WINDOWS=1)
|
||||
else ()
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE -DPLATFORM_LINUX=1)
|
||||
endif ()
|
||||
|
||||
# setup all warnings (from cmake/CompilerWarnings.cmake)
|
||||
set_project_warnings(${PROJECT_NAME})
|
||||
|
||||
if(${PROJECT_NAME}_ENABLE_UNIT_TESTING)
|
||||
message(STATUS "Unit tests are enabled and will be built as '${PROJECT_NAME}-tests'")
|
||||
add_executable(${PROJECT_NAME}-tests ${PRJ_HEADERS} ${PRJ_SOURCES} ${PRJ_TEST_MAIN})
|
||||
target_link_libraries(${PROJECT_NAME}-tests ${PRJ_LIBRARIES})
|
||||
target_include_directories(${PROJECT_NAME}-tests PRIVATE ${PRJ_INCLUDE_DIRS})
|
||||
target_compile_features(${PROJECT_NAME}-tests PRIVATE ${PRJ_COMPILE_FEATURES})
|
||||
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE ${PRJ_DEFINITIONS} ${PRJ_WARNINGS})
|
||||
set_project_warnings(${PROJECT_NAME}-tests)
|
||||
if (WIN32)
|
||||
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE -DPLATFORM_WINDOWS=1)
|
||||
else ()
|
||||
target_compile_definitions(${PROJECT_NAME}-tests PRIVATE -DPLATFORM_LINUX=1)
|
||||
endif ()
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
120
README.md
120
README.md
@@ -1 +1,119 @@
|
||||
# BeamNG-MP-Launcher
|
||||
# Base Template for C++ based projects
|
||||
## How to use
|
||||
|
||||
TODO: section on how to initialize with this
|
||||
|
||||
## Name and Version
|
||||
|
||||
In order to specify the project name, executable name and name of the unit tests executable, edit the CMakeLists.txt.
|
||||
In there, it says:
|
||||
|
||||
```cmake
|
||||
project(
|
||||
"MY_PROJECT" # replace this
|
||||
VERSION 0.1.0
|
||||
LANGUAGES CXX
|
||||
)
|
||||
```
|
||||
|
||||
Edit the `MY_PROJECT` to a name that suits your project, and adjust the `VERSION` if necessary.
|
||||
|
||||
Further, go into `vcpkg.json` and edit the two lines shown here, similarly to how you did in the CMakeLists.txt:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "my-project",
|
||||
"version-string": "0.1.0",
|
||||
...
|
||||
```
|
||||
|
||||
Keep in mind the name constraints and requirements for vcpkg.
|
||||
|
||||
## Adding source files
|
||||
|
||||
To add source files, add them to the following section in the CMakeLists.txt:
|
||||
|
||||
```cmake
|
||||
# add all headers (.h, .hpp) to this
|
||||
set(PRJ_HEADERS )
|
||||
# add all source files (.cpp) to this, except the one with main()
|
||||
set(PRJ_SOURCES )
|
||||
```
|
||||
|
||||
For example, to add `mysource.cpp`, `somefile.cpp` and `myheader.h`, proceed as follows:
|
||||
|
||||
```cmake
|
||||
# add all headers (.h, .hpp) to this
|
||||
set(PRJ_HEADERS mysource.cpp somefile.cpp)
|
||||
# add all source files (.cpp) to this, except the one with main()
|
||||
set(PRJ_SOURCES myheader.h)
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To build, run cmake (`bin` will be the output directory, `.` the source directory):
|
||||
|
||||
```sh
|
||||
cmake -S . -B bin
|
||||
```
|
||||
|
||||
This will configure it with all default settings.
|
||||
Then build with:
|
||||
|
||||
```sh
|
||||
cmake --build bin --parallel
|
||||
```
|
||||
|
||||
## Adding dependencies
|
||||
|
||||
First, find your dependency on vcpkg (for example using [this website](https://vcpkg.io/en/packages.html)). For example, you may be looking for lionkor's `commandline` library, and you will find `lionkor-commandline`.
|
||||
|
||||
Second, note down the name, in our example `lionkor-commandline`, and add it to the vcpkg.json, like so:
|
||||
|
||||
Before:
|
||||
```json
|
||||
{
|
||||
...
|
||||
"dependencies": [
|
||||
"fmt",
|
||||
"doctest"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
After:
|
||||
```json
|
||||
{
|
||||
...
|
||||
"dependencies": [
|
||||
"fmt",
|
||||
"doctest",
|
||||
"lionkor-commandline"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Third, go to CMakeLists.txt and find the following:
|
||||
|
||||
```cmake
|
||||
# add dependency find_package calls and similar here
|
||||
find_package(fmt CONFIG REQUIRED)
|
||||
find_package(doctest CONFIG REQUIRED)
|
||||
...
|
||||
```
|
||||
and add your `find_package` call or equivalent below it.
|
||||
|
||||
Last, find this section (above the previous):
|
||||
```cmake
|
||||
# add all libraries used by the project (WARNING: also set them in vcpkg.json!)
|
||||
set(PRJ_LIBRARIES
|
||||
fmt::fmt
|
||||
...
|
||||
)
|
||||
```
|
||||
and add your library there. The exact expression used here differs from library to library, but should be easy to find in their documentation. When in doubt, it's simply the name of the library.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
111
cmake/CompilerWarnings.cmake
Normal file
111
cmake/CompilerWarnings.cmake
Normal file
@@ -0,0 +1,111 @@
|
||||
# from here:
|
||||
#
|
||||
# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
|
||||
# Courtesy of Jason Turner
|
||||
# License here: https://github.com/cpp-best-practices/cppbestpractices/blob/master/LICENSE
|
||||
#
|
||||
# This version has been modified by the owners of the current respository.
|
||||
# Modifications have mostly been marked with "modified" or similar, though this is not
|
||||
# strictly required.
|
||||
|
||||
function(set_project_warnings project_name)
|
||||
set(MSVC_WARNINGS
|
||||
/W4 # Baseline reasonable warnings
|
||||
/w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss
|
||||
# of data
|
||||
/w14254 # 'operator': conversion from 'type1:field_bits' to
|
||||
# 'type2:field_bits', possible loss of data
|
||||
/w14263 # 'function': member function does not override any base class
|
||||
# virtual member function
|
||||
/w14265 # 'classname': class has virtual functions, but destructor is not
|
||||
# virtual instances of this class may not be destructed correctly
|
||||
/w14287 # 'operator': unsigned/negative constant mismatch
|
||||
/we4289 # nonstandard extension used: 'variable': loop control variable
|
||||
# declared in the for-loop is used outside the for-loop scope
|
||||
/w14296 # 'operator': expression is always 'boolean_value'
|
||||
/w14311 # 'variable': pointer truncation from 'type1' to 'type2'
|
||||
/w14545 # expression before comma evaluates to a function which is missing
|
||||
# an argument list
|
||||
/w14546 # function call before comma missing argument list
|
||||
/w14547 # 'operator': operator before comma has no effect; expected
|
||||
# operator with side-effect
|
||||
/w14549 # 'operator': operator before comma has no effect; did you intend
|
||||
# 'operator'?
|
||||
/w14555 # expression has no effect; expected expression with side- effect
|
||||
/w14619 # pragma warning: there is no warning number 'number'
|
||||
/w14640 # Enable warning on thread un-safe static member initialization
|
||||
/w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may
|
||||
# cause unexpected runtime behavior.
|
||||
/w14905 # wide string literal cast to 'LPSTR'
|
||||
/w14906 # string literal cast to 'LPWSTR'
|
||||
/w14928 # illegal copy-initialization; more than one user-defined
|
||||
# conversion has been implicitly applied
|
||||
/permissive- # standards conformance mode for MSVC compiler.
|
||||
)
|
||||
|
||||
set(CLANG_WARNINGS
|
||||
-Wall
|
||||
-Wextra # reasonable and standard
|
||||
-Wshadow # warn the user if a variable declaration shadows one from a
|
||||
# parent context
|
||||
-Wnon-virtual-dtor # warn the user if a class with virtual functions has a
|
||||
# non-virtual destructor. This helps catch hard to
|
||||
# track down memory errors
|
||||
-Wold-style-cast # warn for c-style casts
|
||||
-Wcast-align # warn for potential performance problem casts
|
||||
-Wunused # warn on anything being unused
|
||||
-Woverloaded-virtual # warn if you overload (not override) a virtual
|
||||
# function
|
||||
-Wpedantic # warn if non-standard C++ is used
|
||||
-Wconversion # warn on type conversions that may lose data
|
||||
-Wsign-conversion # warn on sign conversions
|
||||
-Wnull-dereference # warn if a null dereference is detected
|
||||
-Wdouble-promotion # warn if float is implicit promoted to double
|
||||
-Wformat=2 # warn on security issues around functions that format output
|
||||
# (ie printf)
|
||||
# modified; added more errors / warnings
|
||||
# some have been set to be errors, but the option _WARNINGS_AS_ERRORS
|
||||
# (see below) should still be used in strict pipelines.
|
||||
-Werror=uninitialized
|
||||
-Werror=float-equal
|
||||
-Werror=write-strings
|
||||
-Werror=strict-aliasing -fstrict-aliasing
|
||||
-Werror=missing-declarations
|
||||
-Werror=ctor-dtor-privacy
|
||||
-Wunused-result
|
||||
-Werror=implicit-fallthrough
|
||||
-Wmissing-include-dirs
|
||||
)
|
||||
|
||||
if (${PROJECT_NAME}_WARNINGS_AS_ERRORS)
|
||||
set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror)
|
||||
set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX)
|
||||
endif()
|
||||
|
||||
set(GCC_WARNINGS
|
||||
${CLANG_WARNINGS}
|
||||
-Wmisleading-indentation # warn if indentation implies blocks where blocks
|
||||
# do not exist
|
||||
-Wduplicated-cond # warn if if / else chain has duplicated conditions
|
||||
-Wduplicated-branches # warn if if / else branches have duplicated code
|
||||
-Wlogical-op # warn about logical operations being used where bitwise were
|
||||
# probably wanted
|
||||
# -Wuseless-cast # warn if you perform a cast to the same type (modified: removed)
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
set(PRJ_WARNINGS ${MSVC_WARNINGS})
|
||||
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
|
||||
set(PRJ_WARNINGS ${CLANG_WARNINGS})
|
||||
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
set(PRJ_WARNINGS ${GCC_WARNINGS})
|
||||
else()
|
||||
message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
|
||||
endif()
|
||||
|
||||
target_compile_options(${project_name} PUBLIC ${PRJ_WARNINGS})
|
||||
|
||||
if(NOT TARGET ${project_name})
|
||||
message(AUTHOR_WARNING "${project_name} is not a target, thus no compiler warning were added.")
|
||||
endif()
|
||||
endfunction()
|
||||
26
cmake/Git.cmake
Normal file
26
cmake/Git.cmake
Normal file
@@ -0,0 +1,26 @@
|
||||
find_package(Git)
|
||||
if(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES)
|
||||
if(Git_FOUND)
|
||||
message(STATUS "Git found, submodule update and init")
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --init --recursive
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
message(SEND_ERROR "git submodule update --init --recursive failed with ${GIT_SUBMOD_RESULT}, please checkout submodules. This may result in missing dependencies.")
|
||||
endif()
|
||||
else()
|
||||
message(SEND_ERROR "git required for checking out submodules, but not found. Submodules will not be checked out - this may result in missing dependencies.")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(Git_FOUND)
|
||||
execute_process(
|
||||
COMMAND git log -1 --format=%h
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
|
||||
OUTPUT_VARIABLE PRJ_GIT_HASH
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
else()
|
||||
message(STATUS "Git not found - the version will not include a git hash.")
|
||||
set(PRJ_GIT_HASH "unknown")
|
||||
endif()
|
||||
44
cmake/StandardSettings.cmake
Normal file
44
cmake/StandardSettings.cmake
Normal file
@@ -0,0 +1,44 @@
|
||||
# Modified, original version from https://github.com/filipdutescu/modern-cpp-template (Unlicense)
|
||||
|
||||
option(${PROJECT_NAME}_WARNINGS_AS_ERRORS "Treat compiler warnings as errors." OFF)
|
||||
option(${PROJECT_NAME}_CHECKOUT_GIT_SUBMODULES "If git is found, initialize all submodules." ON)
|
||||
option(${PROJECT_NAME}_ENABLE_UNIT_TESTING "Enable unit tests for the projects (from the `test` subfolder)." ON)
|
||||
option(${PROJECT_NAME}_ENABLE_CLANG_TIDY "Enable static analysis with Clang-Tidy." OFF)
|
||||
option(${PROJECT_NAME}_ENABLE_CPPCHECK "Enable static analysis with Cppcheck." OFF)
|
||||
# TODO Implement code coverage
|
||||
# option(${PROJECT_NAME}_ENABLE_CODE_COVERAGE "Enable code coverage through GCC." OFF)
|
||||
option(${PROJECT_NAME}_ENABLE_DOXYGEN "Enable Doxygen documentation builds of source." OFF)
|
||||
|
||||
# Generate compile_commands.json for clang based tools
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
# Export all symbols when building a shared library
|
||||
if(BUILD_SHARED_LIBS)
|
||||
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)
|
||||
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
||||
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
|
||||
endif()
|
||||
|
||||
option(${PROJECT_NAME}_ENABLE_LTO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)." ON)
|
||||
if(${PROJECT_NAME}_ENABLE_LTO)
|
||||
include(CheckIPOSupported)
|
||||
check_ipo_supported(RESULT result OUTPUT output)
|
||||
if(result)
|
||||
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
||||
else()
|
||||
message(SEND_ERROR "IPO is not supported: ${output}.")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
option(${PROJECT_NAME}_ENABLE_CCACHE "Enable the usage of Ccache, in order to speed up rebuild times." ON)
|
||||
find_program(CCACHE_FOUND ccache)
|
||||
if(CCACHE_FOUND)
|
||||
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
|
||||
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
|
||||
endif()
|
||||
|
||||
option(${PROJECT_NAME}_ENABLE_SANITIZER "Enable sanitizer to detect memory errors, undefined behavior, etc. (slows down the executable)." OFF)
|
||||
if(${PROJECT_NAME}_ENABLE_SANITIZER)
|
||||
add_compile_options(-fsanitize=address,undefined)
|
||||
add_link_options(-fsanitize=address,undefined)
|
||||
endif()
|
||||
20
cmake/StaticAnalyzers.cmake
Normal file
20
cmake/StaticAnalyzers.cmake
Normal file
@@ -0,0 +1,20 @@
|
||||
if(${PROJECT_NAME}_ENABLE_CLANG_TIDY)
|
||||
find_program(CLANGTIDY clang-tidy)
|
||||
if(CLANGTIDY)
|
||||
set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
|
||||
message("Clang-Tidy finished setting up.")
|
||||
else()
|
||||
message(SEND_ERROR "Clang-Tidy requested but executable not found.")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(${PROJECT_NAME}_ENABLE_CPPCHECK)
|
||||
find_program(CPPCHECK cppcheck)
|
||||
if(CPPCHECK)
|
||||
set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all
|
||||
--inline-suppr --inconclusive)
|
||||
message("Cppcheck finished setting up.")
|
||||
else()
|
||||
message(SEND_ERROR "Cppcheck requested but executable not found.")
|
||||
endif()
|
||||
endif()
|
||||
18
cmake/Vcpkg.cmake
Normal file
18
cmake/Vcpkg.cmake
Normal file
@@ -0,0 +1,18 @@
|
||||
if(NOT CMAKE_TOOLCHAIN_FILE)
|
||||
if(NOT EXISTS ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||
find_package(Git)
|
||||
if(Git_FOUND)
|
||||
# shallow-clone vcpkg (we only need the latest revision)
|
||||
execute_process(COMMAND ${GIT_EXECUTABLE} submodule update --depth=1 --init --recursive vcpkg
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
RESULT_VARIABLE GIT_SUBMOD_RESULT)
|
||||
if(NOT GIT_SUBMOD_RESULT EQUAL "0")
|
||||
message(SEND_ERROR "Checking out vcpkg in source tree failed with ${GIT_SUBMOD_RESULT}.")
|
||||
endif()
|
||||
else()
|
||||
message(FATAL_ERROR "Could not find git or vcpkg.cmake. Please either, install git and re-run cmake (or run `git submodule update --init --recursive`), or install vcpkg and add `-DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/scripts/buildsystems/vcpkg.cmake` to your cmake invocation. Please try again after making those changes.")
|
||||
endif()
|
||||
endif()
|
||||
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||
endif()
|
||||
|
||||
1
deps/BeamMP-Protocol
vendored
Submodule
1
deps/BeamMP-Protocol
vendored
Submodule
Submodule deps/BeamMP-Protocol added at 74b4eee8fe
@@ -1,6 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
int Download(const std::string& URL,const std::string& Path,bool close);
|
||||
std::string HTTP_REQUEST(const std::string& IP,int port);
|
||||
@@ -1,11 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
void Discord_Main();
|
||||
std::string GetDName();
|
||||
std::string GetDTag();
|
||||
std::string GetDID();
|
||||
void DAboard();
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(DISCORD_DYNAMIC_LIB)
|
||||
#if defined(_WIN32)
|
||||
#if defined(DISCORD_BUILDING_SDK)
|
||||
#define DISCORD_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define DISCORD_EXPORT __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#define DISCORD_EXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define DISCORD_EXPORT
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
DISCORD_EXPORT void Discord_Register(const char* applicationId, const char* command);
|
||||
DISCORD_EXPORT void Discord_RegisterSteamGame(const char* applicationId, const char* steamId);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -1,87 +0,0 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// clang-format off
|
||||
|
||||
#if defined(DISCORD_DYNAMIC_LIB)
|
||||
# if defined(_WIN32)
|
||||
# if defined(DISCORD_BUILDING_SDK)
|
||||
# define DISCORD_EXPORT __declspec(dllexport)
|
||||
# else
|
||||
# define DISCORD_EXPORT __declspec(dllimport)
|
||||
# endif
|
||||
# else
|
||||
# define DISCORD_EXPORT __attribute__((visibility("default")))
|
||||
# endif
|
||||
#else
|
||||
# define DISCORD_EXPORT
|
||||
#endif
|
||||
|
||||
// clang-format on
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct DiscordRichPresence {
|
||||
const char* state; /* max 128 bytes */
|
||||
const char* details; /* max 128 bytes */
|
||||
int64_t startTimestamp;
|
||||
int64_t endTimestamp;
|
||||
const char* largeImageKey; /* max 32 bytes */
|
||||
const char* largeImageText; /* max 128 bytes */
|
||||
const char* smallImageKey; /* max 32 bytes */
|
||||
const char* smallImageText; /* max 128 bytes */
|
||||
const char* partyId; /* max 128 bytes */
|
||||
int partySize;
|
||||
int partyMax;
|
||||
const char* matchSecret; /* max 128 bytes */
|
||||
const char* joinSecret; /* max 128 bytes */
|
||||
const char* spectateSecret; /* max 128 bytes */
|
||||
int8_t instance;
|
||||
} DiscordRichPresence;
|
||||
|
||||
typedef struct DiscordUser {
|
||||
const char* userId;
|
||||
const char* username;
|
||||
const char* discriminator;
|
||||
const char* avatar;
|
||||
} DiscordUser;
|
||||
|
||||
typedef struct DiscordEventHandlers {
|
||||
void (*ready)(const DiscordUser* request);
|
||||
void (*disconnected)(int errorCode, const char* message);
|
||||
void (*errored)(int errorCode, const char* message);
|
||||
void (*joinGame)(const char* joinSecret);
|
||||
void (*spectateGame)(const char* spectateSecret);
|
||||
void (*joinRequest)(const DiscordUser* request);
|
||||
} DiscordEventHandlers;
|
||||
|
||||
#define DISCORD_REPLY_NO 0
|
||||
#define DISCORD_REPLY_YES 1
|
||||
#define DISCORD_REPLY_IGNORE 2
|
||||
|
||||
DISCORD_EXPORT void Discord_Initialize(const char* applicationId,
|
||||
DiscordEventHandlers* handlers,
|
||||
int autoRegister,
|
||||
const char* optionalSteamId);
|
||||
DISCORD_EXPORT void Discord_Shutdown(void);
|
||||
|
||||
/* checks for incoming messages, dispatches callbacks */
|
||||
DISCORD_EXPORT void Discord_RunCallbacks(void);
|
||||
|
||||
/* If you disable the lib starting its own io thread, you'll need to call this from your own */
|
||||
#ifdef DISCORD_DISABLE_IO_THREAD
|
||||
DISCORD_EXPORT void Discord_UpdateConnection(void);
|
||||
#endif
|
||||
|
||||
DISCORD_EXPORT void Discord_UpdatePresence(const DiscordRichPresence* presence);
|
||||
DISCORD_EXPORT void Discord_ClearPresence(void);
|
||||
|
||||
DISCORD_EXPORT void Discord_Respond(const char* userid, /* DISCORD_REPLY_ */ int reply);
|
||||
|
||||
DISCORD_EXPORT void Discord_UpdateHandlers(DiscordEventHandlers* handlers);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} /* extern "C" */
|
||||
#endif
|
||||
@@ -1,12 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 4/2/2020.
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
void InitLog();
|
||||
void except(const std::string& toPrint);
|
||||
void debug(const std::string& toPrint);
|
||||
void error(const std::string& toPrint);
|
||||
void info(const std::string& toPrint);
|
||||
void warn(const std::string& toPrint);
|
||||
@@ -1,5 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/20/2020
|
||||
///
|
||||
#pragma once
|
||||
void MemoryInit();
|
||||
@@ -1,29 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
void NetReset();
|
||||
extern long long ping;
|
||||
extern bool Dev;
|
||||
void ClearAll();
|
||||
extern int ClientID;
|
||||
extern bool ModLoaded;
|
||||
extern bool Terminate;
|
||||
extern int DEFAULT_PORT;
|
||||
extern bool TCPTerminate;
|
||||
extern std::string MStatus;
|
||||
extern std::string UlStatus;
|
||||
extern std::string ListOfMods;
|
||||
void UDPSend(std::string Data);
|
||||
int KillSocket(uint64_t Dead);
|
||||
void CoreNetwork();
|
||||
void GameSend(std::string Data);
|
||||
void SendLarge(std::string Data);
|
||||
void TCPSend(const std::string&Data);
|
||||
std::string GetAddr(const std::string&IP);
|
||||
void ServerParser(const std::string& Data);
|
||||
void TCPClientMain(const std::string& IP,int Port);
|
||||
void UDPClientMain(const std::string& IP,int Port);
|
||||
void TCPGameServer(const std::string& IP, int Port);
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include "Xor.h"
|
||||
struct RSA{
|
||||
int n = 0;
|
||||
int e = 0;
|
||||
int d = 0;
|
||||
};
|
||||
std::string RSA_D(const std::string& Data,int d, int n);
|
||||
std::string RSA_E(const std::string& Data,int e, int n);
|
||||
std::string LocalEnc(const std::string& Data);
|
||||
std::string LocalDec(const std::string& Data);
|
||||
RSA* GenKey();
|
||||
@@ -1,6 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/19/2020
|
||||
///
|
||||
#pragma once
|
||||
extern unsigned long GamePID;
|
||||
void SecureMods();
|
||||
@@ -1,12 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
void PreGame(int argc, char* argv[],const std::string& GamePath);
|
||||
void InitGame(const std::string& Dir,const std::string&Current);
|
||||
std::string CheckVer(const std::string &path);
|
||||
void SecurityCheck(char* argv[]);
|
||||
void FindDLL(char* args[]);
|
||||
std::string GetGameDir();
|
||||
void LegitimacyCheck();
|
||||
@@ -1,130 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 8/11/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <array>
|
||||
#include <cstdarg>
|
||||
|
||||
#define BEGIN_NAMESPACE(x) namespace x {
|
||||
#define END_NAMESPACE }
|
||||
|
||||
BEGIN_NAMESPACE(XorCompileTime)
|
||||
|
||||
constexpr auto time = __TIME__;
|
||||
constexpr auto seed = static_cast<int>(time[7]) + static_cast<int>(time[6]) * 10 + static_cast<int>(time[4]) * 60 + static_cast<int>(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000;
|
||||
|
||||
// 1988, Stephen Park and Keith Miller
|
||||
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
|
||||
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
|
||||
// with 32-bit math and without division
|
||||
|
||||
template <int N>
|
||||
struct RandomGenerator{
|
||||
private:
|
||||
static constexpr unsigned a = 16807; // 7^5
|
||||
static constexpr unsigned m = 2147483647; // 2^31 - 1
|
||||
|
||||
static constexpr unsigned s = RandomGenerator< N - 1 >::value;
|
||||
static constexpr unsigned lo = a * (s & 0xFFFFu); // Multiply lower 16 bits by 16807
|
||||
static constexpr unsigned hi = a * (s >> 16u); // Multiply higher 16 bits by 16807
|
||||
static constexpr unsigned lo2 = lo + ((hi & 0x7FFFu) << 16u); // Combine lower 15 bits of hi with lo's upper bits
|
||||
static constexpr unsigned hi2 = hi >> 15u; // Discard lower 15 bits of hi
|
||||
static constexpr unsigned lo3 = lo2 + hi;
|
||||
|
||||
public:
|
||||
static constexpr unsigned max = m;
|
||||
static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct RandomGenerator< 0 >{
|
||||
static constexpr unsigned value = seed;
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct RandomInt{
|
||||
static constexpr auto value = RandomGenerator< N + 1 >::value % M;
|
||||
};
|
||||
|
||||
template <int N>
|
||||
struct RandomChar{
|
||||
static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
|
||||
};
|
||||
|
||||
template <size_t N, int K, typename Char>
|
||||
struct XorString{
|
||||
private:
|
||||
const char _key;
|
||||
std::array< Char, N + 1 > _encrypted;
|
||||
|
||||
constexpr Char enc(Char c) const{
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
Char dec(Char c) const{
|
||||
return c ^ _key;
|
||||
}
|
||||
|
||||
public:
|
||||
template <size_t... Is>
|
||||
constexpr __forceinline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
|
||||
{}
|
||||
|
||||
__forceinline decltype(auto) decrypt(){
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
_encrypted[i] = dec(_encrypted[i]);
|
||||
}
|
||||
_encrypted[N] = '\0';
|
||||
return _encrypted.data();
|
||||
}
|
||||
};
|
||||
|
||||
static auto w_printf = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf_s(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_printf_s = [](const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf_s(fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
/*static auto w_sprintf = [](char* buf, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
};*/
|
||||
|
||||
/*static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
|
||||
int ret;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
ret = vsprintf(buf, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
};*/
|
||||
|
||||
static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vsprintf_s(buf, buf_size, fmt, args);
|
||||
va_end(args);
|
||||
};
|
||||
|
||||
static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
|
||||
int ret;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
ret = vsprintf_s(buf, buf_size, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
};
|
||||
#define Sec( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
|
||||
#define SecW( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()
|
||||
END_NAMESPACE
|
||||
@@ -1,10 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
void InitLauncher(int argc, char* argv[]);
|
||||
void CheckDir(int argc,char* args[]);
|
||||
std::string GetVer();
|
||||
std::string GetEN();
|
||||
extern bool Dev;
|
||||
@@ -1,7 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/24/2020
|
||||
///
|
||||
#pragma once
|
||||
#include <string>
|
||||
std::string Comp(std::string Data);
|
||||
std::string DeComp(std::string Compressed);
|
||||
7
scripts/debian-11/1-install-deps.sh
Executable file
7
scripts/debian-11/1-install-deps.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl zip unzip tar cmake make git g++ ninja-build pkg-config
|
||||
7
scripts/debian-11/1.5-git-safe.sh
Normal file
7
scripts/debian-11/1.5-git-safe.sh
Normal file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
git config --global --add safe.directory $(pwd)
|
||||
git config --global --add safe.directory $(pwd)/vcpkg
|
||||
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||
7
scripts/debian-11/2-configure.sh
Executable file
7
scripts/debian-11/2-configure.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Launcher_ENABLE_LTO=ON
|
||||
5
scripts/debian-11/3-build-tests.sh
Executable file
5
scripts/debian-11/3-build-tests.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher-tests
|
||||
10
scripts/debian-11/3-build.sh
Executable file
10
scripts/debian-11/3-build.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher
|
||||
|
||||
objcopy --only-keep-debug bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
objcopy --add-gnu-debuglink bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
|
||||
strip -s bin/BeamMP-Launcher
|
||||
8
scripts/debian-11/4-install-runtime-deps.sh
Executable file
8
scripts/debian-11/4-install-runtime-deps.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl
|
||||
|
||||
7
scripts/debian-12/1-install-deps.sh
Executable file
7
scripts/debian-12/1-install-deps.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl zip unzip tar cmake make git g++ ninja-build pkg-config
|
||||
7
scripts/debian-12/1.5-git-safe.sh
Normal file
7
scripts/debian-12/1.5-git-safe.sh
Normal file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
git config --global --add safe.directory $(pwd)
|
||||
git config --global --add safe.directory $(pwd)/vcpkg
|
||||
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||
7
scripts/debian-12/2-configure.sh
Executable file
7
scripts/debian-12/2-configure.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Launcher_ENABLE_LTO=ON
|
||||
5
scripts/debian-12/3-build-tests.sh
Executable file
5
scripts/debian-12/3-build-tests.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher-tests
|
||||
10
scripts/debian-12/3-build.sh
Executable file
10
scripts/debian-12/3-build.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher
|
||||
|
||||
objcopy --only-keep-debug bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
objcopy --add-gnu-debuglink bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
|
||||
strip -s bin/BeamMP-Launcher
|
||||
8
scripts/debian-12/4-install-runtime-deps.sh
Executable file
8
scripts/debian-12/4-install-runtime-deps.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl
|
||||
|
||||
7
scripts/ubuntu-20.04/1-install-deps.sh
Executable file
7
scripts/ubuntu-20.04/1-install-deps.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl zip unzip tar cmake make git g++ ninja-build pkg-config
|
||||
7
scripts/ubuntu-20.04/1.5-git-safe.sh
Normal file
7
scripts/ubuntu-20.04/1.5-git-safe.sh
Normal file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
git config --global --add safe.directory $(pwd)
|
||||
git config --global --add safe.directory $(pwd)/vcpkg
|
||||
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||
7
scripts/ubuntu-20.04/2-configure.sh
Executable file
7
scripts/ubuntu-20.04/2-configure.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Launcher_ENABLE_LTO=ON
|
||||
5
scripts/ubuntu-20.04/3-build-tests.sh
Executable file
5
scripts/ubuntu-20.04/3-build-tests.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher-tests
|
||||
10
scripts/ubuntu-20.04/3-build.sh
Executable file
10
scripts/ubuntu-20.04/3-build.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher
|
||||
|
||||
objcopy --only-keep-debug bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
objcopy --add-gnu-debuglink bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
|
||||
strip -s bin/BeamMP-Launcher
|
||||
8
scripts/ubuntu-20.04/4-install-runtime-deps.sh
Executable file
8
scripts/ubuntu-20.04/4-install-runtime-deps.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl
|
||||
|
||||
7
scripts/ubuntu-22.04/1-install-deps.sh
Executable file
7
scripts/ubuntu-22.04/1-install-deps.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl zip unzip tar cmake make git g++ ninja-build pkg-config
|
||||
7
scripts/ubuntu-22.04/1.5-git-safe.sh
Normal file
7
scripts/ubuntu-22.04/1.5-git-safe.sh
Normal file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
git config --global --add safe.directory $(pwd)
|
||||
git config --global --add safe.directory $(pwd)/vcpkg
|
||||
git config --global --add safe.directory $(pwd)/deps/commandline
|
||||
7
scripts/ubuntu-22.04/2-configure.sh
Executable file
7
scripts/ubuntu-22.04/2-configure.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
./vcpkg/bootstrap-vcpkg.sh
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-O3 -g -Wl,-z,norelro -Wl,--hash-style=gnu -Wl,--build-id=none -Wl,-z,noseparate-code -ffunction-sections -fdata-sections -Wl,--gc-sections" -DBeamMP-Launcher_ENABLE_LTO=ON
|
||||
5
scripts/ubuntu-22.04/3-build-tests.sh
Executable file
5
scripts/ubuntu-22.04/3-build-tests.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher-tests
|
||||
10
scripts/ubuntu-22.04/3-build.sh
Executable file
10
scripts/ubuntu-22.04/3-build.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher
|
||||
|
||||
objcopy --only-keep-debug bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
objcopy --add-gnu-debuglink bin/BeamMP-Launcher bin/BeamMP-Launcher.debug
|
||||
|
||||
strip -s bin/BeamMP-Launcher
|
||||
8
scripts/ubuntu-22.04/4-install-runtime-deps.sh
Executable file
8
scripts/ubuntu-22.04/4-install-runtime-deps.sh
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update -y
|
||||
|
||||
apt-get install -y curl
|
||||
|
||||
5
scripts/windows/1-configure.sh
Executable file
5
scripts/windows/1-configure.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake . -B bin $1 -DCMAKE_BUILD_TYPE=Release -DBeamMP-Launcher_ENABLE_LTO=ON -DVCPKG_TARGET_TRIPLET=x64-windows-static
|
||||
5
scripts/windows/2-build-tests.sh
Executable file
5
scripts/windows/2-build-tests.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher-tests
|
||||
5
scripts/windows/2-build.sh
Executable file
5
scripts/windows/2-build.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -ex
|
||||
|
||||
cmake --build bin --parallel -t BeamMP-Launcher --config Release
|
||||
643
src/ClientNetwork.cpp
Normal file
643
src/ClientNetwork.cpp
Normal file
@@ -0,0 +1,643 @@
|
||||
#include "ClientNetwork.h"
|
||||
#include "ClientPacket.h"
|
||||
#include "ClientTransport.h"
|
||||
#include "Http.h"
|
||||
#include "Identity.h"
|
||||
#include "Launcher.h"
|
||||
#include "Transport.h"
|
||||
#include "Util.h"
|
||||
|
||||
#include <boost/asio/socket_base.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
void ClientNetwork::run() {
|
||||
ip::tcp::endpoint listen_ep(ip::address::from_string("0.0.0.0"), static_cast<uint16_t>(m_listen_port));
|
||||
ip::tcp::socket listener(m_io);
|
||||
boost::system::error_code ec;
|
||||
listener.open(listen_ep.protocol(), ec);
|
||||
if (ec) {
|
||||
spdlog::error("Failed to open m_game_socket: {}", ec.message());
|
||||
return;
|
||||
}
|
||||
ip::tcp::socket::linger linger_opt {};
|
||||
linger_opt.enabled(false);
|
||||
listener.set_option(linger_opt, ec);
|
||||
if (ec) {
|
||||
spdlog::error("Failed to set up listening m_game_socket to not linger / reuse address. "
|
||||
"This may cause the m_game_socket to refuse to bind(). spdlog::error: {}",
|
||||
ec.message());
|
||||
}
|
||||
|
||||
m_acceptor = ip::tcp::acceptor(m_io, listen_ep);
|
||||
m_acceptor.listen(ip::tcp::socket::max_listen_connections, ec);
|
||||
if (ec) {
|
||||
spdlog::error("listen() failed, which is needed for the launcher to operate. "
|
||||
"Shutting down. spdlog::error: {}",
|
||||
ec.message());
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
std::exit(1);
|
||||
}
|
||||
start_accept();
|
||||
m_io.run();
|
||||
}
|
||||
|
||||
ClientNetwork::ClientNetwork(Launcher& launcher, uint16_t port)
|
||||
: m_listen_port(port)
|
||||
, launcher(launcher) {
|
||||
spdlog::debug("Client network created");
|
||||
}
|
||||
|
||||
ClientNetwork::~ClientNetwork() {
|
||||
spdlog::debug("Client network destroyed");
|
||||
}
|
||||
|
||||
void ClientNetwork::start_read() {
|
||||
client_tcp_read([this](auto&& packet) {
|
||||
handle_packet(packet);
|
||||
start_read();
|
||||
});
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_connection() {
|
||||
// immediately send launcher info (first step of client identification)
|
||||
m_client_state = bmp::ClientState::ClientIdentification;
|
||||
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::LauncherInfo,
|
||||
.raw_data = json_to_vec(
|
||||
{
|
||||
{ "implementation", "Official BeamMP Launcher" },
|
||||
{ "version", { PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH } },
|
||||
{ "mod_cache_path", "/idk sorry/" }, // TODO: mod_cache_path in LauncherInfo
|
||||
}) });
|
||||
|
||||
start_read();
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_packet(bmp::ClientPacket& packet) {
|
||||
spdlog::debug("Got client packet: purpose: 0x{:x}, flags: 0x{:x}, pid: {}, vid: {}, size: {}",
|
||||
uint16_t(packet.purpose),
|
||||
uint8_t(packet.flags),
|
||||
packet.pid, packet.vid,
|
||||
packet.get_readable_data().size());
|
||||
spdlog::debug("Client State: 0x{:x}", int(m_client_state));
|
||||
|
||||
switch (m_client_state) {
|
||||
case bmp::ClientIdentification:
|
||||
handle_client_identification(packet);
|
||||
break;
|
||||
case bmp::Login:
|
||||
handle_login(packet);
|
||||
break;
|
||||
case bmp::QuickJoin:
|
||||
handle_quick_join(packet);
|
||||
break;
|
||||
case bmp::Browsing:
|
||||
handle_browsing(packet);
|
||||
break;
|
||||
case bmp::ServerIdentification:
|
||||
handle_server_identification(packet);
|
||||
break;
|
||||
case bmp::ServerAuthentication:
|
||||
handle_server_authentication(packet);
|
||||
break;
|
||||
case bmp::ServerModDownload:
|
||||
handle_server_mod_download(packet);
|
||||
break;
|
||||
case bmp::ServerSessionSetup:
|
||||
handle_server_session_setup(packet);
|
||||
break;
|
||||
case bmp::ServerPlaying:
|
||||
handle_server_playing(packet);
|
||||
break;
|
||||
case bmp::ServerLeaving:
|
||||
handle_server_leaving(packet);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_client_identification(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::ClientPurpose::GameInfo: {
|
||||
try {
|
||||
auto game_info = vec_to_json(packet.get_readable_data());
|
||||
std::string impl = game_info.at("implementation");
|
||||
std::vector<int> mod_version = game_info.at("mod_version");
|
||||
std::vector<int> game_version = game_info.at("game_version");
|
||||
std::vector<int> protocol_version = game_info.at("protocol_version");
|
||||
if (protocol_version.at(0) != 1) {
|
||||
disconnect(fmt::format("Incompatible protocol version, expected v{}", "1.x.x"));
|
||||
return;
|
||||
}
|
||||
*launcher.mod_version = Version { uint8_t(mod_version.at(0)), uint8_t(mod_version.at(1)), uint8_t(mod_version.at(2)) };
|
||||
*launcher.game_version = Version { uint8_t(game_version.at(0)), uint8_t(game_version.at(1)), uint8_t(game_version.at(2)) };
|
||||
spdlog::info("Connected to {} (mod v{}, game v{}, protocol v{}.{}.{})",
|
||||
impl,
|
||||
launcher.mod_version->to_string(),
|
||||
launcher.game_version->to_string(),
|
||||
protocol_version.at(0),
|
||||
protocol_version.at(1), protocol_version.at(2));
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Failed to read json for purpose 0x{:x}: {}", uint16_t(packet.purpose), e.what());
|
||||
disconnect(fmt::format("Invalid json in purpose 0x{:x}, see launcher logs for more info", uint16_t(packet.purpose)));
|
||||
}
|
||||
start_login();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::start_login() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeLogin,
|
||||
});
|
||||
|
||||
m_client_state = bmp::ClientState::Login;
|
||||
|
||||
if (ident::is_login_cached()) {
|
||||
auto login = ident::login_cached();
|
||||
// case in which the login is cached and login was successful:
|
||||
// we just send the login result and continue to the next state.
|
||||
if (login.has_value()) {
|
||||
*m_identity = login.value();
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::LoginResult,
|
||||
.raw_data = json_to_vec({
|
||||
{ "success", true },
|
||||
{ "message", m_identity->Message },
|
||||
{ "username", m_identity->Username },
|
||||
{ "role", m_identity->Role },
|
||||
}),
|
||||
});
|
||||
// move on to quick join right away
|
||||
start_quick_join();
|
||||
return; // done
|
||||
} else {
|
||||
spdlog::warn("Failed to automatically login with cached/saved login details: {}", login.error());
|
||||
spdlog::info("Trying normal login");
|
||||
}
|
||||
// fallthrough to normal login
|
||||
}
|
||||
|
||||
// first packet in login
|
||||
// TODO: send LoginResult if already logged in.
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::AskForCredentials,
|
||||
});
|
||||
// wait for response, so return
|
||||
}
|
||||
|
||||
void ClientNetwork::disconnect(const std::string& reason) {
|
||||
spdlog::debug("Disconnecting game: {}", reason);
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::Error,
|
||||
.raw_data = json_to_vec({ "message", reason }) },
|
||||
[this](auto ec) {
|
||||
// ignore any error and just shut down
|
||||
// we pass `ec` to both of these and ignore their errors as well
|
||||
// because we dont care if they fail
|
||||
m_game_socket.shutdown(boost::asio::socket_base::shutdown_both, ec);
|
||||
m_game_socket.close(ec);
|
||||
start_accept();
|
||||
});
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_login(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::ClientPurpose::Credentials:
|
||||
try {
|
||||
auto creds = vec_to_json(packet.get_readable_data());
|
||||
std::string username = creds.at("username");
|
||||
std::string password = creds.at("password");
|
||||
bool remember = creds.at("remember");
|
||||
spdlog::debug("Got credentials username: '{}', password: ({} chars) (remember: {})", username, password.size(), remember ? "yes" : "no");
|
||||
// login!
|
||||
auto result = ident::login(username, password, remember);
|
||||
if (result.has_error()) {
|
||||
;
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::LoginResult,
|
||||
.raw_data = json_to_vec({
|
||||
{ "success", false },
|
||||
{ "message", result.error() },
|
||||
}),
|
||||
});
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::AskForCredentials,
|
||||
});
|
||||
return;
|
||||
}
|
||||
*m_identity = result.value();
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::LoginResult,
|
||||
.raw_data = json_to_vec({
|
||||
{ "success", true },
|
||||
{ "message", m_identity->Message },
|
||||
{ "username", m_identity->Username },
|
||||
{ "role", m_identity->Role },
|
||||
}),
|
||||
});
|
||||
|
||||
start_quick_join();
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Failed to read json for purpose 0x{:x}: {}", uint16_t(packet.purpose), e.what());
|
||||
disconnect(fmt::format("Invalid json in purpose 0x{:x}, see launcher logs for more info", uint16_t(packet.purpose)));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_quick_join(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_browsing(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::ClientPurpose::ServerListRequest: {
|
||||
post(m_io, [&, this] {
|
||||
auto list = load_server_list();
|
||||
if (list.has_value()) {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::ServerListResponse,
|
||||
.raw_data = list.value(),
|
||||
});
|
||||
} else {
|
||||
spdlog::error("Failed to load server list: {}", list.error());
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::Error,
|
||||
.raw_data = json_to_vec({ "message", list.error() }),
|
||||
});
|
||||
}
|
||||
});
|
||||
} break;
|
||||
case bmp::ClientPurpose::Logout: {
|
||||
spdlog::error("Logout is not yet implemented");
|
||||
} break;
|
||||
case bmp::ClientPurpose::Connect: {
|
||||
try {
|
||||
auto details = json::parse(packet.get_readable_data());
|
||||
std::string host = details.at("host");
|
||||
uint16_t port = details.at("port");
|
||||
spdlog::info("Game requesting to connect to server [{}]:{}", host, port);
|
||||
auto connect_result = launcher.start_server_network(host, port);
|
||||
if (connect_result.has_error()) {
|
||||
spdlog::error("Failed to connect to server: {}", connect_result.error());
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::ConnectError,
|
||||
.raw_data = json_to_vec({ "message", connect_result.error() }),
|
||||
});
|
||||
} else {
|
||||
spdlog::info("Connected to server!");
|
||||
start_server_identification();
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Failed to read json for purpose 0x{:x}: {}", uint16_t(packet.purpose), e.what());
|
||||
disconnect(fmt::format("Invalid json in purpose 0x{:x}, see launcher logs for more info", uint16_t(packet.purpose)));
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_identification(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_authentication(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_mod_download(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_session_setup(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_playing(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_server_leaving(bmp::ClientPacket& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
disconnect(fmt::format("Invalid packet purpose in state 0x{:x}: 0x{:x}", uint16_t(m_client_state), uint16_t(packet.purpose)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ClientNetwork::client_tcp_read(std::function<void(bmp::ClientPacket&&)> handler) {
|
||||
m_tmp_header_buffer.resize(bmp::ClientHeader::SERIALIZED_SIZE);
|
||||
boost::asio::async_read(m_game_socket, buffer(m_tmp_header_buffer),
|
||||
bind_executor(m_read_strand, [this, handler](auto ec, auto) {
|
||||
if (ec) {
|
||||
disconnect(fmt::format("Failed to read from game: {}", ec.message()));
|
||||
} else {
|
||||
bmp::ClientHeader hdr {};
|
||||
hdr.deserialize_from(m_tmp_header_buffer);
|
||||
// vector eaten up by now, recv again
|
||||
m_tmp_packet.raw_data.resize(hdr.data_size);
|
||||
m_tmp_packet.purpose = hdr.purpose;
|
||||
m_tmp_packet.flags = hdr.flags;
|
||||
spdlog::trace("Got header: purpose: 0x{:x}, flags: 0x{:x}, pid: {}, vid: {}, size: {}",
|
||||
uint16_t(m_tmp_packet.purpose),
|
||||
uint8_t(m_tmp_packet.flags),
|
||||
m_tmp_packet.pid, m_tmp_packet.vid,
|
||||
m_tmp_packet.get_readable_data().size());
|
||||
boost::asio::async_read(m_game_socket, buffer(m_tmp_packet.raw_data),
|
||||
bind_executor(m_read_strand, [handler, this](auto ec, auto) {
|
||||
if (ec) {
|
||||
disconnect(fmt::format("Failed to read from game: {}", ec.message()));
|
||||
} else {
|
||||
// ok!
|
||||
handler(std::move(m_tmp_packet));
|
||||
}
|
||||
}));
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
void ClientNetwork::client_tcp_write(bmp::ClientPacket&& packet, std::function<void(boost::system::error_code)> handler) {
|
||||
boost::asio::post(m_write_strand, [this, packet = std::move(packet), handler = std::move(handler)] {
|
||||
auto purpose = packet.purpose;
|
||||
m_outbox.emplace_back(OutPacket { std::move(packet), handler });
|
||||
if (m_outbox.size() > 1) {
|
||||
// outstanding async_write
|
||||
spdlog::debug("Outstanding write, not writing 0x{:x} now", int(purpose));
|
||||
return;
|
||||
}
|
||||
client_tcp_write_impl();
|
||||
});
|
||||
}
|
||||
|
||||
void ClientNetwork::client_tcp_write_impl() {
|
||||
OutPacket out_packet = std::move(m_outbox.front());
|
||||
|
||||
spdlog::debug("Writing 0x{:x} now", int(out_packet.packet.purpose));
|
||||
// don't pop just yet
|
||||
|
||||
auto header = out_packet.packet.finalize();
|
||||
// copy packet
|
||||
auto owned_packet = std::make_shared<bmp::ClientPacket>(std::move(out_packet.packet));
|
||||
// serialize header
|
||||
auto header_data = std::make_shared<std::vector<uint8_t>>(bmp::ClientHeader::SERIALIZED_SIZE);
|
||||
header.serialize_to(*header_data);
|
||||
std::array<const_buffer, 2> buffers = {
|
||||
buffer(*header_data),
|
||||
buffer(owned_packet->raw_data)
|
||||
};
|
||||
boost::asio::async_write(m_game_socket, buffers,
|
||||
bind_executor(m_write_strand, [this, header_data, owned_packet, handler = std::move(out_packet.handler)](auto ec, auto size) {
|
||||
// only now pop the packet we just sent from the outbox
|
||||
spdlog::trace("Wrote {} bytes for 0x{:x}", size, int(owned_packet->purpose));
|
||||
if (handler) {
|
||||
handler(ec);
|
||||
} else {
|
||||
if (ec) {
|
||||
disconnect(fmt::format("Failed to send packet to game: {}", ec.message()));
|
||||
} else {
|
||||
// ok!
|
||||
spdlog::debug("Sent packet of type 0x{:x}", int(owned_packet->purpose));
|
||||
}
|
||||
}
|
||||
m_outbox.pop_front();
|
||||
// trigger the next send if there's more to send
|
||||
if (!m_outbox.empty()) {
|
||||
// async so this is not recursion!
|
||||
client_tcp_write_impl();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
std::vector<uint8_t> ClientNetwork::json_to_vec(const nlohmann::json& value) {
|
||||
auto str = value.dump();
|
||||
return std::vector<uint8_t>(str.begin(), str.end());
|
||||
}
|
||||
nlohmann::json ClientNetwork::vec_to_json(const std::vector<uint8_t>& vec) {
|
||||
return json::parse(std::string(vec.begin(), vec.end()));
|
||||
}
|
||||
void ClientNetwork::start_quick_join() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeQuickJoin,
|
||||
});
|
||||
m_client_state = bmp::ClientState::QuickJoin;
|
||||
|
||||
// TODO: Implement DoJoin, etc
|
||||
|
||||
start_browsing();
|
||||
}
|
||||
|
||||
void ClientNetwork::start_browsing() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeBrowsing,
|
||||
});
|
||||
m_client_state = bmp::ClientState::Browsing;
|
||||
}
|
||||
|
||||
Result<std::vector<uint8_t>, std::string> ClientNetwork::load_server_list() noexcept {
|
||||
try {
|
||||
auto list = HTTP::Get("https://backend.beammp.com/servers-info/");
|
||||
if (list == "-1") {
|
||||
return outcome::failure("Failed to fetch server list, see launcher log for more information.");
|
||||
}
|
||||
return outcome::success(std::vector<uint8_t>(list.begin(), list.end()));
|
||||
} catch (const std::exception& e) {
|
||||
return outcome::failure(fmt::format("Failed to fetch server list from backend: {}", e.what()));
|
||||
}
|
||||
}
|
||||
void ClientNetwork::handle_server_packet(bmp::Packet&& packet) {
|
||||
post(m_io, [packet, this] {
|
||||
switch (packet.purpose) {
|
||||
case bmp::ProtocolVersionBad:
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::ConnectError,
|
||||
.raw_data = json_to_vec({ "message", "Server is outdated or too new - protocol is incompatible. Please try a different server and make sure your Launcher and Mod are up-to-date." }),
|
||||
});
|
||||
start_browsing();
|
||||
break;
|
||||
case bmp::ProtocolVersionOk:
|
||||
start_server_authentication();
|
||||
break;
|
||||
case bmp::AuthOk:
|
||||
uint32_t player_id;
|
||||
bmp::deserialize(player_id, packet.get_readable_data());
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::AuthenticationOk,
|
||||
.raw_data = json_to_vec({ "pid", player_id }),
|
||||
});
|
||||
start_server_mod_download();
|
||||
break;
|
||||
case bmp::AuthFailed:
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::AuthenticationError,
|
||||
.raw_data = json_to_vec(
|
||||
{ "message",
|
||||
std::string(
|
||||
packet.get_readable_data().begin(),
|
||||
packet.get_readable_data().end()) }),
|
||||
});
|
||||
start_browsing();
|
||||
break;
|
||||
case bmp::PlayerRejected:
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::PlayerRejected,
|
||||
.raw_data = json_to_vec(
|
||||
{ "message",
|
||||
std::string(
|
||||
packet.get_readable_data().begin(),
|
||||
packet.get_readable_data().end()) }),
|
||||
});
|
||||
start_browsing();
|
||||
break;
|
||||
case bmp::ModsInfo:
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::ModSyncStatus,
|
||||
.raw_data = json_to_vec(json::array()), // TODO: send more here i guess
|
||||
});
|
||||
spdlog::debug("Mod stuff not implemented, skipping to session setup");
|
||||
break;
|
||||
case bmp::MapInfo: {
|
||||
auto data = packet.get_readable_data();
|
||||
auto map = std::string(data.begin(), data.end());
|
||||
spdlog::debug("Map: '{}'", map);
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::MapInfo,
|
||||
.raw_data = json_to_vec({ "map", map }),
|
||||
});
|
||||
start_server_session_setup();
|
||||
} break;
|
||||
case bmp::PlayersVehiclesInfo:
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::PlayersAndVehiclesInfo,
|
||||
.raw_data = packet.get_readable_data(),
|
||||
});
|
||||
start_server_playing();
|
||||
break;
|
||||
case bmp::ClientInfo:
|
||||
case bmp::ServerInfo:
|
||||
case bmp::PlayerPublicKey:
|
||||
case bmp::StartUDP:
|
||||
case bmp::ModRequest:
|
||||
case bmp::ModResponse:
|
||||
case bmp::ModRequestInvalid:
|
||||
case bmp::ModsSyncDone:
|
||||
case bmp::SessionReady:
|
||||
case bmp::Ping:
|
||||
case bmp::VehicleSpawn:
|
||||
case bmp::VehicleDelete:
|
||||
case bmp::VehicleReset:
|
||||
case bmp::VehicleEdited:
|
||||
case bmp::VehicleCouplerChanged:
|
||||
case bmp::SpectatorSwitched:
|
||||
case bmp::ApplyInput:
|
||||
case bmp::ApplyElectrics:
|
||||
case bmp::ApplyNodes:
|
||||
case bmp::ApplyBreakgroups:
|
||||
case bmp::ApplyPowertrain:
|
||||
case bmp::ApplyPosition:
|
||||
case bmp::ChatMessage:
|
||||
case bmp::Event:
|
||||
case bmp::PlayerJoined:
|
||||
case bmp::PlayerLeft:
|
||||
case bmp::PlayerPingUpdate:
|
||||
case bmp::Notification:
|
||||
case bmp::Kicked:
|
||||
case bmp::StateChangeIdentification:
|
||||
case bmp::StateChangeAuthentication:
|
||||
case bmp::StateChangeModDownload:
|
||||
case bmp::StateChangeSessionSetup:
|
||||
case bmp::StateChangePlaying:
|
||||
case bmp::StateChangeLeaving:
|
||||
break;
|
||||
case bmp::Invalid:
|
||||
case bmp::ProtocolVersion:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ClientNetwork::start_accept() {
|
||||
m_acceptor.async_accept(m_game_socket, [this](const auto& ec) { handle_accept(ec); });
|
||||
}
|
||||
|
||||
void ClientNetwork::handle_accept(boost::system::error_code ec) {
|
||||
if (ec) {
|
||||
spdlog::error("Failed accepting game connection: {}", ec.message());
|
||||
} else {
|
||||
spdlog::info("Game connected!");
|
||||
auto game_ep = m_game_socket.remote_endpoint();
|
||||
spdlog::debug("Game: [{}]:{}", game_ep.address().to_string(), game_ep.port());
|
||||
handle_connection();
|
||||
}
|
||||
// TODO: We should probably accept() again somewhere once the game disconnected
|
||||
}
|
||||
void ClientNetwork::start_server_identification() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeServerIdentification,
|
||||
});
|
||||
m_client_state = bmp::ClientState::ServerIdentification;
|
||||
}
|
||||
|
||||
void ClientNetwork::start_server_authentication() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeServerAuthentication,
|
||||
});
|
||||
m_client_state = bmp::ClientState::ServerAuthentication;
|
||||
}
|
||||
|
||||
void ClientNetwork::start_server_mod_download() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeServerModDownload,
|
||||
});
|
||||
m_client_state = bmp::ClientState::ServerModDownload;
|
||||
}
|
||||
|
||||
void ClientNetwork::start_server_session_setup() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeServerSessionSetup,
|
||||
});
|
||||
m_client_state = bmp::ClientState::ServerSessionSetup;
|
||||
}
|
||||
|
||||
void ClientNetwork::start_server_playing() {
|
||||
client_tcp_write(bmp::ClientPacket {
|
||||
.purpose = bmp::ClientPurpose::StateChangeServerPlaying,
|
||||
});
|
||||
m_client_state = bmp::ClientState::ServerPlaying;
|
||||
}
|
||||
87
src/ClientNetwork.h
Normal file
87
src/ClientNetwork.h
Normal file
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
|
||||
#include "ClientPacket.h"
|
||||
#include "ClientState.h"
|
||||
#include "Launcher.h"
|
||||
#include "Packet.h"
|
||||
#include "Sync.h"
|
||||
#include "Version.h"
|
||||
|
||||
#include <boost/asio.hpp>
|
||||
#include <deque>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace boost::asio;
|
||||
|
||||
class ClientNetwork {
|
||||
public:
|
||||
ClientNetwork(Launcher& launcher, uint16_t port);
|
||||
|
||||
~ClientNetwork();
|
||||
|
||||
void run();
|
||||
|
||||
void handle_server_packet(bmp::Packet&& packet);
|
||||
|
||||
private:
|
||||
void start_accept();
|
||||
void handle_accept(boost::system::error_code ec);
|
||||
|
||||
void start_read();
|
||||
|
||||
void handle_connection();
|
||||
void client_tcp_read(std::function<void(bmp::ClientPacket&&)> handler);
|
||||
void client_tcp_write(bmp::ClientPacket&& packet, std::function<void(boost::system::error_code)> handler = nullptr);
|
||||
|
||||
struct OutPacket {
|
||||
bmp::ClientPacket packet;
|
||||
std::function<void(boost::system::error_code)> handler;
|
||||
};
|
||||
std::deque<OutPacket> m_outbox {};
|
||||
void client_tcp_write_impl();
|
||||
|
||||
void handle_packet(bmp::ClientPacket& packet);
|
||||
void handle_client_identification(bmp::ClientPacket& packet);
|
||||
void handle_login(bmp::ClientPacket& packet);
|
||||
void handle_quick_join(bmp::ClientPacket& packet);
|
||||
void handle_browsing(bmp::ClientPacket& packet);
|
||||
void handle_server_identification(bmp::ClientPacket& packet);
|
||||
void handle_server_authentication(bmp::ClientPacket& packet);
|
||||
void handle_server_mod_download(bmp::ClientPacket& packet);
|
||||
void handle_server_session_setup(bmp::ClientPacket& packet);
|
||||
void handle_server_playing(bmp::ClientPacket& packet);
|
||||
void handle_server_leaving(bmp::ClientPacket& packet);
|
||||
|
||||
void disconnect(const std::string& reason);
|
||||
void start_login();
|
||||
void start_quick_join();
|
||||
void start_browsing();
|
||||
void start_server_identification();
|
||||
void start_server_authentication();
|
||||
void start_server_mod_download();
|
||||
void start_server_session_setup();
|
||||
void start_server_playing();
|
||||
|
||||
Result<std::vector<uint8_t>, std::string> load_server_list() noexcept;
|
||||
|
||||
static std::vector<uint8_t> json_to_vec(const nlohmann::json& json);
|
||||
static nlohmann::json vec_to_json(const std::vector<uint8_t>& vec);
|
||||
|
||||
Sync<ident::Identity> m_identity {};
|
||||
|
||||
uint16_t m_listen_port {};
|
||||
io_context m_io {};
|
||||
ip::tcp::socket m_game_socket { m_io };
|
||||
Sync<bool> m_shutdown { false };
|
||||
bmp::ClientState m_client_state;
|
||||
|
||||
ip::tcp::acceptor m_acceptor { m_io };
|
||||
boost::asio::io_context::strand m_read_strand { m_io };
|
||||
boost::asio::io_context::strand m_write_strand { m_io };
|
||||
|
||||
// temporary packet and header buffer for async reads
|
||||
bmp::ClientPacket m_tmp_packet {};
|
||||
std::vector<uint8_t> m_tmp_header_buffer {};
|
||||
|
||||
Launcher& launcher;
|
||||
};
|
||||
57
src/Compression.h
Normal file
57
src/Compression.h
Normal file
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <zlib.h>
|
||||
#include <algorithm>
|
||||
|
||||
#define Biggest 30000
|
||||
|
||||
template <typename T>
|
||||
inline T Comp(const T& Data) {
|
||||
std::array<char, Biggest> C {};
|
||||
// obsolete
|
||||
C.fill(0);
|
||||
z_stream defstream;
|
||||
defstream.zalloc = nullptr;
|
||||
defstream.zfree = nullptr;
|
||||
defstream.opaque = nullptr;
|
||||
defstream.avail_in = uInt(Data.size());
|
||||
defstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Data[0]));
|
||||
defstream.avail_out = Biggest;
|
||||
defstream.next_out = reinterpret_cast<Bytef*>(C.data());
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
size_t TotalOut = defstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T DeComp(const T& Compressed) {
|
||||
std::array<char, Biggest> C {};
|
||||
// not needed
|
||||
C.fill(0);
|
||||
z_stream infstream;
|
||||
infstream.zalloc = nullptr;
|
||||
infstream.zfree = nullptr;
|
||||
infstream.opaque = nullptr;
|
||||
infstream.avail_in = Biggest;
|
||||
infstream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(&Compressed[0]));
|
||||
infstream.avail_out = Biggest;
|
||||
infstream.next_out = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(C.data()));
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
size_t TotalOut = infstream.total_out;
|
||||
T Ret;
|
||||
Ret.resize(TotalOut);
|
||||
std::fill(Ret.begin(), Ret.end(), 0);
|
||||
std::copy_n(C.begin(), TotalOut, Ret.begin());
|
||||
return Ret;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/15/2020
|
||||
///
|
||||
|
||||
#include <iostream>
|
||||
#include <zlib.h>
|
||||
|
||||
#define Biggest 30000
|
||||
std::string Comp(std::string Data){
|
||||
char*C = new char[Biggest];
|
||||
memset(C, 0, Biggest);
|
||||
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);
|
||||
deflateInit(&defstream, Z_BEST_COMPRESSION);
|
||||
deflate(&defstream, Z_SYNC_FLUSH);
|
||||
deflate(&defstream, Z_FINISH);
|
||||
deflateEnd(&defstream);
|
||||
int TO = defstream.total_out;
|
||||
std::string Ret(TO,0);
|
||||
memcpy_s(&Ret[0],TO,C,TO);
|
||||
delete [] C;
|
||||
return Ret;
|
||||
}
|
||||
std::string DeComp(std::string Compressed){
|
||||
char*C = new char[Biggest];
|
||||
memset(C, 0, Biggest);
|
||||
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);
|
||||
inflateInit(&infstream);
|
||||
inflate(&infstream, Z_SYNC_FLUSH);
|
||||
inflate(&infstream, Z_FINISH);
|
||||
inflateEnd(&infstream);
|
||||
int TO = infstream.total_out;
|
||||
std::string Ret(TO,0);
|
||||
memcpy_s(&Ret[0],TO,C,TO);
|
||||
delete [] C;
|
||||
return Ret;
|
||||
}
|
||||
41
src/Config.cpp
Normal file
41
src/Config.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
#include "Config.h"
|
||||
|
||||
#include <boost/iostreams/device/mapped_file.hpp>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
Config::Config() {
|
||||
if (std::filesystem::exists("Launcher.cfg")) {
|
||||
boost::iostreams::mapped_file cfg("Launcher.cfg", boost::iostreams::mapped_file::mapmode::readonly);
|
||||
nlohmann::json d = nlohmann::json::parse(cfg.const_data(), nullptr, false);
|
||||
if (d.is_discarded()) {
|
||||
is_valid = false;
|
||||
}
|
||||
// parse config
|
||||
if (d["Port"].is_number()) {
|
||||
port = d["Port"].get<int>();
|
||||
}
|
||||
if (d["Build"].is_string()) {
|
||||
branch = d["Build"].get<std::string>();
|
||||
for (char& c : branch) {
|
||||
c = char(tolower(c));
|
||||
}
|
||||
}
|
||||
if (d["GameDir"].is_string()) {
|
||||
game_dir = d["GameDir"].get<std::string>();
|
||||
}
|
||||
} else {
|
||||
write_to_file();
|
||||
}
|
||||
}
|
||||
|
||||
void Config::write_to_file() const {
|
||||
nlohmann::json d {
|
||||
{ "Port", port },
|
||||
{ "Branch", branch },
|
||||
{ "GameDir", game_dir },
|
||||
};
|
||||
std::ofstream of("Launcher.cfg", std::ios::trunc);
|
||||
of << d.dump(4);
|
||||
}
|
||||
14
src/Config.h
Normal file
14
src/Config.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
struct Config {
|
||||
Config();
|
||||
|
||||
void write_to_file() const;
|
||||
|
||||
bool is_valid = true;
|
||||
int port = 4444;
|
||||
std::string branch = "Default";
|
||||
std::string game_dir = "";
|
||||
};
|
||||
|
||||
127
src/Discord.cpp
127
src/Discord.cpp
@@ -1,127 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Discord/discord_rpc.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <ctime>
|
||||
|
||||
struct DInfo{
|
||||
std::string Name;
|
||||
std::string Tag;
|
||||
std::string DID;
|
||||
};
|
||||
DInfo* DiscordInfo = nullptr;
|
||||
int64_t StartTime;
|
||||
void updateDiscordPresence(){
|
||||
//if (SendPresence) {
|
||||
//char buffer[256];
|
||||
DiscordRichPresence discordPresence;
|
||||
memset(&discordPresence, 0, sizeof(discordPresence));
|
||||
std::string P = Sec("Playing with friends!");
|
||||
discordPresence.state = P.c_str();
|
||||
//sprintf(buffer, "Frustration level: %d", FrustrationLevel);
|
||||
//discordPresence.details = buffer;
|
||||
discordPresence.startTimestamp = StartTime;
|
||||
//discordPresence.endTimestamp = time(0) + 5 * 60;
|
||||
std::string L = Sec("mainlogo");
|
||||
discordPresence.largeImageKey = L.c_str();
|
||||
//discordPresence.smallImageKey = "logo";
|
||||
//discordPresence.partyId = "party1234";
|
||||
//discordPresence.partySize = 1;
|
||||
//discordPresence.partyMax = 6;
|
||||
//discordPresence.matchSecret = "xyzzy";
|
||||
//discordPresence.joinSecret = "join";
|
||||
//discordPresence.spectateSecret = "look";
|
||||
//discordPresence.instance = 0;
|
||||
Discord_UpdatePresence(&discordPresence);
|
||||
//}
|
||||
//else {
|
||||
// Discord_ClearPresence();
|
||||
//}
|
||||
}
|
||||
void handleDiscordReady(const DiscordUser* User){
|
||||
DiscordInfo = new DInfo{
|
||||
LocalEnc(User->username),
|
||||
LocalEnc(User->discriminator),
|
||||
LocalEnc(User->userId)
|
||||
};
|
||||
}
|
||||
void discordInit(){
|
||||
DiscordEventHandlers handlers;
|
||||
memset(&handlers, 0, sizeof(handlers));
|
||||
handlers.ready = handleDiscordReady;
|
||||
/*handlers.disconnected = handleDiscordDisconnected;
|
||||
handlers.errored = handleDiscordError;
|
||||
handlers.joinGame = handleDiscordJoin;
|
||||
handlers.spectateGame = handleDiscordSpectate;
|
||||
handlers.joinRequest = handleDiscordJoinRequest;*/
|
||||
std::string a = Sec("629743237988352010");
|
||||
Discord_Initialize(a.c_str(), &handlers, 1,nullptr);
|
||||
}
|
||||
[[noreturn]] void Loop(){
|
||||
StartTime = time(nullptr);
|
||||
while (true) {
|
||||
updateDiscordPresence();
|
||||
#ifdef DISCORD_DISABLE_IO_THREAD
|
||||
Discord_UpdateConnection();
|
||||
#endif
|
||||
Discord_RunCallbacks();
|
||||
if(DiscordInfo == nullptr){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(250));
|
||||
}else std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
}
|
||||
}
|
||||
void DAS();
|
||||
[[noreturn]] void SecurityLoop(){
|
||||
std::string t,t1,t2;
|
||||
while(true){
|
||||
if(DiscordInfo != nullptr){
|
||||
if(t.empty()){
|
||||
t = LocalDec(DiscordInfo->Name);
|
||||
t1 = LocalDec(DiscordInfo->Tag);
|
||||
t2 = LocalDec(DiscordInfo->DID);
|
||||
}else if(t2 != LocalDec(DiscordInfo->DID) ||
|
||||
t != LocalDec(DiscordInfo->Name) || t1 != LocalDec(DiscordInfo->Tag))DiscordInfo = nullptr;
|
||||
}else if(!t.empty())DiscordInfo->DID.clear();
|
||||
DAS();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
}
|
||||
void DMain(){
|
||||
auto*S = new std::thread(SecurityLoop);
|
||||
S->detach();
|
||||
delete S;
|
||||
discordInit();
|
||||
Loop();
|
||||
}
|
||||
std::string GetDName(){
|
||||
return LocalDec(DiscordInfo->Name);
|
||||
}
|
||||
std::string GetDTag(){
|
||||
return LocalDec(DiscordInfo->Tag);
|
||||
}
|
||||
std::string GetDID(){
|
||||
return LocalDec(DiscordInfo->DID);
|
||||
}
|
||||
void DAboard(){
|
||||
DiscordInfo = nullptr;
|
||||
}
|
||||
void ErrorAboard(){
|
||||
error(Sec("Discord timeout! please start the discord app and try again after 30 secs"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(6);
|
||||
}
|
||||
void Discord_Main(){
|
||||
std::thread t1(DMain);
|
||||
t1.detach();
|
||||
info(Sec("Connecting to discord client..."));
|
||||
int C = 0;
|
||||
while(DiscordInfo == nullptr && C < 80){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
C++;
|
||||
}
|
||||
if(DiscordInfo == nullptr)ErrorAboard();
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/19/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include <Windows.h>
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
unsigned long GamePID = 0;
|
||||
std::string QueryKey(HKEY hKey,int ID);
|
||||
void DeleteKey(){
|
||||
HKEY hKey;
|
||||
LPCTSTR sk = Sec("Software\\BeamNG\\BeamNG.drive");
|
||||
RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
|
||||
RegDeleteValueA(hKey, Sec("userpath_override"));
|
||||
}
|
||||
std::string Write(const std::string&Path){
|
||||
HKEY hKey;
|
||||
LPCTSTR sk = Sec("Software\\BeamNG\\BeamNG.drive");
|
||||
LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
|
||||
if (openRes != ERROR_SUCCESS){
|
||||
error(Sec("Please launch the game at least once"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(5);
|
||||
}
|
||||
std::string Query = QueryKey(hKey,4);
|
||||
LONG setRes = RegSetValueEx(hKey, Sec("userpath_override"), 0, REG_SZ, (LPBYTE)Path.c_str(), DWORD(Path.size()));
|
||||
if(setRes != ERROR_SUCCESS){
|
||||
error(Sec("Failed to launch the game"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(5);
|
||||
}
|
||||
RegCloseKey(hKey);
|
||||
return Query;
|
||||
}
|
||||
void RollBack(const std::string&Val,int T){
|
||||
std::this_thread::sleep_for(std::chrono::seconds(T));
|
||||
if(!Val.empty()){
|
||||
if(Write(Val) == Val)DeleteKey();
|
||||
}else DeleteKey();
|
||||
}
|
||||
std::string Restore;
|
||||
void OnExit(){
|
||||
RollBack(Restore,0);
|
||||
}
|
||||
void StartGame(std::string Dir,std::string Current){
|
||||
Current = Current.substr(0,Current.find_last_of('\\')) + Sec("\\BeamNG\\");
|
||||
BOOL bSuccess = FALSE;
|
||||
PROCESS_INFORMATION pi;
|
||||
STARTUPINFO si = {0};
|
||||
si.cb = sizeof(si);
|
||||
std::string BaseDir = Dir + Sec("\\Bin64");
|
||||
Dir += Sec(R"(\Bin64\BeamNG.drive.x64.exe)");
|
||||
bSuccess = CreateProcessA(Dir.c_str(), nullptr, nullptr, nullptr, TRUE, 0, nullptr, BaseDir.c_str(), &si, &pi);
|
||||
if (bSuccess){
|
||||
info(Sec("Game Launched!"));
|
||||
GamePID = pi.dwProcessId;
|
||||
Restore = Write(Current);
|
||||
atexit(OnExit);
|
||||
std::thread RB(RollBack,Restore,7);
|
||||
RB.detach();
|
||||
WaitForSingleObject(pi.hProcess, INFINITE);
|
||||
error(Sec("Game Closed! launcher closing soon"));
|
||||
RollBack(Restore,0);
|
||||
}else{
|
||||
error(Sec("Failed to Launch the game! launcher closing soon"));
|
||||
RollBack(Write(Current),0);
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(2);
|
||||
}
|
||||
void InitGame(const std::string& Dir,const std::string&Current){
|
||||
if(!Dev){
|
||||
std::thread Game(StartGame, Dir, Current);
|
||||
Game.detach();
|
||||
}
|
||||
}
|
||||
35
src/Hashing.cpp
Normal file
35
src/Hashing.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include "Hashing.h"
|
||||
|
||||
#include <boost/iostreams/device/mapped_file.hpp>
|
||||
#include <cryptopp/hex.h>
|
||||
#include <cryptopp/sha.h>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <errno.h>
|
||||
|
||||
std::string sha256_file(const std::string& path) {
|
||||
CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];
|
||||
digest[sizeof(digest) - 1] = 0;
|
||||
FILE* file = std::fopen(path.c_str(), "rb");
|
||||
if (!file) {
|
||||
throw std::runtime_error(fmt::format("Failed to open {}: {}", path, std::strerror(errno)));
|
||||
}
|
||||
std::vector<uint8_t> buffer{};
|
||||
buffer.resize(std::filesystem::file_size(path));
|
||||
std::fread(buffer.data(), 1, buffer.size(), file);
|
||||
std::fclose(file);
|
||||
CryptoPP::SHA256().CalculateDigest(
|
||||
digest,
|
||||
buffer.data(), buffer.size());
|
||||
CryptoPP::HexEncoder encoder;
|
||||
encoder.Put(digest, sizeof(digest));
|
||||
encoder.MessageEnd();
|
||||
std::string encoded {};
|
||||
if (auto size = encoder.MaxRetrievable(); size != 0)
|
||||
{
|
||||
encoded.resize(size);
|
||||
encoder.Get(reinterpret_cast<CryptoPP::byte*>(&encoded[0]), encoded.size());
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
5
src/Hashing.h
Normal file
5
src/Hashing.h
Normal file
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
std::string sha256_file(const std::string& path);
|
||||
116
src/Http.cpp
Normal file
116
src/Http.cpp
Normal file
@@ -0,0 +1,116 @@
|
||||
#include "Http.h"
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <httplib.h>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
static httplib::Client& get_client(const std::string& host) {
|
||||
static thread_local std::unordered_map<std::string /* host */, httplib::Client> s_clients_cache {};
|
||||
if (!s_clients_cache.contains(host)) {
|
||||
spdlog::debug("Caching connection to {}", host);
|
||||
s_clients_cache.emplace(host, httplib::Client(host));
|
||||
} else {
|
||||
spdlog::debug("Reusing cached connection to {}", host);
|
||||
}
|
||||
return s_clients_cache.at(host);
|
||||
}
|
||||
|
||||
bool HTTP::isDownload = false;
|
||||
std::string HTTP::Get(const std::string& host_and_target) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
auto pos = host_and_target.find('/', 10);
|
||||
|
||||
auto& cli = get_client(host_and_target.substr(0, pos).c_str());
|
||||
cli.set_connection_timeout(std::chrono::seconds(10));
|
||||
cli.set_follow_location(true);
|
||||
|
||||
httplib::Headers headers {
|
||||
{ "Accept-Encoding", "gzip" }
|
||||
};
|
||||
|
||||
auto res = cli.Get(host_and_target.substr(pos).c_str(), headers);
|
||||
std::string Ret;
|
||||
|
||||
if (res) {
|
||||
if (res->status == 200) {
|
||||
Ret = res->body;
|
||||
} else
|
||||
spdlog::error(res->reason);
|
||||
|
||||
} else {
|
||||
if (isDownload) {
|
||||
std::cout << "\n";
|
||||
}
|
||||
spdlog::error("HTTP Get failed on " + to_string(res.error()));
|
||||
}
|
||||
|
||||
return Ret;
|
||||
}
|
||||
|
||||
std::string HTTP::Post(const std::string& host_and_target, const std::string& Fields) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
auto pos = host_and_target.find('/', 10);
|
||||
|
||||
auto& cli = get_client(host_and_target.substr(0, pos).c_str());
|
||||
cli.set_connection_timeout(std::chrono::seconds(10));
|
||||
std::string Ret;
|
||||
|
||||
if (!Fields.empty()) {
|
||||
httplib::Result res = cli.Post(host_and_target.substr(pos).c_str(), Fields, "application/json");
|
||||
|
||||
if (res) {
|
||||
if (res->status != 200) {
|
||||
spdlog::error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
} else {
|
||||
spdlog::error("HTTP Post failed on " + to_string(res.error()));
|
||||
}
|
||||
} else {
|
||||
httplib::Result res = cli.Post(host_and_target.substr(pos).c_str());
|
||||
if (res) {
|
||||
if (res->status != 200) {
|
||||
spdlog::error(res->reason);
|
||||
}
|
||||
Ret = res->body;
|
||||
} else {
|
||||
spdlog::error("HTTP Post failed on " + to_string(res.error()));
|
||||
}
|
||||
}
|
||||
|
||||
if (Ret.empty())
|
||||
return "-1";
|
||||
else
|
||||
return Ret;
|
||||
}
|
||||
|
||||
bool HTTP::Download(const std::string& IP, const std::string& Path) {
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
|
||||
isDownload = true;
|
||||
std::string Ret = Get(IP);
|
||||
isDownload = false;
|
||||
|
||||
if (Ret.empty())
|
||||
return false;
|
||||
|
||||
std::ofstream File(Path, std::ios::binary);
|
||||
if (File.is_open()) {
|
||||
File << Ret;
|
||||
File.close();
|
||||
std::cout << "\n";
|
||||
spdlog::info("Download Complete!");
|
||||
} else {
|
||||
spdlog::error("Failed to open file directory: " + Path);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
18
src/Http.h
Normal file
18
src/Http.h
Normal file
@@ -0,0 +1,18 @@
|
||||
// Copyright (c) 2019-present Anonymous275.
|
||||
// BeamMP Launcher 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>
|
||||
class HTTP {
|
||||
public:
|
||||
static bool Download(const std::string &IP, const std::string &Path);
|
||||
static std::string Post(const std::string& IP, const std::string& Fields);
|
||||
static std::string Get(const std::string &IP);
|
||||
static bool ProgressBar(size_t c, size_t t);
|
||||
public:
|
||||
static bool isDownload;
|
||||
};
|
||||
103
src/Identity.cpp
Normal file
103
src/Identity.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
#include "Identity.h"
|
||||
#include "Http.h"
|
||||
#include <filesystem>
|
||||
#include <fmt/core.h>
|
||||
#include <fstream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
Result<ident::Identity, std::string> ident::login_cached() noexcept {
|
||||
std::string private_key;
|
||||
try {
|
||||
std::ifstream key_file(ident::KEYFILE);
|
||||
if (key_file.is_open()) {
|
||||
auto size = fs::file_size(ident::KEYFILE);
|
||||
private_key.resize(size);
|
||||
key_file.read(&private_key[0], static_cast<long>(size));
|
||||
key_file.close();
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
return fmt::format("Failed to read cached key: {}", e.what());
|
||||
}
|
||||
|
||||
std::string private_key_json {};
|
||||
|
||||
try {
|
||||
private_key_json = nlohmann::json {
|
||||
{ "pk", private_key }
|
||||
}.dump();
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Private key had invalid format, please log in again.");
|
||||
return std::string("Invalid login saved, please log in again.");
|
||||
}
|
||||
|
||||
// login and remember (again)
|
||||
return detail::login(private_key_json, true);
|
||||
}
|
||||
|
||||
bool ident::is_login_cached() noexcept {
|
||||
return std::filesystem::exists(KEYFILE) && std::filesystem::is_regular_file(KEYFILE);
|
||||
}
|
||||
|
||||
Result<ident::Identity, std::string> ident::login(const std::string& username_or_email, const std::string& password, bool remember) {
|
||||
std::string login_json {};
|
||||
|
||||
try {
|
||||
login_json = nlohmann::json {
|
||||
{ "username", username_or_email },
|
||||
{ "password", password },
|
||||
}
|
||||
.dump();
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Username or password has invalid format, please try again.");
|
||||
return std::string("Username or password contain illegal characters, please try again.");
|
||||
}
|
||||
|
||||
return detail::login(login_json, remember);
|
||||
}
|
||||
|
||||
void ident::detail::cache_key(const std::string& private_key) noexcept {
|
||||
try {
|
||||
std::ofstream key_file(ident::KEYFILE, std::ios::trunc);
|
||||
key_file << private_key;
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::warn("Failed to cache key - login will not be remembered: {}", e.what());
|
||||
}
|
||||
}
|
||||
Result<ident::Identity, std::string> ident::detail::login(const std::string& json_params, bool remember) noexcept {
|
||||
auto result = HTTP::Post("https://auth.beammp.com/userlogin", json_params);
|
||||
|
||||
nlohmann::json json = nlohmann::json::parse(result, nullptr, false);
|
||||
|
||||
if (result == "-1" || result.at(0) != '{' || json.is_discarded()) {
|
||||
spdlog::error("auth.beammp.com failed to respond with valid user details");
|
||||
spdlog::trace("auth.beammp.com/userlogin responded with: {}", result);
|
||||
return std::string("Invalid answer from auth server. Please check your internet connection and see if you can reach https://beammp.com.");
|
||||
}
|
||||
|
||||
try {
|
||||
if (json["success"].get<bool>()) {
|
||||
spdlog::info("{}", json["message"].get<std::string>());
|
||||
ident::Identity id {
|
||||
.PublicKey = json["public_key"].get<std::string>(),
|
||||
.PrivateKey = json["private_key"].get<std::string>(),
|
||||
.Role = json["role"].get<std::string>(),
|
||||
.Username = json["username"].get<std::string>(),
|
||||
.Message = json["message"].get<std::string>(),
|
||||
};
|
||||
if (remember) {
|
||||
cache_key(id.PrivateKey);
|
||||
}
|
||||
return id;
|
||||
} else {
|
||||
spdlog::info("Auto-Authentication unsuccessful please re-login!");
|
||||
return json["message"].is_string() ? json["message"].get<std::string>() : "Unknown error, please log in again.";
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Incomplete or invalid answer from auth servers. Please try logging in again.");
|
||||
spdlog::trace("auth.beammp.com/userlogin responded with incomplete data: {}", result);
|
||||
return std::string("Failed to auto-login with saved details, because the auth server responded with invalid details.");
|
||||
}
|
||||
}
|
||||
33
src/Identity.h
Normal file
33
src/Identity.h
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
#include "Result.h"
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace ident {
|
||||
|
||||
constexpr const char* KEYFILE = "key";
|
||||
|
||||
struct Identity {
|
||||
std::string PublicKey {};
|
||||
std::string PrivateKey {};
|
||||
std::string Role {};
|
||||
std::string Username {};
|
||||
std::string Message {};
|
||||
};
|
||||
|
||||
/// Whether a login is cached / remembered
|
||||
bool is_login_cached() noexcept;
|
||||
|
||||
Result<Identity, std::string> login_cached() noexcept;
|
||||
|
||||
Result<Identity, std::string> login(const std::string& username_or_email, const std::string& password, bool remember);
|
||||
|
||||
namespace detail {
|
||||
|
||||
Result<Identity, std::string> login(const std::string& json_params, bool remember) noexcept;
|
||||
|
||||
void cache_key(const std::string& private_key) noexcept;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
326
src/Launcher.cpp
Normal file
326
src/Launcher.cpp
Normal file
@@ -0,0 +1,326 @@
|
||||
#include "Launcher.h"
|
||||
#include "ClientNetwork.h"
|
||||
#include "Compression.h"
|
||||
#include "Hashing.h"
|
||||
#include "Http.h"
|
||||
#include "Identity.h"
|
||||
#include "Platform.h"
|
||||
#include "ServerNetwork.h"
|
||||
#include "Version.h"
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/iostreams/device/mapped_file.hpp>
|
||||
#include <boost/process.hpp>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <httplib.h>
|
||||
#include <limits>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <vector>
|
||||
|
||||
using namespace boost::asio;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
Launcher::Launcher() {
|
||||
spdlog::debug("Launcher startup");
|
||||
m_config = Config {};
|
||||
if (!m_config->is_valid) {
|
||||
spdlog::error("Launcher config invalid!");
|
||||
}
|
||||
// try logging in immediately, for later update requests and such stuff
|
||||
try_auto_login();
|
||||
|
||||
client_network = std::make_unique<ClientNetwork>(*this, m_config->port);
|
||||
|
||||
m_client_network_thread = boost::scoped_thread<>([&] {
|
||||
client_network->run();
|
||||
});
|
||||
}
|
||||
|
||||
/// Sets shared headers for all backend proxy messages
|
||||
static void proxy_set_headers(httplib::Response& res) {
|
||||
res.set_header("Access-Control-Allow-Origin", "*");
|
||||
res.set_header("Access-Control-Request-Method", "POST, OPTIONS, GET");
|
||||
res.set_header("Access-Control-Request-Headers", "X-API-Version");
|
||||
}
|
||||
|
||||
void Launcher::proxy_main() {
|
||||
httplib::Server HTTPProxy;
|
||||
httplib::Headers headers = {
|
||||
{ "User-Agent", fmt::format("BeamMP-Launcher/{}.{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH) },
|
||||
{ "Accept", "*/*" }
|
||||
};
|
||||
std::string pattern = "/:any1";
|
||||
for (int i = 2; i <= 4; i++) {
|
||||
HTTPProxy.Get(pattern, [&](const httplib::Request& req, httplib::Response& res) {
|
||||
httplib::Client cli("https://backend.beammp.com");
|
||||
proxy_set_headers(res);
|
||||
if (req.has_header("X-BMP-Authentication")) {
|
||||
headers.emplace("X-BMP-Authentication", identity->PrivateKey);
|
||||
}
|
||||
if (req.has_header("X-API-Version")) {
|
||||
headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
|
||||
}
|
||||
if (auto cli_res = cli.Get(req.path, headers); cli_res) {
|
||||
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
|
||||
} else {
|
||||
res.set_content(to_string(cli_res.error()), "text/plain");
|
||||
}
|
||||
});
|
||||
|
||||
HTTPProxy.Post(pattern, [&](const httplib::Request& req, httplib::Response& res) {
|
||||
httplib::Client cli("https://backend.beammp.com");
|
||||
proxy_set_headers(res);
|
||||
if (req.has_header("X-BMP-Authentication")) {
|
||||
headers.emplace("X-BMP-Authentication", identity->PrivateKey);
|
||||
}
|
||||
if (req.has_header("X-API-Version")) {
|
||||
headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
|
||||
}
|
||||
if (auto cli_res = cli.Post(req.path, headers, req.body,
|
||||
req.get_header_value("Content-Type"));
|
||||
cli_res) {
|
||||
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
|
||||
} else {
|
||||
res.set_content(to_string(cli_res.error()), "text/plain");
|
||||
}
|
||||
});
|
||||
pattern += "/:any" + std::to_string(i);
|
||||
}
|
||||
HTTPProxy.listen_after_bind();
|
||||
}
|
||||
|
||||
Launcher::~Launcher() {
|
||||
m_proxy_thread.interrupt();
|
||||
m_game_thread.detach();
|
||||
}
|
||||
|
||||
void Launcher::parse_config() {
|
||||
}
|
||||
|
||||
void Launcher::check_for_updates(int argc, char** argv) {
|
||||
std::string LatestHash = HTTP::Get(fmt::format("https://backend.beammp.com/sha/launcher?branch={}&pk={}", m_config->branch, identity->PublicKey));
|
||||
std::string LatestVersion = HTTP::Get(fmt::format("https://backend.beammp.com/version/launcher?branch={}&pk={}", m_config->branch, identity->PublicKey));
|
||||
std::string DownloadURL = fmt::format("https://backend.beammp.com/builds/launcher?download=true"
|
||||
"&pk={}"
|
||||
"&branch={}",
|
||||
identity->PublicKey, m_config->branch);
|
||||
|
||||
spdlog::debug("Latest hash: {}", LatestHash);
|
||||
spdlog::debug("Latest version: {}", LatestVersion);
|
||||
|
||||
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
|
||||
std::string EP = (m_exe_path.get() / m_exe_name.get()).generic_string();
|
||||
std::string Back = (m_exe_path.get() / "BeamMP-Launcher.back").generic_string();
|
||||
|
||||
std::string FileHash = sha256_file(EP);
|
||||
|
||||
if (FileHash != LatestHash
|
||||
&& Version(PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH).is_outdated(Version(LatestVersion))) {
|
||||
spdlog::info("Launcher update found!");
|
||||
fs::remove(Back);
|
||||
fs::rename(EP, Back);
|
||||
spdlog::info("Downloading Launcher update " + LatestHash);
|
||||
HTTP::Download(DownloadURL, EP);
|
||||
plat::URelaunch(argc, argv);
|
||||
} else {
|
||||
spdlog::info("Launcher version is up to date");
|
||||
}
|
||||
}
|
||||
|
||||
void Launcher::find_game() {
|
||||
// try to find the game by multiple means
|
||||
|
||||
spdlog::info("Locating game");
|
||||
// 0. config!
|
||||
if (!m_config->game_dir.empty()
|
||||
&& std::filesystem::exists(std::filesystem::path(m_config->game_dir) / "BeamNG.drive.exe")) {
|
||||
spdlog::debug("Found game directory in config: '{}'", m_config->game_dir);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. magic
|
||||
auto game_dir = plat::get_game_dir_magically();
|
||||
if (!game_dir.empty()) {
|
||||
m_config->game_dir = game_dir;
|
||||
m_config->write_to_file();
|
||||
return;
|
||||
} else {
|
||||
spdlog::debug("Couldn't magically find game directory");
|
||||
}
|
||||
|
||||
// 2. ask
|
||||
m_config->game_dir = plat::ask_for_folder();
|
||||
|
||||
spdlog::debug("Located game at '{}'", m_config->game_dir);
|
||||
m_config->write_to_file();
|
||||
}
|
||||
|
||||
static std::string check_game_version(const std::filesystem::path& dir) {
|
||||
std::string temp;
|
||||
std::string Path = (dir / "integrity.json").generic_string();
|
||||
boost::iostreams::mapped_file file(Path);
|
||||
auto json = nlohmann::json::parse(file.const_begin(), file.const_end());
|
||||
return json["version"].is_string() ? json["version"].get<std::string>() : "";
|
||||
}
|
||||
|
||||
void Launcher::pre_game() {
|
||||
std::string GameVer = check_game_version(m_config->game_dir);
|
||||
if (GameVer.empty()) {
|
||||
spdlog::error("Game version is empty!");
|
||||
}
|
||||
spdlog::info("Game Version: " + GameVer);
|
||||
|
||||
check_mp((std::filesystem::path(m_config->game_dir) / "mods/multiplayer").generic_string());
|
||||
|
||||
std::string LatestHash = HTTP::Get(fmt::format("https://backend.beammp.com/sha/mod?branch={}&pk={}", m_config->branch, identity->PublicKey));
|
||||
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
|
||||
LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
|
||||
[](auto const& c) -> bool { return !std::isalnum(c); }),
|
||||
LatestHash.end());
|
||||
|
||||
try {
|
||||
if (!fs::exists(std::filesystem::path(m_config->game_dir) / "mods/multiplayer")) {
|
||||
fs::create_directories(std::filesystem::path(m_config->game_dir) / "mods/multiplayer");
|
||||
}
|
||||
enable_mp();
|
||||
} catch (std::exception& e) {
|
||||
spdlog::error("Fatal: {}", e.what());
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
auto ZipPath(std::filesystem::path(m_config->game_dir) / "mods/multiplayer/BeamMP.zip");
|
||||
|
||||
std::string FileHash = sha256_file(ZipPath.generic_string());
|
||||
|
||||
if (FileHash != LatestHash) {
|
||||
spdlog::info("Downloading BeamMP Update " + LatestHash);
|
||||
HTTP::Download(fmt::format("https://backend.beammp.com/builds/client?download=true&pk={}&branch={}", identity->PublicKey, m_config->branch), ZipPath.generic_string());
|
||||
}
|
||||
|
||||
auto Target = std::filesystem::path(m_config->game_dir) / "mods/unpacked/beammp";
|
||||
if (fs::is_directory(Target)) {
|
||||
fs::remove_all(Target);
|
||||
}
|
||||
}
|
||||
|
||||
static size_t count_items_in_dir(const std::filesystem::path& path) {
|
||||
return static_cast<size_t>(std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {}));
|
||||
}
|
||||
|
||||
void Launcher::check_mp(const std::string& path) {
|
||||
if (!fs::exists(path))
|
||||
return;
|
||||
size_t c = count_items_in_dir(fs::path(path));
|
||||
try {
|
||||
for (auto& p : fs::directory_iterator(path)) {
|
||||
if (p.exists() && !p.is_directory()) {
|
||||
std::string name = p.path().filename().string();
|
||||
for (char& Ch : name)
|
||||
Ch = char(tolower(Ch));
|
||||
if (name != "beammp.zip")
|
||||
fs::remove(p.path());
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
spdlog::error("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?");
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
void Launcher::enable_mp() {
|
||||
std::string File = (std::filesystem::path(m_config->game_dir) / "mods/db.json").generic_string();
|
||||
if (!fs::exists(File))
|
||||
return;
|
||||
auto Size = fs::file_size(File);
|
||||
if (Size < 2)
|
||||
return;
|
||||
std::ifstream db(File);
|
||||
if (db.is_open()) {
|
||||
std::string Data(Size, 0);
|
||||
db.read(&Data[0], Size);
|
||||
db.close();
|
||||
nlohmann::json d = nlohmann::json::parse(Data, nullptr, false);
|
||||
if (Data.at(0) != '{' || d.is_discarded()) {
|
||||
// spdlog::error("Failed to parse " + File); //TODO illegal formatting
|
||||
return;
|
||||
}
|
||||
if (d.contains("mods") && d["mods"].contains("multiplayerbeammp")) {
|
||||
d["mods"]["multiplayerbeammp"]["active"] = true;
|
||||
std::ofstream ofs(File);
|
||||
if (ofs.is_open()) {
|
||||
ofs << d.dump();
|
||||
ofs.close();
|
||||
} else {
|
||||
spdlog::error("Failed to write " + File);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void Launcher::game_main() {
|
||||
auto path = std::filesystem::current_path();
|
||||
std::filesystem::current_path(m_config->game_dir);
|
||||
#if defined(PLATFORM_LINUX)
|
||||
auto game_path = (std::filesystem::path(m_config->game_dir) / "BinLinux/BeamNG.drive.x64").generic_string();
|
||||
#elif defined(PLATFORM_WINDOWS)
|
||||
auto game_path = (std::filesystem::path(m_config->game_dir) / "Bin64/BeamNG.drive.x64.exe").generic_string();
|
||||
#endif
|
||||
boost::process::child game(game_path, boost::process::std_out > boost::process::null);
|
||||
std::filesystem::current_path(path);
|
||||
if (game.running()) {
|
||||
spdlog::info("Game launched!");
|
||||
game.wait();
|
||||
spdlog::info("Game closed! Launcher closing soon");
|
||||
} else {
|
||||
spdlog::error("Failed to launch the game! Please start the game manually.");
|
||||
}
|
||||
}
|
||||
|
||||
void Launcher::start_game() {
|
||||
m_game_thread = boost::scoped_thread<>(&Launcher::game_main, this);
|
||||
}
|
||||
void Launcher::try_auto_login() {
|
||||
if (identity->PublicKey.empty() && ident::is_login_cached()) {
|
||||
auto login = ident::login_cached();
|
||||
if (login.has_value()) {
|
||||
*identity = login.value();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result<void, std::string> Launcher::start_server_network(const std::string& host, uint16_t port) {
|
||||
ip::tcp::resolver resolver(m_io);
|
||||
boost::system::error_code ec;
|
||||
auto resolved = resolver.resolve(host, std::to_string(port), ec);
|
||||
if (ec) {
|
||||
spdlog::error("Failed to resolve '{}': {}", host, ec.message());
|
||||
return fmt::format("Failed to resolve '{}': {}", host, ec.message());
|
||||
}
|
||||
bool connected = false;
|
||||
|
||||
for (const auto& addr : resolved) {
|
||||
try {
|
||||
server_network = std::make_unique<ServerNetwork>(*this, addr.endpoint());
|
||||
spdlog::info("Resolved and connected to '[{}]:{}'",
|
||||
addr.endpoint().address().to_string(),
|
||||
addr.endpoint().port());
|
||||
connected = true;
|
||||
break;
|
||||
} catch (...) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (!connected) {
|
||||
spdlog::error("Failed to connect to [{}]:{}", host, port);
|
||||
return fmt::format("Failed to connect to [{}]:{}", host, port);
|
||||
} else {
|
||||
m_server_network_thread = boost::scoped_thread<>([&] {
|
||||
server_network->run();
|
||||
});
|
||||
}
|
||||
return outcome::success();
|
||||
}
|
||||
74
src/Launcher.h
Normal file
74
src/Launcher.h
Normal file
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include "Config.h"
|
||||
#include "Identity.h"
|
||||
#include "Sync.h"
|
||||
#include "Version.h"
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/asio/ip/udp.hpp>
|
||||
#include <boost/thread/scoped_thread.hpp>
|
||||
#include <filesystem>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
class ClientNetwork;
|
||||
class ServerNetwork;
|
||||
|
||||
class Launcher {
|
||||
public:
|
||||
Launcher();
|
||||
~Launcher();
|
||||
|
||||
void check_for_updates(int argc, char** argv);
|
||||
|
||||
void set_exe_name(const std::string& name) { m_exe_name = name; }
|
||||
void set_exe_path(const std::filesystem::path& path) { m_exe_path = path; }
|
||||
|
||||
void find_game();
|
||||
|
||||
void pre_game();
|
||||
|
||||
void start_game();
|
||||
|
||||
std::string get_public_key();
|
||||
|
||||
Sync<ident::Identity> identity {};
|
||||
|
||||
Result<void, std::string> start_server_network(const std::string& host, uint16_t port);
|
||||
|
||||
Sync<Version> mod_version {};
|
||||
Sync<Version> game_version {};
|
||||
|
||||
std::unique_ptr<ClientNetwork> client_network {};
|
||||
std::unique_ptr<ServerNetwork> server_network {};
|
||||
|
||||
private:
|
||||
/// Thread main function for the http(s) proxy thread.
|
||||
void proxy_main();
|
||||
|
||||
/// Thread main function for the game thread.
|
||||
void game_main();
|
||||
|
||||
void parse_config();
|
||||
|
||||
static void check_mp(const std::string& path);
|
||||
|
||||
void enable_mp();
|
||||
|
||||
void try_auto_login();
|
||||
|
||||
Sync<bool> m_mod_loaded { false };
|
||||
|
||||
Sync<Config> m_config;
|
||||
|
||||
boost::scoped_thread<> m_proxy_thread { &Launcher::proxy_main, this };
|
||||
boost::scoped_thread<> m_game_thread;
|
||||
boost::scoped_thread<> m_client_network_thread;
|
||||
boost::scoped_thread<> m_server_network_thread;
|
||||
|
||||
Sync<std::string> m_exe_name;
|
||||
Sync<std::filesystem::path> m_exe_path;
|
||||
boost::asio::io_context m_io {};
|
||||
Sync<bool> m_shutdown { false };
|
||||
};
|
||||
@@ -1,80 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/17/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include "Startup.h"
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <chrono>
|
||||
std::string getDate() {
|
||||
typedef std::chrono::duration<int, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>::type> days;
|
||||
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
|
||||
std::chrono::system_clock::duration tp = now.time_since_epoch();
|
||||
days d = std::chrono::duration_cast<days>(tp);tp -= d;
|
||||
auto h = std::chrono::duration_cast<std::chrono::hours>(tp);tp -= h;
|
||||
auto m = std::chrono::duration_cast<std::chrono::minutes>(tp);tp -= m;
|
||||
auto s = std::chrono::duration_cast<std::chrono::seconds>(tp);tp -= s;
|
||||
time_t tt = std::chrono::system_clock::to_time_t(now);
|
||||
tm local_tm{};
|
||||
localtime_s(&local_tm,&tt);
|
||||
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
|
||||
<< "] ";
|
||||
return date.str();
|
||||
}
|
||||
void InitLog(){
|
||||
std::ofstream LFS;
|
||||
LFS.open (Sec("Launcher.log"));
|
||||
if(!LFS.is_open()){
|
||||
error(Sec("logger file init failed!"));
|
||||
}else LFS.close();
|
||||
}
|
||||
void addToLog(const std::string& Line){
|
||||
std::ofstream LFS;
|
||||
LFS.open(Sec("Launcher.log"), std::ios_base::app);
|
||||
LFS << Line.c_str();
|
||||
LFS.close();
|
||||
}
|
||||
void info(const std::string& toPrint) {
|
||||
std::string Print = getDate() + Sec("[INFO] ") + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void debug(const std::string& toPrint) {
|
||||
if(!Dev)return;
|
||||
std::string Print = getDate() + Sec("[DEBUG] ") + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void warn(const std::string& toPrint){
|
||||
std::string Print = getDate() + Sec("[WARN] ") + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
void error(const std::string& toPrint) {
|
||||
static int ECounter = 0;
|
||||
std::string Print = getDate() + Sec("[ERROR] ") + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
if(ECounter > 10)exit(7);
|
||||
ECounter++;
|
||||
}
|
||||
void except(const std::string& toPrint) {
|
||||
std::string Print = getDate() + Sec("[EXCEP] ") + toPrint + "\n";
|
||||
std::cout << Print;
|
||||
addToLog(Print);
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/5/2020
|
||||
///
|
||||
|
||||
#include "Memory.hpp"
|
||||
#include <iostream>
|
||||
#include <utility>
|
||||
|
||||
|
||||
int Memory::GetProcessId(const std::string& processName) {
|
||||
SetLastError(0);
|
||||
PROCESSENTRY32 pe32;
|
||||
HANDLE hSnapshot = nullptr;
|
||||
GetLastError();
|
||||
pe32.dwSize = sizeof(PROCESSENTRY32);
|
||||
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
|
||||
if(Process32First(hSnapshot,&pe32)) {
|
||||
do {
|
||||
if(processName == pe32.szExeFile)
|
||||
break;
|
||||
} while(Process32Next(hSnapshot, &pe32));
|
||||
}
|
||||
|
||||
if(hSnapshot != INVALID_HANDLE_VALUE)
|
||||
CloseHandle(hSnapshot);
|
||||
int err = GetLastError();
|
||||
|
||||
if (err != 0)
|
||||
return 0;
|
||||
return pe32.th32ProcessID;
|
||||
}
|
||||
|
||||
long long Memory::GetModuleBase(HANDLE processHandle, const std::string &sModuleName){
|
||||
HMODULE *hModules = nullptr;
|
||||
char szBuf[50];
|
||||
DWORD cModules;
|
||||
long long dwBase = -1;
|
||||
|
||||
EnumProcessModulesEx(processHandle, hModules, 0, &cModules,LIST_MODULES_ALL);
|
||||
hModules = new HMODULE[cModules/sizeof(HMODULE)];
|
||||
|
||||
if(EnumProcessModulesEx(processHandle, hModules, cModules/sizeof(HMODULE), &cModules,LIST_MODULES_ALL)) {
|
||||
for(size_t i = 0; i < cModules/sizeof(HMODULE); i++) {
|
||||
if(GetModuleBaseName(processHandle, hModules[i], szBuf, sizeof(szBuf))) {
|
||||
if(sModuleName == szBuf) {
|
||||
dwBase = (long long)hModules[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delete[] hModules;
|
||||
return dwBase;
|
||||
}
|
||||
|
||||
void PrintAllBases(HANDLE processHandle){
|
||||
HMODULE *hModules = nullptr;
|
||||
char szBuf[50];
|
||||
DWORD cModules;
|
||||
EnumProcessModulesEx(processHandle, hModules, 0, &cModules,LIST_MODULES_ALL);
|
||||
hModules = new HMODULE[cModules/sizeof(HMODULE)];
|
||||
if(EnumProcessModulesEx(processHandle, hModules, cModules/sizeof(HMODULE), &cModules,LIST_MODULES_ALL)) {
|
||||
for(size_t i = 0; i < cModules/sizeof(HMODULE); i++) {
|
||||
if(GetModuleBaseName(processHandle, hModules[i], szBuf, sizeof(szBuf))) {
|
||||
if(hModules[i] != nullptr){
|
||||
std::cout << szBuf << " : " << hModules[i] << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete[] hModules;
|
||||
}
|
||||
|
||||
BOOL Memory::SetPrivilege(HANDLE hToken, LPCTSTR lpszPrivilege, BOOL bEnablePrivilege){
|
||||
TOKEN_PRIVILEGES tp;
|
||||
LUID luid;
|
||||
|
||||
if (!LookupPrivilegeValue(nullptr, lpszPrivilege, &luid)) {
|
||||
//printf("LookupPrivilegeValue error: %u\n", GetLastError() );
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
tp.PrivilegeCount = 1;
|
||||
tp.Privileges[0].Luid = luid;
|
||||
if (bEnablePrivilege)
|
||||
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
|
||||
else
|
||||
tp.Privileges[0].Attributes = 0;
|
||||
|
||||
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) nullptr, (PDWORD) nullptr)) {
|
||||
//printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
|
||||
//printf("The token does not have the specified privilege. \n");
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
BOOL Memory::GetDebugPrivileges() {
|
||||
HANDLE hToken = nullptr;
|
||||
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
|
||||
return FALSE; //std::cout << "OpenProcessToken() failed, error\n>> " << GetLastError() << std::endl;
|
||||
//else std::cout << "OpenProcessToken() is OK, got the handle!" << std::endl;
|
||||
|
||||
if(!SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
|
||||
return FALSE; //std::cout << "Failed to enable privilege, error:\n>> " << GetLastError() << std::endl;
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
int Memory::ReadInt(HANDLE processHandle, long long address) {
|
||||
if (address == -1)
|
||||
return -1;
|
||||
int buffer = 0;
|
||||
SIZE_T NumberOfBytesToRead = sizeof(buffer); //this is equal to 4
|
||||
SIZE_T NumberOfBytesActuallyRead;
|
||||
BOOL success = ReadProcessMemory(processHandle, (LPCVOID)address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
|
||||
if (!success || NumberOfBytesActuallyRead != NumberOfBytesToRead) {
|
||||
//std::cout << "Memory Error!" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
long long Memory::ReadLong(HANDLE processHandle, long long address) {
|
||||
if (address == -1)
|
||||
return -1;
|
||||
long long buffer = 0;
|
||||
SIZE_T NumberOfBytesToRead = sizeof(buffer);
|
||||
SIZE_T NumberOfBytesActuallyRead;
|
||||
BOOL success = ReadProcessMemory(processHandle, (LPCVOID)address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
|
||||
if (!success || NumberOfBytesActuallyRead != NumberOfBytesToRead) {
|
||||
//std::cout << "Memory Error!" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
int Memory::GetPointerAddress(HANDLE processHandle, long long startAddress, int offsets[], int offsetCount) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
int ptr = ReadInt(processHandle, startAddress);
|
||||
for (int i=0; i<offsetCount-1; i++) {
|
||||
ptr+=offsets[i];
|
||||
ptr = ReadInt(processHandle, ptr);
|
||||
}
|
||||
ptr+=offsets[offsetCount-1];
|
||||
return ptr;
|
||||
}
|
||||
long long Memory::GetPointerAddressLong(HANDLE processHandle, long long startAddress, std::vector<int> offsets) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
long long ptr = ReadLong(processHandle, startAddress);
|
||||
for (int i=0; i< offsets.size()-1; i++) {
|
||||
ptr+=offsets[i];
|
||||
ptr = ReadLong(processHandle, ptr);
|
||||
}
|
||||
ptr+=offsets[offsets.size()-1];
|
||||
return ptr;
|
||||
}
|
||||
int Memory::ReadPointerInt(HANDLE processHandle, long long startAddress, std::vector<int> offsets) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
return ReadInt(processHandle, GetPointerAddressLong(processHandle, startAddress, std::move(offsets)));
|
||||
}
|
||||
long long Memory::ReadPointerLong(HANDLE processHandle, long long startAddress, std::vector<int> offsets) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
return ReadLong(processHandle, GetPointerAddressLong(processHandle, startAddress, std::move(offsets)));
|
||||
}
|
||||
|
||||
float Memory::ReadFloat(HANDLE processHandle, long long address) {
|
||||
if (address == -1)
|
||||
return -1;
|
||||
float buffer = 0.0;
|
||||
SIZE_T NumberOfBytesToRead = sizeof(buffer); //this is equal to 4
|
||||
SIZE_T NumberOfBytesActuallyRead;
|
||||
BOOL success = ReadProcessMemory(processHandle, (LPCVOID)address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
|
||||
if (!success || NumberOfBytesActuallyRead != NumberOfBytesToRead)
|
||||
return -1;
|
||||
return buffer;
|
||||
}
|
||||
void Memory::WriteFloat(HANDLE processHandle, long long address,float Value) {
|
||||
if (address == -1)
|
||||
return;
|
||||
SIZE_T NumberOfBytesToWrite = sizeof(Value); //this is equal to 4
|
||||
SIZE_T NumberOfBytesWritten;
|
||||
BOOL Write = WriteProcessMemory(processHandle, LPVOID(address), &Value, NumberOfBytesToWrite, &NumberOfBytesWritten);
|
||||
}
|
||||
double Memory::ReadDouble(HANDLE processHandle, long long address) {
|
||||
if (address == -1)
|
||||
return -1;
|
||||
double buffer = 0.0;
|
||||
SIZE_T NumberOfBytesToRead = sizeof(buffer); //this is equal to 8
|
||||
SIZE_T NumberOfBytesActuallyRead;
|
||||
BOOL success = ReadProcessMemory(processHandle, (LPCVOID)address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
|
||||
if (!success || NumberOfBytesActuallyRead != NumberOfBytesToRead)
|
||||
return -1;
|
||||
return buffer;
|
||||
}
|
||||
float Memory::ReadPointerFloat(HANDLE processHandle, long long startAddress, std::vector<int> offsets) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
return ReadFloat(processHandle, GetPointerAddressLong(processHandle, startAddress, std::move(offsets)));
|
||||
}
|
||||
double Memory::ReadPointerDouble(HANDLE processHandle, long long startAddress, int offsets[], int offsetCount) {
|
||||
if (startAddress == -1)
|
||||
return -1;
|
||||
return ReadDouble(processHandle, GetPointerAddress(processHandle, startAddress, offsets, offsetCount));
|
||||
}
|
||||
std::string Memory::ReadText(HANDLE processHandle, long long address) {
|
||||
if (address == -1)
|
||||
return "-1";
|
||||
char buffer = 1;
|
||||
char* stringToRead = new char[128];
|
||||
SIZE_T NumberOfBytesToRead = sizeof(buffer);
|
||||
SIZE_T NumberOfBytesActuallyRead;
|
||||
int i = 0;
|
||||
while (buffer != 0) {
|
||||
BOOL success = ReadProcessMemory(processHandle, (LPCVOID)address, &buffer, NumberOfBytesToRead, &NumberOfBytesActuallyRead);
|
||||
if (!success || NumberOfBytesActuallyRead != NumberOfBytesToRead)
|
||||
return "-1";
|
||||
stringToRead[i] = buffer;
|
||||
i++;
|
||||
address++;
|
||||
}
|
||||
return stringToRead;
|
||||
}
|
||||
std::string Memory::ReadPointerText(HANDLE processHandle, long long startAddress, std::vector<int> offsets) {
|
||||
if (startAddress == -1)
|
||||
return "-1";
|
||||
return ReadText(processHandle, GetPointerAddressLong(processHandle, startAddress, std::move(offsets)));
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/5/2020
|
||||
///
|
||||
|
||||
#pragma once
|
||||
#include <Windows.h>
|
||||
#include <TlHelp32.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <psapi.h>
|
||||
|
||||
class Memory{
|
||||
public:
|
||||
DWORD PID = 0;
|
||||
int GetProcessId(const std::string& processName);
|
||||
long long ReadLong(HANDLE processHandle, long long address);
|
||||
long long ReadPointerLong(HANDLE processHandle, long long startAddress, std::vector<int> offsets);
|
||||
long long GetPointerAddressLong(HANDLE processHandle, long long startAddress, std::vector<int> offsets);
|
||||
long long GetModuleBase(HANDLE processHandle, const std::string&sModuleName);
|
||||
BOOL SetPrivilege(HANDLE hToken, LPCTSTR lpszPrivilege, BOOL bEnablePrivilege);
|
||||
BOOL GetDebugPrivileges();
|
||||
int ReadInt(HANDLE processHandle, long long address);
|
||||
int GetPointerAddress(HANDLE processHandle, long long startAddress, int offsets[], int offsetCount);
|
||||
int ReadPointerInt(HANDLE processHandle, long long startAddress, std::vector<int> offsets);
|
||||
float ReadFloat(HANDLE processHandle, long long address);
|
||||
void WriteFloat(HANDLE processHandle, long long address,float Value);
|
||||
double ReadDouble(HANDLE processHandle, long long address);
|
||||
float ReadPointerFloat(HANDLE processHandle, long long startAddress, std::vector<int> offsets);
|
||||
double ReadPointerDouble(HANDLE processHandle, long long startAddress, int offsets[], int offsetCount);
|
||||
std::string ReadText(HANDLE processHandle, long long address);
|
||||
std::string ReadPointerText(HANDLE processHandle, long long startAddress, std::vector<int> offsets);
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 6/17/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Game.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Memory.hpp"
|
||||
#include "Startup.h"
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
Memory Game;
|
||||
std::string GameVer(HANDLE processHandle, long long Address){
|
||||
//lib_Beam
|
||||
Address += 0x1B0688;
|
||||
std::vector<int> Off = {0x0,0xBF0};
|
||||
return Game.ReadPointerText(processHandle,Address,Off);
|
||||
}
|
||||
std::string LoadedMap(HANDLE processHandle, long long Address){
|
||||
//lib_Beam
|
||||
//History : 0x1B0688
|
||||
Address += 0x1A1668;
|
||||
std::vector<int> Off = {0x140,0x0};
|
||||
return Game.ReadPointerText(processHandle,Address,Off);
|
||||
}
|
||||
std::string Tolower(std::string data){
|
||||
for(char&c : data){
|
||||
c = char(tolower(c));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
void MemoryInit(){
|
||||
if(Dev)return;
|
||||
Game.PID = GamePID;
|
||||
if(Game.PID == 0)exit(4);
|
||||
HANDLE processHandle;
|
||||
long long ExeBase; //BeamNG.drive.x64.exe
|
||||
long long Lib1 = 0x180000000; //libbeamng.x64.dll Contains Vehicle Data
|
||||
Game.GetDebugPrivileges();
|
||||
processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, Game.PID);
|
||||
ExeBase = Game.GetModuleBase(processHandle, "BeamNG.drive.x64.exe");
|
||||
|
||||
std::string Map,Temp;
|
||||
while(true){
|
||||
Map = LoadedMap(processHandle,Lib1);
|
||||
if(!Map.empty() && Map != "-1" && Map.find("/info.json") != -1 && Map != Temp){
|
||||
if(Tolower(MStatus).find(Tolower(Map)) == -1){
|
||||
exit(5);
|
||||
}
|
||||
Temp = Map;
|
||||
}
|
||||
Map.clear();
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/20/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Curl/http.h"
|
||||
#include <WinSock2.h>
|
||||
#include <WS2tcpip.h>
|
||||
#include "Startup.h"
|
||||
#include "Memory.h"
|
||||
#include "Logger.h"
|
||||
#include <charconv>
|
||||
#include <thread>
|
||||
#include <set>
|
||||
|
||||
extern int TraceBack;
|
||||
std::set<std::string>* ConfList = nullptr;
|
||||
bool TCPTerminate = false;
|
||||
int DEFAULT_PORT = 4444;
|
||||
bool Terminate = false;
|
||||
std::string UlStatus;
|
||||
std::string MStatus;
|
||||
bool once = false;
|
||||
bool ModLoaded;
|
||||
long long ping = -1;
|
||||
|
||||
void StartSync(const std::string &Data){
|
||||
std::string IP = GetAddr(Data.substr(1,Data.find(':')-1));
|
||||
if(IP.find('.') == -1){
|
||||
if(IP == "DNS")UlStatus = Sec("UlConnection Failed! (DNS Lookup Failed)");
|
||||
else UlStatus = Sec("UlConnection Failed! (WSA failed to start)");
|
||||
ListOfMods = "-";
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
UlStatus = Sec("UlLoading...");
|
||||
TCPTerminate = false;
|
||||
Terminate = false;
|
||||
ConfList->clear();
|
||||
ping = -1;
|
||||
std::thread GS(TCPGameServer,IP,std::stoi(Data.substr(Data.find(':')+1)));
|
||||
GS.detach();
|
||||
info(Sec("Connecting to server"));
|
||||
}
|
||||
void Parse(std::string Data,SOCKET CSocket){
|
||||
char Code = Data.at(0), SubCode = 0;
|
||||
if(Data.length() > 1)SubCode = Data.at(1);
|
||||
switch (Code){
|
||||
case 'A':
|
||||
Data = Data.substr(0,1);
|
||||
break;
|
||||
case 'B':
|
||||
NetReset();
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
Data = Code + HTTP_REQUEST(Sec("https://beammp.com/servers-info"),443);
|
||||
break;
|
||||
case 'C':
|
||||
ListOfMods.clear();
|
||||
StartSync(Data);
|
||||
while(ListOfMods.empty() && !Terminate){
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
if(ListOfMods == "-")Data = "L";
|
||||
else Data = "L"+ListOfMods;
|
||||
break;
|
||||
case 'U':
|
||||
if(SubCode == 'l')Data = UlStatus;
|
||||
if(SubCode == 'p'){
|
||||
if(ping > 800){
|
||||
Data = "Up-2";
|
||||
}else Data = "Up" + std::to_string(ping);
|
||||
}
|
||||
if(!SubCode){
|
||||
std::string Ping;
|
||||
if(ping > 800)Ping = "-2";
|
||||
else Ping = std::to_string(ping);
|
||||
Data = std::string(UlStatus) + "\n" + "Up" + Ping;
|
||||
}
|
||||
break;
|
||||
case 'M':
|
||||
Data = MStatus;
|
||||
break;
|
||||
case 'Q':
|
||||
if(SubCode == 'S'){
|
||||
NetReset();
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
ping = -1;
|
||||
}
|
||||
if(SubCode == 'G')exit(2);
|
||||
Data.clear();
|
||||
break;
|
||||
case 'R': //will send mod name
|
||||
if(ConfList->find(Data) == ConfList->end()){
|
||||
ConfList->insert(Data);
|
||||
ModLoaded = true;
|
||||
}
|
||||
Data.clear();
|
||||
break;
|
||||
case 'Z':
|
||||
Data = "Z" + GetVer();
|
||||
break;
|
||||
default:
|
||||
Data.clear();
|
||||
break;
|
||||
}
|
||||
if(!Data.empty() && CSocket != -1){
|
||||
int res = send(CSocket, (Data+"\n").c_str(), int(Data.size())+1, 0);
|
||||
if(res < 0){
|
||||
debug(Sec("(Core) send failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
}
|
||||
}
|
||||
void GameHandler(SOCKET Client){
|
||||
if (!once){
|
||||
std::thread Memory(MemoryInit);
|
||||
Memory.detach();
|
||||
once = true;
|
||||
}
|
||||
//Read byte by byte until '>' is rcved then get the size and read based on it
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
do{
|
||||
Rcv = 0;
|
||||
do{
|
||||
Temp = recv(Client,&Header[Rcv],1,0);
|
||||
if(Temp < 1)break;
|
||||
if(!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
|
||||
error(Sec("(Core) Invalid lua communication"));
|
||||
KillSocket(Client);
|
||||
return;
|
||||
}
|
||||
}while(Header[Rcv++] != '>');
|
||||
if(Temp < 1)break;
|
||||
if(std::from_chars(Header,&Header[Rcv],Size).ptr[0] != '>'){
|
||||
debug(Sec("(Core) Invalid lua Header -> ") + std::string(Header,Rcv));
|
||||
break;
|
||||
}
|
||||
std::string Ret(Size,0);
|
||||
Rcv = 0;
|
||||
|
||||
do{
|
||||
Temp = recv(Client,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size);
|
||||
if(Temp < 1)break;
|
||||
|
||||
std::thread Respond(Parse, Ret, Client);
|
||||
Respond.detach();
|
||||
}while(Temp > 0);
|
||||
if (Temp == 0) {
|
||||
debug(Sec("(Core) Connection closing"));
|
||||
} else {
|
||||
debug(Sec("(Core) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
NetReset();
|
||||
KillSocket(Client);
|
||||
}
|
||||
void localRes(){
|
||||
MStatus = " ";
|
||||
UlStatus = Sec("Ulstart");
|
||||
if(ConfList != nullptr){
|
||||
ConfList->clear();
|
||||
delete ConfList;
|
||||
ConfList = nullptr;
|
||||
}
|
||||
ConfList = new std::set<std::string>;
|
||||
}
|
||||
void CoreMain() {
|
||||
debug(Sec("Core Network on start!"));
|
||||
WSADATA wsaData;
|
||||
SOCKET LSocket,CSocket;
|
||||
struct addrinfo *res = nullptr;
|
||||
struct addrinfo hints{};
|
||||
int iRes = WSAStartup(514, &wsaData); //2.2
|
||||
if (iRes)debug(Sec("WSAStartup failed with error: ") + std::to_string(iRes));
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
iRes = getaddrinfo(nullptr, std::to_string(DEFAULT_PORT).c_str(), &hints, &res);
|
||||
if (iRes){
|
||||
debug(Sec("(Core) addr info failed with error: ") + std::to_string(iRes));
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
LSocket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (LSocket == -1){
|
||||
debug(Sec("(Core) socket failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
iRes = bind(LSocket, res->ai_addr, int(res->ai_addrlen));
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error(Sec("(Core) bind failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
iRes = listen(LSocket, SOMAXCONN);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
debug(Sec("(Core) listen failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(res);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
do{
|
||||
CSocket = accept(LSocket, nullptr, nullptr);
|
||||
if (CSocket == -1) {
|
||||
error(Sec("(Core) accept failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
continue;
|
||||
}
|
||||
localRes();
|
||||
info(Sec("Game Connected!"));
|
||||
GameHandler(CSocket);
|
||||
warn(Sec("Game Reconnecting..."));
|
||||
}while(CSocket);
|
||||
KillSocket(LSocket);
|
||||
WSACleanup();
|
||||
}
|
||||
int Handle(EXCEPTION_POINTERS *ep){
|
||||
char* hex = new char[100];
|
||||
sprintf_s(hex,100, "%lX", ep->ExceptionRecord->ExceptionCode);
|
||||
except(Sec("(Core) Code : ") + std::string(hex));
|
||||
delete [] hex;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
void CoreNetwork(){
|
||||
while(TraceBack >= 4){
|
||||
__try{
|
||||
CoreMain();
|
||||
}__except(Handle(GetExceptionInformation())){}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 9/25/2020
|
||||
///
|
||||
|
||||
#include <string>
|
||||
#include <winsock.h>
|
||||
#include "Logger.h"
|
||||
#include "Security/Enc.h"
|
||||
std::string GetAddr(const std::string&IP){
|
||||
if(IP.find_first_not_of("0123456789.") == -1)return IP;
|
||||
WSADATA wsaData;
|
||||
hostent *host;
|
||||
if(WSAStartup(514, &wsaData) != 0){
|
||||
error(Sec("WSA Startup Failed!"));
|
||||
WSACleanup();
|
||||
return "";
|
||||
}
|
||||
host = gethostbyname(IP.c_str());
|
||||
if(!host){
|
||||
error(Sec("DNS lookup failed! on ") + IP);
|
||||
WSACleanup();
|
||||
return "DNS";
|
||||
}
|
||||
std::string Ret = inet_ntoa(*((struct in_addr *)host->h_addr));
|
||||
WSACleanup();
|
||||
return Ret;
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/25/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <WinSock2.h>
|
||||
#include <WS2tcpip.h>
|
||||
#include "Logger.h"
|
||||
#include <charconv>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
|
||||
std::chrono::time_point<std::chrono::steady_clock> PingStart,PingEnd;
|
||||
bool GConnected = false;
|
||||
bool CServer = true;
|
||||
extern SOCKET UDPSock;
|
||||
extern SOCKET TCPSock;
|
||||
SOCKET CSocket = -1;
|
||||
SOCKET GSocket = -1;
|
||||
|
||||
int KillSocket(uint64_t Dead){
|
||||
if(Dead == (SOCKET)-1){
|
||||
debug(Sec("Kill socket got -1 returning..."));
|
||||
return 0;
|
||||
}
|
||||
shutdown(Dead,SD_BOTH);
|
||||
int a = closesocket(Dead);
|
||||
if(a != 0){
|
||||
warn(Sec("Failed to close socket!"));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
bool CheckBytes(uint32_t Bytes){
|
||||
if(Bytes == 0){
|
||||
debug(Sec("(Proxy) Connection closing"));
|
||||
return false;
|
||||
}else if(Bytes < 0){
|
||||
debug(Sec("(Proxy) send failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void GameSend(std::string Data){
|
||||
static std::mutex Lock;
|
||||
std::scoped_lock Guard(Lock);
|
||||
if(TCPTerminate || !GConnected || CSocket == -1)return;
|
||||
int32_t Size,Temp,Sent;
|
||||
Data += '\n';
|
||||
Size = int32_t(Data.size());
|
||||
Sent = 0;
|
||||
#ifdef DEBUG
|
||||
if(Size > 1000){
|
||||
debug("Launcher -> game (" +std::to_string(Size)+")");
|
||||
}
|
||||
#endif
|
||||
do{
|
||||
if(Sent > -1){
|
||||
Temp = send(CSocket, &Data[Sent], Size - Sent, 0);
|
||||
}
|
||||
if(!CheckBytes(Temp))return;
|
||||
Sent += Temp;
|
||||
}while(Sent < Size);
|
||||
}
|
||||
void ServerSend(std::string Data, bool Rel){
|
||||
if(Terminate || Data.empty())return;
|
||||
if(Data.find("Zp") != std::string::npos && Data.size() > 500){
|
||||
abort();
|
||||
}
|
||||
char C = 0;
|
||||
bool Ack = false;
|
||||
int DLen = int(Data.length());
|
||||
if(DLen > 3)C = Data.at(0);
|
||||
if (C == 'O' || C == 'T')Ack = true;
|
||||
if(C == 'W' || C == 'Y' || C == 'V' || C == 'E')Rel = true;
|
||||
if(Ack || Rel){
|
||||
if(Ack || DLen > 1000)SendLarge(Data);
|
||||
else TCPSend(Data);
|
||||
}else UDPSend(Data);
|
||||
|
||||
if (DLen > 1000) {
|
||||
debug(Sec("(Launcher->Server) Bytes sent: ") + std::to_string(Data.length()) + " : "
|
||||
+ Data.substr(0, 10)
|
||||
+ Data.substr(Data.length() - 10));
|
||||
}else if(C == 'Z'){
|
||||
//debug("(Game->Launcher) : " + Data);
|
||||
}
|
||||
}
|
||||
|
||||
void NetReset(){
|
||||
TCPTerminate = false;
|
||||
GConnected = false;
|
||||
Terminate = false;
|
||||
UlStatus = Sec("Ulstart");
|
||||
MStatus = " ";
|
||||
if(UDPSock != (SOCKET)(-1)){
|
||||
debug(Sec("Terminating UDP Socket : ") + std::to_string(TCPSock));
|
||||
KillSocket(UDPSock);
|
||||
}
|
||||
UDPSock = -1;
|
||||
if(TCPSock != (SOCKET)(-1)){
|
||||
debug(Sec("Terminating TCP Socket : ") + std::to_string(TCPSock));
|
||||
KillSocket(TCPSock);
|
||||
}
|
||||
TCPSock = -1;
|
||||
if(GSocket != (SOCKET)(-1)){
|
||||
debug(Sec("Terminating GTCP Socket : ") + std::to_string(GSocket));
|
||||
KillSocket(GSocket);
|
||||
}
|
||||
GSocket = -1;
|
||||
ClearAll();
|
||||
}
|
||||
|
||||
SOCKET SetupListener(){
|
||||
if(GSocket != -1)return GSocket;
|
||||
struct addrinfo *result = nullptr;
|
||||
struct addrinfo hints{};
|
||||
WSADATA wsaData;
|
||||
int iRes = WSAStartup(514, &wsaData); //2.2
|
||||
if (iRes != 0) {
|
||||
error(Sec("(Proxy) WSAStartup failed with error: ") + std::to_string(iRes));
|
||||
return -1;
|
||||
}
|
||||
ZeroMemory(&hints, sizeof(hints));
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
hints.ai_flags = AI_PASSIVE;
|
||||
iRes = getaddrinfo(nullptr, std::to_string(DEFAULT_PORT+1).c_str(), &hints, &result);
|
||||
if (iRes != 0) {
|
||||
error(Sec("(Proxy) info failed with error: ") + std::to_string(iRes));
|
||||
WSACleanup();
|
||||
}
|
||||
GSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
|
||||
if (GSocket == -1) {
|
||||
error(Sec("(Proxy) socket failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(result);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
iRes = bind(GSocket, result->ai_addr, (int) result->ai_addrlen);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error(Sec("(Proxy) bind failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
freeaddrinfo(result);
|
||||
KillSocket(GSocket);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
freeaddrinfo(result);
|
||||
iRes = listen(GSocket, SOMAXCONN);
|
||||
if (iRes == SOCKET_ERROR) {
|
||||
error(Sec("(Proxy) listen failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
KillSocket(GSocket);
|
||||
WSACleanup();
|
||||
return -1;
|
||||
}
|
||||
return GSocket;
|
||||
}
|
||||
void AutoPing(){
|
||||
while(!Terminate){
|
||||
ServerSend(Sec("p"),false);
|
||||
PingStart = std::chrono::high_resolution_clock::now();
|
||||
std::this_thread::sleep_for(std::chrono::seconds (1));
|
||||
}
|
||||
}
|
||||
int ClientID = -1;
|
||||
void ParserAsync(const std::string& Data){
|
||||
if(Data.empty())return;
|
||||
char Code = Data.at(0),SubCode = 0;
|
||||
if(Data.length() > 1)SubCode = Data.at(1);
|
||||
switch (Code) {
|
||||
case 'P':
|
||||
ClientID = std::stoi(Data.substr(1));
|
||||
break;
|
||||
case 'p':
|
||||
PingEnd = std::chrono::high_resolution_clock::now();
|
||||
if(PingStart > PingEnd)ping = 0;
|
||||
else ping = std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd-PingStart).count();
|
||||
return;
|
||||
case 'M':
|
||||
MStatus = Data;
|
||||
UlStatus = Sec("Uldone");
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
GameSend(Data);
|
||||
}
|
||||
void ServerParser(const std::string& Data){
|
||||
ParserAsync(Data);
|
||||
}
|
||||
void NetMain(const std::string& IP, int Port){
|
||||
std::thread Ping(AutoPing);
|
||||
Ping.detach();
|
||||
UDPClientMain(IP,Port);
|
||||
CServer = true;
|
||||
Terminate = true;
|
||||
info(Sec("Connection Terminated!"));
|
||||
}
|
||||
void TCPGameServer(const std::string& IP, int Port){
|
||||
GSocket = SetupListener();
|
||||
FindDLL(nullptr);
|
||||
while (!TCPTerminate && GSocket != -1){
|
||||
debug(Sec("MAIN LOOP OF GAME SERVER"));
|
||||
GConnected = false;
|
||||
if(!CServer){
|
||||
warn(Sec("Connection still alive terminating"));
|
||||
NetReset();
|
||||
TCPTerminate = true;
|
||||
Terminate = true;
|
||||
break;
|
||||
}
|
||||
if(CServer) {
|
||||
std::thread Client(TCPClientMain, IP, Port);
|
||||
Client.detach();
|
||||
}
|
||||
CSocket = accept(GSocket, nullptr, nullptr);
|
||||
if (CSocket == -1) {
|
||||
debug(Sec("(Proxy) accept failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
break;
|
||||
}
|
||||
debug(Sec("(Proxy) Game Connected!"));
|
||||
GConnected = true;
|
||||
if(CServer){
|
||||
std::thread t1(NetMain, IP, Port);
|
||||
t1.detach();
|
||||
CServer = false;
|
||||
}
|
||||
int32_t Size,Temp,Rcv;
|
||||
char Header[10] = {0};
|
||||
|
||||
//Read byte by byte until '>' is rcved then get the size and read based on it
|
||||
do{
|
||||
Rcv = 0;
|
||||
|
||||
do{
|
||||
Temp = recv(CSocket,&Header[Rcv],1,0);
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
}while(Header[Rcv++] != '>');
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
if(std::from_chars(Header,&Header[Rcv],Size).ptr[0] != '>'){
|
||||
debug(Sec("(Game) Invalid lua Header -> ") + std::string(Header,Rcv));
|
||||
break;
|
||||
}
|
||||
std::string Ret(Size,0);
|
||||
Rcv = 0;
|
||||
do{
|
||||
Temp = recv(CSocket,&Ret[Rcv],Size-Rcv,0);
|
||||
if(Temp < 1)break;
|
||||
Rcv += Temp;
|
||||
}while(Rcv < Size && !TCPTerminate);
|
||||
if(Temp < 1 || TCPTerminate)break;
|
||||
|
||||
ServerSend(Ret,false);
|
||||
|
||||
}while(Temp > 0 && !TCPTerminate);
|
||||
if(Temp == 0)debug(Sec("(Proxy) Connection closing"));
|
||||
else debug(Sec("(Proxy) recv failed error : ") + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
TCPTerminate = true;
|
||||
GConnected = false;
|
||||
Terminate = true;
|
||||
if(CSocket != SOCKET_ERROR)KillSocket(CSocket);
|
||||
debug(Sec("END OF GAME SERVER"));
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
|
||||
#include "Security/Game.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <curl/curl.h>
|
||||
#include <iostream>
|
||||
#include "Logger.h"
|
||||
#include <mutex>
|
||||
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 HTTP_REQUEST(const std::string& IP,int port){
|
||||
static std::mutex Lock;
|
||||
Lock.lock();
|
||||
CURL *curl;
|
||||
CURLcode res;
|
||||
std::string readBuffer;
|
||||
curl = curl_easy_init();
|
||||
if(curl) {
|
||||
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_PORT, port);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
||||
res = curl_easy_perform(curl);
|
||||
curl_easy_cleanup(curl);
|
||||
if(res != CURLE_OK)return "-1";
|
||||
}
|
||||
Lock.unlock();
|
||||
return readBuffer;
|
||||
}
|
||||
|
||||
int nb_bar;
|
||||
double last_progress, progress_bar_adv;
|
||||
int progress_bar (void *bar, double t, double d){
|
||||
if(last_progress != round(d/t*100)){
|
||||
nb_bar = 25;
|
||||
progress_bar_adv = round(d/t*nb_bar);
|
||||
std::cout<<"\r";
|
||||
std::cout<<Sec("Progress : [ ");
|
||||
if(t!=0)std::cout<<round(d/t*100);else std::cout<<0;
|
||||
std::cout << "% ] [";
|
||||
int i;
|
||||
for(i = 0; i <= progress_bar_adv; i++)std::cout<<"#";
|
||||
for(i = 0; i < nb_bar - progress_bar_adv; i++)std::cout<<".";
|
||||
std::cout<<"]";
|
||||
last_progress = round(d/t*100);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
struct File {
|
||||
const char *filename;
|
||||
FILE *stream;
|
||||
};
|
||||
static size_t my_fwrite(void *buffer,size_t size,size_t nmemb,void *stream){
|
||||
auto *out = (struct File*)stream;
|
||||
if(!out->stream) {
|
||||
fopen_s(&out->stream,out->filename,Sec("wb"));
|
||||
if(!out->stream)return -1;
|
||||
}
|
||||
return fwrite(buffer, size, nmemb, out->stream);
|
||||
}
|
||||
int Download(const std::string& URL,const std::string& Path,bool close){
|
||||
CURL *curl;
|
||||
CURLcode res;
|
||||
struct File file = {Path.c_str(),nullptr};
|
||||
curl = curl_easy_init();
|
||||
if(curl){
|
||||
curl_easy_setopt(curl, CURLOPT_URL,URL.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &file);
|
||||
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
|
||||
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_bar);
|
||||
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
|
||||
res = curl_easy_perform(curl);
|
||||
curl_easy_cleanup(curl);
|
||||
if(res != CURLE_OK)return res;
|
||||
}
|
||||
if(file.stream)fclose(file.stream);
|
||||
if(!close)SecureMods();
|
||||
std::cout << std::endl;
|
||||
return -1;
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 4/11/2020
|
||||
///
|
||||
#include "Discord/discord_info.h"
|
||||
#include "Network/network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <WS2tcpip.h>
|
||||
#include <filesystem>
|
||||
#include "Startup.h"
|
||||
#include <algorithm>
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
|
||||
|
||||
|
||||
namespace fs = std::experimental::filesystem;
|
||||
std::string ListOfMods;
|
||||
std::vector<std::string> Split(const std::string& String,const std::string& delimiter){
|
||||
std::vector<std::string> Val;
|
||||
size_t pos;
|
||||
std::string token,s = String;
|
||||
while ((pos = s.find(delimiter)) != std::string::npos) {
|
||||
token = s.substr(0, pos);
|
||||
if(!token.empty())Val.push_back(token);
|
||||
s.erase(0, pos + delimiter.length());
|
||||
}
|
||||
if(!s.empty())Val.push_back(s);
|
||||
return Val;
|
||||
}
|
||||
|
||||
void STCPSendRaw(SOCKET socket,const std::vector<char>& Data){
|
||||
if(socket == -1){
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
int BytesSent = send(socket, Data.data(), int(Data.size()), 0);
|
||||
if (BytesSent == 0){
|
||||
debug(Sec("(TCP) Connection closing..."));
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
else if (BytesSent < 0) {
|
||||
debug(Sec("(TCP) send failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
KillSocket(socket);
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
}
|
||||
void STCPSend(SOCKET socket,const std::string&Data){
|
||||
STCPSendRaw(socket,std::vector<char>(Data.begin(),Data.end()));
|
||||
}
|
||||
std::pair<char*,size_t> STCPRecv(SOCKET socket){
|
||||
char buf[64000];
|
||||
int len = 64000;
|
||||
ZeroMemory(buf, len);
|
||||
int BytesRcv = recv(socket, buf, len,0);
|
||||
if (BytesRcv == 0){
|
||||
info(Sec("(TCP) Connection closing..."));
|
||||
Terminate = true;
|
||||
return std::make_pair((char*)"",0);
|
||||
}else if (BytesRcv < 0) {
|
||||
info(Sec("(TCP) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
KillSocket(socket);
|
||||
Terminate = true;
|
||||
return std::make_pair((char*)"",0);
|
||||
}
|
||||
char* Ret = new char[BytesRcv];
|
||||
memcpy_s(Ret,BytesRcv,buf,BytesRcv);
|
||||
ZeroMemory(buf, len);
|
||||
return std::make_pair(Ret,BytesRcv);
|
||||
}
|
||||
void CheckForDir(){
|
||||
struct stat info{};
|
||||
if(stat( Sec("Resources"), &info) != 0){
|
||||
_wmkdir(SecW(L"Resources"));
|
||||
}
|
||||
}
|
||||
void WaitForConfirm(){
|
||||
while(!Terminate && !ModLoaded){
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
ModLoaded = false;
|
||||
}
|
||||
|
||||
int N,E;
|
||||
void Parse(const std::string& msg){
|
||||
std::stringstream ss(msg);
|
||||
std::string t;
|
||||
while (std::getline(ss, t, 'g')) {
|
||||
if(t.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return;
|
||||
if(N == 0){
|
||||
N = std::stoi(t, nullptr, 16);
|
||||
}else if(E == 0){
|
||||
E = std::stoi(t, nullptr, 16);
|
||||
}else return;
|
||||
}
|
||||
}
|
||||
std::string GenerateM(RSA*key){
|
||||
std::stringstream stream;
|
||||
stream << std::hex << key->n << "g" << key->e << "g" << RSA_E(Sec("IDC"),key->e,key->n);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void Check(SOCKET TCPSock,std::shared_ptr<std::atomic_bool> ok){
|
||||
size_t accum = 0;
|
||||
while (!*ok) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
accum += 100;
|
||||
if (accum >= 5000) {
|
||||
error(Sec("Identification timed out (Check accum)"));
|
||||
KillSocket(TCPSock);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<char> PrependSize(const std::string& str) {
|
||||
uint32_t Size = htonl(uint32_t(str.size()) + 1);
|
||||
std::vector<char> result;
|
||||
// +1 for \0, +4 for the size
|
||||
result.resize(str.size() + 1 + 4);
|
||||
memcpy(result.data(), &Size, 4);
|
||||
memcpy(result.data() + 4, str.data(), str.size() + 1);
|
||||
return result;
|
||||
}
|
||||
std::string HandShake(SOCKET Sock,RSA*LKey){
|
||||
std::shared_ptr<std::atomic_bool> ok = std::make_shared<std::atomic_bool>(false);
|
||||
std::thread Timeout(Check,Sock,ok);
|
||||
Timeout.detach();
|
||||
N = 0;E = 0;
|
||||
auto Res = STCPRecv(Sock);
|
||||
std::string msg(Res.first,Res.second);
|
||||
Parse(msg);
|
||||
if(N != 0 && E != 0) {
|
||||
STCPSendRaw(Sock,PrependSize(GenerateM(LKey)));
|
||||
Res = STCPRecv(Sock);
|
||||
msg = std::string(Res.first,Res.second);
|
||||
if(RSA_D(msg,LKey->d,LKey->n) != "HC"){
|
||||
Terminate = true;
|
||||
}
|
||||
}else Terminate = true;
|
||||
*ok = true;
|
||||
|
||||
if(Terminate){
|
||||
TCPTerminate = true;
|
||||
UlStatus = Sec("UlDisconnected: full or outdated server");
|
||||
info(Sec("Terminated!"));
|
||||
return "";
|
||||
}
|
||||
msg = RSA_E("NR" + GetDName() + ":" + GetDID(),E,N);
|
||||
if(!msg.empty()) {
|
||||
STCPSendRaw(Sock, PrependSize(msg));
|
||||
STCPSendRaw(Sock, PrependSize(RSA_E("VC" + GetVer(),E,N)));
|
||||
Res = STCPRecv(Sock);
|
||||
msg = Res.first;
|
||||
}
|
||||
|
||||
if(N == 0 || E == 0 || msg.size() < 2 || msg.substr(0,2) != "WS"){
|
||||
|
||||
Terminate = true;
|
||||
TCPTerminate = true;
|
||||
UlStatus = Sec("UlDisconnected: full or outdated server");
|
||||
info(Sec("Terminated!"));
|
||||
return "";
|
||||
}
|
||||
STCPSend(Sock,Sec("SR"));
|
||||
Res = STCPRecv(Sock);
|
||||
if(strlen(Res.first) == 0 || std::string(Res.first) == "-"){
|
||||
info(Sec("Didn't Receive any mods..."));
|
||||
ListOfMods = "-";
|
||||
STCPSend(Sock,Sec("Done"));
|
||||
info(Sec("Done!"));
|
||||
return "";
|
||||
}
|
||||
return Res.first;
|
||||
}
|
||||
|
||||
void SyncResources(SOCKET Sock){
|
||||
RSA*LKey = GenKey();
|
||||
|
||||
std::string Ret = HandShake(Sock,LKey);
|
||||
delete LKey;
|
||||
|
||||
if(Ret.empty())return;
|
||||
|
||||
info(Sec("Checking Resources..."));
|
||||
CheckForDir();
|
||||
|
||||
std::vector<std::string> list = Split(Ret, ";");
|
||||
std::vector<std::string> FNames(list.begin(), list.begin() + (list.size() / 2));
|
||||
std::vector<std::string> FSizes(list.begin() + (list.size() / 2), list.end());
|
||||
list.clear();
|
||||
Ret.clear();
|
||||
int Amount = 0,Pos = 0;
|
||||
std::string a,t;
|
||||
for(const std::string&name : FNames){
|
||||
if(!name.empty()){
|
||||
t += name.substr(name.find_last_of('/') + 1) + ";";
|
||||
}
|
||||
}
|
||||
if(t.empty())ListOfMods = "-";
|
||||
else ListOfMods = t;
|
||||
t.clear();
|
||||
for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
|
||||
auto pos = FN->find_last_of('/');
|
||||
if (pos == std::string::npos)continue;
|
||||
Amount++;
|
||||
}
|
||||
if(!FNames.empty())info(Sec("Syncing..."));
|
||||
for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
|
||||
auto pos = FN->find_last_of('/');
|
||||
if (pos != std::string::npos) {
|
||||
a = Sec("Resources") + FN->substr(pos);
|
||||
} else continue;
|
||||
Pos++;
|
||||
if (fs::exists(a)) {
|
||||
if (FS->find_first_not_of("0123456789") != std::string::npos)continue;
|
||||
if (fs::file_size(a) == std::stoi(*FS)){
|
||||
UlStatus = Sec("UlLoading Resource: (") + std::to_string(Pos) + "/" + std::to_string(Amount) +
|
||||
"): " + a.substr(a.find_last_of('/'));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
try {
|
||||
fs::copy_file(a, Sec("BeamNG/mods") + a.substr(a.find_last_of('/')),
|
||||
fs::copy_options::overwrite_existing);
|
||||
} catch (...) {
|
||||
Terminate = true;
|
||||
continue;
|
||||
}
|
||||
WaitForConfirm();
|
||||
continue;
|
||||
}else remove(a.c_str());
|
||||
}
|
||||
CheckForDir();
|
||||
do {
|
||||
STCPSend(Sock, "f" + *FN);
|
||||
int Recv = 0,Size = std::stoi(*FS);
|
||||
char*File = new char[Size];
|
||||
ZeroMemory(File,Size);
|
||||
do {
|
||||
auto Pair = STCPRecv(Sock);
|
||||
char* Data = Pair.first;
|
||||
size_t BytesRcv = Pair.second;
|
||||
if (strcmp(Data, Sec("Cannot Open")) == 0 || Terminate){
|
||||
if(BytesRcv != 0)delete[] Data;
|
||||
break;
|
||||
}
|
||||
memcpy_s(File+Recv,BytesRcv,Data,BytesRcv);
|
||||
Recv += int(BytesRcv);
|
||||
float per = float(Recv)/std::stof(*FS) * 100;
|
||||
std::string Percent = std::to_string(truncf(per * 10) / 10);
|
||||
UlStatus = Sec("UlDownloading Resource: (") + std::to_string(Pos) + "/" + std::to_string(Amount) +
|
||||
"): " + a.substr(a.find_last_of('/')) + " (" +
|
||||
Percent.substr(0, Percent.find('.') + 2) + "%)";
|
||||
delete[] Data;
|
||||
} while (Recv != Size && Recv < Size && !Terminate);
|
||||
if(Terminate)break;
|
||||
UlStatus = Sec("UlLoading Resource: (") + std::to_string(Pos) + "/" + std::to_string(Amount) +
|
||||
"): " + a.substr(a.find_last_of('/'));
|
||||
std::ofstream LFS;
|
||||
LFS.open(a.c_str(), std::ios_base::app | std::ios::binary);
|
||||
if (LFS.is_open()) {
|
||||
LFS.write(File, Recv);
|
||||
LFS.close();
|
||||
}
|
||||
delete[] File;
|
||||
}while(fs::file_size(a) != std::stoi(*FS) && !Terminate);
|
||||
if(!Terminate)fs::copy_file(a,Sec("BeamNG/mods")+a.substr(a.find_last_of('/')), fs::copy_options::overwrite_existing);
|
||||
WaitForConfirm();
|
||||
}
|
||||
FNames.clear();
|
||||
FSizes.clear();
|
||||
a.clear();
|
||||
if(!Terminate){
|
||||
STCPSend(Sock,Sec("Done"));
|
||||
info(Sec("Done!"));
|
||||
}else{
|
||||
UlStatus = Sec("Ulstart");
|
||||
info(Sec("Connection Terminated!"));
|
||||
}
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
#include "Zlib/Compressor.h"
|
||||
#include "Network/network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <WS2tcpip.h>
|
||||
#include "Logger.h"
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <string>
|
||||
#include <array>
|
||||
#include <set>
|
||||
|
||||
SOCKET UDPSock = -1;
|
||||
sockaddr_in* ToServer = nullptr;
|
||||
struct PacketData{
|
||||
int ID;
|
||||
std::string Data;
|
||||
int Tries;
|
||||
};
|
||||
struct SplitData{
|
||||
int Total{};
|
||||
int ID{};
|
||||
std::set<std::pair<int,std::string>> Fragments;
|
||||
};
|
||||
std::set<SplitData*> SplitPackets;
|
||||
std::set<PacketData*> BigDataAcks;
|
||||
int FC(const std::string& s,const std::string& p,int n) {
|
||||
auto i = s.find(p);
|
||||
int j;
|
||||
for (j = 1; j < n && i != std::string::npos; ++j){
|
||||
i = s.find(p, i+1);
|
||||
}
|
||||
if (j == n)return int(i);
|
||||
else return -1;
|
||||
}
|
||||
void ClearAll(){
|
||||
__try{
|
||||
for (SplitData*S : SplitPackets){
|
||||
if (S != nullptr) {
|
||||
delete S;
|
||||
S = nullptr;
|
||||
}
|
||||
}
|
||||
for (PacketData*S : BigDataAcks){
|
||||
if (S != nullptr) {
|
||||
delete S;
|
||||
S = nullptr;
|
||||
}
|
||||
}
|
||||
}__except(1){}
|
||||
SplitPackets.clear();
|
||||
BigDataAcks.clear();
|
||||
}
|
||||
void UDPSend(std::string Data){
|
||||
if(ClientID == -1 || UDPSock == -1)return;
|
||||
if(Data.length() > 400){
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
std::string Packet = char(ClientID+1) + std::string(":") + Data;
|
||||
int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer));
|
||||
if (sendOk == SOCKET_ERROR)error(Sec("Error Code : ") + std::to_string(WSAGetLastError()));
|
||||
}
|
||||
|
||||
void LOOP(){
|
||||
while(UDPSock != -1) {
|
||||
for (PacketData* p : BigDataAcks) {
|
||||
if(p != nullptr && p->Tries < 15){
|
||||
p->Tries++;
|
||||
UDPSend(p->Data);
|
||||
}else{
|
||||
BigDataAcks.erase(p);
|
||||
if(p != nullptr){
|
||||
delete p;
|
||||
p = nullptr;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
}
|
||||
}
|
||||
|
||||
void AckID(int ID){
|
||||
for(PacketData* p : BigDataAcks){
|
||||
if(p != nullptr && p->ID == ID){
|
||||
p->Tries = 100;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
int PackID(){
|
||||
static int ID = -1;
|
||||
if(ID > 999999)ID = 0;
|
||||
else ID++;
|
||||
return ID;
|
||||
}
|
||||
int SplitID(){
|
||||
static int SID = -1;
|
||||
if(SID > 999999)SID = 0;
|
||||
else SID++;
|
||||
return SID;
|
||||
}
|
||||
void SendLarge(std::string Data){
|
||||
if(Data.length() > 400){
|
||||
std::string CMP(Comp(Data));
|
||||
Data = "ABG:" + CMP;
|
||||
}
|
||||
TCPSend(Data);
|
||||
}
|
||||
std::array<int, 100> HandledIDs = {-1};
|
||||
int APos = 0;
|
||||
void IDReset(){
|
||||
for(int C = 0;C < 100;C++){
|
||||
HandledIDs.at(C) = -1;
|
||||
}
|
||||
}
|
||||
bool Handled(int ID){
|
||||
for(int id : HandledIDs){
|
||||
if(id == ID)return true;
|
||||
}
|
||||
if(APos > 99)APos = 0;
|
||||
HandledIDs.at(APos) = ID;
|
||||
APos++;
|
||||
return false;
|
||||
}
|
||||
SplitData*GetSplit(int SplitID){
|
||||
for(SplitData* a : SplitPackets){
|
||||
if(a != nullptr && a->ID == SplitID)return a;
|
||||
}
|
||||
auto* a = new SplitData();
|
||||
SplitPackets.insert(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
|
||||
void HandleChunk(const std::string&Data){
|
||||
int pos = FC(Data,"|",5);
|
||||
if(pos == -1)return;
|
||||
std::stringstream ss(Data.substr(0,pos++));
|
||||
std::string t;
|
||||
int I = -1;
|
||||
//Current Max ID SID
|
||||
std::vector<int> Num(4,0);
|
||||
while (std::getline(ss, t, '|')) {
|
||||
if(I != -1)Num.at(I) = std::stoi(t);
|
||||
I++;
|
||||
}
|
||||
std::string ack = "TRG:" + std::to_string(Num.at(2));
|
||||
UDPSend(ack);
|
||||
if(Handled(Num.at(2))){
|
||||
return;
|
||||
}
|
||||
std::string Packet = Data.substr(pos);
|
||||
SplitData* SData = GetSplit(Num.at(3));
|
||||
SData->Total = Num.at(1);
|
||||
SData->ID = Num.at(3);
|
||||
SData->Fragments.insert(std::make_pair(Num.at(0),Packet));
|
||||
if(SData->Fragments.size() == SData->Total){
|
||||
std::string ToHandle;
|
||||
for(const std::pair<int,std::string>& a : SData->Fragments){
|
||||
ToHandle += a.second;
|
||||
}
|
||||
ServerParser(ToHandle);
|
||||
SplitPackets.erase(SData);
|
||||
delete SData;
|
||||
SData = nullptr;
|
||||
}
|
||||
}
|
||||
void UDPParser(std::string Packet){
|
||||
if(Packet.substr(0,4) == "ABG:"){
|
||||
Packet = DeComp(Packet.substr(4));
|
||||
}
|
||||
if(Packet.substr(0,4) == "TRG:"){
|
||||
AckID(stoi(Packet.substr(4)));
|
||||
return;
|
||||
}else if(Packet.substr(0,3) == "BD:"){
|
||||
auto pos = Packet.find(':',4);
|
||||
int ID = stoi(Packet.substr(3,pos-3));
|
||||
std::string pckt = "TRG:" + std::to_string(ID);
|
||||
UDPSend(pckt);
|
||||
if(!Handled(ID)) {
|
||||
pckt = Packet.substr(pos + 1);
|
||||
ServerParser(pckt);
|
||||
}
|
||||
return;
|
||||
}else if(Packet.substr(0,2) == "SC"){
|
||||
HandleChunk(Packet);
|
||||
return;
|
||||
}
|
||||
ServerParser(Packet);
|
||||
}
|
||||
void UDPRcv(){
|
||||
sockaddr_in FromServer{};
|
||||
int clientLength = sizeof(FromServer);
|
||||
ZeroMemory(&FromServer, clientLength);
|
||||
std::string Ret(10240,0);
|
||||
if(UDPSock == -1)return;
|
||||
int32_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength);
|
||||
if (Rcv == SOCKET_ERROR)return;
|
||||
UDPParser(Ret.substr(0,Rcv));
|
||||
}
|
||||
void UDPClientMain(const std::string& IP,int Port){
|
||||
WSADATA data;
|
||||
if (WSAStartup(514, &data)){
|
||||
error(Sec("Can't start Winsock!"));
|
||||
return;
|
||||
}
|
||||
delete ToServer;
|
||||
ToServer = new sockaddr_in;
|
||||
ToServer->sin_family = AF_INET;
|
||||
ToServer->sin_port = htons(Port);
|
||||
inet_pton(AF_INET, IP.c_str(), &ToServer->sin_addr);
|
||||
UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
|
||||
std::thread Ack(LOOP);
|
||||
Ack.detach();
|
||||
IDReset();
|
||||
TCPSend(Sec("P"));
|
||||
UDPSend(Sec("p"));
|
||||
while(!Terminate)UDPRcv();
|
||||
KillSocket(UDPSock);
|
||||
WSACleanup();
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 5/8/2020
|
||||
///
|
||||
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include "Logger.h"
|
||||
#include <iostream>
|
||||
#include <WS2tcpip.h>
|
||||
#include <Zlib/Compressor.h>
|
||||
#include "Security/Enc.h"
|
||||
#include "Network/network.h"
|
||||
|
||||
SOCKET TCPSock = -1;
|
||||
bool CheckBytes(int32_t Bytes){
|
||||
if (Bytes == 0){
|
||||
debug(Sec("(TCP) Connection closing... CheckBytes(16)"));
|
||||
Terminate = true;
|
||||
return false;
|
||||
}else if (Bytes < 0) {
|
||||
debug(Sec("(TCP CB) recv failed with error: ") + std::to_string(WSAGetLastError()));
|
||||
KillSocket(TCPSock);
|
||||
Terminate = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void TCPSend(const std::string&Data){
|
||||
if(TCPSock == -1){
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Size is BIG-ENDIAN!
|
||||
//auto Size = htonl(int32_t(Data.size()));
|
||||
///TODO
|
||||
int32_t Size,Sent,Temp;
|
||||
std::string Send(4,0);
|
||||
Size = int32_t(Data.size());
|
||||
memcpy(&Send[0],&Size,sizeof(Size));
|
||||
Send += Data;
|
||||
// Do not use Size before this point for anything but the header
|
||||
Sent = 0;
|
||||
Size += 4;
|
||||
do{
|
||||
if (size_t(Sent) >= Send.size()) {
|
||||
error(Sec("string OOB in ") + std::string(__func__));
|
||||
return;
|
||||
}
|
||||
Temp = send(TCPSock, &Send[Sent], Size - Sent, 0);
|
||||
if(!CheckBytes(Temp))return;
|
||||
Sent += Temp;
|
||||
}while(Sent < Size);
|
||||
}
|
||||
|
||||
void TCPRcv(){
|
||||
if(TCPSock == -1){
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
int32_t Header,BytesRcv = 0,Temp;
|
||||
std::vector<char> Data(sizeof(Header));
|
||||
do{
|
||||
Temp = recv(TCPSock,&Data[BytesRcv],4-BytesRcv,0);
|
||||
if(!CheckBytes(Temp))return;
|
||||
BytesRcv += Temp;
|
||||
}while(BytesRcv < 4);
|
||||
memcpy(&Header,&Data[0],sizeof(Header));
|
||||
|
||||
if(!CheckBytes(BytesRcv))return;
|
||||
Data.resize(Header);
|
||||
BytesRcv = 0;
|
||||
do{
|
||||
Temp = recv(TCPSock,&Data[BytesRcv],Header-BytesRcv,0);
|
||||
if(!CheckBytes(Temp))return;
|
||||
BytesRcv += Temp;
|
||||
}while(BytesRcv < Header);
|
||||
|
||||
std::string Ret(Data.data(),Header);
|
||||
if (Ret.substr(0, 4) == "ABG:") {
|
||||
Ret = DeComp(Ret.substr(4));
|
||||
}
|
||||
#ifdef DEBUG
|
||||
//debug("Parsing from server -> " + std::to_string(Ret.size()));
|
||||
#endif
|
||||
ServerParser(Ret);
|
||||
}
|
||||
|
||||
|
||||
void SyncResources(SOCKET TCPSock);
|
||||
void TCPClientMain(const std::string& IP,int Port){
|
||||
WSADATA wsaData;
|
||||
SOCKADDR_IN ServerAddr;
|
||||
int RetCode;
|
||||
WSAStartup(514, &wsaData); //2.2
|
||||
TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
|
||||
if(TCPSock == -1){
|
||||
printf(Sec("Client: socket failed! Error code: %d\n"), WSAGetLastError());
|
||||
WSACleanup();
|
||||
return;
|
||||
}
|
||||
ServerAddr.sin_family = AF_INET;
|
||||
ServerAddr.sin_port = htons(Port);
|
||||
inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr);
|
||||
RetCode = connect(TCPSock, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr));
|
||||
if(RetCode != 0){
|
||||
UlStatus = Sec("UlConnection Failed!");
|
||||
std::cout << Sec("Client: connect failed! Error code: ") << WSAGetLastError() << std::endl;
|
||||
KillSocket(TCPSock);
|
||||
WSACleanup();
|
||||
Terminate = true;
|
||||
return;
|
||||
}
|
||||
getsockname(TCPSock, (SOCKADDR *)&ServerAddr, (int *)sizeof(ServerAddr));
|
||||
|
||||
SyncResources(TCPSock);
|
||||
while(!Terminate)TCPRcv();
|
||||
GameSend(Sec("T"));
|
||||
////Game Send Terminate
|
||||
if(KillSocket(TCPSock) != 0)
|
||||
debug(Sec("(TCP) Cannot close socket. Error code: ") + std::to_string(WSAGetLastError()));
|
||||
|
||||
if(WSACleanup() != 0)
|
||||
debug(Sec("(TCP) Client: WSACleanup() failed!..."));
|
||||
}
|
||||
14
src/Platform.h
Normal file
14
src/Platform.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
/// Platform-specific code
|
||||
#include <string>
|
||||
namespace plat {
|
||||
|
||||
void clear_screen();
|
||||
void set_console_title(const std::string& title);
|
||||
void URelaunch(int argc,char* args[]);
|
||||
void ReLaunch(int argc,char*args[]);
|
||||
std::string get_game_dir_magically();
|
||||
std::string ask_for_folder();
|
||||
|
||||
}
|
||||
49
src/PlatformLinux.cpp
Normal file
49
src/PlatformLinux.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#include "Platform.h"
|
||||
#if defined(PLATFORM_LINUX)
|
||||
|
||||
#include <fmt/core.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <filesystem>
|
||||
|
||||
void plat::ReLaunch(int argc, char* args[]) {
|
||||
spdlog::warn("Not implemented: {}", __func__);
|
||||
}
|
||||
void plat::URelaunch(int argc, char** argv) {
|
||||
spdlog::warn("Not implemented: {}", __func__);
|
||||
}
|
||||
void plat::set_console_title(const std::string& title) {
|
||||
//fmt::print("\x1b]2;{}\0", title);
|
||||
}
|
||||
void plat::clear_screen() {
|
||||
// unwanted on linux, due to the ability to run this as a command in an existing console.
|
||||
}
|
||||
std::string plat::get_game_dir_magically() {
|
||||
spdlog::warn("Not implemented: {}", __func__);
|
||||
for (const auto& path : { "" }) {
|
||||
if (std::filesystem::exists(std::filesystem::path(path) / "BeamNG.drive.exe")) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
#include <iostream>
|
||||
#include <filesystem>
|
||||
|
||||
std::string plat::ask_for_folder() {
|
||||
spdlog::info("Asking user for path");
|
||||
fmt::print("====\n"
|
||||
"Couldn't find game directory, please enter the path to the game (the folder that contains 'BeamNG.drive.exe')\n"
|
||||
"Path: ");
|
||||
std::string folder;
|
||||
std::getline(std::cin, folder);
|
||||
while (!std::filesystem::exists(std::filesystem::path(folder) / "BeamNG.drive.exe")) {
|
||||
fmt::print("This folder ('{}') doesn't contain 'BeamNG.drive.exe', please try again.\n", folder);
|
||||
fmt::print("Path: ");
|
||||
std::getline(std::cin, folder);
|
||||
}
|
||||
fmt::print("Thank you!\n====\n");
|
||||
spdlog::info("Game path found");
|
||||
return folder;
|
||||
}
|
||||
#endif
|
||||
193
src/PlatformWindows.cpp
Normal file
193
src/PlatformWindows.cpp
Normal file
@@ -0,0 +1,193 @@
|
||||
#include "Platform.h"
|
||||
|
||||
#if defined(PLATFORM_WINDOWS)
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <windows.h>
|
||||
#include <iostream>
|
||||
|
||||
#include <Shlobj.h>
|
||||
// include after shlobj
|
||||
#include <Shlobj_core.h>
|
||||
|
||||
void plat::ReLaunch(int argc, char** argv) {
|
||||
std::string Arg;
|
||||
for (int c = 2; c <= argc; c++) {
|
||||
Arg += " ";
|
||||
Arg += argv[c - 1];
|
||||
}
|
||||
system("cls");
|
||||
ShellExecute(nullptr, "runas", argv[0], Arg.c_str(), nullptr, SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(), 0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void plat::URelaunch(int argc, char** argv) {
|
||||
std::string Arg;
|
||||
for (int c = 2; c <= argc; c++) {
|
||||
Arg += " ";
|
||||
Arg += argv[c - 1];
|
||||
}
|
||||
ShellExecute(nullptr, "open", argv[0], Arg.c_str(), nullptr, SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(), 0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void plat::set_console_title(const std::string& title) {
|
||||
SetConsoleTitleA(title.c_str());
|
||||
}
|
||||
void plat::clear_screen() {
|
||||
system("cls");
|
||||
}
|
||||
LONG OpenKey(HKEY root,const char* path,PHKEY hKey){
|
||||
return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey);
|
||||
}
|
||||
#define MAX_KEY_LENGTH 255
|
||||
#define MAX_VALUE_NAME 16383
|
||||
std::string QueryKey(HKEY hKey,int ID){
|
||||
TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name
|
||||
DWORD cbName; // size of name string
|
||||
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
|
||||
DWORD cchClassName = MAX_PATH; // size of class string
|
||||
DWORD cSubKeys=0; // number of subkeys
|
||||
DWORD cbMaxSubKey; // longest subkey size
|
||||
DWORD cchMaxClass; // longest class string
|
||||
DWORD cValues; // number of values for key
|
||||
DWORD cchMaxValue; // longest value name
|
||||
DWORD cbMaxValueData; // longest value data
|
||||
DWORD cbSecurityDescriptor; // size of security descriptor
|
||||
FILETIME ftLastWriteTime; // last write time
|
||||
|
||||
DWORD i, retCode;
|
||||
|
||||
TCHAR achValue[MAX_VALUE_NAME];
|
||||
DWORD cchValue = MAX_VALUE_NAME;
|
||||
|
||||
retCode = RegQueryInfoKey(
|
||||
hKey, // key handle
|
||||
achClass, // buffer for class name
|
||||
&cchClassName, // size of class string
|
||||
nullptr, // reserved
|
||||
&cSubKeys, // number of subkeys
|
||||
&cbMaxSubKey, // longest subkey size
|
||||
&cchMaxClass, // longest class string
|
||||
&cValues, // number of values for this key
|
||||
&cchMaxValue, // longest value name
|
||||
&cbMaxValueData, // longest value data
|
||||
&cbSecurityDescriptor, // security descriptor
|
||||
&ftLastWriteTime); // last write time
|
||||
|
||||
BYTE* buffer = new BYTE[cbMaxValueData];
|
||||
ZeroMemory(buffer, cbMaxValueData);
|
||||
if (cSubKeys){
|
||||
for (i=0; i<cSubKeys; i++){
|
||||
cbName = MAX_KEY_LENGTH;
|
||||
retCode = RegEnumKeyEx(hKey, i,achKey,&cbName,nullptr,nullptr,nullptr,&ftLastWriteTime);
|
||||
if (retCode == ERROR_SUCCESS){
|
||||
if(strcmp(achKey,"Steam App 284160") == 0){
|
||||
return achKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cValues){
|
||||
for (i=0, retCode = ERROR_SUCCESS; i<cValues; i++){
|
||||
cchValue = MAX_VALUE_NAME;
|
||||
achValue[0] = '\0';
|
||||
retCode = RegEnumValue(hKey, i,achValue,&cchValue,nullptr,nullptr,nullptr,nullptr);
|
||||
if (retCode == ERROR_SUCCESS ){
|
||||
DWORD lpData = cbMaxValueData;
|
||||
buffer[0] = '\0';
|
||||
LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData);
|
||||
std::string data = (char *)(buffer);
|
||||
std::string key = achValue;
|
||||
|
||||
switch (ID){
|
||||
case 1: if(key == "SteamExe"){
|
||||
auto p = data.find_last_of("/\\");
|
||||
if(p != std::string::npos){
|
||||
return data.substr(0,p);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 2: if(key == "Name" && data == "BeamNG.drive")return data;break;
|
||||
case 3: if(key == "rootpath")return data;break;
|
||||
case 4: if(key == "userpath_override")return data;
|
||||
case 5: if(key == "Local AppData")return data;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete [] buffer;
|
||||
return "";
|
||||
}
|
||||
std::string plat::get_game_dir_magically() {
|
||||
std::string Result;
|
||||
std::string K3 = R"(Software\BeamNG\BeamNG.drive)";
|
||||
HKEY hKey;
|
||||
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
|
||||
if (dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 3);
|
||||
if (Result.empty()) {
|
||||
spdlog::error("Couldn't query key from HKEY_CURRENT_USER\\Software\\BeamNG\\BeamNG.drive");
|
||||
Result = "";
|
||||
}
|
||||
} else {
|
||||
spdlog::error("Couldn't open HKEY_CURRENT_USER\\Software\\BeamNG\\BeamNG.drive");
|
||||
}
|
||||
RegCloseKey(hKey);
|
||||
return Result;
|
||||
}
|
||||
|
||||
static int CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData) {
|
||||
if (uMsg == BFFM_INITIALIZED) {
|
||||
std::string tmp = (const char*)lpData;
|
||||
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static std::string impl_ask_for_folder() {
|
||||
TCHAR path[MAX_PATH];
|
||||
std::memset(path, 0, MAX_PATH);
|
||||
|
||||
std::wstring wsaved_path(L"C:\\");
|
||||
const wchar_t* path_param = wsaved_path.c_str();
|
||||
|
||||
BROWSEINFO bi = { 0 };
|
||||
bi.lpszTitle = ("Browse for BeamNG.drive folder...");
|
||||
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
|
||||
bi.lpfn = BrowseCallbackProc;
|
||||
bi.lParam = (LPARAM)path_param;
|
||||
|
||||
LPITEMIDLIST pidl = SHBrowseForFolderA(&bi);
|
||||
|
||||
if (pidl != 0) {
|
||||
// get the name of the folder and put it in path
|
||||
SHGetPathFromIDList(pidl, path);
|
||||
|
||||
// free memory used
|
||||
IMalloc* imalloc = 0;
|
||||
if (SUCCEEDED(SHGetMalloc(&imalloc))) {
|
||||
imalloc->Free(pidl);
|
||||
imalloc->Release();
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
std::string plat::ask_for_folder() {
|
||||
auto folder = impl_ask_for_folder();
|
||||
while (!std::filesystem::exists(std::filesystem::path(folder) / "BeamNG.drive.exe")) {
|
||||
spdlog::error("This folder ('{}') doesn't contain 'BeamNG.drive.exe', please try again.\n", folder);
|
||||
folder = impl_ask_for_folder();
|
||||
}
|
||||
return folder;
|
||||
}
|
||||
|
||||
#endif
|
||||
17
src/Result.h
Normal file
17
src/Result.h
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/outcome.hpp>
|
||||
#include <boost/outcome/success_failure.hpp>
|
||||
|
||||
#ifdef WIN32
|
||||
#define BEAMMP_WARN_UNUSED
|
||||
#else
|
||||
#define BEAMMP_WARN_UNUSED __attribute__((warn_unused_result))
|
||||
#endif
|
||||
|
||||
// attribute because [[nodiscard]] isn't possible on using decls - if you wanna write a standards proposal,
|
||||
// this is one to write.
|
||||
template<typename T, typename EC>
|
||||
using Result BEAMMP_WARN_UNUSED = boost::outcome_v2::result<T, EC>;
|
||||
|
||||
namespace outcome = boost::outcome_v2;
|
||||
@@ -1,289 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/18/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include <filesystem>
|
||||
#include <Windows.h>
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#define MAX_KEY_LENGTH 255
|
||||
#define MAX_VALUE_NAME 16383
|
||||
|
||||
int TraceBack = 0;
|
||||
std::string GameDir;
|
||||
|
||||
void lowExit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
Sec("Failed to find the game please launch it. Report this if the issue persists code ");
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(2);
|
||||
}
|
||||
void Exit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
Sec("Sorry. We do not support cracked copies report this if you believe this is a mistake code ");
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(3);
|
||||
}
|
||||
void SteamExit(int code){
|
||||
TraceBack = 0;
|
||||
std::string msg =
|
||||
Sec("Illegal steam modifications detected report this if you believe this is a mistake code ");
|
||||
error(msg+std::to_string(code));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||
exit(4);
|
||||
}
|
||||
std::string GetGameDir(){
|
||||
if(TraceBack != 4)Exit(0);
|
||||
return GameDir.substr(0,GameDir.find_last_of('\\'));
|
||||
}
|
||||
LONG OpenKey(HKEY root,const char* path,PHKEY hKey){
|
||||
return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey);
|
||||
}
|
||||
std::string QueryKey(HKEY hKey,int ID){
|
||||
TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name
|
||||
DWORD cbName; // size of name string
|
||||
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
|
||||
DWORD cchClassName = MAX_PATH; // size of class string
|
||||
DWORD cSubKeys=0; // number of subkeys
|
||||
DWORD cbMaxSubKey; // longest subkey size
|
||||
DWORD cchMaxClass; // longest class string
|
||||
DWORD cValues; // number of values for key
|
||||
DWORD cchMaxValue; // longest value name
|
||||
DWORD cbMaxValueData; // longest value data
|
||||
DWORD cbSecurityDescriptor; // size of security descriptor
|
||||
FILETIME ftLastWriteTime; // last write time
|
||||
|
||||
DWORD i, retCode;
|
||||
|
||||
TCHAR achValue[MAX_VALUE_NAME];
|
||||
DWORD cchValue = MAX_VALUE_NAME;
|
||||
|
||||
retCode = RegQueryInfoKey(
|
||||
hKey, // key handle
|
||||
achClass, // buffer for class name
|
||||
&cchClassName, // size of class string
|
||||
nullptr, // reserved
|
||||
&cSubKeys, // number of subkeys
|
||||
&cbMaxSubKey, // longest subkey size
|
||||
&cchMaxClass, // longest class string
|
||||
&cValues, // number of values for this key
|
||||
&cchMaxValue, // longest value name
|
||||
&cbMaxValueData, // longest value data
|
||||
&cbSecurityDescriptor, // security descriptor
|
||||
&ftLastWriteTime); // last write time
|
||||
|
||||
BYTE* buffer = new BYTE[cbMaxValueData];
|
||||
ZeroMemory(buffer, cbMaxValueData);
|
||||
if (cSubKeys){
|
||||
for (i=0; i<cSubKeys; i++){
|
||||
cbName = MAX_KEY_LENGTH;
|
||||
retCode = RegEnumKeyEx(hKey, i,achKey,&cbName,nullptr,nullptr,nullptr,&ftLastWriteTime);
|
||||
if (retCode == ERROR_SUCCESS){
|
||||
if(strcmp(achKey,Sec("Steam App 284160")) == 0){
|
||||
return achKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cValues){
|
||||
for (i=0, retCode = ERROR_SUCCESS; i<cValues; i++){
|
||||
cchValue = MAX_VALUE_NAME;
|
||||
achValue[0] = '\0';
|
||||
retCode = RegEnumValue(hKey, i,achValue,&cchValue,nullptr,nullptr,nullptr,nullptr);
|
||||
if (retCode == ERROR_SUCCESS ){
|
||||
DWORD lpData = cbMaxValueData;
|
||||
buffer[0] = '\0';
|
||||
LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData);
|
||||
std::string data = reinterpret_cast<const char *const>(buffer);
|
||||
std::string key = achValue;
|
||||
switch (ID){
|
||||
case 1: if(key == Sec("SteamExe")){
|
||||
auto p = data.find_last_of('/');
|
||||
if(p != std::string::npos)return data.substr(0,p);
|
||||
}break;
|
||||
case 2: if(key == Sec("Name") && data == Sec("BeamNG.drive"))return data;break;
|
||||
case 3: if(key == Sec("rootpath"))return data;break;
|
||||
case 4: if(key == Sec("userpath_override"))return data;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
delete [] buffer;
|
||||
return "";
|
||||
}
|
||||
namespace fs = std::experimental::filesystem;
|
||||
void FileList(std::vector<std::string>&a,const std::string& Path){
|
||||
for (const auto &entry : fs::directory_iterator(Path)) {
|
||||
auto pos = entry.path().filename().string().find('.');
|
||||
if (pos != std::string::npos) {
|
||||
a.emplace_back(entry.path().string());
|
||||
}else FileList(a,entry.path().string());
|
||||
}
|
||||
}
|
||||
bool Find(const std::string& FName,const std::string& Path){
|
||||
std::vector<std::string> FS;
|
||||
FileList(FS,Path+Sec("/userdata"));
|
||||
for(std::string&a : FS){
|
||||
if(a.find(FName) != std::string::npos){
|
||||
FS.clear();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
FS.clear();
|
||||
return false;
|
||||
}
|
||||
bool FindHack(const std::string& Path){
|
||||
bool s = true;
|
||||
for (const auto &entry : fs::directory_iterator(Path)) {
|
||||
std::string Name = entry.path().filename().string();
|
||||
for(char&c : Name)c = char(tolower(c));
|
||||
if(Name == Sec("steam.exe"))s = false;
|
||||
if(Name.find(Sec("greenluma")) != -1)return true;
|
||||
Name.clear();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
std::vector<std::string> GetID(const std::string& log){
|
||||
std::string vec,t,r;
|
||||
std::vector<std::string> Ret;
|
||||
std::ifstream f(log.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
vec.resize(size_t(fileSize) + 1);
|
||||
f.seekg(0, std::ios_base::beg);
|
||||
f.read(&vec[0], fileSize);
|
||||
f.close();
|
||||
std::stringstream ss(vec);
|
||||
bool S = false;
|
||||
while (std::getline(ss, t, '{')) {
|
||||
if(!S)S = true;
|
||||
else{
|
||||
for(char& c : t){
|
||||
if(isdigit(c))r += c;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ret.emplace_back(r);
|
||||
r.clear();
|
||||
S = false;
|
||||
bool L = true;
|
||||
while (std::getline(ss, t, '}')) {
|
||||
if(L){
|
||||
L = false;
|
||||
continue;
|
||||
}
|
||||
for(char& c : t){
|
||||
if(c == '"'){
|
||||
if(!S)S = true;
|
||||
else{
|
||||
if(r.length() > 10) {
|
||||
Ret.emplace_back(r);
|
||||
}
|
||||
r.clear();
|
||||
S = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(isdigit(c))r += c;
|
||||
}
|
||||
}
|
||||
vec.clear();
|
||||
return Ret;
|
||||
}
|
||||
std::string GetManifest(const std::string& Man){
|
||||
std::string vec;
|
||||
std::ifstream f(Man.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
vec.resize(size_t(fileSize) + 1);
|
||||
f.seekg(0, std::ios_base::beg);
|
||||
f.read(&vec[0], fileSize);
|
||||
f.close();
|
||||
std::string ToFind = Sec("\"LastOwner\"\t\t\"");
|
||||
int pos = int(vec.find(ToFind));
|
||||
if(pos != -1){
|
||||
pos += int(ToFind.length());
|
||||
vec = vec.substr(pos);
|
||||
return vec.substr(0,vec.find('\"'));
|
||||
}else return "";
|
||||
}
|
||||
bool IDCheck(std::string Man, std::string steam){
|
||||
bool a = false,b = true;
|
||||
int pos = int(Man.rfind(Sec("steamapps")));
|
||||
if(pos == -1)Exit(5);
|
||||
Man = Man.substr(0,pos+9) + Sec("/appmanifest_284160.acf");
|
||||
steam += Sec("/config/loginusers.vdf");
|
||||
if(fs::exists(Man) && fs::exists(steam)){
|
||||
for(const std::string&ID : GetID(steam)){
|
||||
if(ID == GetManifest(Man))b = false;
|
||||
}
|
||||
if(b)Exit(6);
|
||||
}else a = true;
|
||||
return a;
|
||||
}
|
||||
void LegitimacyCheck(){
|
||||
std::string Result,T;
|
||||
std::string K1 = Sec("Software\\Valve\\Steam");
|
||||
std::string K2 = Sec("Software\\Valve\\Steam\\Apps\\284160");
|
||||
std::string K3 = Sec("Software\\BeamNG\\BeamNG.drive");
|
||||
HKEY hKey;
|
||||
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K1.c_str(), &hKey);
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 1);
|
||||
if(Result.empty())Exit(1);
|
||||
if(fs::exists(Result)){
|
||||
if(!Find(Sec("284160.json"),Result))Exit(2);
|
||||
if(FindHack(Result))SteamExit(1);
|
||||
}else Exit(3);
|
||||
T = Result;
|
||||
Result.clear();
|
||||
TraceBack++;
|
||||
}else Exit(4);
|
||||
K1.clear();
|
||||
RegCloseKey(hKey);
|
||||
dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K2.c_str(), &hKey);
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 2);
|
||||
if(Result.empty())lowExit(1);
|
||||
TraceBack++;
|
||||
}else lowExit(2);
|
||||
K2.clear();
|
||||
RegCloseKey(hKey);
|
||||
dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
|
||||
if(dwRegOPenKey == ERROR_SUCCESS) {
|
||||
Result = QueryKey(hKey, 3);
|
||||
if(Result.empty())lowExit(3);
|
||||
if(IDCheck(Result,T))lowExit(5);
|
||||
GameDir = Result;
|
||||
TraceBack++;
|
||||
}else lowExit(4);
|
||||
K3.clear();
|
||||
Result.clear();
|
||||
RegCloseKey(hKey);
|
||||
if(TraceBack < 3)exit(-1);
|
||||
}
|
||||
std::string CheckVer(const std::string &dir){
|
||||
std::string vec,temp,Path = dir + Sec("\\integrity.json");
|
||||
std::ifstream f(Path.c_str(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
vec.resize(size_t(fileSize) + 1);
|
||||
f.seekg(0, std::ios_base::beg);
|
||||
f.read(&vec[0], fileSize);
|
||||
f.close();
|
||||
vec = vec.substr(vec.find_last_of(Sec("version")),vec.find_last_of('"'));
|
||||
for(const char &a : vec){
|
||||
if(isdigit(a) || a == '.')temp+=a;
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Discord/discord_info.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <windows.h>
|
||||
#include "Startup.h"
|
||||
#include <tlhelp32.h>
|
||||
#include "Logger.h"
|
||||
#include <fstream>
|
||||
#include <Psapi.h>
|
||||
void DAS(){
|
||||
#ifndef DEBUG
|
||||
int i = 0;
|
||||
std::ifstream f(GetEN(), std::ios::binary);
|
||||
f.seekg(0, std::ios_base::end);
|
||||
std::streampos fileSize = f.tellg();
|
||||
if(IsDebuggerPresent() || fileSize > 0x4C4B40){
|
||||
i++;
|
||||
DAboard();
|
||||
}
|
||||
if(i)DAboard();
|
||||
f.close();
|
||||
#endif
|
||||
}
|
||||
DWORD getParentPID(DWORD pid){
|
||||
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
PROCESSENTRY32 pe = {0};
|
||||
DWORD ppid = 0;
|
||||
pe.dwSize = sizeof(PROCESSENTRY32);
|
||||
if(Process32First(h, &pe)){
|
||||
do{
|
||||
if(pe.th32ProcessID == pid){
|
||||
ppid = pe.th32ParentProcessID;
|
||||
break;
|
||||
}
|
||||
}while(Process32Next(h, &pe));
|
||||
}
|
||||
CloseHandle(h);
|
||||
return ppid;
|
||||
}
|
||||
|
||||
HANDLE getProcess(DWORD pid, LPSTR fname, DWORD sz) {
|
||||
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
|
||||
if (h) {
|
||||
GetModuleFileNameEx(h, nullptr, fname, sz);
|
||||
return h;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void UnderSimulation(char* argv[]){
|
||||
DWORD ppid;
|
||||
std::string Parent(MAX_PATH,0);
|
||||
ppid = getParentPID(GetCurrentProcessId());
|
||||
HANDLE Process = getProcess(ppid, &Parent[0], MAX_PATH);
|
||||
std::string Code = Sec("Code ");
|
||||
if(Process == nullptr){
|
||||
error(Code+std::to_string(2));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
auto P = Parent.find(Sec(".exe"));
|
||||
if(P != std::string::npos)Parent.resize(P + 4);
|
||||
else return;
|
||||
std::string S1 = Sec("\\Windows\\explorer.exe");
|
||||
std::string S2 = Sec("JetBrains\\CLion");
|
||||
std::string S3 = Sec("\\Windows\\System32\\cmd.exe");
|
||||
std::string S4 = Sec("steam.exe");
|
||||
if(Parent == std::string(argv[0]))return;
|
||||
if(Parent.find(S1) == 2)return;
|
||||
if(Parent.find(S2) != std::string::npos)return;
|
||||
if(Parent.find(S3) == 2)return;
|
||||
if(Parent.find(S3) != -1)return;
|
||||
//TerminateProcess(Process, 1);
|
||||
//error(Code + std::to_string(4));
|
||||
//exit(1); //TODO look into that later
|
||||
}
|
||||
void SecurityCheck(char* argv[]){
|
||||
//UnderSimulation(argv);
|
||||
DAS();
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 11/13/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Enc.h"
|
||||
#include <windows.h>
|
||||
#include "Logger.h"
|
||||
#include <psapi.h>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
|
||||
DWORD getParentPID(DWORD pid);
|
||||
HANDLE getProcess(DWORD pid, LPSTR fname, DWORD sz);
|
||||
|
||||
void Kill(){
|
||||
static bool Run = false;
|
||||
if(!Run)Run = true;
|
||||
else return;
|
||||
while(Run){
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
NetReset();
|
||||
#ifdef DEBUG
|
||||
debug(Sec("Attention! NetReset Check!"));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void FindDLL(char* args[]){
|
||||
static auto argv = args;
|
||||
HANDLE hProcess = GetCurrentProcess();
|
||||
std::string Parent(MAX_PATH,0);
|
||||
DWORD ppid = getParentPID(GetCurrentProcessId());
|
||||
HANDLE Process = getProcess(ppid, &Parent[0], MAX_PATH);
|
||||
if(Process == nullptr){
|
||||
HMODULE hMods[1024];
|
||||
DWORD cbNeeded;
|
||||
unsigned int i;
|
||||
if(K32EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)){
|
||||
for ( i = 1; i < (cbNeeded / sizeof(HMODULE)); i++ ){
|
||||
TCHAR szModName[MAX_PATH];
|
||||
if (K32GetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR))){
|
||||
std::string Name(szModName),PName(argv[0]);
|
||||
Name = Name.substr(0,Name.rfind(Sec("\\")));
|
||||
PName = PName.substr(0,PName.rfind(Sec("\\")));
|
||||
if(Name == PName){
|
||||
std::thread t1(Kill);
|
||||
t1.detach();
|
||||
}
|
||||
}
|
||||
ZeroMemory(szModName,MAX_PATH);
|
||||
}
|
||||
}
|
||||
}
|
||||
CloseHandle(hProcess);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
#include "Security/Enc.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <random>
|
||||
|
||||
int LocalKeys[] = {7406809,6967,4810803}; //n e d
|
||||
|
||||
int log_power(int n,unsigned int p, int mod){
|
||||
int result = 1;
|
||||
for (; p; p >>= 1u){
|
||||
if (p & 1u)result = int((1LL * result * n) % mod);
|
||||
n = int((1LL * n * n) % mod);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int Rand(){
|
||||
std::random_device r;
|
||||
std::default_random_engine e1(r());
|
||||
std::uniform_int_distribution<int> uniform_dist(1, 5000);
|
||||
return uniform_dist(e1);
|
||||
}
|
||||
|
||||
bool rabin_miller(int n){
|
||||
bool ok = true;
|
||||
for (int i = 1; i <= 5 && ok; i++) {
|
||||
int a = Rand() + 1;
|
||||
int result = log_power(a, n - 1, n);
|
||||
ok &= (result == 1);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
int generate_prime(){
|
||||
int generated = Rand();
|
||||
while (!rabin_miller(generated))generated = Rand();
|
||||
return generated;
|
||||
}
|
||||
int gcd(int a, int b){
|
||||
while (b){
|
||||
int r = a % b;
|
||||
a = b;
|
||||
b = r;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
int generate_coprime(int n){
|
||||
int generated = Rand();
|
||||
while (gcd(n, generated) != 1)generated = Rand();
|
||||
return generated;
|
||||
}
|
||||
|
||||
std::pair<int, int> euclid_extended(int a, int b) {
|
||||
if(!b)return {1, 0};
|
||||
auto result = euclid_extended(b, a % b);
|
||||
return {result.second, result.first - (a / b) * result.second};
|
||||
}
|
||||
|
||||
int modular_inverse(int n, int mod){
|
||||
int inverse = euclid_extended(n, mod).first;
|
||||
while(inverse < 0)inverse += mod;
|
||||
return inverse;
|
||||
}
|
||||
|
||||
RSA* GenKey(){
|
||||
int p, q;
|
||||
p = generate_prime();
|
||||
q = generate_prime();
|
||||
int n = p * q;
|
||||
int phi = (p -1) * (q - 1);
|
||||
int e = generate_coprime(phi);
|
||||
int d = modular_inverse(e, phi);
|
||||
return new RSA{n,e,d};
|
||||
}
|
||||
int Enc(int value,int e,int n){
|
||||
return log_power(value, e, n);
|
||||
}
|
||||
|
||||
int Dec(int value,int d,int n){
|
||||
return log_power(value, d, n);
|
||||
}
|
||||
std::string LocalEnc(const std::string& Data){
|
||||
std::stringstream stream;
|
||||
for(const char&c : Data){
|
||||
stream << std::hex << Enc(uint8_t(c),LocalKeys[1],LocalKeys[0]) << "g";
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
std::string LocalDec(const std::string& Data){
|
||||
std::stringstream ss(Data);
|
||||
std::string token,ret;
|
||||
while (std::getline(ss, token, 'g')) {
|
||||
if(token.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return "";
|
||||
int c = std::stoi(token, nullptr, 16);
|
||||
ret += char(Dec(c,LocalKeys[2],LocalKeys[0]));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::string RSA_E(const std::string& Data,int e, int n){
|
||||
std::stringstream stream;
|
||||
for(const char&c : Data){
|
||||
stream << std::hex << Enc(uint8_t(c),e,n) << "g";
|
||||
}
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::string RSA_D(const std::string& Data, int d, int n){
|
||||
std::stringstream ss(Data);
|
||||
std::string token,ret;
|
||||
while (std::getline(ss, token, 'g')) {
|
||||
if(token.find_first_not_of(Sec("0123456789abcdef")) != std::string::npos)return "";
|
||||
int c = std::stoi(token, nullptr, 16);
|
||||
ret += char(Dec(c,d,n));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/19/2020
|
||||
///
|
||||
#include "Security/Enc.h"
|
||||
#include <windows.h>
|
||||
#include "Security/Game.h"
|
||||
#include <filesystem>
|
||||
#include <RestartManager.h>
|
||||
#include "Logger.h"
|
||||
#include <thread>
|
||||
|
||||
namespace fs = std::experimental::filesystem;
|
||||
void CheckDirs(){
|
||||
for (auto& p : fs::directory_iterator(Sec("BeamNG\\mods"))) {
|
||||
if(fs::is_directory(p.path()))exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
bool BeamLoad(PCWSTR pszFile){
|
||||
bool Ret = false;
|
||||
DWORD dwSession;
|
||||
WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = {0};
|
||||
DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey);
|
||||
if (dwError == ERROR_SUCCESS) {
|
||||
dwError = RmRegisterResources(dwSession, 1, &pszFile,
|
||||
0, nullptr, 0, nullptr);
|
||||
if (dwError == ERROR_SUCCESS) {
|
||||
DWORD dwReason;
|
||||
UINT nProcInfoNeeded;
|
||||
UINT nProcInfo = 10;
|
||||
RM_PROCESS_INFO rgpi[10];
|
||||
dwError = RmGetList(dwSession, &nProcInfoNeeded,&nProcInfo, rgpi, &dwReason);
|
||||
if (dwError == ERROR_SUCCESS) {
|
||||
if(nProcInfo == 1){
|
||||
std::string AppName(50,0);
|
||||
size_t N;
|
||||
wcstombs_s(&N,&AppName[0],50, rgpi[0].strAppName, 50);
|
||||
if(!AppName.find(Sec("BeamNG.drive")) && GamePID == rgpi[0].Process.dwProcessId){
|
||||
Ret = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RmEndSession(dwSession);
|
||||
}
|
||||
return Ret;
|
||||
}
|
||||
void ContinuousCheck(fs::file_time_type last){
|
||||
std::string path = Sec(R"(BeamNG\mods\BeamMP.zip)");
|
||||
int i = 0;
|
||||
while(fs::exists(path) && last == fs::last_write_time(path)){
|
||||
if(!BeamLoad(SecW(L"BeamNG\\mods\\BeamMP.zip"))) {
|
||||
if (i < 60)i++;
|
||||
else {
|
||||
error(Sec("Mod did not load! launcher closing soon"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(0);
|
||||
}
|
||||
}else i = 0;
|
||||
CheckDirs();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(800));
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
void SecureMods(){
|
||||
fs::file_time_type last = fs::last_write_time(Sec(R"(BeamNG\mods\BeamMP.zip)"));
|
||||
auto* HandleCheck = new std::thread(ContinuousCheck,last);
|
||||
HandleCheck->detach();
|
||||
delete HandleCheck;
|
||||
}
|
||||
356
src/ServerNetwork.cpp
Normal file
356
src/ServerNetwork.cpp
Normal file
@@ -0,0 +1,356 @@
|
||||
#include "ServerNetwork.h"
|
||||
#include "ClientInfo.h"
|
||||
#include "ClientNetwork.h"
|
||||
#include "ClientPacket.h"
|
||||
#include "ClientTransport.h"
|
||||
#include "Identity.h"
|
||||
#include "ImplementationInfo.h"
|
||||
#include "Launcher.h"
|
||||
#include "Packet.h"
|
||||
#include "ProtocolVersion.h"
|
||||
#include "ServerInfo.h"
|
||||
#include "Transport.h"
|
||||
#include "Util.h"
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
ServerNetwork::ServerNetwork(Launcher& launcher, const ip::tcp::endpoint& ep)
|
||||
: m_tcp_ep(ep)
|
||||
, launcher(launcher) {
|
||||
spdlog::debug("Server network created");
|
||||
boost::system::error_code ec;
|
||||
m_tcp_socket.connect(m_tcp_ep, ec);
|
||||
if (ec) {
|
||||
throw std::runtime_error(ec.message());
|
||||
}
|
||||
}
|
||||
|
||||
ServerNetwork::~ServerNetwork() {
|
||||
spdlog::debug("Server network destroyed");
|
||||
}
|
||||
|
||||
void ServerNetwork::run() {
|
||||
// start the connection by going to the identification state and sending
|
||||
// the first packet in the identification protocol (protocol version)
|
||||
m_state = bmp::State::Identification;
|
||||
bmp::Packet version_packet {
|
||||
.purpose = bmp::Purpose::ProtocolVersion,
|
||||
.raw_data = std::vector<uint8_t>(6),
|
||||
};
|
||||
spdlog::trace("Protocol version: v{}.{}.{}", 1, 0, 0);
|
||||
struct bmp::ProtocolVersion version {
|
||||
.version = {
|
||||
.major = 1,
|
||||
.minor = 0,
|
||||
.patch = 0,
|
||||
},
|
||||
};
|
||||
version.serialize_to(version_packet.raw_data);
|
||||
tcp_write(std::move(version_packet));
|
||||
|
||||
start_tcp_read();
|
||||
|
||||
m_io.run();
|
||||
}
|
||||
|
||||
void ServerNetwork::handle_packet(bmp::Packet&& packet) {
|
||||
// handle ping immediately
|
||||
if (m_state > bmp::State::Identification && packet.purpose == bmp::Purpose::Ping) {
|
||||
tcp_write(bmp::Packet {
|
||||
.purpose = bmp::Purpose::Ping,
|
||||
});
|
||||
return;
|
||||
}
|
||||
switch (m_state) {
|
||||
case bmp::State::None:
|
||||
m_state = bmp::State::Identification;
|
||||
[[fallthrough]];
|
||||
case bmp::State::Identification:
|
||||
handle_identification(packet);
|
||||
break;
|
||||
case bmp::State::Authentication:
|
||||
handle_authentication(packet);
|
||||
break;
|
||||
case bmp::State::ModDownload:
|
||||
handle_mod_download(packet);
|
||||
break;
|
||||
case bmp::State::SessionSetup:
|
||||
handle_session_setup(packet);
|
||||
break;
|
||||
case bmp::State::Playing:
|
||||
handle_playing(packet);
|
||||
break;
|
||||
case bmp::State::Leaving:
|
||||
break;
|
||||
}
|
||||
|
||||
launcher.client_network->handle_server_packet(std::move(packet));
|
||||
}
|
||||
|
||||
void ServerNetwork::handle_mod_download(const bmp::Packet& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::Purpose::ModsInfo: {
|
||||
auto data = packet.get_readable_data();
|
||||
auto mods_info = nlohmann::json::parse(data.begin(), data.end());
|
||||
spdlog::info("Got info about {} mod(s)", mods_info.size());
|
||||
for (const auto& mod : mods_info) {
|
||||
spdlog::warn("Mod download not implemented, but data is: {}", mod.dump(4));
|
||||
}
|
||||
// TODO: implement mod download
|
||||
// for now we just pretend we're all good!
|
||||
tcp_write(bmp::Packet {
|
||||
.purpose = bmp::Purpose::ModsSyncDone,
|
||||
});
|
||||
spdlog::info("Done syncing mods");
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::MapInfo: {
|
||||
auto data = packet.get_readable_data();
|
||||
std::string map(data.begin(), data.end());
|
||||
// TODO: Send to game
|
||||
spdlog::debug("Map: '{}'", map);
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::StateChangeSessionSetup: {
|
||||
spdlog::info("Starting session setup");
|
||||
m_state = bmp::State::SessionSetup;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
|
||||
// todo: disconnect gracefully
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerNetwork::handle_authentication(const bmp::Packet& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::Purpose::AuthOk: {
|
||||
spdlog::info("Authentication succeeded");
|
||||
uint32_t player_id;
|
||||
bmp::deserialize(player_id, packet.get_readable_data());
|
||||
spdlog::debug("Player id: {}", player_id);
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::AuthFailed: {
|
||||
auto data = packet.get_readable_data();
|
||||
spdlog::error("Authentication failed: {}", std::string(data.begin(), data.end()));
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::PlayerRejected: {
|
||||
auto data = packet.get_readable_data();
|
||||
spdlog::error("Server rejected me: {}", std::string(data.begin(), data.end()));
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::StartUDP: {
|
||||
bmp::deserialize(m_udp_magic, packet.get_readable_data());
|
||||
spdlog::debug("UDP start, got magic 0x{:x}", m_udp_magic);
|
||||
m_udp_ep = ip::udp::endpoint(m_tcp_ep.address(), m_tcp_ep.port());
|
||||
m_udp_socket.open(m_tcp_ep.address().is_v4() ? ip::udp::v4() : ip::udp::v6());
|
||||
auto copy = bmp::Packet {
|
||||
.purpose = bmp::Purpose::StartUDP,
|
||||
.raw_data = packet.get_readable_data(),
|
||||
};
|
||||
udp_write(copy);
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::StateChangeModDownload: {
|
||||
spdlog::info("Starting mod sync");
|
||||
m_state = bmp::State::ModDownload;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
|
||||
// todo: disconnect gracefully
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerNetwork::handle_identification(const bmp::Packet& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::Purpose::ProtocolVersionOk: {
|
||||
spdlog::debug("Protocol version ok");
|
||||
bmp::Packet ci_packet {
|
||||
.purpose = bmp::Purpose::ClientInfo,
|
||||
.raw_data = std::vector<uint8_t>(1024),
|
||||
};
|
||||
struct bmp::ClientInfo ci {
|
||||
.program_version = { .major = PRJ_VERSION_MAJOR, .minor = PRJ_VERSION_MINOR, .patch = PRJ_VERSION_PATCH },
|
||||
.game_version = {
|
||||
.major = launcher.game_version->major,
|
||||
.minor = launcher.game_version->minor,
|
||||
.patch = launcher.game_version->patch,
|
||||
},
|
||||
.mod_version = {
|
||||
.major = launcher.mod_version->major,
|
||||
.minor = launcher.mod_version->minor,
|
||||
.patch = launcher.mod_version->patch,
|
||||
},
|
||||
.implementation = bmp::ImplementationInfo {
|
||||
.value = "Official BeamMP Launcher",
|
||||
},
|
||||
};
|
||||
auto sz = ci.serialize_to(ci_packet.raw_data);
|
||||
ci_packet.raw_data.resize(sz);
|
||||
tcp_write(std::move(ci_packet));
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::ProtocolVersionBad:
|
||||
spdlog::error("The server rejected our protocol version!");
|
||||
throw std::runtime_error("Protocol version rejected");
|
||||
break;
|
||||
case bmp::Purpose::ServerInfo: {
|
||||
struct bmp::ServerInfo si { };
|
||||
si.deserialize_from(packet.get_readable_data());
|
||||
spdlog::debug("Connected to server implementation '{}' v{}.{}.{}",
|
||||
si.implementation.value,
|
||||
si.program_version.major,
|
||||
si.program_version.minor,
|
||||
si.program_version.patch);
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::StateChangeAuthentication: {
|
||||
spdlog::debug("Starting authentication");
|
||||
m_state = bmp::State::Authentication;
|
||||
auto ident = launcher.identity.synchronize();
|
||||
tcp_write(bmp::Packet {
|
||||
.purpose = bmp::Purpose::PlayerPublicKey,
|
||||
.raw_data = std::vector<uint8_t>(ident->PublicKey.begin(), ident->PublicKey.end()) });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
|
||||
// todo: disconnect gracefully
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerNetwork::tcp_read(std::function<void(bmp::Packet&&)> handler) {
|
||||
m_tmp_header_buffer.resize(bmp::Header::SERIALIZED_SIZE);
|
||||
boost::asio::async_read(m_tcp_socket, buffer(m_tmp_header_buffer),
|
||||
[this, handler](auto ec, auto) {
|
||||
if (ec) {
|
||||
spdlog::error("Failed to read from server: {}", ec.message());
|
||||
} else {
|
||||
bmp::Header hdr {};
|
||||
hdr.deserialize_from(m_tmp_header_buffer);
|
||||
// vector eaten up by now, recv again
|
||||
m_tmp_packet.raw_data.resize(hdr.size);
|
||||
m_tmp_packet.purpose = hdr.purpose;
|
||||
m_tmp_packet.flags = hdr.flags;
|
||||
boost::asio::async_read(m_tcp_socket, buffer(m_tmp_packet.raw_data),
|
||||
[handler, this](auto ec, auto) {
|
||||
if (ec) {
|
||||
spdlog::error("Failed to read from server: {}", ec.message());
|
||||
} else {
|
||||
// ok!
|
||||
handler(std::move(m_tmp_packet));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerNetwork::tcp_write(bmp::Packet&& packet, std::function<void(boost::system::error_code)> handler) {
|
||||
// finalize the packet (compress etc) and produce header
|
||||
auto header = packet.finalize();
|
||||
|
||||
auto owned_packet = std::make_shared<bmp::Packet>(std::move(packet));
|
||||
// serialize header
|
||||
auto header_data = std::make_shared<std::vector<uint8_t>>(bmp::Header::SERIALIZED_SIZE);
|
||||
header.serialize_to(*header_data);
|
||||
std::array<const_buffer, 2> buffers = {
|
||||
buffer(*header_data),
|
||||
buffer(owned_packet->raw_data)
|
||||
};
|
||||
boost::asio::async_write(m_tcp_socket, buffers,
|
||||
[this, header_data, owned_packet, handler](auto ec, auto size) {
|
||||
spdlog::trace("Wrote {} bytes for 0x{:x} to server", size, int(owned_packet->purpose));
|
||||
if (handler) {
|
||||
handler(ec);
|
||||
} else {
|
||||
if (ec) {
|
||||
spdlog::error("Failed to send packet of type 0x{:x} to server", int(owned_packet->purpose));
|
||||
} else {
|
||||
// ok!
|
||||
spdlog::trace("Sent packet of type 0x{:x} to server", int(owned_packet->purpose));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerNetwork::udp_read(std::function<void(ip::udp::endpoint&&, bmp::Packet&&)> handler) {
|
||||
// maximum we can ever expect from udp
|
||||
auto ep = std::make_shared<ip::udp::endpoint>();
|
||||
m_udp_socket.async_receive_from(buffer(m_tmp_udp_buffer), *ep, [this, ep, handler](auto ec, auto) {
|
||||
if (ec) {
|
||||
spdlog::error("Failed to receive UDP from server: {}", ec.message());
|
||||
} else {
|
||||
bmp::Packet packet;
|
||||
bmp::Header header {};
|
||||
auto offset = header.deserialize_from(m_tmp_udp_buffer);
|
||||
packet.raw_data.resize(header.size);
|
||||
std::copy(m_tmp_udp_buffer.begin() + long(offset), m_tmp_udp_buffer.begin() + long(offset) + header.size, packet.raw_data.begin());
|
||||
handler(std::move(*ep), std::move(packet));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerNetwork::udp_write(bmp::Packet& packet) {
|
||||
auto header = packet.finalize();
|
||||
auto data = std::make_shared<std::vector<uint8_t>>(header.size + bmp::Header::SERIALIZED_SIZE);
|
||||
auto offset = header.serialize_to(*data);
|
||||
std::copy(packet.raw_data.begin(), packet.raw_data.end(), data->begin() + static_cast<long>(offset));
|
||||
m_udp_socket.async_send_to(buffer(*data), m_udp_ep, [data](auto ec, auto size) {
|
||||
if (ec) {
|
||||
spdlog::error("Failed to UDP write to server: {}", ec.message());
|
||||
} else {
|
||||
spdlog::trace("Wrote {} bytes to server via UDP", size);
|
||||
}
|
||||
});
|
||||
}
|
||||
void ServerNetwork::handle_session_setup(const bmp::Packet& packet) {
|
||||
switch (packet.purpose) {
|
||||
case bmp::Purpose::PlayersVehiclesInfo: {
|
||||
spdlog::debug("Players and vehicles info: {} bytes ({} bytes on arrival)", packet.get_readable_data().size(), packet.raw_data.size());
|
||||
// TODO: Send to game
|
||||
tcp_write(bmp::Packet {
|
||||
.purpose = bmp::Purpose::SessionReady,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case bmp::Purpose::StateChangePlaying: {
|
||||
spdlog::info("Playing!");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
|
||||
// todo: disconnect gracefully
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerNetwork::handle_playing(const bmp::Packet& packet) {
|
||||
switch (packet.purpose) {
|
||||
default:
|
||||
spdlog::error("Got 0x{:x} in state {}. This is not allowed. Disconnecting", uint16_t(packet.purpose), int(m_state));
|
||||
// todo: disconnect gracefully
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerNetwork::start_tcp_read() {
|
||||
tcp_read([this](auto&& packet) {
|
||||
spdlog::debug("Got packet 0x{:x} from server", int(packet.purpose));
|
||||
handle_packet(std::move(packet));
|
||||
start_tcp_read();
|
||||
});
|
||||
}
|
||||
|
||||
void ServerNetwork::start_udp_read() {
|
||||
udp_read([this](auto&& ep, auto&& packet) {
|
||||
spdlog::debug("Got packet 0x{:x} from server via UDP", int(packet.purpose));
|
||||
handle_packet(std::move(packet));
|
||||
start_udp_read();
|
||||
});
|
||||
}
|
||||
60
src/ServerNetwork.h
Normal file
60
src/ServerNetwork.h
Normal file
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include "Packet.h"
|
||||
#include "State.h"
|
||||
#include <boost/asio.hpp>
|
||||
|
||||
using namespace boost::asio;
|
||||
|
||||
class Launcher;
|
||||
|
||||
class ServerNetwork {
|
||||
public:
|
||||
ServerNetwork(Launcher& launcher, const ip::tcp::endpoint& ep);
|
||||
~ServerNetwork();
|
||||
|
||||
/// Starts and runs the connection to the server.
|
||||
/// Calls back to the Launcher.
|
||||
/// Blocking!
|
||||
void run();
|
||||
|
||||
private:
|
||||
void start_tcp_read();
|
||||
void start_udp_read();
|
||||
|
||||
/// Reads a single packet from the TCP stream. Blocks all other reads (not writes).
|
||||
void tcp_read(std::function<void(bmp::Packet&&)> handler);
|
||||
/// Writes the packet to the TCP stream. Blocks all other writes.
|
||||
void tcp_write(bmp::Packet&& packet, std::function<void(boost::system::error_code)> handler = nullptr);
|
||||
|
||||
/// Reads a packet from the given UDP socket, returning the client's endpoint as an out-argument.
|
||||
void udp_read(std::function<void(ip::udp::endpoint&&, bmp::Packet&&)> handler);
|
||||
/// Sends a packet to the specified UDP endpoint via the UDP socket.
|
||||
void udp_write(bmp::Packet& packet);
|
||||
|
||||
void handle_packet(bmp::Packet&& packet);
|
||||
void handle_identification(const bmp::Packet& packet);
|
||||
void handle_authentication(const bmp::Packet& packet);
|
||||
void handle_mod_download(const bmp::Packet& packet);
|
||||
void handle_session_setup(const bmp::Packet& packet);
|
||||
void handle_playing(const bmp::Packet& packet);
|
||||
|
||||
io_context m_io {};
|
||||
ip::tcp::socket m_tcp_socket { m_io };
|
||||
ip::udp::socket m_udp_socket { m_io };
|
||||
|
||||
// these two tmp fields are used for temporary reading into by read, don't use anywhere else please
|
||||
bmp::Packet m_tmp_packet {};
|
||||
std::vector<uint8_t> m_tmp_header_buffer {};
|
||||
// this is used by udp read, don't touch
|
||||
std::vector<uint8_t> m_tmp_udp_buffer { static_cast<unsigned char>(std::numeric_limits<uint16_t>::max()) };
|
||||
|
||||
bmp::State m_state {};
|
||||
|
||||
uint64_t m_udp_magic {};
|
||||
|
||||
ip::tcp::endpoint m_tcp_ep;
|
||||
ip::udp::endpoint m_udp_ep;
|
||||
|
||||
Launcher& launcher;
|
||||
};
|
||||
232
src/Startup.cpp
232
src/Startup.cpp
@@ -1,232 +0,0 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Discord/discord_info.h"
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include "Security/Enc.h"
|
||||
#include "Curl/http.h"
|
||||
#include <curl/curl.h>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include "Logger.h"
|
||||
#include <thread>
|
||||
|
||||
extern int TraceBack;
|
||||
bool Dev = false;
|
||||
namespace fs = std::experimental::filesystem;
|
||||
std::string GetEN(){
|
||||
return std::string(Sec("BeamMP-Launcher.exe"));
|
||||
}
|
||||
std::string GetVer(){
|
||||
return std::string(Sec("1.70"));
|
||||
}
|
||||
std::string GetPatch(){
|
||||
return std::string(Sec(".1"));
|
||||
}
|
||||
void ReLaunch(int argc,char*args[]){
|
||||
std::string Arg;
|
||||
for(int c = 2; c <= argc; c++){
|
||||
Arg += " ";
|
||||
Arg += args[c-1];
|
||||
}
|
||||
system(Sec("cls"));
|
||||
ShellExecute(nullptr,Sec("runas"),GetEN().c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(),0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void URelaunch(int argc,char* args[]){
|
||||
std::string Arg;
|
||||
for(int c = 2; c <= argc; c++){
|
||||
Arg += " ";
|
||||
Arg += args[c-1];
|
||||
}
|
||||
ShellExecute(nullptr,Sec("open"),GetEN().c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
|
||||
ShowWindow(GetConsoleWindow(),0);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
exit(1);
|
||||
}
|
||||
void CheckName(int argc,char* args[]){
|
||||
struct stat info{};
|
||||
std::string DN = GetEN(),CDir = args[0],FN = CDir.substr(CDir.find_last_of('\\')+1);
|
||||
if(FN != DN){
|
||||
if(stat(DN.c_str(),&info)==0)remove(DN.c_str());
|
||||
if(stat(DN.c_str(),&info)==0)ReLaunch(argc,args);
|
||||
std::rename(FN.c_str(), DN.c_str());
|
||||
URelaunch(argc,args);
|
||||
}
|
||||
}
|
||||
void RequestRole(){
|
||||
auto NPos = std::string::npos;
|
||||
std::string HTTP_Result = HTTP_REQUEST(Sec("https://beammp.com/entitlement?did=")+GetDID()+Sec("&t=l"),443);
|
||||
if(HTTP_Result == "-1"){
|
||||
HTTP_Result = HTTP_REQUEST(Sec("https://backup1.beammp.com/entitlement?did=")+GetDID()+Sec("&t=l"),443);
|
||||
if(HTTP_Result == "-1") {
|
||||
error(Sec("Sorry Backend System Outage! Don't worry it will back on soon!"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
exit(-1);
|
||||
}
|
||||
}
|
||||
if(HTTP_Result.find(Sec("\"MDEV\"")) != NPos || HTTP_Result.find(Sec("\"CON\"")) != NPos){
|
||||
if(GetDID() != "125792589621231616"){
|
||||
Dev = true;
|
||||
}
|
||||
}
|
||||
if(HTTP_Result.find(Sec("Error")) != NPos){
|
||||
error(Sec("Sorry You need to be in the official BeamMP Discord to proceed! https://discord.gg/beammp"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
exit(-1);
|
||||
}
|
||||
info(Sec("Client Connected!"));
|
||||
}
|
||||
|
||||
void CheckForUpdates(int argc,char*args[],const std::string& CV){
|
||||
std::string link = Sec("https://beammp.com/builds/launcher?version=true");
|
||||
std::string HTTP = HTTP_REQUEST(link,443);
|
||||
bool fallback = false;
|
||||
if(HTTP.find_first_of("0123456789") == std::string::npos){
|
||||
link = Sec("https://backup1.beammp.com/builds/launcher?version=true");
|
||||
HTTP = HTTP_REQUEST(link,443);
|
||||
fallback = true;
|
||||
if(HTTP.find_first_of("0123456789") == std::string::npos) {
|
||||
error(Sec("Primary Servers Offline! sorry for the inconvenience!"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(4));
|
||||
exit(-1);
|
||||
}
|
||||
}
|
||||
if(fallback){
|
||||
link = Sec("https://backup1.beammp.com/builds/launcher?download=true");
|
||||
}else link = Sec("https://beammp.com/builds/launcher?download=true");
|
||||
|
||||
struct stat buffer{};
|
||||
std::string Back = Sec("BeamMP-Launcher.back");
|
||||
if(stat(Back.c_str(), &buffer) == 0)remove(Back.c_str());
|
||||
if(HTTP > CV){
|
||||
system(Sec("cls"));
|
||||
info(Sec("Update found!"));
|
||||
info(Sec("Updating..."));
|
||||
if(std::rename(GetEN().c_str(), Back.c_str()))error(Sec("failed creating a backup!"));
|
||||
int i = Download(link, GetEN(),true);
|
||||
if(i != -1){
|
||||
error(Sec("Launcher Update failed! trying again... code : ") + std::to_string(i));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
int i2 = Download(link, GetEN(),true);
|
||||
if(i2 != -1){
|
||||
error(Sec("Launcher Update failed! code : ") + std::to_string(i2));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
ReLaunch(argc,args);
|
||||
}
|
||||
}
|
||||
URelaunch(argc,args);
|
||||
}else{
|
||||
info(Sec("Version is up to date"));
|
||||
}
|
||||
TraceBack++;
|
||||
}
|
||||
void CheckDir(int argc,char*args[]){
|
||||
std::string CDir = args[0];
|
||||
std::string MDir = Sec("BeamNG\\mods");
|
||||
if(!fs::is_directory(Sec("BeamNG"))){
|
||||
if(!fs::create_directory(Sec("BeamNG"))){
|
||||
error(Sec("Cannot Create BeamNG Directory! Retrying..."));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
ReLaunch(argc,args);
|
||||
}
|
||||
}
|
||||
if(fs::is_directory(MDir) && !Dev){
|
||||
int c = 0;
|
||||
for (auto& p : fs::directory_iterator(MDir))c++;
|
||||
if(c > 2) {
|
||||
warn(std::to_string(c-1) + Sec(" local mods will be wiped! Close this window if you don't want that!"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(15));
|
||||
}
|
||||
try{
|
||||
fs::remove_all(MDir);
|
||||
} catch (...) {
|
||||
error(Sec("Please close the game and try again"));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
if(fs::is_directory(MDir) && !Dev)ReLaunch(argc,args);
|
||||
if(!fs::create_directory(MDir) && !Dev){
|
||||
error(Sec("Cannot Create Mods Directory! Retrying..."));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
ReLaunch(argc,args);
|
||||
}
|
||||
if(!fs::is_directory(Sec("BeamNG\\settings"))){
|
||||
if(!fs::create_directory(Sec("BeamNG\\settings"))){
|
||||
error(Sec("Cannot Create Settings Directory! Retrying..."));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
ReLaunch(argc,args);
|
||||
}
|
||||
}
|
||||
}
|
||||
void CustomPort(int argc, char* argv[]){
|
||||
if(argc > 1){
|
||||
std::string Port = argv[1];
|
||||
if(Port.find_first_not_of("0123456789") == std::string::npos){
|
||||
if(std::stoi(Port) > 1000){
|
||||
DEFAULT_PORT = std::stoi(Port);
|
||||
warn(Sec("Running on custom port : ") + std::to_string(DEFAULT_PORT));
|
||||
}
|
||||
}
|
||||
if(argc > 2)Dev = false;
|
||||
}
|
||||
}
|
||||
void InitLauncher(int argc, char* argv[]) {
|
||||
system(Sec("cls"));
|
||||
curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
SetConsoleTitleA((Sec("BeamMP Launcher v") + std::string(GetVer()) + GetPatch()).c_str());
|
||||
InitLog();
|
||||
CheckName(argc, argv);
|
||||
FindDLL(argv);
|
||||
SecurityCheck(argv);
|
||||
Discord_Main();
|
||||
RequestRole();
|
||||
CustomPort(argc, argv);
|
||||
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
|
||||
}
|
||||
|
||||
void PreGame(int argc, char* argv[],const std::string& GamePath){
|
||||
info(Sec("Game Version : ") + CheckVer(GamePath));
|
||||
std::string DUI = Sec(R"(BeamNG\settings\uiapps-layouts.json)");
|
||||
std::string GS = Sec(R"(BeamNG\settings\game-settings.ini)");
|
||||
std::string link = Sec("https://beammp.com/client-ui-data");
|
||||
bool fallback = false;
|
||||
int i;
|
||||
if(!fs::exists(DUI)){
|
||||
info(Sec("Downloading default ui data..."));
|
||||
i = Download(link,DUI,true);
|
||||
if(i != -1){
|
||||
fallback = true;
|
||||
remove(DUI.c_str());
|
||||
link = Sec("https://backup1.beammp.com/client-ui-data");
|
||||
i = Download(link,DUI,true);
|
||||
if(i != -1) {
|
||||
error(Sec("Failed to download code : ") + std::to_string(i));
|
||||
std::this_thread::sleep_for(std::chrono::seconds(3));
|
||||
ReLaunch(argc, argv);
|
||||
}
|
||||
}
|
||||
info(Sec("Download Complete!"));
|
||||
}
|
||||
if(!fs::exists(GS)) {
|
||||
info(Sec("Downloading default game settings..."));
|
||||
if(fallback)link = Sec("https://backup1.beammp.com/client-settings-data");
|
||||
else link = Sec("https://beammp.com/client-settings-data");
|
||||
Download(link, GS,true);
|
||||
info(Sec("Download Complete!"));
|
||||
}
|
||||
if(!Dev) {
|
||||
info(Sec("Downloading mod..."));
|
||||
if(fallback)link = Sec("https://backup1.beammp.com/builds/client?did=") + GetDID();
|
||||
else link = Sec("https://beammp.com/builds/client?did=") + GetDID();
|
||||
Download(link, Sec(R"(BeamNG\mods\BeamMP.zip)"), false);
|
||||
info(Sec("Download Complete!"));
|
||||
}
|
||||
debug(Sec("Name : ") + GetDName());
|
||||
debug(Sec("Discriminator : ") + GetDTag());
|
||||
debug(Sec("Unique ID : ") + GetDID());
|
||||
}
|
||||
11
src/Sync.h
Normal file
11
src/Sync.h
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/thread/synchronized_value.hpp>
|
||||
#include <mutex>
|
||||
|
||||
/// This header provides convenience aliases for synchronization primitives.
|
||||
|
||||
template<typename T>
|
||||
using Sync = boost::synchronized_value<T, std::recursive_mutex>;
|
||||
|
||||
|
||||
37
src/Version.cpp
Normal file
37
src/Version.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include "Version.h"
|
||||
#include <charconv>
|
||||
#include <fmt/format.h>
|
||||
#include <sstream>
|
||||
|
||||
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
|
||||
: major(major)
|
||||
, minor(minor)
|
||||
, patch(patch) { }
|
||||
|
||||
Version::Version(const std::array<uint8_t, 3>& v)
|
||||
: Version(v[0], v[1], v[2]) {
|
||||
}
|
||||
|
||||
std::string Version::to_string() {
|
||||
return fmt::format("{:d}.{:d}.{:d}", major, minor, patch);
|
||||
}
|
||||
|
||||
bool Version::is_outdated(const Version& new_version) {
|
||||
if (new_version.major > major) {
|
||||
return true;
|
||||
} else if (new_version.major == major && new_version.minor > minor) {
|
||||
return true;
|
||||
} else if (new_version.major == major && new_version.minor == minor && new_version.patch > patch) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Version::Version(const std::string& str) {
|
||||
std::stringstream ss(str);
|
||||
std::string Part;
|
||||
std::getline(ss, Part, '.');
|
||||
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), major);
|
||||
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), minor);
|
||||
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), patch);
|
||||
}
|
||||
17
src/Version.h
Normal file
17
src/Version.h
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <array>
|
||||
#include <string>
|
||||
|
||||
struct Version {
|
||||
uint8_t major {};
|
||||
uint8_t minor {};
|
||||
uint8_t patch {};
|
||||
Version() {}
|
||||
Version(uint8_t major, uint8_t minor, uint8_t patch);
|
||||
Version(const std::array<uint8_t, 3>& v);
|
||||
explicit Version(const std::string& str);
|
||||
std::string to_string();
|
||||
bool is_outdated(const Version& new_version);
|
||||
};
|
||||
185
src/main.cpp
185
src/main.cpp
@@ -1,28 +1,169 @@
|
||||
///
|
||||
/// Created by Anonymous275 on 7/16/2020
|
||||
///
|
||||
#include "Network/network.h"
|
||||
#include "Security/Init.h"
|
||||
#include "Startup.h"
|
||||
#include <thread>
|
||||
#include <boost/system/detail/errc.hpp>
|
||||
#include <boost/system/detail/error_category.hpp>
|
||||
#include <spdlog/sinks/basic_file_sink.h>
|
||||
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
#include "ClientNetwork.h"
|
||||
#include "Launcher.h"
|
||||
#include "Platform.h"
|
||||
#include "ServerNetwork.h"
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
[[noreturn]] void aa(){
|
||||
while(true){
|
||||
std::cout.flush();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
/// Sets up a file- and console logger and makes it the default spdlog logger.
|
||||
static void setup_logger(bool debug = false);
|
||||
static std::shared_ptr<spdlog::logger> default_logger {};
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
bool enable_debug = false;
|
||||
bool enable_dev = false;
|
||||
int custom_port = 0;
|
||||
std::string_view invalid_arg;
|
||||
std::string all_args = std::string { argv[0] } + " ";
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string_view arg(argv[i]);
|
||||
all_args += "'" + std::string(arg) + "' ";
|
||||
std::string_view next(i + 1 < argc ? argv[i + 1] : "");
|
||||
// --debug flag enables debug printing in console
|
||||
if (arg == "--debug") {
|
||||
enable_debug = true;
|
||||
// --dev enables developer mode (game is not started)
|
||||
} else if (arg == "--dev") {
|
||||
enable_dev = true;
|
||||
} else if (arg == "0" && next == "0") {
|
||||
enable_dev = true;
|
||||
++i;
|
||||
// an argument that is all digits and not 0 is a custom port, backwards-compat
|
||||
} else if (std::all_of(arg.begin(), arg.end(), [](char c) { return std::isdigit(c); })) {
|
||||
custom_port = std::stoi(arg.data());
|
||||
} else {
|
||||
invalid_arg = arg;
|
||||
}
|
||||
}
|
||||
setup_logger(enable_debug || enable_dev);
|
||||
|
||||
spdlog::trace("BeamMP Launcher invoked as: {}", all_args);
|
||||
|
||||
if (enable_debug) {
|
||||
spdlog::debug("Debug mode enabled");
|
||||
}
|
||||
if (enable_dev) {
|
||||
spdlog::debug("Development mode enabled");
|
||||
}
|
||||
if (custom_port != 0) {
|
||||
spdlog::debug("Custom port set: {}", custom_port);
|
||||
}
|
||||
|
||||
if (!invalid_arg.empty()) {
|
||||
spdlog::warn("One or more invalid argument(s) passed via commandline switches, last one: '{}'. This argument was ignored.", invalid_arg);
|
||||
}
|
||||
|
||||
plat::clear_screen();
|
||||
plat::set_console_title(fmt::format("BeamMP Launcher v{}.{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH));
|
||||
spdlog::trace("BeamMP Launcher v{}.{}.{}", PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH);
|
||||
|
||||
spdlog::info("BeamMP Launcher v{}.{}.{} is a PRE-RELEASE build. Please report any errors immediately at https://github.com/BeamMP/BeamMP-Launcher.",
|
||||
PRJ_VERSION_MAJOR, PRJ_VERSION_MINOR, PRJ_VERSION_PATCH);
|
||||
|
||||
Launcher launcher {};
|
||||
|
||||
std::filesystem::path arg0(argv[0]);
|
||||
launcher.set_exe_name(arg0.filename().generic_string());
|
||||
launcher.set_exe_path(arg0.parent_path());
|
||||
|
||||
if (custom_port > 0) {
|
||||
// launcher.set_port(custom_port);
|
||||
}
|
||||
|
||||
if (!enable_dev) {
|
||||
//&launcher.check_for_updates(argc, argv);
|
||||
} else {
|
||||
spdlog::debug("Skipping update check due to dev mode");
|
||||
}
|
||||
|
||||
if (!enable_dev) {
|
||||
launcher.find_game();
|
||||
} else {
|
||||
spdlog::debug("Skipping game finding due to dev mode");
|
||||
}
|
||||
|
||||
if (!enable_dev) {
|
||||
launcher.pre_game();
|
||||
launcher.start_game();
|
||||
} else {
|
||||
spdlog::debug("Not launching the game due to dev mode");
|
||||
}
|
||||
|
||||
while (true) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
|
||||
// auto _ = launcher.start_server_network("beamcruise.com", 10814);
|
||||
|
||||
// old: launcher.start_network();
|
||||
|
||||
/*
|
||||
Launcher launcher {};
|
||||
|
||||
std::filesystem::path arg0(argv[0]);
|
||||
launcher.set_exe_name(arg0.filename().generic_string());
|
||||
launcher.set_exe_path(arg0.parent_path());
|
||||
|
||||
try {
|
||||
ServerNetwork sn(launcher, ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 30814));
|
||||
sn.run();
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Connection to server closed: {}", e.what());
|
||||
}
|
||||
spdlog::info("Shutting down.");
|
||||
*/
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
#ifdef DEBUG
|
||||
std::thread gb(aa);
|
||||
gb.detach();
|
||||
#endif
|
||||
InitLauncher(argc,argv);
|
||||
CheckDir(argc,argv);
|
||||
LegitimacyCheck();
|
||||
PreGame(argc,argv,GetGameDir());
|
||||
InitGame(GetGameDir(),argv[0]);
|
||||
CoreNetwork();
|
||||
void setup_logger(bool debug) {
|
||||
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||
console_sink->set_pattern("[%H:%M:%S] [%^%l%$] %v");
|
||||
if (debug) {
|
||||
console_sink->set_level(spdlog::level::debug);
|
||||
} else {
|
||||
console_sink->set_level(spdlog::level::info);
|
||||
}
|
||||
|
||||
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("Launcher.log", true);
|
||||
file_sink->set_level(spdlog::level::trace);
|
||||
file_sink->set_pattern("[%H:%M:%S.%e] [%t] [%L] %v");
|
||||
|
||||
default_logger = std::make_shared<spdlog::logger>(spdlog::logger("default", { console_sink, file_sink }));
|
||||
|
||||
default_logger->set_level(spdlog::level::trace);
|
||||
default_logger->flush_on(spdlog::level::trace);
|
||||
|
||||
spdlog::set_default_logger(default_logger);
|
||||
|
||||
spdlog::debug("Logger initialized");
|
||||
}
|
||||
|
||||
/*
|
||||
int oldmain(int argc, char* argv[]) {
|
||||
#ifdef DEBUG
|
||||
std::thread th(flush);
|
||||
th.detach();
|
||||
#endif
|
||||
GetEP(argv[0]);
|
||||
|
||||
InitLauncher(argc, argv);
|
||||
|
||||
try {
|
||||
LegitimacyCheck();
|
||||
} catch (std::exception& e) {
|
||||
fatal("Main 1 : " + std::string(e.what()));
|
||||
}
|
||||
|
||||
StartProxy();
|
||||
PreGame(GetGameDir());
|
||||
InitGame(GetGameDir());
|
||||
CoreNetwork();
|
||||
|
||||
/// TODO: make sure to use argv[0] for everything that should be in the same dir (mod down ect...)
|
||||
}
|
||||
*/
|
||||
|
||||
3
tests/test_main.cpp
Normal file
3
tests/test_main.cpp
Normal file
@@ -0,0 +1,3 @@
|
||||
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
|
||||
#include <doctest/doctest.h>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user