10 Commits

Author SHA1 Message Date
Lion Kortlepel
5e5fe80202 set terminate = false 2024-06-04 20:03:53 +02:00
Lion Kortlepel
7ff4681263 Revert "move NetReset"
This reverts commit 3be1262b07.
2024-06-04 19:32:58 +02:00
Lion Kortlepel
3be1262b07 move NetReset 2024-06-04 19:12:37 +02:00
Lion Kortlepel
cfcabf31a4 fix stupid socket 2024-06-04 18:42:38 +02:00
Lion Kortlepel
5714c3de76 move socket decls around 2024-06-04 18:08:38 +02:00
Lion Kortlepel
12711d77c7 add missing include 2024-06-04 17:42:44 +02:00
Lion Kortlepel
e08a4de6db fix for CSocket not existing 2024-06-04 17:38:54 +02:00
Lion Kortlepel
acd5f4ed09 prepend missing N 2024-06-04 17:34:14 +02:00
Lion Kortlepel
c4e7b9a919 send on correct socket 2024-06-04 17:33:12 +02:00
Lion Kortlepel
3db1f6773e add mod download warning 2024-06-04 16:45:02 +02:00
78 changed files with 1797 additions and 2865 deletions

View File

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

View File

@@ -1,42 +0,0 @@
name: CMake Linux Build
on: [push, pull_request, workflow_dispatch]
env:
BUILD_TYPE: Release
jobs:
linux-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Restore artifacts, or run vcpkg, build and cache artifacts
uses: lukka/run-vcpkg@v7
id: runvcpkg
with:
vcpkgArguments: 'zlib nlohmann-json openssl cpp-httplib[openssl]'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '40616a5e954f7be1077ef37db3fbddbd5dcd1ca6'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_TOOLCHAIN_FILE='${{ runner.workspace }}/b/vcpkg/scripts/buildsystems/vcpkg.cmake'
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Archive artifacts
uses: actions/upload-artifact@v2
with:
name: BeamMP-Launcher
path: ${{github.workspace}}/build-linux/BeamMP-Launcher

View File

@@ -1,6 +1,6 @@
name: CMake Windows Build name: CMake Windows Build
on: [push, pull_request, workflow_dispatch] on: [push, pull_request]
env: env:
BUILD_TYPE: Release BUILD_TYPE: Release
@@ -20,7 +20,7 @@ jobs:
with: with:
vcpkgArguments: 'discord-rpc zlib nlohmann-json openssl cpp-httplib[openssl]' vcpkgArguments: 'discord-rpc zlib nlohmann-json openssl cpp-httplib[openssl]'
vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg' vcpkgDirectory: '${{ runner.workspace }}/b/vcpkg'
vcpkgGitCommitId: '40616a5e954f7be1077ef37db3fbddbd5dcd1ca6' vcpkgGitCommitId: '16ee2ecb31788c336ace8bb14c21801efb6836e4'
vcpkgTriplet: 'x64-windows-static' vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment - name: Create Build Environment

View File

@@ -28,7 +28,6 @@ jobs:
body: | body: |
Files included in this release: Files included in this release:
- `BeamMP-Launcher.exe` windows build - `BeamMP-Launcher.exe` windows build
- `BeamMP-Launcher` linux build
upload-release-files-windows: upload-release-files-windows:
name: Upload Windows Release Files name: Upload Windows Release Files
@@ -71,34 +70,3 @@ jobs:
asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Launcher.exe asset_path: ${{github.workspace}}/build-windows/Release/BeamMP-Launcher.exe
asset_name: BeamMP-Launcher.exe asset_name: BeamMP-Launcher.exe
asset_content_type: application/vnd.microsoft.portable-executable asset_content_type: application/vnd.microsoft.portable-executable
upload-release-files-linux:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: 'true'
- name: Create Build Environment
run: cmake -E make_directory ${{github.workspace}}/build-linux
- name: Configure CMake
shell: bash
working-directory: ${{github.workspace}}/build-linux
run: cmake $GITHUB_WORKSPACE -DCMAKE_BUILD_TYPE=$BUILD_TYPE
- name: Build
working-directory: ${{github.workspace}}/build-linux
shell: bash
run: cmake --build . --config $BUILD_TYPE
- name: Upload Release Asset
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.create-release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps
asset_path: ${{github.workspace}}/build-linux/BeamMP-Launcher
asset_name: BeamMP-Launcher
asset_content_type: application/octet-stream

9
.gitignore vendored
View File

@@ -4,11 +4,4 @@ cmake-build-release
*.log *.log
/*.sh /*.sh
/*.obj /*.obj
/*.exe /*.exe
.cache/
.https_debug/
Launcher.cfg
Resources/
bin/
compile_commands.json
key

View File

@@ -1,5 +1,4 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(Launcher) project(Launcher)
if (WIN32) if (WIN32)
@@ -12,28 +11,32 @@ set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "src/*/*.hpp" "include/*.h" "include/*/*.h" "include/*/*/*.h" "include/*.hpp" "include/*/*.hpp" "include/*/*/*.hpp") file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "src/*/*.hpp" "include/*.h" "include/*/*.h" "include/*/*/*.h")
find_package(httplib CONFIG REQUIRED) find_package(httplib CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED) find_package(nlohmann_json CONFIG REQUIRED)
find_package(asio CONFIG REQUIRED)
find_package(fmt CONFIG REQUIRED)
add_executable(${PROJECT_NAME} ${source_files}) add_executable(${PROJECT_NAME} ${source_files})
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "BeamMP-Launcher") set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME "BeamMP-Launcher")
if (WIN32) if (WIN32)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
find_package(OpenSSL REQUIRED) find_package(OpenSSL REQUIRED)
#-DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
include_directories(${VcpkgRoot}/include)
link_directories(${VcpkgRoot}/lib)
target_link_libraries(${PROJECT_NAME} PRIVATE target_link_libraries(${PROJECT_NAME} PRIVATE
ZLIB::ZLIB OpenSSL::SSL OpenSSL::Crypto ws2_32 httplib::httplib nlohmann_json::nlohmann_json asio::asio fmt::fmt) ZLIB::ZLIB OpenSSL::SSL OpenSSL::Crypto ws2_32 httplib::httplib nlohmann_json::nlohmann_json)
elseif (LINUX)
find_package(ZLIB REQUIRED) if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
find_package(OpenSSL REQUIRED) target_link_libraries(${PROJECT_NAME} PRIVATE ${VcpkgRoot}/lib/discord-rpc.lib)
target_link_libraries(${PROJECT_NAME} PRIVATE else ()
ZLIB::ZLIB OpenSSL::SSL OpenSSL::Crypto asio::asio fmt::fmt) target_link_libraries(${PROJECT_NAME} PRIVATE ${VcpkgRoot}/debug/lib/discord-rpc.lib)
elseif (WIN32) #MINGW endif()
else(WIN32) #MINGW
add_definitions("-D_WIN32_WINNT=0x0600") add_definitions("-D_WIN32_WINNT=0x0600")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -s --static") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -s --static")
target_link_libraries(${PROJECT_NAME} ssl crypto ws2_32 ssp crypt32 z asio::asio fmt::fmt) target_link_libraries(${PROJECT_NAME} discord-rpc ssl crypto ws2_32 ssp crypt32 z)
endif(WIN32) endif(WIN32)
target_include_directories(${PROJECT_NAME} PRIVATE "include") target_include_directories(${PROJECT_NAME} PRIVATE "include")

View File

@@ -2,10 +2,6 @@
The launcher is the way we communitcate to outside the game, it does a few automated actions such as but not limited to: downloading the mod, launching the game, and create a connection to a server. The launcher is the way we communitcate to outside the game, it does a few automated actions such as but not limited to: downloading the mod, launching the game, and create a connection to a server.
## How to build
1. `cmake . -B bin -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static`
2. `cmake --build bin --parallel`
Copyright (c) 2019-present Anonymous275. Copyright (c) 2019-present Anonymous275.
BeamMP Launcher code is not in the public domain and is not free software. BeamMP Launcher code is not in the public domain and is not free software.

15
include/Discord/discord_info.h Executable file
View File

@@ -0,0 +1,15 @@
// 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/16/2020
///
#pragma once
#include <string>
void Discord_Main();
std::string GetDName();
std::string GetDTag();
std::string GetDID();
void DAboard();

View File

@@ -0,0 +1,26 @@
#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

View File

@@ -0,0 +1,87 @@
#pragma once
#include <cstdint>
// 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

View File

@@ -1,11 +0,0 @@
#include <span>
#include <string>
#include <vector>
#pragma once
using ByteSpan = std::span<const char>;
std::string bytespan_to_string(ByteSpan span);
std::vector<char> strtovec(std::string_view str);

7
include/Http.h Normal file → Executable file
View File

@@ -6,15 +6,14 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include "Logger.h"
#include <string> #include <string>
#include "Logger.h"
class HTTP { class HTTP {
public: public:
static bool Download(const std::string& IP, const std::string& Path); 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 Post(const std::string& IP, const std::string& Fields);
static std::string Get(const std::string& IP); static std::string Get(const std::string &IP);
static bool ProgressBar(size_t c, size_t t); static bool ProgressBar(size_t c, size_t t);
public: public:
static bool isDownload; static bool isDownload;
}; };

3
include/Logger.h Normal file → Executable file
View File

@@ -6,8 +6,8 @@
/// Created by Anonymous275 on 4/2/2020. /// Created by Anonymous275 on 4/2/2020.
/// ///
#pragma once #pragma once
#include <iostream>
#include <string> #include <string>
#include <iostream>
void InitLog(); void InitLog();
void except(const std::string& toPrint); void except(const std::string& toPrint);
void fatal(const std::string& toPrint); void fatal(const std::string& toPrint);
@@ -15,4 +15,3 @@ void debug(const std::string& toPrint);
void error(const std::string& toPrint); void error(const std::string& toPrint);
void info(const std::string& toPrint); void info(const std::string& toPrint);
void warn(const std::string& toPrint); void warn(const std::string& toPrint);
std::string getDate();

51
include/Network/network.h Executable file
View File

@@ -0,0 +1,51 @@
// 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>
void NetReset();
extern bool Dev;
extern int ping;
extern bool ModWarningConfirmed;
[[noreturn]] void CoreNetwork();
extern int ProxyPort;
extern int ClientID;
extern int LastPort;
extern bool ModLoaded;
extern bool Terminate;
extern int DEFAULT_PORT;
extern uint64_t UDPSock;
extern uint64_t TCPSock;
extern std::string Branch;
extern bool TCPTerminate;
extern std::string LastIP;
extern std::string MStatus;
extern std::string UlStatus;
extern std::string PublicKey;
extern std::string PrivateKey;
extern std::string ListOfMods;
int KillSocket(uint64_t Dead);
void UUl(const std::string& R);
void UDPSend(std::string Data);
bool CheckBytes(int32_t Bytes);
void GameSend(std::string Data);
void SendLarge(std::string Data);
std::string TCPRcv(uint64_t Sock);
void SyncResources(uint64_t TCPSock);
std::string GetAddr(const std::string&IP);
void ServerParser(const std::string& Data);
std::string Login(const std::string& fields);
void TCPSend(const std::string&Data,uint64_t Sock);
void TCPClientMain(const std::string& IP,int Port);
void UDPClientMain(const std::string& IP,int Port);
void TCPGameServer(const std::string& IP, int Port);

View File

@@ -1,66 +0,0 @@
// 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 "Helpers.h"
#include "asio/io_context.hpp"
#include "asio/ip/address.hpp"
#include <span>
#include <string>
#ifdef __linux__
#include "linuxfixes.h"
#include <bits/types/siginfo_t.h>
#include <cstdint>
#include <sys/ucontext.h>
#include <vector>
#endif
#include <asio.hpp>
extern asio::io_context io;
void NetReset();
extern bool Dev;
extern int ping;
[[noreturn]] void CoreNetwork();
extern int ProxyPort;
extern int ClientID;
extern int LastPort;
extern bool ModLoaded;
extern bool Terminate;
extern int DEFAULT_PORT;
extern std::shared_ptr<asio::ip::udp::socket> UDPSock;
extern std::shared_ptr<asio::ip::tcp::socket> TCPSock;
extern std::string Branch;
extern bool TCPTerminate;
extern std::string LastIP;
extern std::string MStatus;
extern std::string UlStatus;
extern std::string PublicKey;
extern std::string PrivateKey;
extern std::string ListOfMods;
void KillSocket(std::shared_ptr<asio::ip::tcp::socket>& Dead);
void KillSocket(std::shared_ptr<asio::ip::udp::socket>& Dead);
void KillSocket(asio::ip::tcp::socket& Dead);
void KillSocket(asio::ip::udp::socket& Dead);
void UUl(const std::string& R);
void UDPSend(const std::vector<char>& Data);
bool CheckBytes(int32_t Bytes);
void GameSend(std::string_view Data);
void SendLarge(const std::vector<char>& Data);
std::string TCPRcv(asio::ip::tcp::socket& Sock);
void SyncResources(asio::ip::tcp::socket& TCPSock);
std::string GetAddr(const std::string& IP);
void ServerParser(std::string_view Data);
std::string Login(const std::string& fields);
void TCPSend(const std::vector<char>& Data, asio::ip::tcp::socket& Sock);
void TCPClientMain(asio::ip::tcp::socket&& Socket);
void UDPClientMain(asio::ip::address addr, uint16_t port);
void TCPGameServer(asio::ip::tcp::socket&& Socket);

View File

@@ -1,6 +0,0 @@
#pragma once
#include <asio.hpp>
#include <vector>
void ReceiveFromGame(asio::ip::tcp::socket& socket, std::vector<char>& out_data);

0
include/Security/Game.h Normal file → Executable file
View File

2
include/Security/Init.h Normal file → Executable file
View File

@@ -8,7 +8,7 @@
#pragma once #pragma once
#include <string> #include <string>
void PreGame(const std::string& GamePath); void PreGame(const std::string& GamePath);
std::string CheckVer(const std::string& path); std::string CheckVer(const std::string &path);
void InitGame(const std::string& Dir); void InitGame(const std::string& Dir);
std::string GetGameDir(); std::string GetGameDir();
void LegitimacyCheck(); void LegitimacyCheck();

11
include/Startup.h Normal file → Executable file
View File

@@ -6,12 +6,12 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <compare>
#include <string> #include <string>
#include <compare>
#include <vector> #include <vector>
void InitLauncher(int argc, char* argv[]); void InitLauncher(int argc, char* argv[]);
std::string GetEP(char* P = nullptr); std::string GetEP(char*P = nullptr);
std::string GetGamePath(); std::string GetGamePath();
std::string GetVer(); std::string GetVer();
std::string GetEN(); std::string GetEN();
@@ -19,3 +19,10 @@ void StartProxy();
void ConfigInit(); void ConfigInit();
extern bool Dev; extern bool Dev;
struct VersionParser {
explicit VersionParser(const std::string& from_string);
std::strong_ordering operator<=>(VersionParser const& rhs) const noexcept;
bool operator==(VersionParser const& rhs) const noexcept;
std::vector<std::string> split;
std::vector<size_t> data;
};

8
include/Zlib/Compressor.h Normal file → Executable file
View File

@@ -6,8 +6,6 @@
/// Created by Anonymous275 on 7/24/2020 /// Created by Anonymous275 on 7/24/2020
/// ///
#pragma once #pragma once
#include <span> #include <string>
#include <vector> std::string Comp(std::string Data);
std::string DeComp(std::string Compressed);
std::vector<char> Comp(std::span<const char> input);
std::vector<char> DeComp(std::span<const char> input);

View File

@@ -1,19 +0,0 @@
#ifndef _LINUXFIXES_H
#define _LINUXFIXES_H
#include <stdint.h>
// Translate windows sockets stuff to linux sockets
#define SOCKET uint64_t
#define SOCKADDR sockaddr
#define SOCKADDR_IN sockaddr_in
#define WSAGetLastError() errno
#define closesocket close
#define SD_BOTH SHUT_RDWR
// We dont need wsacleanup
#define WSACleanup()
#define SOCKET_ERROR -1
#define ZeroMemory(mem, len) memset(mem, 0, len)
#endif

0
include/rapidjson/allocators.h Normal file → Executable file
View File

0
include/rapidjson/cursorstreamwrapper.h Normal file → Executable file
View File

0
include/rapidjson/document.h Normal file → Executable file
View File

0
include/rapidjson/encodedstream.h Normal file → Executable file
View File

0
include/rapidjson/encodings.h Normal file → Executable file
View File

0
include/rapidjson/error/en.h Normal file → Executable file
View File

0
include/rapidjson/error/error.h Normal file → Executable file
View File

0
include/rapidjson/filereadstream.h Normal file → Executable file
View File

0
include/rapidjson/filewritestream.h Normal file → Executable file
View File

0
include/rapidjson/fwd.h Normal file → Executable file
View File

0
include/rapidjson/internal/biginteger.h Normal file → Executable file
View File

0
include/rapidjson/internal/clzll.h Normal file → Executable file
View File

0
include/rapidjson/internal/diyfp.h Normal file → Executable file
View File

0
include/rapidjson/internal/dtoa.h Normal file → Executable file
View File

0
include/rapidjson/internal/ieee754.h Normal file → Executable file
View File

0
include/rapidjson/internal/itoa.h Normal file → Executable file
View File

0
include/rapidjson/internal/meta.h Normal file → Executable file
View File

0
include/rapidjson/internal/pow10.h Normal file → Executable file
View File

0
include/rapidjson/internal/regex.h Normal file → Executable file
View File

0
include/rapidjson/internal/stack.h Normal file → Executable file
View File

0
include/rapidjson/internal/strfunc.h Normal file → Executable file
View File

0
include/rapidjson/internal/strtod.h Normal file → Executable file
View File

0
include/rapidjson/internal/swap.h Normal file → Executable file
View File

0
include/rapidjson/istreamwrapper.h Normal file → Executable file
View File

0
include/rapidjson/memorybuffer.h Normal file → Executable file
View File

0
include/rapidjson/memorystream.h Normal file → Executable file
View File

0
include/rapidjson/msinttypes/inttypes.h Normal file → Executable file
View File

0
include/rapidjson/msinttypes/stdint.h Normal file → Executable file
View File

0
include/rapidjson/ostreamwrapper.h Normal file → Executable file
View File

0
include/rapidjson/pointer.h Normal file → Executable file
View File

0
include/rapidjson/prettywriter.h Normal file → Executable file
View File

0
include/rapidjson/rapidjson.h Normal file → Executable file
View File

0
include/rapidjson/reader.h Normal file → Executable file
View File

0
include/rapidjson/schema.h Normal file → Executable file
View File

0
include/rapidjson/stream.h Normal file → Executable file
View File

0
include/rapidjson/stringbuffer.h Normal file → Executable file
View File

0
include/rapidjson/writer.h Normal file → Executable file
View File

View File

@@ -1,730 +0,0 @@
//MIT License
//
//Copyright(c) 2016 Matthias Moeller
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
#ifndef __TYTI_STEAM_VDF_PARSER_H__
#define __TYTI_STEAM_VDF_PARSER_H__
#include <map>
#include <vector>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <memory>
#include <unordered_set>
#include <algorithm>
#include <iterator>
#include <functional>
#include <system_error>
#include <exception>
//for wstring support
#include <locale>
#include <string>
// internal
#include <stack>
//VS < 2015 has only partial C++11 support
#if defined(_MSC_VER) && _MSC_VER < 1900
#ifndef CONSTEXPR
#define CONSTEXPR
#endif
#ifndef NOEXCEPT
#define NOEXCEPT
#endif
#else
#ifndef CONSTEXPR
#define CONSTEXPR constexpr
#define TYTI_UNDEF_CONSTEXPR
#endif
#ifndef NOEXCEPT
#define NOEXCEPT noexcept
#define TYTI_UNDEF_NOEXCEPT
#endif
#endif
namespace tyti
{
namespace vdf
{
namespace detail
{
///////////////////////////////////////////////////////////////////////////
// Helper functions selecting the right encoding (char/wchar_T)
///////////////////////////////////////////////////////////////////////////
template <typename T>
struct literal_macro_help
{
static CONSTEXPR const char* result(const char* c, const wchar_t*) NOEXCEPT
{
return c;
}
static CONSTEXPR const char result(const char c, const wchar_t) NOEXCEPT
{
return c;
}
};
template <>
struct literal_macro_help<wchar_t>
{
static CONSTEXPR const wchar_t* result(const char*, const wchar_t* wc) NOEXCEPT
{
return wc;
}
static CONSTEXPR const wchar_t result(const char, const wchar_t wc) NOEXCEPT
{
return wc;
}
};
#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)
inline std::string string_converter(const std::string& w) NOEXCEPT
{
return w;
}
// utility wrapper to adapt locale-bound facets for wstring/wbuffer convert
// from cppreference
template <class Facet>
struct deletable_facet : Facet
{
template <class... Args>
deletable_facet(Args &&... args) : Facet(std::forward<Args>(args)...) {}
~deletable_facet() {}
};
inline std::string string_converter(const std::wstring& w) //todo: use us-locale
{
std::wstring_convert<deletable_facet<std::codecvt<wchar_t, char, std::mbstate_t>>> conv1;
return conv1.to_bytes(w);
}
///////////////////////////////////////////////////////////////////////////
// Writer helper functions
///////////////////////////////////////////////////////////////////////////
template <typename charT>
class tabs
{
const size_t t;
public:
explicit CONSTEXPR tabs(size_t i) NOEXCEPT : t(i) {}
std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT, '\t')); }
inline CONSTEXPR tabs operator+(size_t i) const NOEXCEPT
{
return tabs(t + i);
}
};
template <typename oStreamT>
oStreamT& operator<<(oStreamT& s, const tabs<typename oStreamT::char_type> t)
{
s << t.print();
return s;
}
} // end namespace detail
///////////////////////////////////////////////////////////////////////////
// Interface
///////////////////////////////////////////////////////////////////////////
/// custom objects and their corresponding write functions
/// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens
template <typename CharT>
struct basic_object
{
typedef CharT char_type;
std::basic_string<char_type> name;
std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type>> attribs;
std::unordered_map<std::basic_string<char_type>, std::shared_ptr<basic_object<char_type>>> childs;
void add_attribute(std::basic_string<char_type> key, std::basic_string<char_type> value)
{
attribs.emplace(std::move(key), std::move(value));
}
void add_child(std::unique_ptr<basic_object<char_type>> child)
{
std::shared_ptr<basic_object<char_type>> obj{ child.release() };
childs.emplace(obj->name, obj);
}
void set_name(std::basic_string<char_type> n)
{
name = std::move(n);
}
};
template <typename CharT>
struct basic_multikey_object
{
typedef CharT char_type;
std::basic_string<char_type> name;
std::unordered_multimap<std::basic_string<char_type>, std::basic_string<char_type>> attribs;
std::unordered_multimap<std::basic_string<char_type>, std::shared_ptr<basic_multikey_object<char_type>>> childs;
void add_attribute(std::basic_string<char_type> key, std::basic_string<char_type> value)
{
attribs.emplace(std::move(key), std::move(value));
}
void add_child(std::unique_ptr<basic_multikey_object<char_type>> child)
{
std::shared_ptr<basic_multikey_object<char_type>> obj{ child.release() };
childs.emplace(obj->name, obj);
}
void set_name(std::basic_string<char_type> n)
{
name = std::move(n);
}
};
typedef basic_object<char> object;
typedef basic_object<wchar_t> wobject;
typedef basic_multikey_object<char> multikey_object;
typedef basic_multikey_object<wchar_t> wmultikey_object;
struct Options
{
bool strip_escape_symbols;
bool ignore_all_platform_conditionals;
bool ignore_includes;
Options() : strip_escape_symbols(true), ignore_all_platform_conditionals(false), ignore_includes(false) {}
};
//forward decls
//forward decl
template <typename OutputT, typename iStreamT>
OutputT read(iStreamT& inStream, const Options& opt = Options{});
/** \brief writes given object tree in vdf format to given stream.
Output is prettyfied, using tabs
*/
template <typename oStreamT, typename T>
void write(oStreamT& s, const T& r,
const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>(0))
{
typedef typename oStreamT::char_type charT;
using namespace detail;
s << tab << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tab << TYTI_L(charT, "{\n");
for (const auto& i : r.attribs)
s << tab + 1 << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n");
for (const auto& i : r.childs)
if (i.second)
write(s, *i.second, tab + 1);
s << tab << TYTI_L(charT, "}\n");
}
namespace detail
{
template <typename iStreamT>
std::basic_string<typename iStreamT::char_type> read_file(iStreamT& inStream)
{
// cache the file
typedef typename iStreamT::char_type charT;
std::basic_string<charT> str;
inStream.seekg(0, std::ios::end);
str.resize(static_cast<size_t>(inStream.tellg()));
if (str.empty())
return str;
inStream.seekg(0, std::ios::beg);
inStream.read(&str[0], str.size());
return str;
}
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
@param exclude_files list of files which cant be included anymore.
prevents circular includes
can thow:
- "std::runtime_error" if a parsing error occured
- "std::bad_alloc" if not enough memory coup be allocated
*/
template <typename OutputT, typename IterT>
std::vector<std::unique_ptr<OutputT>> read_internal(IterT first, const IterT last,
std::unordered_set<std::basic_string<typename std::iterator_traits<IterT>::value_type>>& exclude_files,
const Options& opt)
{
static_assert(std::is_default_constructible<OutputT>::value,
"Output Type must be default constructible (provide constructor without arguments)");
static_assert(std::is_move_constructible<OutputT>::value,
"Output Type must be move constructible");
typedef typename std::iterator_traits<IterT>::value_type charT;
const std::basic_string<charT> comment_end_str = TYTI_L(charT, "*/");
const std::basic_string<charT> whitespaces = TYTI_L(charT, " \n\v\f\r\t");
#ifdef WIN32
std::function<bool(const std::basic_string<charT>&)> is_platform_str = [](const std::basic_string<charT>& in) {
return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$WINDOWS");
};
#elif __APPLE__
// WIN32 stands for pc in general
std::function<bool(const std::basic_string<charT>&)> is_platform_str = [](const std::basic_string<charT>& in) {
return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$POSIX") || in == TYTI_L(charT, "$OSX");
};
#elif __linux__
// WIN32 stands for pc in general
std::function<bool(const std::basic_string<charT>&)> is_platform_str = [](const std::basic_string<charT>& in) {
return in == TYTI_L(charT, "$WIN32") || in == TYTI_L(charT, "$POSIX") || in == TYTI_L(charT, "$LINUX");
};
#else
std::function<bool(const std::basic_string<charT>&)> is_platform_str = [](const std::basic_string<charT>& in) {
return false;
};
#endif
if (opt.ignore_all_platform_conditionals)
is_platform_str = [](const std::basic_string<charT>&) {
return false;
};
// function for skipping a comment block
// iter: iterator poition to the position after a '/'
auto skip_comments = [&comment_end_str](IterT iter, const IterT& last) -> IterT {
++iter;
if (iter != last)
{
if (*iter == TYTI_L(charT, '/'))
{
// line comment, skip whole line
iter = std::find(iter + 1, last, TYTI_L(charT, '\n'));
}
if (*iter == '*')
{
// block comment, skip until next occurance of "*\"
iter = std::search(iter + 1, last, std::begin(comment_end_str), std::end(comment_end_str));
iter += 2;
}
}
return iter;
};
auto end_quote = [](IterT iter, const IterT& last) -> IterT {
const auto begin = iter;
auto last_esc = iter;
do
{
++iter;
iter = std::find(iter, last, TYTI_L(charT, '\"'));
if (iter == last)
break;
last_esc = std::prev(iter);
while (last_esc != begin && *last_esc == '\\')
--last_esc;
} while (!(std::distance(last_esc, iter) % 2));
if (iter == last)
throw std::runtime_error{ "quote was opened but not closed." };
return iter;
};
auto end_word = [&whitespaces](IterT iter, const IterT& last) -> IterT {
const auto begin = iter;
auto last_esc = iter;
do
{
++iter;
iter = std::find_first_of(iter, last, std::begin(whitespaces), std::end(whitespaces));
if (iter == last)
break;
last_esc = std::prev(iter);
while (last_esc != begin && *last_esc == '\\')
--last_esc;
} while (!(std::distance(last_esc, iter) % 2));
//if (iter == last)
// throw std::runtime_error{ "word wasnt properly ended" };
return iter;
};
auto skip_whitespaces = [&whitespaces](IterT iter, const IterT& last) -> IterT {
iter = std::find_if_not(iter, last, [&whitespaces](charT c) {
// return true if whitespace
return std::any_of(std::begin(whitespaces), std::end(whitespaces), [c](charT pc) { return pc == c; });
});
return iter;
};
std::function<void(std::basic_string<charT>&)> strip_escape_symbols = [](std::basic_string<charT>& s) {
auto quote_searcher = [&s](size_t pos) { return s.find(TYTI_L(charT, "\\\""), pos); };
auto p = quote_searcher(0);
while (p != s.npos)
{
s.replace(p, 2, TYTI_L(charT, "\""));
p = quote_searcher(p);
}
auto searcher = [&s](size_t pos) { return s.find(TYTI_L(charT, "\\\\"), pos); };
p = searcher(0);
while (p != s.npos)
{
s.replace(p, 2, TYTI_L(charT, "\\"));
p = searcher(p);
}
};
if (!opt.strip_escape_symbols)
strip_escape_symbols = [](std::basic_string<charT>&) {};
auto conditional_fullfilled = [&skip_whitespaces, &is_platform_str](IterT& iter, const IterT& last) {
iter = skip_whitespaces(iter, last);
if (*iter == '[')
{
++iter;
const auto end = std::find(iter, last, ']');
const bool negate = *iter == '!';
if (negate)
++iter;
auto conditional = std::basic_string<charT>(iter, end);
const bool is_platform = is_platform_str(conditional);
iter = end + 1;
return static_cast<bool>(is_platform ^ negate);
}
return true;
};
//read header
// first, quoted name
std::unique_ptr<OutputT> curObj = nullptr;
std::vector<std::unique_ptr<OutputT>> roots;
std::stack<std::unique_ptr<OutputT>> lvls;
auto curIter = first;
while (curIter != last && *curIter != '\0')
{
//find first starting attrib/child, or ending
curIter = skip_whitespaces(curIter, last);
if (curIter == last || *curIter == '\0')
break;
if (*curIter == TYTI_L(charT, '/'))
{
curIter = skip_comments(curIter, last);
}
else if (*curIter != TYTI_L(charT, '}'))
{
// get key
const auto keyEnd = (*curIter == TYTI_L(charT, '\"')) ? end_quote(curIter, last) : end_word(curIter, last);
if (*curIter == TYTI_L(charT, '\"'))
++curIter;
std::basic_string<charT> key(curIter, keyEnd);
strip_escape_symbols(key);
curIter = keyEnd + ((*keyEnd == TYTI_L(charT, '\"')) ? 1 : 0);
curIter = skip_whitespaces(curIter, last);
auto conditional = conditional_fullfilled(curIter, last);
if (!conditional)
continue;
while (*curIter == TYTI_L(charT, '/'))
{
curIter = skip_comments(curIter, last);
if (curIter == last || *curIter == '}')
throw std::runtime_error{ "key declared, but no value" };
curIter = skip_whitespaces(curIter, last);
if (curIter == last || *curIter == '}')
throw std::runtime_error{ "key declared, but no value" };
}
// get value
if (*curIter != '{')
{
const auto valueEnd = (*curIter == TYTI_L(charT, '\"')) ? end_quote(curIter, last) : end_word(curIter, last);
if (*curIter == TYTI_L(charT, '\"'))
++curIter;
auto value = std::basic_string<charT>(curIter, valueEnd);
strip_escape_symbols(value);
curIter = valueEnd + ((*valueEnd == TYTI_L(charT, '\"')) ? 1 : 0);
auto conditional = conditional_fullfilled(curIter, last);
if (!conditional)
continue;
// process value
if (key != TYTI_L(charT, "#include") && key != TYTI_L(charT, "#base"))
{
if (curObj)
{
curObj->add_attribute(std::move(key), std::move(value));
}
else
{
throw std::runtime_error{ "unexpected key without object" };
}
}
else
{
if (!opt.ignore_includes && exclude_files.find(value) == exclude_files.end())
{
exclude_files.insert(value);
std::basic_ifstream<charT> i(detail::string_converter(value));
auto str = read_file(i);
auto file_objs = read_internal<OutputT>(str.begin(), str.end(), exclude_files, opt);
for (auto& n : file_objs)
{
if (curObj)
curObj->add_child(std::move(n));
else
roots.push_back(std::move(n));
}
exclude_files.erase(value);
}
}
}
else if (*curIter == '{')
{
if (curObj)
lvls.push(std::move(curObj));
curObj = std::make_unique<OutputT>();
curObj->set_name(std::move(key));
++curIter;
}
}
//end of new object
else if (curObj && *curIter == TYTI_L(charT, '}'))
{
if (!lvls.empty())
{
//get object before
std::unique_ptr<OutputT> prev{ std::move(lvls.top()) };
lvls.pop();
// add finished obj to obj before and release it from processing
prev->add_child(std::move(curObj));
curObj = std::move(prev);
}
else
{
roots.push_back(std::move(curObj));
curObj.reset();
}
++curIter;
}
else
{
throw std::runtime_error{ "unexpected '}'" };
}
}
if (curObj != nullptr || !lvls.empty())
{
throw std::runtime_error{ "object is not closed with '}'" };
}
return roots;
}
} // namespace detail
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
can thow:
- "std::runtime_error" if a parsing error occured
- "std::bad_alloc" if not enough memory coup be allocated
*/
template <typename OutputT, typename IterT>
OutputT read(IterT first, const IterT last, const Options& opt = Options{})
{
auto exclude_files = std::unordered_set<std::basic_string<typename std::iterator_traits<IterT>::value_type>>{};
auto roots = detail::read_internal<OutputT>(first, last, exclude_files, opt);
OutputT result;
if (roots.size() > 1)
{
for (auto& i : roots)
result.add_child(std::move(i));
}
else if (roots.size() == 1)
result = std::move(*roots[0]);
return result;
}
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
@param ec output bool. 0 if ok, otherwise, holds an system error code
Possible error codes:
std::errc::protocol_error: file is mailformatted
std::errc::not_enough_memory: not enough space
std::errc::invalid_argument: iterators throws e.g. out of range
*/
template <typename OutputT, typename IterT>
OutputT read(IterT first, IterT last, std::error_code& ec, const Options& opt = Options{}) NOEXCEPT
{
ec.clear();
OutputT r{};
try
{
r = read<OutputT>(first, last, opt);
}
catch (std::runtime_error&)
{
ec = std::make_error_code(std::errc::protocol_error);
}
catch (std::bad_alloc&)
{
ec = std::make_error_code(std::errc::not_enough_memory);
}
catch (...)
{
ec = std::make_error_code(std::errc::invalid_argument);
}
return r;
}
/** \brief Read VDF formatted sequences defined by the range [first, last).
If the file is mailformatted, parser will try to read it until it can.
@param first begin iterator
@param end end iterator
@param ok output bool. true, if parser successed, false, if parser failed
*/
template <typename OutputT, typename IterT>
OutputT read(IterT first, const IterT last, bool* ok, const Options& opt = Options{}) NOEXCEPT
{
std::error_code ec;
auto r = read<OutputT>(first, last, ec, opt);
if (ok)
*ok = !ec;
return r;
}
template <typename IterT>
inline auto read(IterT first, const IterT last, bool* ok, const Options& opt = Options{}) NOEXCEPT -> basic_object<typename std::iterator_traits<IterT>::value_type>
{
return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, ok, opt);
}
template <typename IterT>
inline auto read(IterT first, IterT last, std::error_code& ec, const Options& opt = Options{}) NOEXCEPT
-> basic_object<typename std::iterator_traits<IterT>::value_type>
{
return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, ec, opt);
}
template <typename IterT>
inline auto read(IterT first, const IterT last, const Options& opt = Options{})
-> basic_object<typename std::iterator_traits<IterT>::value_type>
{
return read<basic_object<typename std::iterator_traits<IterT>::value_type>>(first, last, opt);
}
/** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
throws "std::bad_alloc" if file buffer could not be allocated
*/
template <typename OutputT, typename iStreamT>
OutputT read(iStreamT& inStream, std::error_code& ec, const Options& opt = Options{})
{
// cache the file
typedef typename iStreamT::char_type charT;
std::basic_string<charT> str = detail::read_file(inStream);
// parse it
return read<OutputT>(str.begin(), str.end(), ec, opt);
}
template <typename iStreamT>
inline basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec, const Options& opt = Options{})
{
return read<basic_object<typename iStreamT::char_type>>(inStream, ec, opt);
}
/** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
throws "std::bad_alloc" if file buffer could not be allocated
ok == false, if a parsing error occured
*/
template <typename OutputT, typename iStreamT>
OutputT read(iStreamT& inStream, bool* ok, const Options& opt = Options{})
{
std::error_code ec;
const auto r = read<OutputT>(inStream, ec, opt);
if (ok)
*ok = !ec;
return r;
}
template <typename iStreamT>
inline basic_object<typename iStreamT::char_type> read(iStreamT& inStream, bool* ok, const Options& opt = Options{})
{
return read<basic_object<typename iStreamT::char_type>>(inStream, ok, opt);
}
/** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
throws "std::bad_alloc" if file buffer could not be allocated
throws "std::runtime_error" if a parsing error occured
*/
template <typename OutputT, typename iStreamT>
OutputT read(iStreamT& inStream, const Options& opt)
{
// cache the file
typedef typename iStreamT::char_type charT;
std::basic_string<charT> str = detail::read_file(inStream);
// parse it
return read<OutputT>(str.begin(), str.end(), opt);
}
template <typename iStreamT>
inline basic_object<typename iStreamT::char_type> read(iStreamT& inStream, const Options& opt = Options{})
{
return read<basic_object<typename iStreamT::char_type>>(inStream, opt);
}
} // namespace vdf
} // namespace tyti
#ifndef TYTI_NO_L_UNDEF
#undef TYTI_L
#endif
#ifdef TYTI_UNDEF_CONSTEXPR
#undef CONSTEXPR
#undef TYTI_NO_L_UNDEF
#endif
#ifdef TYTI_UNDEF_NOTHROW
#undef NOTHROW
#undef TYTI_UNDEF_NOTHROW
#endif
#endif //__TYTI_STEAM_VDF_PARSER_H__

95
src/Compressor.cpp Normal file → Executable file
View File

@@ -6,58 +6,49 @@
/// Created by Anonymous275 on 7/15/2020 /// Created by Anonymous275 on 7/15/2020
/// ///
#include "Logger.h" #include <iostream>
#include <span>
#include <vector>
#include <zconf.h>
#include <zlib.h> #include <zlib.h>
#ifdef __linux__
#include <cstring>
#endif
std::vector<char> Comp(std::span<const char> input) { #define Biggest 30000
auto max_size = compressBound(input.size()); std::string Comp(std::string Data){
std::vector<char> output(max_size); char*C = new char[Biggest];
uLongf output_size = output.size(); memset(C, 0, Biggest);
int res = compress2( z_stream defstream;
reinterpret_cast<Bytef*>(output.data()), defstream.zalloc = Z_NULL;
&output_size, defstream.zfree = Z_NULL;
reinterpret_cast<const Bytef*>(input.data()), defstream.opaque = Z_NULL;
static_cast<uLongf>(input.size()), defstream.avail_in = (uInt)Data.length();
3); defstream.next_in = (Bytef *)&Data[0];
if (res != Z_OK) { defstream.avail_out = Biggest;
error("zlib compress() failed: " + std::to_string(res)); defstream.next_out = reinterpret_cast<Bytef *>(C);
throw std::runtime_error("zlib compress() failed"); deflateInit(&defstream, Z_BEST_COMPRESSION);
} deflate(&defstream, Z_SYNC_FLUSH);
debug("zlib compressed " + std::to_string(input.size()) + " B to " + std::to_string(output_size) + " B"); deflate(&defstream, Z_FINISH);
output.resize(output_size); deflateEnd(&defstream);
return output; int TO = defstream.total_out;
} std::string Ret(TO,0);
memcpy_s(&Ret[0],TO,C,TO);
std::vector<char> DeComp(std::span<const char> input) { delete [] C;
std::vector<char> output_buffer(std::min<size_t>(input.size() * 5, 15 * 1024 * 1024)); return Ret;
uLongf output_size = output_buffer.size();
while (true) {
int res = uncompress(
reinterpret_cast<Bytef*>(output_buffer.data()),
&output_size,
reinterpret_cast<const Bytef*>(input.data()),
static_cast<uLongf>(input.size()));
if (res == Z_BUF_ERROR) {
if (output_buffer.size() > 30 * 1024 * 1024) {
throw std::runtime_error("decompressed packet size of 30 MB exceeded");
}
debug("zlib uncompress() failed, trying with 2x buffer size of " + std::to_string(output_buffer.size() * 2));
output_buffer.resize(output_buffer.size() * 2);
output_size = output_buffer.size();
} else if (res != Z_OK) {
error("zlib uncompress() failed: " + std::to_string(res));
throw std::runtime_error("zlib uncompress() failed");
} else if (res == Z_OK) {
break;
}
} output_buffer.resize(output_size);
return output_buffer;
} }
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;
}

117
src/Config.cpp Normal file → Executable file
View File

@@ -1,59 +1,58 @@
/// ///
/// Created by Anonymous275 on 2/23/2021 /// Created by Anonymous275 on 2/23/2021
/// ///
#include "Logger.h" #include <nlohmann/json.hpp>
#include "Network/network.hpp" #include "Network/network.h"
#include <cstdint> #include <filesystem>
#include <filesystem> #include "Logger.h"
#include <fstream> #include <fstream>
#include <nlohmann/json.hpp> #include <cstdint>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string Branch; std::string Branch;
void ParseConfig(const nlohmann::json& d) { void ParseConfig(const nlohmann::json& d){
if (d["Port"].is_number()) { if(d["Port"].is_number()){
DEFAULT_PORT = d["Port"].get<int>(); DEFAULT_PORT = d["Port"].get<int>();
} }
// Default -1 //Default -1
// Release 1 //Release 1
// EA 2 //EA 2
// Dev 3 //Dev 3
// Custom 3 //Custom 3
if (d["Build"].is_string()) { if(d["Build"].is_string()){
Branch = d["Build"].get<std::string>(); Branch = d["Build"].get<std::string>();
for (char& c : Branch) for(char& c : Branch)c = char(tolower(c));
c = char(tolower(c)); }
} }
}
void ConfigInit(){
void ConfigInit() { if(fs::exists("Launcher.cfg")){
if (fs::exists("Launcher.cfg")) { std::ifstream cfg("Launcher.cfg");
std::ifstream cfg("Launcher.cfg"); if(cfg.is_open()){
if (cfg.is_open()) { auto Size = fs::file_size("Launcher.cfg");
auto Size = fs::file_size("Launcher.cfg"); std::string Buffer(Size, 0);
std::string Buffer(Size, 0); cfg.read(&Buffer[0], Size);
cfg.read(&Buffer[0], Size); cfg.close();
cfg.close(); nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false); if(d.is_discarded()){
if (d.is_discarded()) { fatal("Config failed to parse make sure it's valid JSON!");
fatal("Config failed to parse make sure it's valid JSON!"); }
} ParseConfig(d);
ParseConfig(d); }else fatal("Failed to open Launcher.cfg!");
} else }else{
fatal("Failed to open Launcher.cfg!"); std::ofstream cfg("Launcher.cfg");
} else { if(cfg.is_open()){
std::ofstream cfg("Launcher.cfg"); cfg <<
if (cfg.is_open()) { R"({
cfg << "Port": 4444,
R"({ "Build": "Default"
"Port": 4444, })";
"Build": "Default" cfg.close();
})"; }else{
cfg.close(); fatal("Failed to write config on disk!");
} else { }
fatal("Failed to write config on disk!"); }
} }
}
}

111
src/Discord.cpp Executable file
View File

@@ -0,0 +1,111 @@
// 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/16/2020
///
#include "Discord/discord_rpc.h"
#include "Logger.h"
#include <cstring>
#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 = "Playing with friends!"; ///to be revisited
discordPresence.state = P.c_str();
//sprintf(buffer, "Frustration level: %d", FrustrationLevel);
//discordPresence.details = buffer;
discordPresence.startTimestamp = StartTime;
//discordPresence.endTimestamp = time(0) + 5 * 60;
discordPresence.largeImageKey = "mainlogo";
//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{
User->username,
User->discriminator,
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;*/
Discord_Initialize("629743237988352010", &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 DMain(){
discordInit();
Loop();
}
std::string GetDName(){
return DiscordInfo->Name;
}
std::string GetDTag(){
return DiscordInfo->Tag;
}
std::string GetDID(){
return DiscordInfo->DID;
}
void DAboard(){
DiscordInfo = nullptr;
}
void ErrorAboard(){
error("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("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();*/
}

110
src/GameStart.cpp Normal file → Executable file
View File

@@ -6,134 +6,64 @@
/// Created by Anonymous275 on 7/19/2020 /// Created by Anonymous275 on 7/19/2020
/// ///
#if defined(_WIN32)
#include <windows.h>
#elif defined(__linux__)
#include "vdf_parser.hpp"
#include <cerrno>
#include <cstring>
#include <pwd.h>
#include <spawn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#include "Logger.h"
#include "Startup.h"
#include <Security/Init.h> #include <Security/Init.h>
#include <filesystem> #include <windows.h>
#include "Startup.h"
#include "Logger.h"
#include <thread> #include <thread>
unsigned long GamePID = 0; unsigned long GamePID = 0;
#if defined(_WIN32) std::string QueryKey(HKEY hKey,int ID);
std::string QueryKey(HKEY hKey, int ID); std::string GetGamePath(){
std::string GetGamePath() {
static std::string Path; static std::string Path;
if (!Path.empty()) if(!Path.empty())return Path;
return Path;
HKEY hKey; HKEY hKey;
LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive"; LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive";
LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey); LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
if (openRes != ERROR_SUCCESS) { if (openRes != ERROR_SUCCESS){
fatal("Please launch the game at least once!"); fatal("Please launch the game at least once!");
} }
Path = QueryKey(hKey, 4); Path = QueryKey(hKey,4);
if (Path.empty()) { if(Path.empty()){
sk = R"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)"; sk = R"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders)";
openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey); openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS, &hKey);
if (openRes != ERROR_SUCCESS) { if (openRes != ERROR_SUCCESS){
fatal("Cannot get Local Appdata directory!"); fatal("Cannot get Local Appdata directory!");
} }
Path = QueryKey(hKey, 5); Path = QueryKey(hKey,5);
Path += "\\BeamNG.drive\\"; Path += "\\BeamNG.drive\\";
} }
std::string Ver = CheckVer(GetGameDir()); std::string Ver = CheckVer(GetGameDir());
Ver = Ver.substr(0, Ver.find('.', Ver.find('.') + 1)); Ver = Ver.substr(0,Ver.find('.',Ver.find('.')+1));
Path += Ver + "\\"; Path += Ver + "\\";
return Path; return Path;
} }
#elif defined(__linux__)
std::string GetGamePath() {
// Right now only steam is supported
struct passwd* pw = getpwuid(getuid());
std::string homeDir = pw->pw_dir;
std::string Path = homeDir + "/.local/share/BeamNG.drive/"; void StartGame(std::string Dir){
std::string Ver = CheckVer(GetGameDir());
Ver = Ver.substr(0, Ver.find('.', Ver.find('.') + 1));
Path += Ver + "/";
return Path;
}
#endif
#if defined(_WIN32)
void StartGame(std::string Dir) {
BOOL bSuccess = FALSE; BOOL bSuccess = FALSE;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
STARTUPINFO si = { 0 }; STARTUPINFO si = {0};
si.cb = sizeof(si); si.cb = sizeof(si);
std::string BaseDir = Dir; //+"\\Bin64"; std::string BaseDir = Dir; //+"\\Bin64";
// Dir += R"(\Bin64\BeamNG.drive.x64.exe)"; //Dir += R"(\Bin64\BeamNG.drive.x64.exe)";
Dir += "\\BeamNG.drive.exe"; Dir += "\\BeamNG.drive.exe";
bSuccess = CreateProcessA(Dir.c_str(), nullptr, nullptr, nullptr, TRUE, 0, nullptr, BaseDir.c_str(), &si, &pi); bSuccess = CreateProcessA(Dir.c_str(), nullptr, nullptr, nullptr, TRUE, 0, nullptr, BaseDir.c_str(), &si, &pi);
if (bSuccess) { if (bSuccess){
info("Game Launched!"); info("Game Launched!");
GamePID = pi.dwProcessId; GamePID = pi.dwProcessId;
WaitForSingleObject(pi.hProcess, INFINITE); WaitForSingleObject(pi.hProcess, INFINITE);
error("Game Closed! launcher closing soon"); error("Game Closed! launcher closing soon");
} else { }else{
error("Failed to Launch the game! launcher closing soon"); error("Failed to Launch the game! launcher closing soon");
} }
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
exit(2); exit(2);
} }
#elif defined(__linux__)
void StartGame(std::string Dir) {
std::string filename = (Dir + "/BinLinux/BeamNG.drive.x64");
char* argv[] = { filename.data(), NULL };
pid_t pid;
posix_spawn_file_actions_t file_actions; void InitGame(const std::string& Dir){
auto status = posix_spawn_file_actions_init(&file_actions); if(!Dev){
// disable stdout
if (status != 0) {
error(std::string("posix_spawn_file_actions_init failed: ") + std::strerror(errno));
}
status = posix_spawn_file_actions_addclose(&file_actions, STDOUT_FILENO);
if (status != 0) {
error(std::string("posix_spawn_file_actions_addclose for STDOUT failed: ") + std::strerror(errno));
}
status = posix_spawn_file_actions_addclose(&file_actions, STDERR_FILENO);
if (status != 0) {
error(std::string("posix_spawn_file_actions_addclose for STDERR failed: ") + std::strerror(errno));
}
// launch the game
int result = posix_spawn(&pid, filename.c_str(), &file_actions, NULL, argv, environ);
if (result != 0) {
error("Failed to Launch the game! launcher closing soon");
return;
} else {
waitpid(pid, &status, 0);
error("Game Closed! launcher closing soon");
}
status = posix_spawn_file_actions_destroy(&file_actions);
if (status != 0) {
warn(std::string("posix_spawn_file_actions_destroy failed: ") + std::strerror(errno));
}
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(2);
}
#endif
void InitGame(const std::string& Dir) {
if (!Dev) {
std::thread Game(StartGame, Dir); std::thread Game(StartGame, Dir);
Game.detach(); Game.detach();
} }

View File

@@ -1,9 +0,0 @@
#include "Helpers.h"
std::string bytespan_to_string(ByteSpan span) {
return std::string(span.data(), span.size());
}
std::vector<char> strtovec(std::string_view str) {
return std::vector<char>(str.begin(), str.end());
}

46
src/Logger.cpp Normal file → Executable file
View File

@@ -6,11 +6,11 @@
/// Created by Anonymous275 on 7/17/2020 /// Created by Anonymous275 on 7/17/2020
/// ///
#include "Logger.h"
#include "Startup.h" #include "Startup.h"
#include <chrono> #include "Logger.h"
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <chrono>
#include <thread> #include <thread>
std::string getDate() { std::string getDate() {
@@ -24,25 +24,24 @@ std::string getDate() {
std::string Min = (M > 9 ? std::to_string(M) : "0" + std::to_string(M)); 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)); std::string Hour = (H > 9 ? std::to_string(H) : "0" + std::to_string(H));
date date
<< "[" << "["
<< local_tm.tm_mday << "/" << local_tm.tm_mday << "/"
<< local_tm.tm_mon + 1 << "/" << local_tm.tm_mon + 1 << "/"
<< local_tm.tm_year + 1900 << " " << local_tm.tm_year + 1900 << " "
<< Hour << ":" << Hour << ":"
<< Min << ":" << Min << ":"
<< Secs << Secs
<< "] "; << "] ";
return date.str(); return date.str();
} }
void InitLog() { void InitLog(){
std::ofstream LFS; std::ofstream LFS;
LFS.open(GetEP() + "Launcher.log"); LFS.open(GetEP() + "Launcher.log");
if (!LFS.is_open()) { if(!LFS.is_open()){
error("logger file init failed!"); error("logger file init failed!");
} else }else LFS.close();
LFS.close();
} }
void addToLog(const std::string& Line) { void addToLog(const std::string& Line){
std::ofstream LFS; std::ofstream LFS;
LFS.open(GetEP() + "Launcher.log", std::ios_base::app); LFS.open(GetEP() + "Launcher.log", std::ios_base::app);
LFS << Line.c_str(); LFS << Line.c_str();
@@ -50,35 +49,34 @@ void addToLog(const std::string& Line) {
} }
void info(const std::string& toPrint) { void info(const std::string& toPrint) {
std::string Print = getDate() + "[INFO] " + toPrint + "\n"; std::string Print = getDate() + "[INFO] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
} }
void debug(const std::string& toPrint) { void debug(const std::string& toPrint) {
if (!Dev) if(!Dev)return;
return;
std::string Print = getDate() + "[DEBUG] " + toPrint + "\n"; std::string Print = getDate() + "[DEBUG] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
} }
void warn(const std::string& toPrint) { void warn(const std::string& toPrint){
std::string Print = getDate() + "[WARN] " + toPrint + "\n"; std::string Print = getDate() + "[WARN] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
} }
void error(const std::string& toPrint) { void error(const std::string& toPrint) {
std::string Print = getDate() + "[ERROR] " + toPrint + "\n"; std::string Print = getDate() + "[ERROR] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
} }
void fatal(const std::string& toPrint) { void fatal(const std::string& toPrint) {
std::string Print = getDate() + "[FATAL] " + toPrint + "\n"; std::string Print = getDate() + "[FATAL] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
_Exit(-1); _Exit(-1);
} }
void except(const std::string& toPrint) { void except(const std::string& toPrint) {
std::string Print = getDate() + "[EXCEP] " + toPrint + "\n"; std::string Print = getDate() + "[EXCEP] " + toPrint + "\n";
std::cout << Print << std::flush; std::cout << Print;
addToLog(Print); addToLog(Print);
} }

496
src/Network/Core.cpp Normal file → Executable file
View File

@@ -5,31 +5,19 @@
/// ///
/// Created by Anonymous275 on 7/20/2020 /// Created by Anonymous275 on 7/20/2020
/// ///
#include "Http.h"
#include "Network/network.hpp"
#include "NetworkHelpers.h"
#include "Security/Init.h"
#include <asio/io_context.hpp>
#include <cstdlib>
#include <optional>
#include <regex>
#if defined(__linux__)
#include <cstring>
#include <errno.h>
#include <netdb.h>
#include <spawn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#include "Logger.h" #include "Network/network.h"
#include "Security/Init.h"
#include <regex>
#include "Http.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include "Startup.h" #include "Startup.h"
#include <charconv> #include "Logger.h"
#include <fmt/format.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <set> #include <charconv>
#include <thread> #include <thread>
#include <set>
extern int TraceBack; extern int TraceBack;
std::set<std::string>* ConfList = nullptr; std::set<std::string>* ConfList = nullptr;
@@ -44,321 +32,271 @@ std::string MStatus;
bool ModLoaded; bool ModLoaded;
int ping = -1; int ping = -1;
asio::io_context io {}; void StartSync(const std::string &Data){
std::string IP = GetAddr(Data.substr(1,Data.find(':')-1));
static asio::ip::tcp::socket ResolveAndConnect(const std::string& host_port_string) { if(IP.find('.') == -1){
if(IP == "DNS")UlStatus ="UlConnection Failed! (DNS Lookup Failed)";
using namespace asio; else UlStatus = "UlConnection Failed! (WSA failed to start)";
ip::tcp::resolver resolver(io);
asio::error_code ec;
auto port = host_port_string.substr(host_port_string.find_last_of(':') + 1);
auto host = host_port_string.substr(0, host_port_string.find_last_of(':'));
auto resolved = resolver.resolve(host, port, ec);
if (ec) {
::error(fmt::format("Failed to resolve '[{}]:{}': {}", host, port, ec.message()));
throw std::runtime_error(fmt::format("Failed to resolve '{}': {}", host_port_string, ec.message()));
}
bool connected = false;
UlStatus = "UlLoading...";
for (const auto& addr : resolved) {
try {
info(fmt::format("Resolved and connected to '[{}]:{}'",
addr.endpoint().address().to_string(),
addr.endpoint().port()));
ip::tcp::socket socket(io);
socket.connect(addr);
// done, connected fine
return socket;
} catch (...) {
// ignore
}
}
throw std::runtime_error(fmt::format("Failed to connect to '{}'; connection refused", host_port_string));
}
void StartSync(const std::string& Data) {
try {
auto Socket = ResolveAndConnect(Data.substr(1));
ListOfMods = "-"; ListOfMods = "-";
CheckLocalKey();
TCPTerminate = false;
Terminate = false;
ConfList->clear();
ping = -1;
std::thread GS(TCPGameServer, std::move(Socket));
GS.detach();
info("Connecting to server");
} catch (const std::exception& e) {
UlStatus = "UlConnection Failed!";
error(fmt::format("Client: connect failed! Error: {}", e.what()));
WSACleanup();
Terminate = true; Terminate = true;
return;
} }
CheckLocalKey();
UlStatus = "UlLoading...";
TCPTerminate = false;
Terminate = false;
ConfList->clear();
ping = -1;
std::thread GS(TCPGameServer,IP,std::stoi(Data.substr(Data.find(':')+1)));
GS.detach();
info("Connecting to server");
} }
bool IsAllowedLink(const std::string& Link) { bool IsAllowedLink(const std::string& Link) {
std::vector<std::string> allowed_links = { std::regex link_pattern(R"(https:\/\/(?:\w+)?(?:\.)?(?:beammp\.com|discord\.gg))");
R"(patreon\.com\/beammp$)", std::smatch link_match;
R"(discord\.gg\/beammp$)", return std::regex_search(Link,link_match, link_pattern) && link_match.position() == 0;
R"(forum\.beammp\.com$)",
R"(beammp\.com$)",
R"(patreon\.com\/beammp\/$)",
R"(discord\.gg\/beammp\/$)",
R"(forum\.beammp\.com\/$)",
R"(beammp\.com\/$)",
R"(docs\.beammp\.com$)",
R"(wiki\.beammp\.com$)",
R"(docs\.beammp\.com\/$)",
R"(wiki\.beammp\.com\/$)",
R"(docs\.beammp\.com\/.*$)",
R"(wiki\.beammp\.com\/.*$)",
};
for (const auto& allowed_link : allowed_links) {
if (std::regex_match(Link, std::regex(std::string(R"(^http(s)?:\/\/)") + allowed_link))) {
return true;
}
}
return false;
} }
void Parse(std::span<char> InData, asio::ip::tcp::socket& CSocket) { bool ModWarningConfirmed = false;
std::string OutData;
char Code = InData[0], SubCode = 0;
if (InData.size() > 1)
SubCode = InData[1];
switch (Code) {
case 'A':
OutData = "A";
break;
case 'B':
NetReset();
Terminate = true;
TCPTerminate = true;
OutData = Code + HTTP::Get("https://backend.beammp.com/servers-info");
break;
case 'C':
ListOfMods.clear();
StartSync(std::string(InData.data(), InData.size()));
while (ListOfMods.empty() && !Terminate) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (ListOfMods == "-")
OutData = "L";
else
OutData = "L" + ListOfMods;
break;
case 'O': // open default browser with URL
if (IsAllowedLink(bytespan_to_string(InData.subspan(1)))) {
#if defined(__linux)
if (char* browser = getenv("BROWSER"); browser != nullptr && !std::string_view(browser).empty()) {
pid_t pid;
auto arg = bytespan_to_string(InData.subspan(1));
char* argv[] = { browser, arg.data() };
auto status = posix_spawn(&pid, browser, nullptr, nullptr, argv, environ);
if (status == 0) {
debug("Browser PID: " + std::to_string(pid));
// we don't wait for it to exit, because we just don't care.
// typically, you'd waitpid() here.
} else {
error("Failed to open the following link in the browser (error follows below): " + arg);
error(std::string("posix_spawn: ") + strerror(status));
}
} else {
error("Failed to open the following link in the browser because the $BROWSER environment variable is not set: " + bytespan_to_string(InData.subspan(1)));
}
#elif defined(WIN32)
ShellExecuteA(nullptr, "open", InData.subspan(1).data(), nullptr, nullptr, SW_SHOW); /// TODO: Look at when working on linux port
#endif
info("Opening Link \"" + bytespan_to_string(InData.subspan(1)) + "\""); void Parse(std::string Data,SOCKET CSocket){
} char Code = Data.at(0), SubCode = 0;
OutData.clear(); if(Data.length() > 1)SubCode = Data.at(1);
break; switch (Code){
case 'P': case 'A':
OutData = Code + std::to_string(ProxyPort); Data = Data.substr(0,1);
break; break;
case 'U': case 'B':
if (SubCode == 'l')
OutData = UlStatus;
if (SubCode == 'p') {
if (ping > 800) {
OutData = "Up-2";
} else
OutData = "Up" + std::to_string(ping);
}
if (!SubCode) {
std::string Ping;
if (ping > 800)
Ping = "-2";
else
Ping = std::to_string(ping);
OutData = std::string(UlStatus) + "\n" + "Up" + Ping;
}
break;
case 'M':
OutData = MStatus;
break;
case 'Q':
if (SubCode == 'S') {
NetReset(); NetReset();
Terminate = true; Terminate = true;
TCPTerminate = true; TCPTerminate = true;
ping = -1; Data = Code + HTTP::Get("https://backend.beammp.com/servers-info");
} break;
if (SubCode == 'G') case 'C':
exit(2); ListOfMods.clear();
OutData.clear(); StartSync(Data);
break; while(ListOfMods.empty() && !Terminate){
case 'R': // will send mod name std::this_thread::sleep_for(std::chrono::seconds(1));
{
auto str = bytespan_to_string(InData);
if (ConfList->find(str) == ConfList->end()) {
ConfList->insert(str);
ModLoaded = true;
}
OutData.clear();
} break;
case 'Z':
OutData = "Z" + GetVer();
break;
case 'N':
if (SubCode == 'c') {
nlohmann::json Auth = {
{ "Auth", LoginAuth ? 1 : 0 },
};
if (!Username.empty()) {
Auth["username"] = Username;
} }
if (!UserRole.empty()) { if(ListOfMods == "-")Data = "L";
Auth["role"] = UserRole; else Data = "L"+ListOfMods;
break;
case 'O': //open default browser with URL
if(IsAllowedLink(Data.substr(1))) {
ShellExecuteA(nullptr, "open", Data.substr(1).c_str(), nullptr, nullptr,SW_SHOW); ///TODO: Look at when working on linux port
info("Opening Link \"" + Data.substr(1) + "\"");
}
Data.clear();
break;
// response to "WMODS_FOUND" message, either Y (yes ok) or N (no)
case 'W': {
if (SubCode == 'Y') {
ModWarningConfirmed = true;
} else if (SubCode == 'N') {
ModWarningConfirmed = false;
NetReset();
Terminate = true;
TCPTerminate = true;
} }
OutData = "N" + Auth.dump();
} else {
auto indata_str = bytespan_to_string(InData);
OutData = "N" + Login(indata_str.substr(indata_str.find(':') + 1));
} }
break; case 'P':
default: Data = Code + std::to_string(ProxyPort);
OutData.clear(); break;
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;
case 'N':
if (SubCode == 'c'){
nlohmann::json Auth = {
{"Auth", LoginAuth ? 1 : 0 },
};
if (!Username.empty()) {
Auth["username"] = Username;
}
if (!UserRole.empty()) {
Auth["role"] = UserRole;
}
Data = "N" + Auth.dump();
}else{
Data = "N" + Login(Data.substr(Data.find(':') + 1));
}
break;
default:
Data.clear();
break;
} }
if (!OutData.empty() && CSocket.is_open()) { if(!Data.empty() && CSocket != -1){
uint32_t DataSize = OutData.size(); int res = send(CSocket, (Data+"\n").c_str(), int(Data.size())+1, 0);
std::vector<char> ToSend(sizeof(DataSize) + OutData.size()); if(res < 0){
std::copy_n(reinterpret_cast<char*>(&DataSize), sizeof(DataSize), ToSend.begin()); debug("(Core) send failed with error: " + std::to_string(WSAGetLastError()));
std::copy_n(OutData.data(), OutData.size(), ToSend.begin() + sizeof(DataSize));
asio::error_code ec;
asio::write(CSocket, asio::buffer(ToSend), ec);
if (ec) {
debug(fmt::format("(Core) send failed with error: {}", ec.message()));
} }
} }
} }
void GameHandler(asio::ip::tcp::socket& Client) { void GameHandler(SOCKET Client){
std::vector<char> data {};
do { int32_t Size,Temp,Rcv;
try { char Header[10] = {0};
ReceiveFromGame(Client, data); do{
Parse(data, Client); Rcv = 0;
} catch (const std::exception& e) { do{
error(std::string("Error while receiving from game: ") + e.what()); Temp = recv(Client,&Header[Rcv],1,0);
if(Temp < 1)break;
if(!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
error("(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("(Core) Invalid lua Header -> " + std::string(Header,Rcv));
break; break;
} }
} while (true); 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("(Core) Connection closing");
} else {
debug("(Core) recv failed with error: " + std::to_string(WSAGetLastError()));
}
NetReset(); NetReset();
KillSocket(Client); KillSocket(Client);
} }
void localRes() { void localRes(){
MStatus = " "; MStatus = " ";
UlStatus = "Ulstart"; UlStatus = "Ulstart";
if (ConfList != nullptr) { if(ConfList != nullptr){
ConfList->clear(); ConfList->clear();
delete ConfList; delete ConfList;
ConfList = nullptr; ConfList = nullptr;
} }
ConfList = new std::set<std::string>; ConfList = new std::set<std::string>;
} }
uint64_t TheClientSocket;
void CoreMain() { void CoreMain() {
debug("Core Network on start!"); debug("Core Network on start!");
WSADATA wsaData;
asio::ip::tcp::endpoint listen_ep(asio::ip::address::from_string("0.0.0.0"), static_cast<uint16_t>(DEFAULT_PORT)); SOCKET LSocket,CSocket;
asio::ip::tcp::socket LSocket(io); struct addrinfo *res = nullptr;
asio::error_code ec; struct addrinfo hints{};
LSocket.open(listen_ep.protocol(), ec); int iRes = WSAStartup(514, &wsaData); //2.2
if (ec) { if (iRes)debug("WSAStartup failed with error: " + std::to_string(iRes));
::error(fmt::format("Failed to open core socket: {}", ec.message())); 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("(Core) addr info failed with error: " + std::to_string(iRes));
WSACleanup();
return; return;
} }
asio::ip::tcp::socket::linger linger_opt {}; LSocket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
linger_opt.enabled(false); if (LSocket == -1){
LSocket.set_option(linger_opt, ec); debug("(Core) socket failed with error: " + std::to_string(WSAGetLastError()));
if (ec) { freeaddrinfo(res);
::error(fmt::format("Failed to set up listening core socket to not linger / reuse address. " WSACleanup();
"This may cause the core socket to refuse to bind(). Error: {}",
ec.message()));
return; return;
} }
asio::ip::tcp::socket::reuse_address reuse_opt { true }; iRes = bind(LSocket, res->ai_addr, int(res->ai_addrlen));
LSocket.set_option(reuse_opt, ec); if (iRes == SOCKET_ERROR) {
if (ec) { error("(Core) bind failed with error: " + std::to_string(WSAGetLastError()));
::error(fmt::format("Failed to set up listening core socket to not linger / reuse address. " freeaddrinfo(res);
"This may cause the core socket to refuse to bind(). Error: {}", KillSocket(LSocket);
ec.message())); WSACleanup();
return; return;
} }
iRes = listen(LSocket, SOMAXCONN);
auto acceptor = asio::ip::tcp::acceptor(io, listen_ep); if (iRes == SOCKET_ERROR) {
acceptor.listen(asio::ip::tcp::socket::max_listen_connections, ec); debug("(Core) listen failed with error: " + std::to_string(WSAGetLastError()));
if (ec) { freeaddrinfo(res);
::error(fmt::format("listen() failed, which is needed for the launcher to operate. Error: {}", KillSocket(LSocket);
ec.message())); WSACleanup();
return; return;
} }
do{
do { CSocket = accept(LSocket, nullptr, nullptr);
auto CSocket = acceptor.accept(ec); if (CSocket == -1) {
if (ec) { error("(Core) accept failed with error: " + std::to_string(WSAGetLastError()));
error(fmt::format("(Core) accept failed with error: {}", ec.message()));
continue; continue;
} }
TheClientSocket = CSocket;
localRes(); localRes();
info("Game Connected!"); info("Game Connected!");
GameHandler(CSocket); GameHandler(CSocket);
warn("Game Reconnecting..."); warn("Game Reconnecting...");
} while (LSocket.is_open()); }while(CSocket);
KillSocket(LSocket); KillSocket(LSocket);
WSACleanup(); WSACleanup();
} }
int Handle(EXCEPTION_POINTERS *ep){
#if defined(_WIN32)
int Handle(EXCEPTION_POINTERS* ep) {
char* hex = new char[100]; char* hex = new char[100];
sprintf_s(hex, 100, "%lX", ep->ExceptionRecord->ExceptionCode); sprintf_s(hex,100, "%lX", ep->ExceptionRecord->ExceptionCode);
except("(Core) Code : " + std::string(hex)); except("(Core) Code : " + std::string(hex));
delete[] hex; delete [] hex;
return 1; return 1;
} }
[[noreturn]] void CoreNetwork(){
while(true) {
#ifndef __MINGW32__
__try{
#endif #endif
CoreMain();
[[noreturn]] void CoreNetwork() { #ifndef __MINGW32__
while (true) { }__except(Handle(GetExceptionInformation())){}
#if not defined(__MINGW32__)
__try {
#endif #endif
CoreMain();
#if not defined(__MINGW32__) and not defined(__linux__)
} __except (Handle(GetExceptionInformation())) { }
#elif not defined(__MINGW32__) and defined(__linux__)
}
catch (...) {
except("(Core) Code : " + std::string(strerror(errno)));
}
#endif
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
} }

24
src/Network/DNS.cpp Normal file → Executable file
View File

@@ -7,37 +7,25 @@
/// ///
#include <string> #include <string>
#if defined(_WIN32)
#include <winsock2.h> #include <winsock2.h>
#elif defined(__linux__)
#include "linuxfixes.h"
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include "Logger.h" #include "Logger.h"
std::string GetAddr(const std::string& IP) { std::string GetAddr(const std::string&IP){
if (IP.find_first_not_of("0123456789.") == -1) if(IP.find_first_not_of("0123456789.") == -1)return IP;
return IP;
hostent* host;
#ifdef _WIN32
WSADATA wsaData; WSADATA wsaData;
if (WSAStartup(514, &wsaData) != 0) { hostent *host;
if(WSAStartup(514, &wsaData) != 0){
error("WSA Startup Failed!"); error("WSA Startup Failed!");
WSACleanup(); WSACleanup();
return ""; return "";
} }
#endif
host = gethostbyname(IP.c_str()); host = gethostbyname(IP.c_str());
if (!host) { if(!host){
error("DNS lookup failed! on " + IP); error("DNS lookup failed! on " + IP);
WSACleanup(); WSACleanup();
return "DNS"; return "DNS";
} }
std::string Ret = inet_ntoa(*((struct in_addr*)host->h_addr)); std::string Ret = inet_ntoa(*((struct in_addr *)host->h_addr));
WSACleanup(); WSACleanup();
return Ret; return Ret;
} }

355
src/Network/GlobalHandler.cpp Normal file → Executable file
View File

@@ -5,254 +5,259 @@
/// ///
/// Created by Anonymous275 on 7/25/2020 /// Created by Anonymous275 on 7/25/2020
/// ///
#include "Helpers.h" #include "Network/network.h"
#include "Network/network.hpp"
#include "NetworkHelpers.h"
#include "asio/socket_base.hpp"
#include <algorithm>
#include <span>
#include <vector>
#include <zlib.h>
#if defined(_WIN32)
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__)
#include "linuxfixes.h"
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include "Logger.h" #include "Logger.h"
#include <charconv> #include <charconv>
#include <fmt/format.h>
#include <mutex>
#include <string> #include <string>
#include <thread> #include <thread>
#include <mutex>
std::chrono::time_point<std::chrono::high_resolution_clock> PingStart, PingEnd; std::chrono::time_point<std::chrono::high_resolution_clock> PingStart,PingEnd;
bool GConnected = false; bool GConnected = false;
bool CServer = true; bool CServer = true;
std::shared_ptr<asio::ip::tcp::socket> CSocket = nullptr; SOCKET CSocket = -1;
std::shared_ptr<asio::ip::tcp::socket> GSocket = nullptr; SOCKET GSocket = -1;
void KillSocket(std::shared_ptr<asio::ip::tcp::socket>& Dead) { int KillSocket(uint64_t Dead){
if (!Dead) if(Dead == (SOCKET)-1){
return; debug("Kill socket got -1 returning...");
asio::error_code ec; return 0;
Dead->shutdown(asio::socket_base::shutdown_both, ec); }
shutdown(Dead,SD_BOTH);
int a = closesocket(Dead);
if(a != 0){
warn("Failed to close socket!");
}
return a;
} }
void KillSocket(std::shared_ptr<asio::ip::udp::socket>& Dead) { bool CheckBytes(uint32_t Bytes){
if (!Dead) if(Bytes == 0){
return;
asio::error_code ec;
Dead->shutdown(asio::socket_base::shutdown_both, ec);
}
void KillSocket(asio::ip::tcp::socket& Dead) {
asio::error_code ec;
Dead.shutdown(asio::socket_base::shutdown_both, ec);
}
void KillSocket(asio::ip::udp::socket& Dead) {
asio::error_code ec;
Dead.shutdown(asio::socket_base::shutdown_both, ec);
}
bool CheckBytes(uint32_t Bytes) {
if (Bytes == 0) {
debug("(Proxy) Connection closing"); debug("(Proxy) Connection closing");
return false; return false;
} else if (Bytes < 0) { }else if(Bytes < 0){
debug("(Proxy) send failed with error: " + std::to_string(WSAGetLastError())); debug("(Proxy) send failed with error: " + std::to_string(WSAGetLastError()));
return false; return false;
} }
return true; return true;
} }
void GameSend(std::string_view RawData) { void GameSend(std::string Data){
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
if (TCPTerminate || !GConnected || CSocket == nullptr) if(TCPTerminate || !GConnected || CSocket == -1)return;
return; int32_t Size,Temp,Sent;
int32_t Size, Temp, Sent; Data += '\n';
uint32_t DataSize = RawData.size(); Size = int32_t(Data.size());
std::vector<char> Data(sizeof(DataSize) + RawData.size());
std::copy_n(reinterpret_cast<char*>(&DataSize), sizeof(DataSize), Data.begin());
std::copy_n(RawData.data(), RawData.size(), Data.begin() + sizeof(DataSize));
Size = Data.size();
Sent = 0; 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 == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')Rel = true;
if(Ack || Rel){
if(Ack || DLen > 1000)SendLarge(Data);
else TCPSend(Data,TCPSock);
}else UDPSend(Data);
asio::error_code ec; if (DLen > 1000) {
asio::write(*CSocket, asio::buffer(Data), ec); debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : "
if (ec) { + Data.substr(0, 10)
debug(fmt::format("(TCP CB) recv failed with error: {}", ec.message())); + Data.substr(Data.length() - 10));
KillSocket(TCPSock); }else if(C == 'Z'){
Terminate = true; //debug("(Game->Launcher) : " + Data);
} }
} }
void ServerSend(const std::vector<char>& Data, bool Rel) { void NetReset(){
if (Terminate || Data.empty())
return;
char C = 0;
bool Ack = false;
int DLen = int(Data.size());
if (DLen > 3)
C = Data.at(0);
if (C == 'O' || C == 'T')
Ack = true;
if (C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')
Rel = true;
if (compressBound(Data.size()) > 1024)
Rel = true;
if (Ack || Rel) {
if (Ack || DLen > 1000)
SendLarge(Data);
else if (TCPSock)
TCPSend(Data, *TCPSock);
} else
UDPSend(Data);
}
void NetReset() {
TCPTerminate = false; TCPTerminate = false;
GConnected = false; GConnected = false;
Terminate = false; Terminate = false;
UlStatus = "Ulstart"; UlStatus = "Ulstart";
MStatus = " "; MStatus = " ";
if (UDPSock != nullptr) { if(UDPSock != (SOCKET)(-1)){
KillSocket(*UDPSock); debug("Terminating UDP Socket : " + std::to_string(TCPSock));
KillSocket(UDPSock);
} }
UDPSock = nullptr; UDPSock = -1;
if (TCPSock != nullptr) { if(TCPSock != (SOCKET)(-1)){
KillSocket(*TCPSock); debug("Terminating TCP Socket : " + std::to_string(TCPSock));
KillSocket(TCPSock);
} }
TCPSock = nullptr; TCPSock = -1;
if (GSocket != nullptr) { if(GSocket != (SOCKET)(-1)){
KillSocket(*GSocket); debug("Terminating GTCP Socket : " + std::to_string(GSocket));
KillSocket(GSocket);
} }
GSocket = nullptr; GSocket = -1;
} }
void AutoPing() { SOCKET SetupListener(){
while (!Terminate) { if(GSocket != -1)return GSocket;
ServerSend(strtovec("p"), false); struct addrinfo *result = nullptr;
struct addrinfo hints{};
WSADATA wsaData;
int iRes = WSAStartup(514, &wsaData); //2.2
if (iRes != 0) {
error("(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("(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("(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("(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("(Proxy) listen failed with error: " + std::to_string(WSAGetLastError()));
KillSocket(GSocket);
WSACleanup();
return -1;
}
return GSocket;
}
void AutoPing(){
while(!Terminate){
ServerSend("p",false);
PingStart = std::chrono::high_resolution_clock::now(); PingStart = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds (1));
} }
} }
int ClientID = -1; int ClientID = -1;
void ParserAsync(std::string_view Data) { void ParserAsync(const std::string& Data){
if (Data.empty()) if(Data.empty())return;
return; char Code = Data.at(0),SubCode = 0;
char Code = Data.at(0), SubCode = 0; if(Data.length() > 1)SubCode = Data.at(1);
if (Data.length() > 1)
SubCode = Data.at(1);
switch (Code) { switch (Code) {
case 'p': case 'p':
PingEnd = std::chrono::high_resolution_clock::now(); PingEnd = std::chrono::high_resolution_clock::now();
if (PingStart > PingEnd) if(PingStart > PingEnd)ping = 0;
ping = 0; else ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd-PingStart).count());
else return;
ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd - PingStart).count()); case 'M':
return; MStatus = Data;
case 'M': UlStatus = "Uldone";
MStatus = Data; return;
UlStatus = "Uldone"; default:
return; break;
default:
break;
} }
GameSend(Data); GameSend(Data);
} }
void ServerParser(std::string_view Data) { void ServerParser(const std::string& Data){
ParserAsync(Data); ParserAsync(Data);
} }
void NetMain(asio::ip::address addr, uint16_t port) { void NetMain(const std::string& IP, int Port){
std::thread Ping(AutoPing); std::thread Ping(AutoPing);
Ping.detach(); Ping.detach();
UDPClientMain(addr, port); UDPClientMain(IP,Port);
CServer = true; CServer = true;
Terminate = true; Terminate = true;
info("Connection Terminated!"); info("Connection Terminated!");
} }
void TCPGameServer(asio::ip::tcp::socket&& Socket) { void TCPGameServer(const std::string& IP, int Port){
asio::ip::tcp::endpoint listen_ep(asio::ip::address::from_string("0.0.0.0"), static_cast<uint16_t>(DEFAULT_PORT + 1)); GSocket = SetupListener();
asio::ip::tcp::socket listener(io); while (!TCPTerminate && GSocket != -1){
asio::error_code ec;
listener.open(listen_ep.protocol(), ec);
if (ec) {
::error(fmt::format("Failed to open game socket: {}", ec.message()));
return;
}
asio::ip::tcp::socket::linger linger_opt {};
linger_opt.enabled(false);
listener.set_option(linger_opt, ec);
if (ec) {
::error(fmt::format("Failed to set up listening game socket to not linger / reuse address. "
"This may cause the game socket to refuse to bind(). Error: {}",
ec.message()));
}
asio::ip::tcp::socket::reuse_address reuse_opt { true };
listener.set_option(reuse_opt, ec);
if (ec) {
::error(fmt::format("Failed to set up listening core socket to not linger / reuse address. "
"This may cause the core socket to refuse to bind(). Error: {}",
ec.message()));
return;
}
auto acceptor = asio::ip::tcp::acceptor(io, listen_ep);
acceptor.listen(asio::ip::tcp::socket::max_listen_connections, ec);
if (ec) {
debug(fmt::format("Proxy accept failed: {}", ec.message()));
TCPTerminate = true; // skip the loop
}
debug(fmt::format("Game server listening on {}:{}", acceptor.local_endpoint().address().to_string(), acceptor.local_endpoint().port()));
while (!TCPTerminate && acceptor.is_open()) {
debug("MAIN LOOP OF GAME SERVER"); debug("MAIN LOOP OF GAME SERVER");
GConnected = false; GConnected = false;
if (!CServer) { if(!CServer){
warn("Connection still alive terminating"); warn("Connection still alive terminating");
NetReset(); NetReset();
TCPTerminate = true; TCPTerminate = true;
Terminate = true; Terminate = true;
break; break;
} }
if (CServer) { if(CServer) {
std::thread Client(TCPClientMain, std::move(Socket)); std::thread Client(TCPClientMain, IP, Port);
Client.detach(); Client.detach();
} }
CSocket = accept(GSocket, nullptr, nullptr);
CSocket = std::make_shared<asio::ip::tcp::socket>(acceptor.accept()); if (CSocket == -1) {
debug("(Proxy) accept failed with error: " + std::to_string(WSAGetLastError()));
break;
}
debug("(Proxy) Game Connected!"); debug("(Proxy) Game Connected!");
GConnected = true; GConnected = true;
if (CServer) { if(CServer){
std::thread t1(NetMain, CSocket->remote_endpoint().address(), CSocket->remote_endpoint().port()); std::thread t1(NetMain, IP, Port);
t1.detach(); t1.detach();
CServer = false; CServer = false;
} }
std::vector<char> data {}; 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 //Read byte by byte until '>' is rcved then get the size and read based on it
while (!TCPTerminate && !CSocket) { do{
try { Rcv = 0;
ReceiveFromGame(*CSocket, data);
ServerSend(data, false); do{
} catch (const std::exception& e) { Temp = recv(CSocket,&Header[Rcv],1,0);
error(std::string("Error while receiving from game: ") + e.what()); if(Temp < 1 || TCPTerminate)break;
}while(Header[Rcv++] != '>');
if(Temp < 1 || TCPTerminate)break;
if(std::from_chars(Header,&Header[Rcv],Size).ptr[0] != '>'){
debug("(Game) Invalid lua Header -> " + std::string(Header,Rcv));
break; 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("(Proxy) Connection closing");
else debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError()));
} }
TCPTerminate = true; TCPTerminate = true;
GConnected = false; GConnected = false;
Terminate = true; Terminate = true;
if (CSocket != nullptr) if(CSocket != SOCKET_ERROR)KillSocket(CSocket);
KillSocket(CSocket);
debug("END OF GAME SERVER"); debug("END OF GAME SERVER");
} }

118
src/Network/Http.cpp Normal file → Executable file
View File

@@ -7,62 +7,20 @@
/// ///
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
#include "Http.h"
#include <Logger.h>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <httplib.h>
#include <iostream> #include <iostream>
#include <Logger.h>
#include <fstream>
#include "Http.h"
#include <mutex> #include <mutex>
#include <nlohmann/json.hpp> #include <cmath>
#include <httplib.h>
void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try {
const std::filesystem::path folder = ".https_debug";
std::filesystem::create_directories(folder);
if (!std::filesystem::exists(folder / "WHAT IS THIS FOLDER.txt")) {
std::ofstream ignore { folder / "WHAT IS THIS FOLDER.txt" };
ignore << "This folder exists to help debug current issues with the backend. Do not share this folder with anyone but BeamMP staff. It contains detailed logs of any failed http requests." << std::endl;
}
const auto file = folder / (method + ".json");
// 1 MB limit
if (std::filesystem::exists(file) && std::filesystem::file_size(file) > 1'000'000) {
std::filesystem::rename(file, file.generic_string() + ".bak");
}
std::ofstream of { file, std::ios::app };
nlohmann::json js {
{ "utc", std::chrono::system_clock::now().time_since_epoch().count() },
{ "target", target },
{ "client_info", {
{ "openssl_verify_result", client.get_openssl_verify_result() },
{ "host", client.host() },
{ "port", client.port() },
{ "socket_open", client.is_socket_open() },
{ "valid", client.is_valid() },
} },
};
if (result) {
auto value = result.value();
js["result"] = {};
js["result"]["body"] = value.body;
js["result"]["status"] = value.status;
js["result"]["headers"] = value.headers;
js["result"]["version"] = value.version;
js["result"]["location"] = value.location;
js["result"]["reason"] = value.reason;
}
of << js.dump();
} catch (const std::exception& e) {
error(e.what());
}
bool HTTP::isDownload = false; bool HTTP::isDownload = false;
std::string HTTP::Get(const std::string& IP) { std::string HTTP::Get(const std::string &IP) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
auto pos = IP.find('/', 10); auto pos = IP.find('/',10);
httplib::Client cli(IP.substr(0, pos).c_str()); httplib::Client cli(IP.substr(0, pos).c_str());
cli.set_connection_timeout(std::chrono::seconds(10)); cli.set_connection_timeout(std::chrono::seconds(10));
@@ -70,19 +28,16 @@ std::string HTTP::Get(const std::string& IP) {
auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar); auto res = cli.Get(IP.substr(pos).c_str(), ProgressBar);
std::string Ret; std::string Ret;
if (res) { if(res){
if (res->status == 200) { if(res->status == 200){
Ret = res->body; Ret = res->body;
} else { }else error(res->reason);
WriteHttpDebug(cli, "GET", IP, res);
error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); }else{
} if(isDownload) {
} else {
if (isDownload) {
std::cout << "\n"; std::cout << "\n";
} }
WriteHttpDebug(cli, "GET", IP, res); error("HTTP Get failed on " + to_string(res.error()));
error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
return Ret; return Ret;
@@ -92,45 +47,41 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
auto pos = IP.find('/', 10); auto pos = IP.find('/',10);
httplib::Client cli(IP.substr(0, pos).c_str()); httplib::Client cli(IP.substr(0, pos).c_str());
cli.set_connection_timeout(std::chrono::seconds(10)); cli.set_connection_timeout(std::chrono::seconds(10));
std::string Ret; std::string Ret;
if (!Fields.empty()) { if(!Fields.empty()) {
httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json"); httplib::Result res = cli.Post(IP.substr(pos).c_str(), Fields, "application/json");
if (res) { if(res) {
if (res->status != 200) { if (res->status != 200) {
error(res->reason); error(res->reason);
} }
Ret = res->body; Ret = res->body;
} else { }else{
WriteHttpDebug(cli, "POST", IP, res); error("HTTP Post failed on " + to_string(res.error()));
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} else { }else{
httplib::Result res = cli.Post(IP.substr(pos).c_str()); httplib::Result res = cli.Post(IP.substr(pos).c_str());
if (res) { if(res) {
if (res->status != 200) { if (res->status != 200) {
error(res->reason); error(res->reason);
} }
Ret = res->body; Ret = res->body;
} else { }else{
WriteHttpDebug(cli, "POST", IP, res); error("HTTP Post failed on " + to_string(res.error()));
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} }
if (Ret.empty()) if(Ret.empty())return "-1";
return "-1"; else return Ret;
else
return Ret;
} }
bool HTTP::ProgressBar(size_t c, size_t t) { bool HTTP::ProgressBar(size_t c, size_t t){
if (isDownload) { if(isDownload) {
static double last_progress, progress_bar_adv; static double last_progress, progress_bar_adv;
progress_bar_adv = round(c / double(t) * 25); progress_bar_adv = round(c / double(t) * 25);
std::cout << "\r"; std::cout << "\r";
@@ -138,17 +89,15 @@ bool HTTP::ProgressBar(size_t c, size_t t) {
std::cout << round(c / double(t) * 100); std::cout << round(c / double(t) * 100);
std::cout << "% ] ["; std::cout << "% ] [";
int i; int i;
for (i = 0; i <= progress_bar_adv; i++) for (i = 0; i <= progress_bar_adv; i++)std::cout << "#";
std::cout << "#"; for (i = 0; i < 25 - progress_bar_adv; i++)std::cout << ".";
for (i = 0; i < 25 - progress_bar_adv; i++)
std::cout << ".";
std::cout << "]"; std::cout << "]";
last_progress = round(c / double(t) * 100); last_progress = round(c / double(t) * 100);
} }
return true; return true;
} }
bool HTTP::Download(const std::string& IP, const std::string& Path) { bool HTTP::Download(const std::string &IP, const std::string &Path) {
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
@@ -156,16 +105,15 @@ bool HTTP::Download(const std::string& IP, const std::string& Path) {
std::string Ret = Get(IP); std::string Ret = Get(IP);
isDownload = false; isDownload = false;
if (Ret.empty()) if(Ret.empty())return false;
return false;
std::ofstream File(Path, std::ios::binary); std::ofstream File(Path, std::ios::binary);
if (File.is_open()) { if(File.is_open()) {
File << Ret; File << Ret;
File.close(); File.close();
std::cout << "\n"; std::cout << "\n";
info("Download Complete!"); info("Download Complete!");
} else { }else{
error("Failed to open file directory: " + Path); error("Failed to open file directory: " + Path);
return false; return false;
} }

289
src/Network/Resources.cpp Normal file → Executable file
View File

@@ -6,151 +6,133 @@
/// Created by Anonymous275 on 4/11/2020 /// Created by Anonymous275 on 4/11/2020
/// ///
#include "Network/network.hpp" #include "Network/network.h"
#include "fmt/core.h"
#if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__)
#include <arpa/inet.h>
#include <cstring>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif
#include "Logger.h"
#include "Startup.h"
#include <atomic>
#include <cmath>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <fstream> #include "Startup.h"
#include <future> #include "Logger.h"
#include <asio.hpp>
#include <iostream> #include <iostream>
#include <cstring>
#include <fstream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <atomic>
#include <vector> #include <vector>
#include <future>
#include <cmath>
extern SOCKET TheClientSocket;
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string ListOfMods; std::string ListOfMods;
std::vector<std::string> Split(const std::string& String, const std::string& delimiter) { std::vector<std::string> Split(const std::string& String,const std::string& delimiter){
std::vector<std::string> Val; std::vector<std::string> Val;
size_t pos; size_t pos;
std::string token, s = String; std::string token,s = String;
while ((pos = s.find(delimiter)) != std::string::npos) { while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos); token = s.substr(0, pos);
if (!token.empty()) if(!token.empty())Val.push_back(token);
Val.push_back(token);
s.erase(0, pos + delimiter.length()); s.erase(0, pos + delimiter.length());
} }
if (!s.empty()) if(!s.empty())Val.push_back(s);
Val.push_back(s);
return Val; return Val;
} }
void CheckForDir() { void CheckForDir(){
if (!fs::exists("Resources")) { if(!fs::exists("Resources")){
// Could we just use fs::create_directory instead?
#if defined(_WIN32)
_wmkdir(L"Resources"); _wmkdir(L"Resources");
#elif defined(__linux__)
fs::create_directory(L"Resources");
#endif
} }
} }
void WaitForConfirm() { void WaitForConfirm(){
while (!Terminate && !ModLoaded) { while(!Terminate && !ModLoaded){
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
} }
ModLoaded = false; ModLoaded = false;
} }
void Abord() {
void Abord(){
Terminate = true; Terminate = true;
TCPTerminate = true; TCPTerminate = true;
info("Terminated!"); info("Terminated!");
} }
std::string Auth(asio::ip::tcp::socket& Sock) { std::string Auth(SOCKET Sock){
TCPSend(strtovec("VC" + GetVer()), Sock); TCPSend("VC" + GetVer(),Sock);
auto Res = TCPRcv(Sock); auto Res = TCPRcv(Sock);
if (Res.empty() || Res[0] == 'E' || Res[0] == 'K') { if(Res.empty() || Res[0] == 'E' || Res[0] == 'K'){
Abord(); Abord();
return ""; return "";
} }
TCPSend(strtovec(PublicKey), Sock); TCPSend(PublicKey,Sock);
if (Terminate) if(Terminate)return "";
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
if (Res.empty() || Res[0] != 'P') { if(Res.empty() || Res[0] != 'P'){
Abord(); Abord();
return ""; return "";
} }
Res = Res.substr(1); Res = Res.substr(1);
if (Res.find_first_not_of("0123456789") == std::string::npos) { if(Res.find_first_not_of("0123456789") == std::string::npos){
ClientID = std::stoi(Res); ClientID = std::stoi(Res);
} else { }else{
Abord(); Abord();
UUl("Authentication failed!"); UUl("Authentication failed!");
return ""; return "";
} }
TCPSend(strtovec("SR"), Sock); TCPSend("SR",Sock);
if (Terminate) if(Terminate)return "";
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
if (Res[0] == 'E' || Res[0] == 'K') { if(Res[0] == 'E' || Res[0] == 'K'){
Abord(); Abord();
return ""; return "";
} }
if (Res.empty() || Res == "-") { if(Res.empty() || Res == "-"){
info("Didn't Receive any mods..."); info("Didn't Receive any mods...");
ListOfMods = "-"; ListOfMods = "-";
TCPSend(strtovec("Done"), Sock); TCPSend("Done",Sock);
info("Done!"); info("Done!");
return ""; return "";
} }
return Res; return Res;
} }
void UpdateUl(bool D, const std::string& msg) { void UpdateUl(bool D,const std::string& msg){
if (D) if(D)UlStatus = "UlDownloading Resource " + msg;
UlStatus = "UlDownloading Resource " + msg; else UlStatus = "UlLoading Resource " + msg;
else
UlStatus = "UlLoading Resource " + msg;
} }
void AsyncUpdate(uint64_t& Rcv, uint64_t Size, const std::string& Name) { void AsyncUpdate(uint64_t& Rcv,uint64_t Size,const std::string& Name){
do { do {
double pr = double(Rcv) / double(Size) * 100; double pr = double(Rcv) / double(Size) * 100;
std::string Per = std::to_string(trunc(pr * 10) / 10); std::string Per = std::to_string(trunc(pr * 10) / 10);
UpdateUl(true, Name + " (" + Per.substr(0, Per.find('.') + 2) + "%)"); UpdateUl(true, Name + " (" + Per.substr(0, Per.find('.') + 2) + "%)");
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
} while (!Terminate && Rcv < Size); }while(!Terminate && Rcv < Size);
} }
char* TCPRcvRaw(asio::ip::tcp::socket& Sock, uint64_t& GRcv, uint64_t Size) { char* TCPRcvRaw(SOCKET Sock,uint64_t& GRcv, uint64_t Size){
if(Sock == -1){
Terminate = true;
UUl("Invalid Socket");
return nullptr;
}
char* File = new char[Size]; char* File = new char[Size];
uint64_t Rcv = 0; uint64_t Rcv = 0;
asio::error_code ec; do{
do { int Len = int(Size-Rcv);
int Len = int(Size - Rcv); if(Len > 1000000)Len = 1000000;
if (Len > 1000000) int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
Len = 1000000; if(Temp < 1){
int32_t Temp = asio::read(Sock, asio::buffer(&File[Rcv], Len), ec); info(std::to_string(Temp));
if (ec) { UUl("Socket Closed Code 1");
::error(fmt::format("Failed to receive data from server: {}", ec.message()));
UUl("Failed to receive data from server, connection closed (Code 1)");
KillSocket(Sock); KillSocket(Sock);
Terminate = true; Terminate = true;
delete[] File; delete[] File;
@@ -158,26 +140,32 @@ char* TCPRcvRaw(asio::ip::tcp::socket& Sock, uint64_t& GRcv, uint64_t Size) {
} }
Rcv += Temp; Rcv += Temp;
GRcv += Temp; GRcv += Temp;
} while (Rcv < Size && !Terminate); }while(Rcv < Size && !Terminate);
return File; return File;
} }
void MultiKill(asio::ip::tcp::socket& Sock, asio::ip::tcp::socket& Sock1) { void MultiKill(SOCKET Sock,SOCKET Sock1){
KillSocket(Sock1); KillSocket(Sock1);
KillSocket(Sock); KillSocket(Sock);
Terminate = true; Terminate = true;
} }
std::shared_ptr<asio::ip::tcp::socket> InitDSock(asio::ip::tcp::endpoint ep) { SOCKET InitDSock(){
auto DSock = std::make_shared<asio::ip::tcp::socket>(io); SOCKET DSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
asio::error_code ec; SOCKADDR_IN ServerAddr;
DSock->connect(ep, ec); if(DSock < 1){
if (ec) {
KillSocket(DSock); KillSocket(DSock);
Terminate = true; Terminate = true;
return nullptr; return 0;
} }
char Code[2] = { 'D', char(ClientID) }; ServerAddr.sin_family = AF_INET;
asio::write(*DSock, asio::buffer(Code, 2), ec); ServerAddr.sin_port = htons(LastPort);
if (ec) { inet_pton(AF_INET, LastIP.c_str(), &ServerAddr.sin_addr);
if(connect(DSock, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr)) != 0){
KillSocket(DSock);
Terminate = true;
return 0;
}
char Code[2] = {'D',char(ClientID)};
if(send(DSock,Code,2,0) != 2){
KillSocket(DSock); KillSocket(DSock);
Terminate = true; Terminate = true;
return 0; return 0;
@@ -185,56 +173,72 @@ std::shared_ptr<asio::ip::tcp::socket> InitDSock(asio::ip::tcp::endpoint ep) {
return DSock; return DSock;
} }
std::string MultiDownload(asio::ip::tcp::socket& MSock, asio::ip::tcp::socket& DSock, uint64_t Size, const std::string& Name) { std::string MultiDownload(SOCKET MSock,SOCKET DSock, uint64_t Size, const std::string& Name){
uint64_t GRcv = 0, MSize = Size / 2, DSize = Size - MSize; uint64_t GRcv = 0, MSize = Size/2, DSize = Size - MSize;
std::thread Au(AsyncUpdate, std::ref(GRcv), Size, Name); std::thread Au(AsyncUpdate,std::ref(GRcv), Size, Name);
std::packaged_task<char*()> task([&] { return TCPRcvRaw(MSock, GRcv, MSize); }); std::packaged_task<char*()> task([&] { return TCPRcvRaw(MSock,GRcv,MSize); });
std::future<char*> f1 = task.get_future(); std::future<char*> f1 = task.get_future();
std::thread Dt(std::move(task)); std::thread Dt(std::move(task));
Dt.detach(); Dt.detach();
char* DData = TCPRcvRaw(DSock, GRcv, DSize); char* DData = TCPRcvRaw(DSock,GRcv,DSize);
if (!DData) { if(!DData){
MultiKill(MSock, DSock); MultiKill(MSock,DSock);
return ""; return "";
} }
f1.wait(); f1.wait();
char* MData = f1.get(); char* MData = f1.get();
if (!MData) { if(!MData){
MultiKill(MSock, DSock); MultiKill(MSock,DSock);
return ""; return "";
} }
if (Au.joinable()) if(Au.joinable())Au.join();
Au.join();
/// omg yes very ugly my god but i was in a rush will revisit
std::string Ret(Size, 0);
memcpy(&Ret[0], MData, MSize);
delete[] MData;
memcpy(&Ret[MSize], DData, DSize); ///omg yes very ugly my god but i was in a rush will revisit
delete[] DData; std::string Ret(Size,0);
memcpy_s(&Ret[0],MSize,MData,MSize);
delete[]MData;
memcpy_s(&Ret[MSize],DSize,DData,DSize);
delete[]DData;
return Ret; return Ret;
} }
void InvalidResource(const std::string& File) { void InvalidResource(const std::string& File){
UUl("Invalid mod \"" + File + "\""); UUl("Invalid mod \"" + File + "\"");
warn("The server tried to sync \"" + File + "\" that is not a .zip file!"); warn("The server tried to sync \"" + File + "\" that is not a .zip file!");
Terminate = true; Terminate = true;
} }
void SyncResources(asio::ip::tcp::socket& Sock) { void SyncResources(SOCKET Sock){
std::string Ret = Auth(Sock); std::string Ret = Auth(Sock);
if (Ret.empty()) if(Ret.empty())return;
ModWarningConfirmed = false;
Terminate = false;
std::string Data = "WMODS_FOUND";
send(TheClientSocket, (Data + "\n").c_str(), int(Data.size())+1, 0);
while (!Terminate && !ModWarningConfirmed) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (!ModWarningConfirmed) {
UlStatus = "UlMods rejected!";
info("Mods rejected by user!");
// game has already cancelled by now
return; return;
}
info("Checking Resources..."); info("Checking Resources...");
CheckForDir(); CheckForDir();
@@ -245,59 +249,46 @@ void SyncResources(asio::ip::tcp::socket& Sock) {
list.clear(); list.clear();
Ret.clear(); Ret.clear();
int Amount = 0, Pos = 0; int Amount = 0,Pos = 0;
std::string a, t; std::string a,t;
for (const std::string& name : FNames) { for(const std::string&name : FNames){
if (!name.empty()) { if(!name.empty()){
t += name.substr(name.find_last_of('/') + 1) + ";"; t += name.substr(name.find_last_of('/') + 1) + ";";
} }
} }
if (t.empty()) if(t.empty())ListOfMods = "-";
ListOfMods = "-"; else ListOfMods = t;
else
ListOfMods = t;
t.clear(); t.clear();
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) { for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
auto ZIP = FN->find(".zip"); auto ZIP = FN->find(".zip");
if (ZIP == std::string::npos || FN->length() - ZIP != 4) { if (ZIP == std::string::npos || FN->length() - ZIP != 4) {
InvalidResource(*FN); InvalidResource(*FN);
return; return;
} }
if (pos == std::string::npos) if (pos == std::string::npos)continue;
continue;
Amount++; Amount++;
} }
if (!FNames.empty()) if(!FNames.empty())info("Syncing...");
info("Syncing..."); SOCKET DSock = InitDSock();
auto DSock = InitDSock(Sock.remote_endpoint()); for(auto FN = FNames.begin(),FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN,++FS) {
for (auto FN = FNames.begin(), FS = FSizes.begin(); FN != FNames.end() && !Terminate; ++FN, ++FS) {
auto pos = FN->find_last_of('/'); auto pos = FN->find_last_of('/');
if (pos != std::string::npos) { if (pos != std::string::npos) {
a = "Resources" + FN->substr(pos); a = "Resources" + FN->substr(pos);
} else } else continue;
continue;
Pos++; Pos++;
if (fs::exists(a)) { if (fs::exists(a)) {
if (FS->find_first_not_of("0123456789") != std::string::npos) if (FS->find_first_not_of("0123456789") != std::string::npos)continue;
continue; if (fs::file_size(a) == std::stoull(*FS)){
if (fs::file_size(a) == std::stoull(*FS)) { UpdateUl(false,std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/')));
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + a.substr(a.find_last_of('/')));
std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::this_thread::sleep_for(std::chrono::milliseconds(50));
try { try {
if (!fs::exists(GetGamePath() + "mods/multiplayer")) { if(!fs::exists(GetGamePath() + "mods/multiplayer")){
fs::create_directories(GetGamePath() + "mods/multiplayer"); fs::create_directories(GetGamePath() + "mods/multiplayer");
} }
auto modname = a.substr(a.find_last_of('/')); auto name = GetGamePath() + "mods/multiplayer" + a.substr(a.find_last_of('/'));
#if defined(__linux__)
// Linux version of the game doesnt support uppercase letters in mod names
for (char& c : modname) {
c = ::tolower(c);
}
#endif
auto name = GetGamePath() + "mods/multiplayer" + modname;
auto tmp_name = name + ".tmp"; auto tmp_name = name + ".tmp";
fs::copy_file(a, tmp_name, fs::copy_options::overwrite_existing); fs::copy_file(a,tmp_name,fs::copy_options::overwrite_existing);
fs::rename(tmp_name, name); fs::rename(tmp_name, name);
} catch (std::exception& e) { } catch (std::exception& e) {
error("Failed copy to the mods folder! " + std::string(e.what())); error("Failed copy to the mods folder! " + std::string(e.what()));
@@ -306,16 +297,15 @@ void SyncResources(asio::ip::tcp::socket& Sock) {
} }
WaitForConfirm(); WaitForConfirm();
continue; continue;
} else }else remove(a.c_str());
remove(a.c_str());
} }
CheckForDir(); CheckForDir();
std::string FName = a.substr(a.find_last_of('/')); std::string FName = a.substr(a.find_last_of('/'));
do { do {
TCPSend(strtovec("f" + *FN), Sock); TCPSend("f" + *FN,Sock);
std::string Data = TCPRcv(Sock); std::string Data = TCPRcv(Sock);
if (Data == "CO" || Terminate) { if (Data == "CO" || Terminate){
Terminate = true; Terminate = true;
UUl("Server cannot find " + FName); UUl("Server cannot find " + FName);
break; break;
@@ -323,11 +313,10 @@ void SyncResources(asio::ip::tcp::socket& Sock) {
std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName; std::string Name = std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName;
Data = MultiDownload(Sock, *DSock, std::stoull(*FS), Name); Data = MultiDownload(Sock,DSock,std::stoull(*FS), Name);
if (Terminate) if(Terminate)break;
break; UpdateUl(false,std::to_string(Pos)+"/"+std::to_string(Amount)+": "+FName);
UpdateUl(false, std::to_string(Pos) + "/" + std::to_string(Amount) + ": " + FName);
std::ofstream LFS; std::ofstream LFS;
LFS.open(a.c_str(), std::ios_base::app | std::ios::binary); LFS.open(a.c_str(), std::ios_base::app | std::ios::binary);
if (LFS.is_open()) { if (LFS.is_open()) {
@@ -335,28 +324,20 @@ void SyncResources(asio::ip::tcp::socket& Sock) {
LFS.close(); LFS.close();
} }
} while (fs::file_size(a) != std::stoull(*FS) && !Terminate); }while(fs::file_size(a) != std::stoull(*FS) && !Terminate);
if (!Terminate) { if(!Terminate){
if (!fs::exists(GetGamePath() + "mods/multiplayer")) { if(!fs::exists(GetGamePath() + "mods/multiplayer")){
fs::create_directories(GetGamePath() + "mods/multiplayer"); fs::create_directories(GetGamePath() + "mods/multiplayer");
} }
fs::copy_file(a,GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
// Linux version of the game doesnt support uppercase letters in mod names
#if defined(__linux__)
for (char& c : FName) {
c = ::tolower(c);
}
#endif
fs::copy_file(a, GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
} }
WaitForConfirm(); WaitForConfirm();
} }
KillSocket(DSock); KillSocket(DSock);
if (!Terminate) { if(!Terminate){
TCPSend(strtovec("Done"), Sock); TCPSend("Done",Sock);
info("Done!"); info("Done!");
} else { }else{
UlStatus = "Ulstart"; UlStatus = "Ulstart";
info("Connection Terminated!"); info("Connection Terminated!");
} }

123
src/Network/VehicleData.cpp Normal file → Executable file
View File

@@ -5,98 +5,69 @@
/// ///
/// Created by Anonymous275 on 5/8/2020 /// Created by Anonymous275 on 5/8/2020
/// ///
#include "Network/network.hpp"
#include "Zlib/Compressor.h" #include "Zlib/Compressor.h"
#include "asio/ip/address.hpp" #include "Network/network.h"
#include "fmt/format.h"
#if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__)
#include "linuxfixes.h"
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif
#include "Logger.h" #include "Logger.h"
#include <array>
#include <string> #include <string>
#include <set>
std::shared_ptr<asio::ip::udp::socket> UDPSock = nullptr; SOCKET UDPSock = -1;
sockaddr_in* ToServer = nullptr;
void UDPSend(const std::vector<char>& RawData) { void UDPSend(std::string Data){
if (ClientID == -1 || UDPSock == nullptr) if(ClientID == -1 || UDPSock == -1)return;
return; if(Data.length() > 400){
std::string Data; std::string CMP(Comp(Data));
if (Data.size() > 400) { Data = "ABG:" + CMP;
auto res = Comp(RawData);
Data = "ABG:" + std::string(res.data(), res.size());
} else {
Data = std::string(RawData.data(), RawData.size());
} }
std::string Packet = char(ClientID + 1) + std::string(":") + Data; std::string Packet = char(ClientID+1) + std::string(":") + Data;
int sendOk = UDPSock->send(asio::buffer(Packet)); int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer));
if (sendOk == SOCKET_ERROR) if (sendOk == SOCKET_ERROR)error("Error Code : " + std::to_string(WSAGetLastError()));
error("Error Code : " + std::to_string(WSAGetLastError()));
} }
void SendLarge(const std::vector<char>& Data) {
if (Data.size() > 400) { void SendLarge(std::string Data){
auto res = Comp(Data); if(Data.length() > 400){
res.insert(res.begin(), { 'A', 'B', 'G', ':' }); std::string CMP(Comp(Data));
if (!TCPSock) { Data = "ABG:" + CMP;
::debug("TCPSock is null");
return;
}
TCPSend(res, *TCPSock);
} else {
if (!TCPSock) {
::debug("TCPSock is null");
return;
}
TCPSend(Data, *TCPSock);
} }
TCPSend(Data,TCPSock);
} }
void UDPParser(std::string_view Packet) { void UDPParser(std::string Packet){
if (Packet.substr(0, 4) == "ABG:") { if(Packet.substr(0,4) == "ABG:"){
auto substr = Packet.substr(4); Packet = DeComp(Packet.substr(4));
auto res = DeComp(std::span<const char>(substr.data(), substr.size()));
std::string DeCompPacket = std::string(res.data(), res.size());
ServerParser(DeCompPacket);
} else {
ServerParser(Packet);
} }
ServerParser(Packet);
} }
void UDPRcv() { void UDPRcv(){
static thread_local std::array<char, 10240> Ret {}; sockaddr_in FromServer{};
if (UDPSock == nullptr) { int clientLength = sizeof(FromServer);
::debug("UDPSock is null"); 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("Can't start Winsock!");
return; return;
} }
asio::error_code ec; delete ToServer;
int32_t Rcv = UDPSock->receive(asio::buffer(Ret.data(), Ret.size() - 1), 0, ec); ToServer = new sockaddr_in;
if (ec) ToServer->sin_family = AF_INET;
return; ToServer->sin_port = htons(Port);
Ret[Rcv] = 0; inet_pton(AF_INET, IP.c_str(), &ToServer->sin_addr);
UDPParser(std::string_view(Ret.data(), Rcv)); UDPSock = socket(AF_INET, SOCK_DGRAM, 0);
} GameSend("P"+std::to_string(ClientID));
void UDPClientMain(asio::ip::address addr, uint16_t port) { TCPSend("H",TCPSock);
UDPSock = std::make_shared<asio::ip::udp::socket>(io); UDPSend("p");
asio::error_code ec; while(!Terminate)UDPRcv();
UDPSock->connect(asio::ip::udp::endpoint(addr, port), ec);
if (ec) {
::error(fmt::format("Failed to connect UDP to server: {}", ec.message()));
Terminate = true;
}
GameSend("P" + std::to_string(ClientID));
TCPSend(strtovec("H"), *TCPSock);
UDPSend(strtovec("p"));
while (!Terminate)
UDPRcv();
KillSocket(UDPSock); KillSocket(UDPSock);
WSACleanup(); WSACleanup();
} }

170
src/Network/VehicleEvent.cpp Normal file → Executable file
View File

@@ -6,36 +6,26 @@
/// Created by Anonymous275 on 5/8/2020 /// Created by Anonymous275 on 5/8/2020
/// ///
#include "Logger.h"
#include "fmt/format.h"
#include <Zlib/Compressor.h>
#include <chrono> #include <chrono>
#include <iostream>
#include <vector> #include <vector>
#include "Logger.h"
#if defined(_WIN32) #include <iostream>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__) #include <Zlib/Compressor.h>
#include <arpa/inet.h>
#include <cstring> #include "Network/network.h"
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif
#include "Network/network.hpp"
int LastPort; int LastPort;
std::string LastIP; std::string LastIP;
std::shared_ptr<asio::ip::tcp::socket> TCPSock = nullptr; SOCKET TCPSock = -1;
bool CheckBytes(int32_t Bytes) { bool CheckBytes(int32_t Bytes){
if (Bytes == 0) { if (Bytes == 0){
debug("(TCP) Connection closing... CheckBytes(16)"); debug("(TCP) Connection closing... CheckBytes(16)");
Terminate = true; Terminate = true;
return false; return false;
} else if (Bytes < 0) { }else if (Bytes < 0) {
debug("(TCP CB) recv failed with error: " + std::to_string(WSAGetLastError())); debug("(TCP CB) recv failed with error: " + std::to_string(WSAGetLastError()));
KillSocket(TCPSock); KillSocket(TCPSock);
Terminate = true; Terminate = true;
@@ -43,87 +33,125 @@ bool CheckBytes(int32_t Bytes) {
} }
return true; return true;
} }
void UUl(const std::string& R) { void UUl(const std::string& R){
UlStatus = "UlDisconnected: " + R; UlStatus = "UlDisconnected: " + R;
} }
void TCPSend(const std::vector<char>& Data, asio::ip::tcp::socket& Sock) { void TCPSend(const std::string&Data,uint64_t Sock){
if (!Sock.is_open()) { if(Sock == -1){
Terminate = true; Terminate = true;
UUl("Invalid Socket"); UUl("Invalid Socket");
return; return;
} }
int32_t Size, Sent, Temp; int32_t Size,Sent,Temp;
std::string Send(4, 0); std::string Send(4,0);
Size = int32_t(Data.size()); Size = int32_t(Data.size());
memcpy(&Send[0], &Size, sizeof(Size)); memcpy(&Send[0],&Size,sizeof(Size));
Send += std::string(Data.data(), Data.size()); Send += Data;
// Do not use Size before this point for anything but the header // Do not use Size before this point for anything but the header
Sent = 0; Sent = 0;
Size += 4; Size += 4;
asio::error_code ec; do{
asio::write(Sock, asio::buffer(Send), ec); if (size_t(Sent) >= Send.size()) {
if (ec) { error("string OOB in " + std::string(__func__));
UUl(fmt::format("Failed to send data: {}", ec.message())); UUl("TCP Send OOB");
} return;
}
Temp = send(Sock, &Send[Sent], Size - Sent, 0);
if(!CheckBytes(Temp)){
UUl("Socket Closed Code 2");
return;
}
Sent += Temp;
}while(Sent < Size);
} }
std::string TCPRcv(asio::ip::tcp::socket& Sock) { std::string TCPRcv(SOCKET Sock){
if (!Sock.is_open()) { if(Sock == -1){
Terminate = true; Terminate = true;
UUl("Invalid Socket"); UUl("Invalid Socket");
return ""; return "";
} }
int32_t Header, BytesRcv = 0, Temp; int32_t Header,BytesRcv = 0,Temp;
std::vector<char> Data(sizeof(Header)); std::vector<char> Data(sizeof(Header));
asio::error_code ec; do{
asio::read(Sock, asio::buffer(Data), ec); Temp = recv(Sock,&Data[BytesRcv],4-BytesRcv,0);
if (ec) { if(!CheckBytes(Temp)){
UUl(fmt::format("Failed to receive header: {}", ec.message())); UUl("Socket Closed Code 3");
} return "";
memcpy(&Header, &Data[0], sizeof(Header)); }
BytesRcv += Temp;
}while(BytesRcv < 4);
memcpy(&Header,&Data[0],sizeof(Header));
if(!CheckBytes(BytesRcv)){
UUl("Socket Closed Code 4");
return "";
}
Data.resize(Header); Data.resize(Header);
asio::read(Sock, asio::buffer(Data), ec); BytesRcv = 0;
if (ec) { do{
UUl(fmt::format("Failed to receive data: {}", ec.message())); Temp = recv(Sock,&Data[BytesRcv],Header-BytesRcv,0);
} if(!CheckBytes(Temp)){
UUl("Socket Closed Code 5");
return "";
}
BytesRcv += Temp;
}while(BytesRcv < Header);
std::string Ret(Data.data(), Header); std::string Ret(Data.data(),Header);
if (Ret.substr(0, 4) == "ABG:") { if (Ret.substr(0, 4) == "ABG:") {
auto substr = Ret.substr(4); Ret = DeComp(Ret.substr(4));
auto res = DeComp(strtovec(substr));
Ret = std::string(res.data(), res.size());
} }
#ifdef DEBUG #ifdef DEBUG
// debug("Parsing from server -> " + std::to_string(Ret.size())); //debug("Parsing from server -> " + std::to_string(Ret.size()));
#endif #endif
if (Ret[0] == 'E' || Ret[0] == 'K') if(Ret[0] == 'E' || Ret[0] == 'K')UUl(Ret.substr(1));
UUl(Ret.substr(1));
return Ret; return Ret;
} }
void TCPClientMain(asio::ip::tcp::socket&& socket) { void TCPClientMain(const std::string& IP,int Port){
if (!TCPSock) { LastIP = IP;
return; LastPort = Port;
} WSADATA wsaData;
LastIP = socket.remote_endpoint().address().to_string();
LastPort = socket.remote_endpoint().port();
SOCKADDR_IN ServerAddr; SOCKADDR_IN ServerAddr;
int RetCode; int RetCode;
TCPSock = std::make_shared<asio::ip::tcp::socket>(std::move(socket)); WSAStartup(514, &wsaData); //2.2
TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(TCPSock == -1){
printf("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 = "UlConnection Failed!";
error("Client: connect failed! Error code: " + std::to_string(WSAGetLastError()));
KillSocket(TCPSock);
WSACleanup();
Terminate = true;
return;
}
info("Connected!"); info("Connected!");
char Code = 'C'; char Code = 'C';
asio::write(*TCPSock, asio::buffer(&Code, 1)); send(TCPSock, &Code, 1, 0);
SyncResources(*TCPSock); SyncResources(TCPSock);
while (!Terminate && TCPSock) { while(!Terminate){
ServerParser(TCPRcv(*TCPSock)); ServerParser(TCPRcv(TCPSock));
} }
GameSend("T"); GameSend("T");
KillSocket(TCPSock); ////Game Send Terminate
if(KillSocket(TCPSock) != 0)
debug("(TCP) Cannot close socket. Error code: " + std::to_string(WSAGetLastError()));
if(WSACleanup() != 0)
debug("(TCP) Client: WSACleanup() failed!...");
} }

View File

@@ -1,35 +0,0 @@
#include "NetworkHelpers.h"
#include <array>
#include <cerrno>
#include <cstring>
#include <stdexcept>
using asio::ip::tcp;
static uint32_t RecvHeader(tcp::socket& socket) {
std::array<uint8_t, sizeof(uint32_t)> header_buffer {};
asio::error_code ec;
auto n = asio::read(socket, asio::buffer(header_buffer), ec);
if (ec) {
throw std::runtime_error(std::string("recv() of header failed: ") + ec.message());
}
if (n == 0) {
throw std::runtime_error("Game disconnected");
}
return *reinterpret_cast<uint32_t*>(header_buffer.data());
}
/// Throws!!!
void ReceiveFromGame(tcp::socket& socket, std::vector<char>& out_data) {
auto header = RecvHeader(socket);
out_data.resize(header);
asio::error_code ec;
auto n = asio::read(socket, asio::buffer(out_data), ec);
if (ec) {
throw std::runtime_error(std::string("recv() of data failed: ") + ec.message());
}
if (n == 0) {
throw std::runtime_error("Game disconnected");
}
}

330
src/Security/BeamNG.cpp Normal file → Executable file
View File

@@ -7,14 +7,7 @@
/// ///
#include <filesystem> #include <filesystem>
#if defined(_WIN32)
#include <windows.h> #include <windows.h>
#elif defined(__linux__)
#include "vdf_parser.hpp"
#include <pwd.h>
#include <unistd.h>
#include <vector>
#endif
#include "Logger.h" #include "Logger.h"
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
@@ -27,10 +20,11 @@
int TraceBack = 0; int TraceBack = 0;
std::string GameDir; std::string GameDir;
void lowExit(int code) { void lowExit(int code){
TraceBack = 0; TraceBack = 0;
std::string msg = "Failed to find the game please launch it. Report this if the issue persists code "; std::string msg =
error(msg + std::to_string(code)); "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)); std::this_thread::sleep_for(std::chrono::seconds(10));
exit(2); exit(2);
} }
@@ -50,136 +44,117 @@ void SteamExit(int code){
std::this_thread::sleep_for(std::chrono::seconds(10)); std::this_thread::sleep_for(std::chrono::seconds(10));
exit(4); exit(4);
}*/ }*/
std::string GetGameDir() { std::string GetGameDir(){
// if(TraceBack != 4)Exit(0); //if(TraceBack != 4)Exit(0);
#if defined(_WIN32) return GameDir.substr(0,GameDir.find_last_of('\\'));
return GameDir.substr(0, GameDir.find_last_of('\\'));
#elif defined(__linux__)
return GameDir.substr(0, GameDir.find_last_of('/'));
#endif
} }
#ifdef _WIN32 LONG OpenKey(HKEY root,const char* path,PHKEY hKey){
LONG OpenKey(HKEY root, const char* path, PHKEY hKey) {
return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey); return RegOpenKeyEx(root, reinterpret_cast<LPCSTR>(path), 0, KEY_READ, hKey);
} }
std::string QueryKey(HKEY hKey, int ID) { std::string QueryKey(HKEY hKey,int ID){
TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name TCHAR achKey[MAX_KEY_LENGTH]; // buffer for subkey name
DWORD cbName; // size of name string DWORD cbName; // size of name string
TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name TCHAR achClass[MAX_PATH] = TEXT(""); // buffer for class name
DWORD cchClassName = MAX_PATH; // size of class string DWORD cchClassName = MAX_PATH; // size of class string
DWORD cSubKeys = 0; // number of subkeys DWORD cSubKeys=0; // number of subkeys
DWORD cbMaxSubKey; // longest subkey size DWORD cbMaxSubKey; // longest subkey size
DWORD cchMaxClass; // longest class string DWORD cchMaxClass; // longest class string
DWORD cValues; // number of values for key DWORD cValues; // number of values for key
DWORD cchMaxValue; // longest value name DWORD cchMaxValue; // longest value name
DWORD cbMaxValueData; // longest value data DWORD cbMaxValueData; // longest value data
DWORD cbSecurityDescriptor; // size of security descriptor DWORD cbSecurityDescriptor; // size of security descriptor
FILETIME ftLastWriteTime; // last write time FILETIME ftLastWriteTime; // last write time
DWORD i, retCode; DWORD i, retCode;
TCHAR achValue[MAX_VALUE_NAME]; TCHAR achValue[MAX_VALUE_NAME];
DWORD cchValue = MAX_VALUE_NAME; DWORD cchValue = MAX_VALUE_NAME;
retCode = RegQueryInfoKey( retCode = RegQueryInfoKey(
hKey, // key handle hKey, // key handle
achClass, // buffer for class name achClass, // buffer for class name
&cchClassName, // size of class string &cchClassName, // size of class string
nullptr, // reserved nullptr, // reserved
&cSubKeys, // number of subkeys &cSubKeys, // number of subkeys
&cbMaxSubKey, // longest subkey size &cbMaxSubKey, // longest subkey size
&cchMaxClass, // longest class string &cchMaxClass, // longest class string
&cValues, // number of values for this key &cValues, // number of values for this key
&cchMaxValue, // longest value name &cchMaxValue, // longest value name
&cbMaxValueData, // longest value data &cbMaxValueData, // longest value data
&cbSecurityDescriptor, // security descriptor &cbSecurityDescriptor, // security descriptor
&ftLastWriteTime); // last write time &ftLastWriteTime); // last write time
BYTE* buffer = new BYTE[cbMaxValueData]; BYTE* buffer = new BYTE[cbMaxValueData];
ZeroMemory(buffer, cbMaxValueData); ZeroMemory(buffer, cbMaxValueData);
if (cSubKeys) { if (cSubKeys){
for (i = 0; i < cSubKeys; i++) { for (i=0; i<cSubKeys; i++){
cbName = MAX_KEY_LENGTH; cbName = MAX_KEY_LENGTH;
retCode = RegEnumKeyEx(hKey, i, achKey, &cbName, nullptr, nullptr, nullptr, &ftLastWriteTime); retCode = RegEnumKeyEx(hKey, i,achKey,&cbName,nullptr,nullptr,nullptr,&ftLastWriteTime);
if (retCode == ERROR_SUCCESS) { if (retCode == ERROR_SUCCESS){
if (strcmp(achKey, "Steam App 284160") == 0) { if(strcmp(achKey,"Steam App 284160") == 0){
return achKey; return achKey;
} }
} }
} }
} }
if (cValues) { if (cValues){
for (i = 0, retCode = ERROR_SUCCESS; i < cValues; i++) { for (i=0, retCode = ERROR_SUCCESS; i<cValues; i++){
cchValue = MAX_VALUE_NAME; cchValue = MAX_VALUE_NAME;
achValue[0] = '\0'; achValue[0] = '\0';
retCode = RegEnumValue(hKey, i, achValue, &cchValue, nullptr, nullptr, nullptr, nullptr); retCode = RegEnumValue(hKey, i,achValue,&cchValue,nullptr,nullptr,nullptr,nullptr);
if (retCode == ERROR_SUCCESS) { if (retCode == ERROR_SUCCESS ){
DWORD lpData = cbMaxValueData; DWORD lpData = cbMaxValueData;
buffer[0] = '\0'; buffer[0] = '\0';
LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData); LONG dwRes = RegQueryValueEx(hKey, achValue, nullptr, nullptr, buffer, &lpData);
std::string data = (char*)(buffer); std::string data = (char *)(buffer);
std::string key = achValue; std::string key = achValue;
switch (ID) { switch (ID){
case 1: case 1: if(key == "SteamExe"){
if (key == "SteamExe") { auto p = data.find_last_of("/\\");
auto p = data.find_last_of("/\\"); if(p != std::string::npos){
if (p != std::string::npos) { return data.substr(0,p);
return data.substr(0, p); }
} }
} break;
break; case 2: if(key == "Name" && data == "BeamNG.drive")return data;break;
case 2: case 3: if(key == "rootpath")return data;break;
if (key == "Name" && data == "BeamNG.drive") case 4: if(key == "userpath_override")return data;
return data; case 5: if(key == "Local AppData")return data;
break; default: 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; delete [] buffer;
return ""; return "";
} }
#endif
namespace fs = std::filesystem; namespace fs = std::filesystem;
bool NameValid(const std::string& N) { bool NameValid(const std::string& N){
if (N == "config" || N == "librarycache") { if(N == "config" || N == "librarycache"){
return true; return true;
} }
if (N.find_first_not_of("0123456789") == std::string::npos) { if(N.find_first_not_of("0123456789") == std::string::npos){
return true; return true;
} }
return false; return false;
} }
void FileList(std::vector<std::string>& a, const std::string& Path) { void FileList(std::vector<std::string>&a,const std::string& Path){
for (const auto& entry : fs::directory_iterator(Path)) { for (const auto &entry : fs::directory_iterator(Path)) {
const auto& DPath = entry.path(); const auto& DPath = entry.path();
if (!entry.is_directory()) { if (!entry.is_directory()) {
a.emplace_back(DPath.string()); a.emplace_back(DPath.string());
} else if (NameValid(DPath.filename().string())) { }else if(NameValid(DPath.filename().string())){
FileList(a, DPath.string()); FileList(a, DPath.string());
} }
} }
} }
bool Find(const std::string& FName, const std::string& Path) { bool Find(const std::string& FName,const std::string& Path){
std::vector<std::string> FS; std::vector<std::string> FS;
FileList(FS, Path + "\\userdata"); FileList(FS,Path+"\\userdata");
for (std::string& a : FS) { for(std::string&a : FS){
if (a.find(FName) != std::string::npos) { if(a.find(FName) != std::string::npos){
FS.clear(); FS.clear();
return true; return true;
} }
@@ -187,24 +162,22 @@ bool Find(const std::string& FName, const std::string& Path) {
FS.clear(); FS.clear();
return false; return false;
} }
bool FindHack(const std::string& Path) { bool FindHack(const std::string& Path){
bool s = true; bool s = true;
for (const auto& entry : fs::directory_iterator(Path)) { for (const auto &entry : fs::directory_iterator(Path)) {
std::string Name = entry.path().filename().string(); std::string Name = entry.path().filename().string();
for (char& c : Name) for(char&c : Name)c = char(tolower(c));
c = char(tolower(c)); if(Name == "steam.exe")s = false;
if (Name == "steam.exe") if(Name.find("greenluma") != -1){
s = false; error("Found malicious file/folder \"" + Name+"\"");
if (Name.find("greenluma") != -1) {
error("Found malicious file/folder \"" + Name + "\"");
return true; return true;
} }
Name.clear(); Name.clear();
} }
return s; return s;
} }
std::vector<std::string> GetID(const std::string& log) { std::vector<std::string> GetID(const std::string& log){
std::string vec, t, r; std::string vec,t,r;
std::vector<std::string> Ret; std::vector<std::string> Ret;
std::ifstream f(log.c_str(), std::ios::binary); std::ifstream f(log.c_str(), std::ios::binary);
f.seekg(0, std::ios_base::end); f.seekg(0, std::ios_base::end);
@@ -216,12 +189,10 @@ std::vector<std::string> GetID(const std::string& log) {
std::stringstream ss(vec); std::stringstream ss(vec);
bool S = false; bool S = false;
while (std::getline(ss, t, '{')) { while (std::getline(ss, t, '{')) {
if (!S) if(!S)S = true;
S = true; else{
else { for(char& c : t){
for (char& c : t) { if(isdigit(c))r += c;
if (isdigit(c))
r += c;
} }
break; break;
} }
@@ -231,16 +202,15 @@ std::vector<std::string> GetID(const std::string& log) {
S = false; S = false;
bool L = true; bool L = true;
while (std::getline(ss, t, '}')) { while (std::getline(ss, t, '}')) {
if (L) { if(L){
L = false; L = false;
continue; continue;
} }
for (char& c : t) { for(char& c : t){
if (c == '"') { if(c == '"'){
if (!S) if(!S)S = true;
S = true; else{
else { if(r.length() > 10) {
if (r.length() > 10) {
Ret.emplace_back(r); Ret.emplace_back(r);
} }
r.clear(); r.clear();
@@ -248,14 +218,13 @@ std::vector<std::string> GetID(const std::string& log) {
continue; continue;
} }
} }
if (isdigit(c)) if(isdigit(c))r += c;
r += c;
} }
} }
vec.clear(); vec.clear();
return Ret; return Ret;
} }
std::string GetManifest(const std::string& Man) { std::string GetManifest(const std::string& Man){
std::string vec; std::string vec;
std::ifstream f(Man.c_str(), std::ios::binary); std::ifstream f(Man.c_str(), std::ios::binary);
f.seekg(0, std::ios_base::end); f.seekg(0, std::ios_base::end);
@@ -266,109 +235,84 @@ std::string GetManifest(const std::string& Man) {
f.close(); f.close();
std::string ToFind = "\"LastOwner\"\t\t\""; std::string ToFind = "\"LastOwner\"\t\t\"";
int pos = int(vec.find(ToFind)); int pos = int(vec.find(ToFind));
if (pos != -1) { if(pos != -1){
pos += int(ToFind.length()); pos += int(ToFind.length());
vec = vec.substr(pos); vec = vec.substr(pos);
return vec.substr(0, vec.find('\"')); return vec.substr(0,vec.find('\"'));
} else }else return "";
return "";
} }
bool IDCheck(std::string Man, std::string steam) { bool IDCheck(std::string Man, std::string steam){
bool a = false, b = true; bool a = false,b = true;
int pos = int(Man.rfind("steamapps")); int pos = int(Man.rfind("steamapps"));
// if(pos == -1)Exit(5); // if(pos == -1)Exit(5);
Man = Man.substr(0, pos + 9) + "\\appmanifest_284160.acf"; Man = Man.substr(0,pos+9) + "\\appmanifest_284160.acf";
steam += "\\config\\loginusers.vdf"; steam += "\\config\\loginusers.vdf";
if (fs::exists(Man) && fs::exists(steam)) { if(fs::exists(Man) && fs::exists(steam)){
for (const std::string& ID : GetID(steam)) { for(const std::string&ID : GetID(steam)){
if (ID == GetManifest(Man)) if(ID == GetManifest(Man))b = false;
b = false;
} }
// if(b)Exit(6); //if(b)Exit(6);
} else }else a = true;
a = true;
return a; return a;
} }
void LegitimacyCheck() { void LegitimacyCheck(){
// std::string K1 = R"(Software\Valve\Steam)"; //std::string K1 = R"(Software\Valve\Steam)";
// std::string K2 = R"(Software\Valve\Steam\Apps\284160)"; //std::string K2 = R"(Software\Valve\Steam\Apps\284160)";
/*LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K1.c_str(), &hKey); /*LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K1.c_str(), &hKey);
if(dwRegOPenKey == ERROR_SUCCESS) { if(dwRegOPenKey == ERROR_SUCCESS) {
Result = QueryKey(hKey, 1); Result = QueryKey(hKey, 1);
if(Result.empty())Exit(1); if(Result.empty())Exit(1);
if(fs::exists(Result)){ if(fs::exists(Result)){
if(!Find("284160.json",Result))Exit(2); if(!Find("284160.json",Result))Exit(2);
if(FindHack(Result))SteamExit(1); if(FindHack(Result))SteamExit(1);
}else Exit(3); }else Exit(3);
T = Result; T = Result;
Result.clear(); Result.clear();
TraceBack++; TraceBack++;
}else Exit(4); }else Exit(4);
K1.clear(); K1.clear();
RegCloseKey(hKey); RegCloseKey(hKey);
dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K2.c_str(), &hKey); dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K2.c_str(), &hKey);
if(dwRegOPenKey == ERROR_SUCCESS) { if(dwRegOPenKey == ERROR_SUCCESS) {
Result = QueryKey(hKey, 2); Result = QueryKey(hKey, 2);
if(Result.empty())lowExit(1); if(Result.empty())lowExit(1);
TraceBack++; TraceBack++;
}else lowExit(2); }else lowExit(2);
K2.clear(); K2.clear();
RegCloseKey(hKey);*/ RegCloseKey(hKey);*/
#if defined(_WIN32)
std::string Result; std::string Result;
std::string K3 = R"(Software\BeamNG\BeamNG.drive)"; std::string K3 = R"(Software\BeamNG\BeamNG.drive)";
HKEY hKey; HKEY hKey;
LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey); LONG dwRegOPenKey = OpenKey(HKEY_CURRENT_USER, K3.c_str(), &hKey);
if (dwRegOPenKey == ERROR_SUCCESS) { if(dwRegOPenKey == ERROR_SUCCESS) {
Result = QueryKey(hKey, 3); Result = QueryKey(hKey, 3);
if (Result.empty()) if(Result.empty())lowExit(3);
lowExit(3); //if(IDCheck(Result,T))lowExit(5);
// if(IDCheck(Result,T))lowExit(5);
GameDir = Result; GameDir = Result;
// TraceBack++; //TraceBack++;
} else }else lowExit(4);
lowExit(4);
K3.clear(); K3.clear();
Result.clear(); Result.clear();
RegCloseKey(hKey); RegCloseKey(hKey);
// if(TraceBack < 3)exit(-1); //if(TraceBack < 3)exit(-1);
#elif defined(__linux__)
struct passwd* pw = getpwuid(getuid());
std::string homeDir = pw->pw_dir;
// Right now only steam is supported
std::ifstream libraryFolders(homeDir + "/.steam/root/steamapps/libraryfolders.vdf");
auto root = tyti::vdf::read(libraryFolders);
for (auto folderInfo : root.childs) {
if (std::filesystem::exists(folderInfo.second->attribs["path"] + "/steamapps/common/BeamNG.drive/")) {
GameDir = folderInfo.second->attribs["path"] + "/steamapps/common/BeamNG.drive/";
break;
}
}
#endif
} }
std::string CheckVer(const std::string& dir) { std::string CheckVer(const std::string &dir){
#if defined(_WIN32) std::string temp,Path = dir + "\\integrity.json";
std::string temp, Path = dir + "\\integrity.json";
#elif defined(__linux__)
std::string temp, Path = dir + "/integrity.json";
#endif
std::ifstream f(Path.c_str(), std::ios::binary); std::ifstream f(Path.c_str(), std::ios::binary);
int Size = int(std::filesystem::file_size(Path)); int Size = int(std::filesystem::file_size(Path));
std::string vec(Size, 0); std::string vec(Size,0);
f.read(&vec[0], Size); f.read(&vec[0], Size);
f.close(); f.close();
vec = vec.substr(vec.find_last_of("version"), vec.find_last_of('"')); vec = vec.substr(vec.find_last_of("version"),vec.find_last_of('"'));
for (const char& a : vec) { for(const char &a : vec){
if (isdigit(a) || a == '.') if(isdigit(a) || a == '.')temp+=a;
temp += a;
} }
return temp; return temp;
} }

284
src/Security/Login.cpp Normal file → Executable file
View File

@@ -1,143 +1,141 @@
// Copyright (c) 2019-present Anonymous275. // Copyright (c) 2019-present Anonymous275.
// BeamMP Launcher code is not in the public domain and is not free software. // 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. // 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. // Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
/// ///
/// Created by Anonymous275 on 11/26/2020 /// Created by Anonymous275 on 11/26/2020
/// ///
#include "Http.h" #include <nlohmann/json.hpp>
#include "Logger.h" #include "Http.h"
#include <filesystem> #include <filesystem>
#include <fstream> #include "Logger.h"
#include <nlohmann/json.hpp> #include <fstream>
namespace fs = std::filesystem;
std::string PublicKey; namespace fs = std::filesystem;
std::string PrivateKey; std::string PublicKey;
extern bool LoginAuth; std::string PrivateKey;
extern std::string Username; extern bool LoginAuth;
extern std::string UserRole; extern std::string Username;
extern std::string UserRole;
void UpdateKey(const char* newKey) {
if (newKey && std::isalnum(newKey[0])) { void UpdateKey(const char* newKey){
PrivateKey = newKey; if(newKey && std::isalnum(newKey[0])){
std::ofstream Key("key"); PrivateKey = newKey;
if (Key.is_open()) { std::ofstream Key("key");
Key << newKey; if(Key.is_open()){
Key.close(); Key << newKey;
} else Key.close();
fatal("Cannot write to disk!"); }else fatal("Cannot write to disk!");
} else if (fs::exists("key")) { }else if(fs::exists("key")){
remove("key"); remove("key");
} }
} }
/// "username":"value","password":"value" /// "username":"value","password":"value"
/// "Guest":"Name" /// "Guest":"Name"
/// "pk":"private_key" /// "pk":"private_key"
std::string GetFail(const std::string& R) { std::string GetFail(const std::string& R){
std::string DRet = R"({"success":false,"message":)"; std::string DRet = R"({"success":false,"message":)";
DRet += "\"" + R + "\"}"; DRet += "\""+R+"\"}";
error(R); error(R);
return DRet; return DRet;
} }
std::string Login(const std::string& fields) { std::string Login(const std::string& fields){
if (fields == "LO") { if(fields == "LO"){
Username = ""; Username = "";
UserRole = ""; UserRole = "";
LoginAuth = false; LoginAuth = false;
UpdateKey(nullptr); UpdateKey(nullptr);
return ""; return "";
} }
info("Attempting to authenticate..."); info("Attempting to authenticate...");
try { try {
std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields); std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
if (Buffer == "-1") { if(Buffer == "-1"){
return GetFail("Failed to communicate with the auth system!"); return GetFail("Failed to communicate with the auth system!");
} }
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false); nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
if (Buffer.at(0) != '{' || d.is_discarded()) { if (Buffer.at(0) != '{' || d.is_discarded()) {
error(Buffer); error(Buffer);
return GetFail("Invalid answer from authentication servers, please try again later!"); return GetFail("Invalid answer from authentication servers, please try again later!");
} }
if (d.contains("success") && d["success"].get<bool>()) { if(d.contains("success") && d["success"].get<bool>()){
LoginAuth = true; LoginAuth = true;
if (d.contains("username")) { if (d.contains("username")) {
Username = d["username"].get<std::string>(); Username = d["username"].get<std::string>();
} }
if (d.contains("role")) { if (d.contains("role")) {
UserRole = d["role"].get<std::string>(); UserRole = d["role"].get<std::string>();
} }
if (d.contains("private_key")) { if(d.contains("private_key")) {
UpdateKey(d["private_key"].get<std::string>().c_str()); UpdateKey(d["private_key"].get<std::string>().c_str());
} }
if (d.contains("public_key")) { if(d.contains("public_key")){
PublicKey = d["public_key"].get<std::string>(); PublicKey = d["public_key"].get<std::string>();
} }
info("Authentication successful!"); info("Authentication successful!");
} else }else info("Authentication failed!");
info("Authentication failed!"); if(d.contains("message")){
if (d.contains("message")) { d.erase("private_key");
d.erase("private_key"); d.erase("public_key");
d.erase("public_key"); return d.dump();
return d.dump(); }
} return GetFail("Invalid message parsing!");
return GetFail("Invalid message parsing!"); } catch (const std::exception& e) {
} catch (const std::exception& e) { return GetFail(e.what());
return GetFail(e.what()); }
} }
}
void CheckLocalKey(){
void CheckLocalKey() { if(fs::exists("key") && fs::file_size("key") < 100){
if (fs::exists("key") && fs::file_size("key") < 100) { std::ifstream Key("key");
std::ifstream Key("key"); if(Key.is_open()) {
if (Key.is_open()) { auto Size = fs::file_size("key");
auto Size = fs::file_size("key"); std::string Buffer(Size, 0);
std::string Buffer(Size, 0); Key.read(&Buffer[0], Size);
Key.read(&Buffer[0], Size); Key.close();
Key.close();
for (char& c : Buffer) {
for (char& c : Buffer) { if (!std::isalnum(c) && c != '-') {
if (!std::isalnum(c) && c != '-') { UpdateKey(nullptr);
UpdateKey(nullptr); return;
return; }
} }
}
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
nlohmann::json d = nlohmann::json::parse(Buffer, nullptr, false);
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) {
if (Buffer == "-1" || Buffer.at(0) != '{' || d.is_discarded()) { error(Buffer);
error(Buffer); info("Invalid answer from authentication servers.");
info("Invalid answer from authentication servers."); UpdateKey(nullptr);
UpdateKey(nullptr); }
} if(d["success"].get<bool>()){
if (d["success"].get<bool>()) { LoginAuth = true;
LoginAuth = true; UpdateKey(d["private_key"].get<std::string>().c_str());
UpdateKey(d["private_key"].get<std::string>().c_str()); PublicKey = d["public_key"].get<std::string>();
PublicKey = d["public_key"].get<std::string>(); if (d.contains("username")) {
if (d.contains("username")) { Username = d["username"].get<std::string>();
Username = d["username"].get<std::string>(); }
} if (d.contains("role")) {
if (d.contains("role")) { UserRole = d["role"].get<std::string>();
UserRole = d["role"].get<std::string>(); }
} //info(Role);
// info(Role); }else{
} else { info("Auto-Authentication unsuccessful please re-login!");
info("Auto-Authentication unsuccessful please re-login!"); UpdateKey(nullptr);
UpdateKey(nullptr); }
} }else{
} else { warn("Could not open saved key!");
warn("Could not open saved key!"); UpdateKey(nullptr);
UpdateKey(nullptr); }
} }else UpdateKey(nullptr);
} else }
UpdateKey(nullptr);
}

758
src/Startup.cpp Normal file → Executable file
View File

@@ -1,432 +1,326 @@
// Copyright (c) 2019-present Anonymous275. // Copyright (c) 2019-present Anonymous275.
// BeamMP Launcher code is not in the public domain and is not free software. // 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. // 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. // Anything else is prohibited. Modified works may not be published and have be upstreamed to the official repository.
/// ///
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include "zip_file.h" #include <nlohmann/json.hpp>
#include <charconv> #include <httplib.h>
#include <httplib.h> #include "zip_file.h"
#include <nlohmann/json.hpp> #include <windows.h>
#include <string> #include "Discord/discord_info.h"
#if defined(_WIN32) #include "Network/network.h"
#include <windows.h> #include "Security/Init.h"
#elif defined(__linux__) #include <filesystem>
#include <unistd.h> #include "Startup.h"
#endif #include "hashpp.h"
#include "Http.h" #include "Logger.h"
#include "Logger.h" #include <fstream>
#include "Network/network.hpp" #include <thread>
#include "Security/Init.h" #include "Http.h"
#include "Startup.h"
#include "hashpp.h"
#include <filesystem> extern int TraceBack;
#include <fstream> bool Dev = false;
#include <thread> int ProxyPort = 0;
extern int TraceBack; namespace fs = std::filesystem;
bool Dev = false;
int ProxyPort = 0; VersionParser::VersionParser(const std::string& from_string) {
std::string token;
namespace fs = std::filesystem; std::istringstream tokenStream(from_string);
while (std::getline(tokenStream, token, '.')) {
struct Version { data.emplace_back(std::stol(token));
uint8_t major; split.emplace_back(token);
uint8_t minor; }
uint8_t patch; }
Version(uint8_t major, uint8_t minor, uint8_t patch);
Version(const std::array<uint8_t, 3>& v); std::strong_ordering VersionParser::operator<=>(
}; const VersionParser& rhs) const noexcept {
size_t const fields = std::min(data.size(), rhs.data.size());
std::array<uint8_t, 3> VersionStrToInts(const std::string& str) { for (size_t i = 0; i != fields; ++i) {
std::array<uint8_t, 3> Version; if (data[i] == rhs.data[i]) continue;
std::stringstream ss(str); else if (data[i] < rhs.data[i]) return std::strong_ordering::less;
for (uint8_t& i : Version) { else return std::strong_ordering::greater;
std::string Part; }
std::getline(ss, Part, '.'); if (data.size() == rhs.data.size()) return std::strong_ordering::equal;
std::from_chars(&*Part.begin(), &*Part.begin() + Part.size(), i); else if (data.size() > rhs.data.size()) return std::strong_ordering::greater;
} else return std::strong_ordering::less;
return Version; }
}
bool VersionParser::operator==(const VersionParser& rhs) const noexcept {
bool IsOutdated(const Version& Current, const Version& Newest) { return std::is_eq(*this <=> rhs);
if (Newest.major > Current.major) { }
return true;
} else if (Newest.major == Current.major && Newest.minor > Current.minor) {
return true; std::string GetEN(){
} else if (Newest.major == Current.major && Newest.minor == Current.minor && Newest.patch > Current.patch) { return "BeamMP-Launcher.exe";
return true; }
} else { std::string GetVer(){
return false; return "2.0";
} }
} std::string GetPatch(){
return ".85";
Version::Version(uint8_t major, uint8_t minor, uint8_t patch) }
: major(major)
, minor(minor) std::string GetEP(char*P){
, patch(patch) { } static std::string Ret = [&](){
std::string path(P);
Version::Version(const std::array<uint8_t, 3>& v) return path.substr(0, path.find_last_of("\\/") + 1);
: Version(v[0], v[1], v[2]) { } ();
} return Ret;
}
std::string GetEN() { void ReLaunch(int argc,char*args[]){
#if defined(_WIN32) std::string Arg;
return "BeamMP-Launcher.exe"; for(int c = 2; c <= argc; c++){
#elif defined(__linux__) Arg += " ";
return "BeamMP-Launcher"; Arg += args[c-1];
#endif }
} system("cls");
ShellExecute(nullptr,"runas",(GetEP() + GetEN()).c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
std::string GetVer() { ShowWindow(GetConsoleWindow(),0);
return "2.1"; std::this_thread::sleep_for(std::chrono::seconds(1));
} exit(1);
std::string GetPatch() { }
return ".0"; void URelaunch(int argc,char* args[]){
} std::string Arg;
for(int c = 2; c <= argc; c++){
std::string GetEP(char* P) { Arg += " ";
static std::string Ret = [&]() { Arg += args[c-1];
std::string path(P); }
return path.substr(0, path.find_last_of("\\/") + 1); ShellExecute(nullptr,"open",(GetEP() + GetEN()).c_str(),Arg.c_str(),nullptr,SW_SHOWNORMAL);
}(); ShowWindow(GetConsoleWindow(),0);
return Ret; std::this_thread::sleep_for(std::chrono::seconds(1));
} exit(1);
#if defined(_WIN32) }
void ReLaunch(int argc, char* args[]) { void CheckName(int argc,char* args[]){
std::string Arg; std::string DN = GetEN(),CDir = args[0],FN = CDir.substr(CDir.find_last_of('\\')+1);
for (int c = 2; c <= argc; c++) { if(FN != DN){
Arg += " "; if(fs::exists(DN))remove(DN.c_str());
Arg += args[c - 1]; if(fs::exists(DN))ReLaunch(argc,args);
} std::rename(FN.c_str(), DN.c_str());
system("cls"); URelaunch(argc,args);
ShellExecute(nullptr, "runas", (GetEP() + GetEN()).c_str(), Arg.c_str(), nullptr, SW_SHOWNORMAL); }
ShowWindow(GetConsoleWindow(), 0); }
std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1); void CheckForUpdates(int argc, char* args[], const std::string& CV) {
} std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/launcher?branch=" + Branch + "&pk=" + PublicKey);
void URelaunch(int argc, char* args[]) { std::string LatestVersion = HTTP::Get(
std::string Arg; "https://backend.beammp.com/version/launcher?branch=" + Branch + "&pk=" + PublicKey);
for (int c = 2; c <= argc; c++) {
Arg += " "; transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
Arg += args[c - 1]; std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back");
}
ShellExecute(nullptr, "open", (GetEP() + GetEN()).c_str(), Arg.c_str(), nullptr, SW_SHOWNORMAL); std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, EP);
ShowWindow(GetConsoleWindow(), 0);
std::this_thread::sleep_for(std::chrono::seconds(1)); if (FileHash != LatestHash && VersionParser(LatestVersion) > VersionParser(GetVer()+GetPatch())) {
exit(1); info("Launcher update found!");
} fs::remove(Back);
#elif defined(__linux__) fs::rename(EP, Back);
void ReLaunch(int argc, char* args[]) { info("Downloading Launcher update " + LatestHash);
std::string Arg; HTTP::Download(
for (int c = 2; c <= argc; c++) { "https://backend.beammp.com/builds/launcher?download=true"
Arg += " "; "&pk=" +
Arg += args[c - 1]; PublicKey + "&branch=" + Branch,
} EP);
system("clear"); URelaunch(argc, args);
execl((GetEP() + GetEN()).c_str(), Arg.c_str(), NULL); } else info("Launcher version is up to date");
std::this_thread::sleep_for(std::chrono::seconds(1)); TraceBack++;
exit(1); }
}
void URelaunch(int argc, char* args[]) { void CustomPort(int argc, char* argv[]){
std::string Arg; if(argc > 1){
for (int c = 2; c <= argc; c++) { std::string Port = argv[1];
Arg += " "; if(Port.find_first_not_of("0123456789") == std::string::npos){
Arg += args[c - 1]; if(std::stoi(Port) > 1000){
} DEFAULT_PORT = std::stoi(Port);
execl((GetEP() + GetEN()).c_str(), Arg.c_str(), NULL); warn("Running on custom port : " + std::to_string(DEFAULT_PORT));
std::this_thread::sleep_for(std::chrono::seconds(1)); }
exit(1); }
} if(argc > 2)Dev = true;
#endif }
}
void CheckName(int argc, char* args[]) {
#if defined(_WIN32) void LinuxPatch(){
std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('\\') + 1); HKEY hKey = nullptr;
#elif defined(__linux__) LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey);
std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('/') + 1); if (result != ERROR_SUCCESS || getenv("USER") == nullptr)return;
#endif RegCloseKey(hKey);
if (FN != DN) { info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit");
if (fs::exists(DN)) info("Applying patches...");
remove(DN.c_str());
if (fs::exists(DN)) result = RegCreateKey(HKEY_CURRENT_USER, R"(Software\Valve\Steam\Apps\284160)", &hKey);
ReLaunch(argc, args);
std::rename(FN.c_str(), DN.c_str()); if (result != ERROR_SUCCESS){
URelaunch(argc, args); fatal(R"(failed to create HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)");
} return;
} }
void CheckForUpdates(int argc, char* args[], const std::string& CV) { result = RegSetValueEx(hKey, "Name", 0, REG_SZ, (BYTE*)"BeamNG.drive", 12);
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/launcher?branch=" + Branch + "&pk=" + PublicKey);
std::string LatestVersion = HTTP::Get( if (result != ERROR_SUCCESS){
"https://backend.beammp.com/version/launcher?branch=" + Branch + "&pk=" + PublicKey); fatal(R"(failed to create the value "Name" under HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)");
return;
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower); }
std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back"); RegCloseKey(hKey);
std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, EP); info("Patched!");
#if defined(_WIN32) }
#elif defined(__linux__)
system("clear"); void InitLauncher(int argc, char* argv[]) {
#endif system("cls");
SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str());
if (FileHash != LatestHash && IsOutdated(Version(VersionStrToInts(GetVer() + GetPatch())), Version(VersionStrToInts(LatestVersion)))) { InitLog();
info("Launcher update found!"); CheckName(argc, argv);
#if defined(__linux__) LinuxPatch();
error("Auto update is NOT implemented for the Linux version. Please update manually ASAP as updates contain security patches."); CheckLocalKey();
#else ConfigInit();
fs::remove(Back); CustomPort(argc, argv);
fs::rename(EP, Back); Discord_Main();
info("Downloading Launcher update " + LatestHash); CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
HTTP::Download( }
"https://backend.beammp.com/builds/launcher?download=true"
"&pk=" size_t DirCount(const std::filesystem::path& path){
+ PublicKey + "&branch=" + Branch, return (size_t)std::distance(std::filesystem::directory_iterator{path}, std::filesystem::directory_iterator{});
EP); }
URelaunch(argc, args);
#endif void CheckMP(const std::string& Path) {
} else if (!fs::exists(Path))return;
info("Launcher version is up to date"); size_t c = DirCount(fs::path(Path));
TraceBack++; try {
} for (auto& p : fs::directory_iterator(Path)){
if(p.exists() && !p.is_directory()){
void CustomPort(int argc, char* argv[]) { std::string Name = p.path().filename().string();
if (argc > 1) { for(char&Ch : Name)Ch = char(tolower(Ch));
std::string Port = argv[1]; if(Name != "beammp.zip")fs::remove(p.path());
if (Port.find_first_not_of("0123456789") == std::string::npos) { }
if (std::stoi(Port) > 1000) { }
DEFAULT_PORT = std::stoi(Port); } catch (...) {
warn("Running on custom port : " + std::to_string(DEFAULT_PORT)); fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?");
} }
}
if (argc > 2) }
Dev = true;
} void EnableMP(){
for (int i = 1; i < argc; ++i) { std::string File(GetGamePath() + "mods/db.json");
if (std::string_view(argv[i]) == "--dev") { if(!fs::exists(File))return;
Dev = true; auto Size = fs::file_size(File);
} else if (std::string_view(argv[i]) == "--no-dev") { if(Size < 2)return;
Dev = false; std::ifstream db(File);
} if(db.is_open()) {
} std::string Data(Size, 0);
} db.read(&Data[0], Size);
db.close();
#ifdef _WIN32 nlohmann::json d = nlohmann::json::parse(Data, nullptr, false);
void LinuxPatch() { if(Data.at(0) != '{' || d.is_discarded()) {
HKEY hKey = nullptr; //error("Failed to parse " + File); //TODO illegal formatting
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey); return;
if (result != ERROR_SUCCESS || getenv("USER") == nullptr) }
return; if(d.contains("mods") && d["mods"].contains("multiplayerbeammp")){
RegCloseKey(hKey); d["mods"]["multiplayerbeammp"]["active"] = true;
info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit"); std::ofstream ofs(File);
info("Applying patches..."); if(ofs.is_open()){
ofs << d.dump();
result = RegCreateKey(HKEY_CURRENT_USER, R"(Software\Valve\Steam\Apps\284160)", &hKey); ofs.close();
}else{
if (result != ERROR_SUCCESS) { error("Failed to write " + File);
fatal(R"(failed to create HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)"); }
return; }
} }
}
result = RegSetValueEx(hKey, "Name", 0, REG_SZ, (BYTE*)"BeamNG.drive", 12);
void PreGame(const std::string& GamePath){
if (result != ERROR_SUCCESS) { std::string GameVer = CheckVer(GamePath);
fatal(R"(failed to create the value "Name" under HKEY_CURRENT_USER\Software\Valve\Steam\Apps\284160)"); info("Game Version : " + GameVer);
return;
} CheckMP(GetGamePath() + "mods/multiplayer");
RegCloseKey(hKey);
if(!Dev) {
info("Patched!"); std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey);
} transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
#endif LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
[](auto const& c ) -> bool { return !std::isalnum(c); } ), LatestHash.end());
#if defined(_WIN32)
void InitLauncher(int argc, char* argv[]) { try {
system("cls"); if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str()); fs::create_directories(GetGamePath() + "mods/multiplayer");
InitLog(); }
CheckName(argc, argv); EnableMP();
LinuxPatch(); }catch(std::exception&e){
CheckLocalKey(); fatal(e.what());
ConfigInit(); }
CustomPort(argc, argv);
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch()); std::string ZipPath(GetGamePath() + R"(mods\multiplayer\BeamMP.zip)");
}
#elif defined(__linux__) std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, ZipPath);
void InitLauncher(int argc, char* argv[]) {
system("clear"); if (FileHash != LatestHash) {
InitLog(); info("Downloading BeamMP Update " + LatestHash);
CheckName(argc, argv); HTTP::Download("https://backend.beammp.com/builds/client?download=true"
CheckLocalKey(); "&pk=" + PublicKey + "&branch=" + Branch, ZipPath);
ConfigInit(); }
CustomPort(argc, argv);
bool update = true; std::string Target(GetGamePath() + "mods/unpacked/beammp");
for (int i = 1; i < argc; ++i) {
if (std::string_view(argv[i]) == "--no-update") { if(fs::is_directory(Target)) {
update = false; fs::remove_all(Target);
} }
} }
if (update) { }
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
} void set_headers(httplib::Response& res) {
} res.set_header("Access-Control-Allow-Origin", "*");
#endif res.set_header("Access-Control-Request-Method", "POST, OPTIONS, GET");
res.set_header("Access-Control-Request-Headers", "X-API-Version");
size_t DirCount(const std::filesystem::path& path) { }
return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {});
} void StartProxy() {
std::thread proxy([&](){
void CheckMP(const std::string& Path) { httplib::Server HTTPProxy;
if (!fs::exists(Path)) httplib::Headers headers = {
return; {"User-Agent", "BeamMP-Launcher/" + GetVer() + GetPatch()},
size_t c = DirCount(fs::path(Path)); {"Accept", "*/*"}
try { };
for (auto& p : fs::directory_iterator(Path)) { std::string pattern = "/:any1";
if (p.exists() && !p.is_directory()) { for (int i = 2; i <= 4; i++) {
std::string Name = p.path().filename().string(); HTTPProxy.Get(pattern, [&](const httplib::Request &req, httplib::Response &res) {
for (char& Ch : Name) httplib::Client cli("https://backend.beammp.com");
Ch = char(tolower(Ch)); set_headers(res);
if (Name != "beammp.zip") if (req.has_header("X-BMP-Authentication")) {
fs::remove(p.path()); headers.emplace("X-BMP-Authentication", PrivateKey);
} }
} if (req.has_header("X-API-Version")) {
} catch (...) { headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?"); }
} 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 {
void EnableMP() { res.set_content(to_string(cli_res.error()), "text/plain");
std::string File(GetGamePath() + "mods/db.json"); }
if (!fs::exists(File)) });
return;
auto Size = fs::file_size(File); HTTPProxy.Post(pattern, [&](const httplib::Request &req, httplib::Response &res) {
if (Size < 2) httplib::Client cli("https://backend.beammp.com");
return; set_headers(res);
std::ifstream db(File); if (req.has_header("X-BMP-Authentication")) {
if (db.is_open()) { headers.emplace("X-BMP-Authentication", PrivateKey);
std::string Data(Size, 0); }
db.read(&Data[0], Size); if (req.has_header("X-API-Version")) {
db.close(); headers.emplace("X-API-Version", req.get_header_value("X-API-Version"));
nlohmann::json d = nlohmann::json::parse(Data, nullptr, false); }
if (Data.at(0) != '{' || d.is_discarded()) { if (auto cli_res = cli.Post(req.path, headers, req.body,
// error("Failed to parse " + File); //TODO illegal formatting req.get_header_value("Content-Type")); cli_res) {
return; res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
} } else {
if (d.contains("mods") && d["mods"].contains("multiplayerbeammp")) { res.set_content(to_string(cli_res.error()), "text/plain");
d["mods"]["multiplayerbeammp"]["active"] = true; }
std::ofstream ofs(File); });
if (ofs.is_open()) { pattern += "/:any" + std::to_string(i);
ofs << d.dump(); }
ofs.close(); ProxyPort = HTTPProxy.bind_to_any_port("0.0.0.0");
} else { HTTPProxy.listen_after_bind();
error("Failed to write " + File); });
} proxy.detach();
} }
}
}
void PreGame(const std::string& GamePath) {
std::string GameVer = CheckVer(GamePath);
info("Game Version : " + GameVer);
CheckMP(GetGamePath() + "mods/multiplayer");
info("Game user path: '" + GetGamePath() + "'");
if (!Dev) {
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + 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(GetGamePath() + "mods/multiplayer")) {
fs::create_directories(GetGamePath() + "mods/multiplayer");
}
EnableMP();
} catch (std::exception& e) {
fatal(e.what());
}
#if defined(_WIN32)
std::string ZipPath(GetGamePath() + R"(mods\multiplayer\BeamMP.zip)");
#elif defined(__linux__)
// Linux version of the game cant handle mods with uppercase names
std::string ZipPath(GetGamePath() + R"(mods/multiplayer/beammp.zip)");
#endif
std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, ZipPath);
if (FileHash != LatestHash) {
info("Downloading BeamMP Update " + LatestHash);
HTTP::Download("https://backend.beammp.com/builds/client?download=true"
"&pk="
+ PublicKey + "&branch=" + Branch,
ZipPath);
}
std::string Target(GetGamePath() + "mods/unpacked/beammp");
if (fs::is_directory(Target)) {
fs::remove_all(Target);
}
}
}
void 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 StartProxy() {
std::thread proxy([&]() {
httplib::Server HTTPProxy;
httplib::Headers headers = {
{ "User-Agent", "BeamMP-Launcher/" + GetVer() + GetPatch() },
{ "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");
set_headers(res);
if (req.has_header("X-BMP-Authentication")) {
headers.emplace("X-BMP-Authentication", 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");
set_headers(res);
if (req.has_header("X-BMP-Authentication")) {
headers.emplace("X-BMP-Authentication", 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);
}
ProxyPort = HTTPProxy.bind_to_any_port("0.0.0.0");
HTTPProxy.listen_after_bind();
});
proxy.detach();
}

15
src/main.cpp Normal file → Executable file
View File

@@ -5,16 +5,16 @@
/// ///
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include "Http.h" #include "Network/network.h"
#include "Logger.h"
#include "Network/network.hpp"
#include "Security/Init.h" #include "Security/Init.h"
#include "Startup.h" #include "Startup.h"
#include <iostream> #include <iostream>
#include "Logger.h"
#include <thread> #include <thread>
#include "Http.h"
[[noreturn]] void flush() { [[noreturn]] void flush(){
while (true) { while(true){
std::cout.flush(); std::cout.flush();
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
} }
@@ -25,14 +25,13 @@ int main(int argc, char* argv[]) {
std::thread th(flush); std::thread th(flush);
th.detach(); th.detach();
#endif #endif
GetEP(argv[0]); GetEP(argv[0]);
InitLauncher(argc, argv); InitLauncher(argc, argv);
try { try {
LegitimacyCheck(); LegitimacyCheck();
} catch (std::exception& e) { } catch (std::exception &e) {
fatal("Main 1 : " + std::string(e.what())); fatal("Main 1 : " + std::string(e.what()));
} }
@@ -41,5 +40,5 @@ int main(int argc, char* argv[]) {
InitGame(GetGameDir()); InitGame(GetGameDir());
CoreNetwork(); CoreNetwork();
/// TODO: make sure to use argv[0] for everything that should be in the same dir (mod down ect...) ///TODO: make sure to use argv[0] for everything that should be in the same dir (mod down ect...)
} }

View File

@@ -1,10 +0,0 @@
{
"dependencies": [
"cpp-httplib",
"nlohmann-json",
"zlib",
"openssl",
"asio",
"fmt"
]
}