Merge pull request #96 from BeamMP/finalize-linux-merge

Finalize linux merge
This commit is contained in:
Lion 2024-06-18 09:57:24 +02:00 committed by GitHub
commit e0e2607632
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 2523 additions and 1298 deletions

5
.clang-format Normal file
View File

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

42
.github/workflows/cmake-linux.yml vendored Normal file
View File

@ -0,0 +1,42 @@
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] on: [push, pull_request, workflow_dispatch]
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: '16ee2ecb31788c336ace8bb14c21801efb6836e4' vcpkgGitCommitId: '40616a5e954f7be1077ef37db3fbddbd5dcd1ca6'
vcpkgTriplet: 'x64-windows-static' vcpkgTriplet: 'x64-windows-static'
- name: Create Build Environment - name: Create Build Environment

View File

@ -28,6 +28,7 @@ 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
@ -70,3 +71,34 @@ 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

7
.gitignore vendored
View File

@ -5,3 +5,10 @@ cmake-build-release
/*.sh /*.sh
/*.obj /*.obj
/*.exe /*.exe
.cache/
.https_debug/
Launcher.cfg
Resources/
bin/
compile_commands.json
key

View File

@ -12,7 +12,7 @@ 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") file(GLOB source_files "src/*.cpp" "src/*/*.cpp" "src/*/*.hpp" "include/*.h" "include/*/*.h" "include/*/*/*.h" "include/*.hpp" "include/*/*.hpp" "include/*/*/*.hpp")
find_package(httplib CONFIG REQUIRED) find_package(httplib CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED) find_package(nlohmann_json CONFIG REQUIRED)
@ -24,6 +24,11 @@ if (WIN32)
find_package(OpenSSL REQUIRED) find_package(OpenSSL REQUIRED)
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) ZLIB::ZLIB OpenSSL::SSL OpenSSL::Crypto ws2_32 httplib::httplib nlohmann_json::nlohmann_json)
elseif (LINUX)
find_package(ZLIB REQUIRED)
find_package(OpenSSL REQUIRED)
target_link_libraries(${PROJECT_NAME} PRIVATE
ZLIB::ZLIB OpenSSL::SSL OpenSSL::Crypto)
else(WIN32) #MINGW 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")

View File

@ -6,14 +6,15 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string>
#include "Logger.h" #include "Logger.h"
#include <string>
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;
}; };

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 <string>
#include <iostream> #include <iostream>
#include <string>
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);

View File

@ -6,9 +6,16 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string> #include <string>
#ifdef __linux__
#include "linuxfixes.h"
#include <bits/types/siginfo_t.h>
#include <cstdint>
#include <sys/ucontext.h>
#endif
void NetReset(); void NetReset();
extern bool Dev; extern bool Dev;
extern int ping; extern int ping;
@ -45,4 +52,3 @@ void TCPSend(const std::string&Data,uint64_t Sock);
void TCPClientMain(const std::string& IP, int Port); void TCPClientMain(const std::string& IP, int Port);
void UDPClientMain(const std::string& IP, int Port); void UDPClientMain(const std::string& IP, int Port);
void TCPGameServer(const std::string& IP, int Port); void TCPGameServer(const std::string& IP, int Port);

View File

@ -6,8 +6,8 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <string>
#include <compare> #include <compare>
#include <string>
#include <vector> #include <vector>
void InitLauncher(int argc, char* argv[]); void InitLauncher(int argc, char* argv[]);

19
include/linuxfixes.h Normal file
View File

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

730
include/vdf_parser.hpp Normal file
View File

@ -0,0 +1,730 @@
//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__

View File

@ -8,6 +8,9 @@
#include <iostream> #include <iostream>
#include <zlib.h> #include <zlib.h>
#ifdef __linux__
#include <cstring>
#endif
#define Biggest 30000 #define Biggest 30000
std::string Comp(std::string Data) { std::string Comp(std::string Data) {
@ -27,7 +30,7 @@ std::string Comp(std::string Data){
deflateEnd(&defstream); deflateEnd(&defstream);
int TO = defstream.total_out; int TO = defstream.total_out;
std::string Ret(TO, 0); std::string Ret(TO, 0);
memcpy_s(&Ret[0],TO,C,TO); memcpy(&Ret[0], C, TO);
delete[] C; delete[] C;
return Ret; return Ret;
} }
@ -48,7 +51,7 @@ std::string DeComp(std::string Compressed){
inflateEnd(&infstream); inflateEnd(&infstream);
int TO = infstream.total_out; int TO = infstream.total_out;
std::string Ret(TO, 0); std::string Ret(TO, 0);
memcpy_s(&Ret[0],TO,C,TO); memcpy(&Ret[0], C, TO);
delete[] C; delete[] C;
return Ret; return Ret;
} }

View File

@ -2,12 +2,12 @@
/// Created by Anonymous275 on 2/23/2021 /// Created by Anonymous275 on 2/23/2021
/// ///
#include <nlohmann/json.hpp>
#include "Network/network.h"
#include <filesystem>
#include "Logger.h" #include "Logger.h"
#include <fstream> #include "Network/network.hpp"
#include <cstdint> #include <cstdint>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string Branch; std::string Branch;
@ -23,7 +23,8 @@ void ParseConfig(const nlohmann::json& d){
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)c = char(tolower(c)); for (char& c : Branch)
c = char(tolower(c));
} }
} }
@ -40,7 +41,8 @@ void ConfigInit(){
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
fatal("Failed to open Launcher.cfg!");
} else { } else {
std::ofstream cfg("Launcher.cfg"); std::ofstream cfg("Launcher.cfg");
if (cfg.is_open()) { if (cfg.is_open()) {
@ -55,4 +57,3 @@ void ConfigInit(){
} }
} }
} }

View File

@ -6,17 +6,30 @@
/// Created by Anonymous275 on 7/19/2020 /// Created by Anonymous275 on 7/19/2020
/// ///
#include <Security/Init.h> #if defined(_WIN32)
#include <windows.h> #include <windows.h>
#include "Startup.h" #elif defined(__linux__)
#include "vdf_parser.hpp"
#include <pwd.h>
#include <spawn.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#include "Logger.h" #include "Logger.h"
#include "Startup.h"
#include <Security/Init.h>
#include <filesystem>
#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())return Path; if (!Path.empty())
return Path;
HKEY hKey; HKEY hKey;
LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive"; LPCTSTR sk = "Software\\BeamNG\\BeamNG.drive";
@ -40,7 +53,21 @@ std::string GetGamePath(){
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/";
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) { void StartGame(std::string Dir) {
BOOL bSuccess = FALSE; BOOL bSuccess = FALSE;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
@ -61,6 +88,26 @@ void StartGame(std::string Dir){
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) {
int status;
std::string filename = (Dir + "/BinLinux/BeamNG.drive.x64");
char* argv[] = { filename.data(), NULL };
pid_t pid;
int result = posix_spawn(&pid, filename.c_str(), NULL, 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");
}
std::this_thread::sleep_for(std::chrono::seconds(5));
exit(2);
}
#endif
void InitGame(const std::string& Dir) { void InitGame(const std::string& Dir) {
if (!Dev) { if (!Dev) {

View File

@ -6,11 +6,11 @@
/// Created by Anonymous275 on 7/17/2020 /// Created by Anonymous275 on 7/17/2020
/// ///
#include "Startup.h"
#include "Logger.h" #include "Logger.h"
#include "Startup.h"
#include <chrono>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <chrono>
#include <thread> #include <thread>
std::string getDate() { std::string getDate() {
@ -39,7 +39,8 @@ void InitLog(){
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 LFS.close(); } else
LFS.close();
} }
void addToLog(const std::string& Line) { void addToLog(const std::string& Line) {
std::ofstream LFS; std::ofstream LFS;
@ -53,7 +54,8 @@ void info(const std::string& toPrint) {
addToLog(Print); addToLog(Print);
} }
void debug(const std::string& toPrint) { void debug(const std::string& toPrint) {
if(!Dev)return; if (!Dev)
return;
std::string Print = getDate() + "[DEBUG] " + toPrint + "\n"; std::string Print = getDate() + "[DEBUG] " + toPrint + "\n";
std::cout << Print; std::cout << Print;
addToLog(Print); addToLog(Print);

View File

@ -5,19 +5,31 @@
/// ///
/// Created by Anonymous275 on 7/20/2020 /// Created by Anonymous275 on 7/20/2020
/// ///
#include "Network/network.h"
#include "Security/Init.h"
#include <regex>
#include "Http.h" #include "Http.h"
#include "Network/network.hpp"
#include "Security/Init.h"
#include <cstdlib>
#include <regex>
#if defined(_WIN32)
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#include "Startup.h" #elif defined(__linux__)
#include <cstring>
#include <errno.h>
#include <netdb.h>
#include <spawn.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#include "Logger.h" #include "Logger.h"
#include <nlohmann/json.hpp> #include "Startup.h"
#include <charconv> #include <charconv>
#include <thread> #include <nlohmann/json.hpp>
#include <set> #include <set>
#include <thread>
extern int TraceBack; extern int TraceBack;
std::set<std::string>* ConfList = nullptr; std::set<std::string>* ConfList = nullptr;
@ -35,8 +47,10 @@ int ping = -1;
void StartSync(const std::string& Data) { void StartSync(const std::string& Data) {
std::string IP = GetAddr(Data.substr(1, Data.find(':') - 1)); std::string IP = GetAddr(Data.substr(1, Data.find(':') - 1));
if (IP.find('.') == -1) { if (IP.find('.') == -1) {
if(IP == "DNS")UlStatus ="UlConnection Failed! (DNS Lookup Failed)"; if (IP == "DNS")
else UlStatus = "UlConnection Failed! (WSA failed to start)"; UlStatus = "UlConnection Failed! (DNS Lookup Failed)";
else
UlStatus = "UlConnection Failed! (WSA failed to start)";
ListOfMods = "-"; ListOfMods = "-";
Terminate = true; Terminate = true;
return; return;
@ -60,7 +74,8 @@ bool IsAllowedLink(const std::string& Link) {
void Parse(std::string Data, SOCKET CSocket) { void Parse(std::string Data, SOCKET CSocket) {
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 'A': case 'A':
Data = Data.substr(0, 1); Data = Data.substr(0, 1);
@ -77,12 +92,34 @@ void Parse(std::string Data,SOCKET CSocket){
while (ListOfMods.empty() && !Terminate) { while (ListOfMods.empty() && !Terminate) {
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
if(ListOfMods == "-")Data = "L"; if (ListOfMods == "-")
else Data = "L"+ListOfMods; Data = "L";
else
Data = "L" + ListOfMods;
break; break;
case 'O': // open default browser with URL case 'O': // open default browser with URL
if (IsAllowedLink(Data.substr(1))) { if (IsAllowedLink(Data.substr(1))) {
#if defined(__linux)
if (char* browser = getenv("BROWSER"); browser != nullptr && !std::string_view(browser).empty()) {
pid_t pid;
auto arg = Data.substr(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: " + Data.substr(1));
}
#elif defined(WIN32)
ShellExecuteA(nullptr, "open", Data.substr(1).c_str(), nullptr, nullptr, SW_SHOW); /// TODO: Look at when working on linux port ShellExecuteA(nullptr, "open", Data.substr(1).c_str(), nullptr, nullptr, SW_SHOW); /// TODO: Look at when working on linux port
#endif
info("Opening Link \"" + Data.substr(1) + "\""); info("Opening Link \"" + Data.substr(1) + "\"");
} }
Data.clear(); Data.clear();
@ -91,16 +128,20 @@ void Parse(std::string Data,SOCKET CSocket){
Data = Code + std::to_string(ProxyPort); Data = Code + std::to_string(ProxyPort);
break; break;
case 'U': case 'U':
if(SubCode == 'l')Data = UlStatus; if (SubCode == 'l')
Data = UlStatus;
if (SubCode == 'p') { if (SubCode == 'p') {
if (ping > 800) { if (ping > 800) {
Data = "Up-2"; Data = "Up-2";
}else Data = "Up" + std::to_string(ping); } else
Data = "Up" + std::to_string(ping);
} }
if (!SubCode) { if (!SubCode) {
std::string Ping; std::string Ping;
if(ping > 800)Ping = "-2"; if (ping > 800)
else Ping = std::to_string(ping); Ping = "-2";
else
Ping = std::to_string(ping);
Data = std::string(UlStatus) + "\n" + "Up" + Ping; Data = std::string(UlStatus) + "\n" + "Up" + Ping;
} }
break; break;
@ -114,7 +155,8 @@ void Parse(std::string Data,SOCKET CSocket){
TCPTerminate = true; TCPTerminate = true;
ping = -1; ping = -1;
} }
if(SubCode == 'G')exit(2); if (SubCode == 'G')
exit(2);
Data.clear(); Data.clear();
break; break;
case 'R': // will send mod name case 'R': // will send mod name
@ -138,7 +180,7 @@ void Parse(std::string Data,SOCKET CSocket){
if (!UserRole.empty()) { if (!UserRole.empty()) {
Auth["role"] = UserRole; Auth["role"] = UserRole;
} }
Data = Auth.dump(); Data = "N" + Auth.dump();
} else { } else {
Data = "N" + Login(Data.substr(Data.find(':') + 1)); Data = "N" + Login(Data.substr(Data.find(':') + 1));
} }
@ -162,14 +204,16 @@ void GameHandler(SOCKET Client){
Rcv = 0; Rcv = 0;
do { do {
Temp = recv(Client, &Header[Rcv], 1, 0); Temp = recv(Client, &Header[Rcv], 1, 0);
if(Temp < 1)break; if (Temp < 1)
break;
if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') { if (!isdigit(Header[Rcv]) && Header[Rcv] != '>') {
error("(Core) Invalid lua communication"); error("(Core) Invalid lua communication");
KillSocket(Client); KillSocket(Client);
return; return;
} }
} while (Header[Rcv++] != '>'); } while (Header[Rcv++] != '>');
if(Temp < 1)break; if (Temp < 1)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') { if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
debug("(Core) Invalid lua Header -> " + std::string(Header, Rcv)); debug("(Core) Invalid lua Header -> " + std::string(Header, Rcv));
break; break;
@ -179,10 +223,12 @@ void GameHandler(SOCKET Client){
do { do {
Temp = recv(Client, &Ret[Rcv], Size - Rcv, 0); Temp = recv(Client, &Ret[Rcv], Size - Rcv, 0);
if(Temp < 1)break; if (Temp < 1)
break;
Rcv += Temp; Rcv += Temp;
} while (Rcv < Size); } while (Rcv < Size);
if(Temp < 1)break; if (Temp < 1)
break;
std::thread Respond(Parse, Ret, Client); std::thread Respond(Parse, Ret, Client);
Respond.detach(); Respond.detach();
@ -207,13 +253,19 @@ void localRes(){
} }
void CoreMain() { void CoreMain() {
debug("Core Network on start!"); debug("Core Network on start!");
WSADATA wsaData;
SOCKET LSocket, CSocket; SOCKET LSocket, CSocket;
struct addrinfo* res = nullptr; struct addrinfo* res = nullptr;
struct addrinfo hints { }; struct addrinfo hints { };
int iRes = WSAStartup(514, &wsaData); //2.2 int iRes;
if (iRes)debug("WSAStartup failed with error: " + std::to_string(iRes)); #ifdef _WIN32
WSADATA wsaData;
iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes)
debug("WSAStartup failed with error: " + std::to_string(iRes));
#endif
ZeroMemory(&hints, sizeof(hints)); ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP; hints.ai_protocol = IPPROTO_TCP;
@ -261,6 +313,8 @@ void CoreMain() {
KillSocket(LSocket); KillSocket(LSocket);
WSACleanup(); WSACleanup();
} }
#if defined(_WIN32)
int Handle(EXCEPTION_POINTERS* ep) { 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);
@ -268,17 +322,25 @@ int Handle(EXCEPTION_POINTERS *ep){
delete[] hex; delete[] hex;
return 1; return 1;
} }
#endif
[[noreturn]] void CoreNetwork() { [[noreturn]] void CoreNetwork() {
while (true) { while (true) {
#ifndef __MINGW32__ #if not defined(__MINGW32__)
__try { __try {
#endif #endif
CoreMain(); CoreMain();
#ifndef __MINGW32__
#if not defined(__MINGW32__) and not defined(__linux__)
} __except (Handle(GetExceptionInformation())) { } } __except (Handle(GetExceptionInformation())) { }
#elif not defined(__MINGW32__) and defined(__linux__)
}
catch (...) {
except("(Core) Code : " + std::string(strerror(errno)));
}
#endif #endif
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
} }
} }

View File

@ -7,18 +7,30 @@
/// ///
#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)return IP; if (IP.find_first_not_of("0123456789.") == -1)
WSADATA wsaData; return IP;
hostent* host; hostent* host;
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(514, &wsaData) != 0) { 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);

View File

@ -5,14 +5,25 @@
/// ///
/// Created by Anonymous275 on 7/25/2020 /// Created by Anonymous275 on 7/25/2020
/// ///
#include "Network/network.h" #include "Network/network.hpp"
#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 <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;
@ -47,7 +58,8 @@ bool CheckBytes(uint32_t Bytes){
void GameSend(std::string Data) { 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 == -1)return; if (TCPTerminate || !GConnected || CSocket == -1)
return;
int32_t Size, Temp, Sent; int32_t Size, Temp, Sent;
Data += '\n'; Data += '\n';
Size = int32_t(Data.size()); Size = int32_t(Data.size());
@ -61,25 +73,33 @@ void GameSend(std::string Data){
if (Sent > -1) { if (Sent > -1) {
Temp = send(CSocket, &Data[Sent], Size - Sent, 0); Temp = send(CSocket, &Data[Sent], Size - Sent, 0);
} }
if(!CheckBytes(Temp))return; if (!CheckBytes(Temp))
return;
Sent += Temp; Sent += Temp;
} while (Sent < Size); } while (Sent < Size);
} }
void ServerSend(std::string Data, bool Rel) { void ServerSend(std::string Data, bool Rel) {
if(Terminate || Data.empty())return; if (Terminate || Data.empty())
return;
if (Data.find("Zp") != std::string::npos && Data.size() > 500) { if (Data.find("Zp") != std::string::npos && Data.size() > 500) {
abort(); abort();
} }
char C = 0; char C = 0;
bool Ack = false; bool Ack = false;
int DLen = int(Data.length()); int DLen = int(Data.length());
if(DLen > 3)C = Data.at(0); if (DLen > 3)
if (C == 'O' || C == 'T')Ack = true; C = Data.at(0);
if(C == 'N' || C == 'W' || C == 'Y' || C == 'V' || C == 'E' || C == 'C')Rel = true; 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 || Rel) {
if(Ack || DLen > 1000)SendLarge(Data); if (Ack || DLen > 1000)
else TCPSend(Data,TCPSock); SendLarge(Data);
}else UDPSend(Data); else
TCPSend(Data, TCPSock);
} else
UDPSend(Data);
if (DLen > 1000) { if (DLen > 1000) {
debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : " debug("(Launcher->Server) Bytes sent: " + std::to_string(Data.length()) + " : "
@ -114,15 +134,20 @@ void NetReset(){
} }
SOCKET SetupListener() { SOCKET SetupListener() {
if(GSocket != -1)return GSocket; if (GSocket != -1)
return GSocket;
struct addrinfo* result = nullptr; struct addrinfo* result = nullptr;
struct addrinfo hints { }; struct addrinfo hints { };
int iRes;
#ifdef _WIN32
WSADATA wsaData; WSADATA wsaData;
int iRes = WSAStartup(514, &wsaData); //2.2 iRes = WSAStartup(514, &wsaData); // 2.2
if (iRes != 0) { if (iRes != 0) {
error("(Proxy) WSAStartup failed with error: " + std::to_string(iRes)); error("(Proxy) WSAStartup failed with error: " + std::to_string(iRes));
return -1; return -1;
} }
#endif
ZeroMemory(&hints, sizeof(hints)); ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
@ -167,14 +192,18 @@ void AutoPing(){
} }
int ClientID = -1; int ClientID = -1;
void ParserAsync(const std::string& Data) { void ParserAsync(const std::string& Data) {
if(Data.empty())return; if (Data.empty())
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)ping = 0; if (PingStart > PingEnd)
else ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd-PingStart).count()); ping = 0;
else
ping = int(std::chrono::duration_cast<std::chrono::milliseconds>(PingEnd - PingStart).count());
return; return;
case 'M': case 'M':
MStatus = Data; MStatus = Data;
@ -233,9 +262,11 @@ void TCPGameServer(const std::string& IP, int Port){
do { do {
Temp = recv(CSocket, &Header[Rcv], 1, 0); Temp = recv(CSocket, &Header[Rcv], 1, 0);
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
} while (Header[Rcv++] != '>'); } while (Header[Rcv++] != '>');
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') { if (std::from_chars(Header, &Header[Rcv], Size).ptr[0] != '>') {
debug("(Game) Invalid lua Header -> " + std::string(Header, Rcv)); debug("(Game) Invalid lua Header -> " + std::string(Header, Rcv));
break; break;
@ -244,20 +275,25 @@ void TCPGameServer(const std::string& IP, int Port){
Rcv = 0; Rcv = 0;
do { do {
Temp = recv(CSocket, &Ret[Rcv], Size - Rcv, 0); Temp = recv(CSocket, &Ret[Rcv], Size - Rcv, 0);
if(Temp < 1)break; if (Temp < 1)
break;
Rcv += Temp; Rcv += Temp;
} while (Rcv < Size && !TCPTerminate); } while (Rcv < Size && !TCPTerminate);
if(Temp < 1 || TCPTerminate)break; if (Temp < 1 || TCPTerminate)
break;
ServerSend(Ret, false); ServerSend(Ret, false);
} while (Temp > 0 && !TCPTerminate); } while (Temp > 0 && !TCPTerminate);
if(Temp == 0)debug("(Proxy) Connection closing"); if (Temp == 0)
else debug("(Proxy) recv failed error : " + std::to_string(WSAGetLastError())); 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 != SOCKET_ERROR)KillSocket(CSocket); if (CSocket != SOCKET_ERROR)
KillSocket(CSocket);
debug("END OF GAME SERVER"); debug("END OF GAME SERVER");
} }

View File

@ -7,14 +7,14 @@
/// ///
#define CPPHTTPLIB_OPENSSL_SUPPORT #define CPPHTTPLIB_OPENSSL_SUPPORT
#include <iostream>
#include <Logger.h>
#include <fstream>
#include "Http.h" #include "Http.h"
#include <mutex> #include <Logger.h>
#include <cmath> #include <cmath>
#include <filesystem> #include <filesystem>
#include <fstream>
#include <httplib.h> #include <httplib.h>
#include <iostream>
#include <mutex>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try { void WriteHttpDebug(const httplib::Client& client, const std::string& method, const std::string& target, const httplib::Result& result) try {
@ -40,8 +40,7 @@ void WriteHttpDebug(const httplib::Client& client, const std::string& method, co
{ "port", client.port() }, { "port", client.port() },
{ "socket_open", client.is_socket_open() }, { "socket_open", client.is_socket_open() },
{ "valid", client.is_valid() }, { "valid", client.is_valid() },
} } },
},
}; };
if (result) { if (result) {
auto value = result.value(); auto value = result.value();
@ -54,8 +53,7 @@ void WriteHttpDebug(const httplib::Client& client, const std::string& method, co
js["result"]["reason"] = value.reason; js["result"]["reason"] = value.reason;
} }
of << js.dump(); of << js.dump();
} } catch (const std::exception& e) {
catch (const std::exception& e) {
error(e.what()); error(e.what());
} }
@ -75,20 +73,16 @@ std::string HTTP::Get(const std::string& IP) {
if (res) { if (res) {
if (res->status == 200) { if (res->status == 200) {
Ret = res->body; Ret = res->body;
} } else {
else {
WriteHttpDebug(cli, "GET", IP, res); WriteHttpDebug(cli, "GET", IP, res);
error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("Failed to GET '" + IP + "': " + res->reason + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} } else {
else {
if (isDownload) { if (isDownload) {
std::cout << "\n"; std::cout << "\n";
} }
WriteHttpDebug(cli, "GET", IP, res); WriteHttpDebug(cli, "GET", IP, res);
error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("HTTP Get failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
return Ret; return Ret;
@ -112,30 +106,27 @@ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
error(res->reason); error(res->reason);
} }
Ret = res->body; Ret = res->body;
} } else {
else {
WriteHttpDebug(cli, "POST", IP, res); WriteHttpDebug(cli, "POST", IP, res);
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); 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); WriteHttpDebug(cli, "POST", IP, res);
error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result())); error("HTTP Post failed on " + to_string(res.error()) + ", ssl verify = " + std::to_string(cli.get_openssl_verify_result()));
} }
} }
if (Ret.empty())return "-1"; if (Ret.empty())
else return Ret; return "-1";
else
return Ret;
} }
bool HTTP::ProgressBar(size_t c, size_t t) { bool HTTP::ProgressBar(size_t c, size_t t) {
@ -147,8 +138,10 @@ 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++)std::cout << "#"; for (i = 0; i <= progress_bar_adv; i++)
for (i = 0; i < 25 - progress_bar_adv; i++)std::cout << "."; 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);
} }
@ -163,7 +156,8 @@ 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())return false; if (Ret.empty())
return false;
std::ofstream File(Path, std::ios::binary); std::ofstream File(Path, std::ios::binary);
if (File.is_open()) { if (File.is_open()) {
@ -171,8 +165,7 @@ bool HTTP::Download(const std::string& IP, const std::string& Path) {
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;
} }

View File

@ -6,20 +6,31 @@
/// Created by Anonymous275 on 4/11/2020 /// Created by Anonymous275 on 4/11/2020
/// ///
#include "Network/network.h" #include "Network/network.hpp"
#if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#include <filesystem> #elif defined(__linux__)
#include "Startup.h" #include <arpa/inet.h>
#include "Logger.h"
#include <iostream>
#include <cstring> #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 <fstream> #include <fstream>
#include <future>
#include <iostream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <atomic>
#include <vector> #include <vector>
#include <future>
#include <cmath>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string ListOfMods; std::string ListOfMods;
@ -29,16 +40,23 @@ std::vector<std::string> Split(const std::string& String,const std::string& deli
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())Val.push_back(token); if (!token.empty())
Val.push_back(token);
s.erase(0, pos + delimiter.length()); s.erase(0, pos + delimiter.length());
} }
if(!s.empty())Val.push_back(s); if (!s.empty())
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() {
@ -48,7 +66,6 @@ void WaitForConfirm(){
ModLoaded = false; ModLoaded = false;
} }
void Abord() { void Abord() {
Terminate = true; Terminate = true;
TCPTerminate = true; TCPTerminate = true;
@ -66,7 +83,8 @@ std::string Auth(SOCKET Sock){
} }
TCPSend(PublicKey, Sock); TCPSend(PublicKey, Sock);
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
if (Res.empty() || Res[0] != 'P') { if (Res.empty() || Res[0] != 'P') {
@ -83,7 +101,8 @@ std::string Auth(SOCKET Sock){
return ""; return "";
} }
TCPSend("SR", Sock); TCPSend("SR", Sock);
if(Terminate)return ""; if (Terminate)
return "";
Res = TCPRcv(Sock); Res = TCPRcv(Sock);
@ -103,8 +122,10 @@ std::string Auth(SOCKET Sock){
} }
void UpdateUl(bool D, const std::string& msg) { void UpdateUl(bool D, const std::string& msg) {
if(D)UlStatus = "UlDownloading Resource " + msg; if (D)
else UlStatus = "UlLoading Resource " + msg; UlStatus = "UlDownloading 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) {
@ -126,7 +147,8 @@ char* TCPRcvRaw(SOCKET Sock,uint64_t& GRcv, uint64_t Size){
uint64_t Rcv = 0; uint64_t Rcv = 0;
do { do {
int Len = int(Size - Rcv); int Len = int(Size - Rcv);
if(Len > 1000000)Len = 1000000; if (Len > 1000000)
Len = 1000000;
int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL); int32_t Temp = recv(Sock, &File[Rcv], Len, MSG_WAITALL);
if (Temp < 1) { if (Temp < 1) {
info(std::to_string(Temp)); info(std::to_string(Temp));
@ -197,15 +219,15 @@ std::string MultiDownload(SOCKET MSock,SOCKET DSock, uint64_t Size, const std::s
return ""; return "";
} }
if(Au.joinable())Au.join(); if (Au.joinable())
Au.join();
/// omg yes very ugly my god but i was in a rush will revisit /// omg yes very ugly my god but i was in a rush will revisit
std::string Ret(Size, 0); std::string Ret(Size, 0);
memcpy_s(&Ret[0],MSize,MData,MSize); memcpy(&Ret[0], MData, MSize);
delete[] MData; delete[] MData;
memcpy_s(&Ret[MSize],DSize,DData,DSize); memcpy(&Ret[MSize], DData, DSize);
delete[] DData; delete[] DData;
return Ret; return Ret;
@ -219,7 +241,8 @@ void InvalidResource(const std::string& File){
void SyncResources(SOCKET Sock) { void SyncResources(SOCKET Sock) {
std::string Ret = Auth(Sock); std::string Ret = Auth(Sock);
if(Ret.empty())return; if (Ret.empty())
return;
info("Checking Resources..."); info("Checking Resources...");
CheckForDir(); CheckForDir();
@ -237,8 +260,10 @@ void SyncResources(SOCKET Sock){
t += name.substr(name.find_last_of('/') + 1) + ";"; t += name.substr(name.find_last_of('/') + 1) + ";";
} }
} }
if(t.empty())ListOfMods = "-"; if (t.empty())
else ListOfMods = t; ListOfMods = "-";
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('/');
@ -247,19 +272,23 @@ void SyncResources(SOCKET Sock){
InvalidResource(*FN); InvalidResource(*FN);
return; return;
} }
if (pos == std::string::npos)continue; if (pos == std::string::npos)
continue;
Amount++; Amount++;
} }
if(!FNames.empty())info("Syncing..."); if (!FNames.empty())
info("Syncing...");
SOCKET DSock = InitDSock(); SOCKET DSock = InitDSock();
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 continue; } else
continue;
Pos++; Pos++;
if (fs::exists(a)) { if (fs::exists(a)) {
if (FS->find_first_not_of("0123456789") != std::string::npos)continue; if (FS->find_first_not_of("0123456789") != std::string::npos)
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));
@ -268,6 +297,12 @@ void SyncResources(SOCKET Sock){
fs::create_directories(GetGamePath() + "mods/multiplayer"); fs::create_directories(GetGamePath() + "mods/multiplayer");
} }
auto name = GetGamePath() + "mods/multiplayer" + 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 : name) {
c = ::tolower(c);
}
#endif
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);
@ -278,7 +313,8 @@ void SyncResources(SOCKET Sock){
} }
WaitForConfirm(); WaitForConfirm();
continue; continue;
}else remove(a.c_str()); } else
remove(a.c_str());
} }
CheckForDir(); CheckForDir();
std::string FName = a.substr(a.find_last_of('/')); std::string FName = a.substr(a.find_last_of('/'));
@ -296,7 +332,8 @@ void SyncResources(SOCKET Sock){
Data = MultiDownload(Sock, DSock, std::stoull(*FS), Name); Data = MultiDownload(Sock, DSock, std::stoull(*FS), Name);
if(Terminate)break; if (Terminate)
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);
@ -310,6 +347,14 @@ void SyncResources(SOCKET Sock){
if (!fs::exists(GetGamePath() + "mods/multiplayer")) { if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
fs::create_directories(GetGamePath() + "mods/multiplayer"); fs::create_directories(GetGamePath() + "mods/multiplayer");
} }
// 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); fs::copy_file(a, GetGamePath() + "mods/multiplayer" + FName, fs::copy_options::overwrite_existing);
} }
WaitForConfirm(); WaitForConfirm();

View File

@ -5,29 +5,41 @@
/// ///
/// 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 "Network/network.h"
#if defined(_WIN32)
#include <ws2tcpip.h> #include <ws2tcpip.h>
#elif defined(__linux__)
#include "linuxfixes.h"
#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 "Logger.h"
#include <string>
#include <set> #include <set>
#include <string>
SOCKET UDPSock = -1; SOCKET UDPSock = -1;
sockaddr_in* ToServer = nullptr; sockaddr_in* ToServer = nullptr;
void UDPSend(std::string Data) { void UDPSend(std::string Data) {
if(ClientID == -1 || UDPSock == -1)return; if (ClientID == -1 || UDPSock == -1)
return;
if (Data.length() > 400) { if (Data.length() > 400) {
std::string CMP(Comp(Data)); std::string CMP(Comp(Data));
Data = "ABG:" + CMP; Data = "ABG:" + CMP;
} }
std::string Packet = char(ClientID + 1) + std::string(":") + Data; std::string Packet = char(ClientID + 1) + std::string(":") + Data;
int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer)); int sendOk = sendto(UDPSock, Packet.c_str(), int(Packet.size()), 0, (sockaddr*)ToServer, sizeof(*ToServer));
if (sendOk == SOCKET_ERROR)error("Error Code : " + std::to_string(WSAGetLastError())); if (sendOk == SOCKET_ERROR)
error("Error Code : " + std::to_string(WSAGetLastError()));
} }
void SendLarge(std::string Data) { void SendLarge(std::string Data) {
if (Data.length() > 400) { if (Data.length() > 400) {
std::string CMP(Comp(Data)); std::string CMP(Comp(Data));
@ -44,20 +56,29 @@ void UDPParser(std::string Packet){
} }
void UDPRcv() { void UDPRcv() {
sockaddr_in FromServer {}; sockaddr_in FromServer {};
#if defined(_WIN32)
int clientLength = sizeof(FromServer); int clientLength = sizeof(FromServer);
#elif defined(__linux__)
socklen_t clientLength = sizeof(FromServer);
#endif
ZeroMemory(&FromServer, clientLength); ZeroMemory(&FromServer, clientLength);
std::string Ret(10240, 0); std::string Ret(10240, 0);
if(UDPSock == -1)return; if (UDPSock == -1)
return;
int32_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength); int32_t Rcv = recvfrom(UDPSock, &Ret[0], 10240, 0, (sockaddr*)&FromServer, &clientLength);
if (Rcv == SOCKET_ERROR)return; if (Rcv == SOCKET_ERROR)
return;
UDPParser(Ret.substr(0, Rcv)); UDPParser(Ret.substr(0, Rcv));
} }
void UDPClientMain(const std::string& IP, int Port) { void UDPClientMain(const std::string& IP, int Port) {
#ifdef _WIN32
WSADATA data; WSADATA data;
if (WSAStartup(514, &data)) { if (WSAStartup(514, &data)) {
error("Can't start Winsock!"); error("Can't start Winsock!");
return; return;
} }
#endif
delete ToServer; delete ToServer;
ToServer = new sockaddr_in; ToServer = new sockaddr_in;
ToServer->sin_family = AF_INET; ToServer->sin_family = AF_INET;
@ -67,7 +88,8 @@ void UDPClientMain(const std::string& IP,int Port){
GameSend("P" + std::to_string(ClientID)); GameSend("P" + std::to_string(ClientID));
TCPSend("H", TCPSock); TCPSend("H", TCPSock);
UDPSend("p"); UDPSend("p");
while(!Terminate)UDPRcv(); while (!Terminate)
UDPRcv();
KillSocket(UDPSock); KillSocket(UDPSock);
WSACleanup(); WSACleanup();
} }

View File

@ -6,15 +6,24 @@
/// Created by Anonymous275 on 5/8/2020 /// Created by Anonymous275 on 5/8/2020
/// ///
#include <chrono>
#include <vector>
#include "Logger.h" #include "Logger.h"
#include <iostream>
#include <ws2tcpip.h>
#include <Zlib/Compressor.h> #include <Zlib/Compressor.h>
#include <chrono>
#include <iostream>
#include <vector>
#include "Network/network.h" #if defined(_WIN32)
#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 "Network/network.hpp"
int LastPort; int LastPort;
std::string LastIP; std::string LastIP;
@ -109,17 +118,20 @@ std::string TCPRcv(SOCKET Sock){
#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')UUl(Ret.substr(1)); if (Ret[0] == 'E' || Ret[0] == 'K')
UUl(Ret.substr(1));
return Ret; return Ret;
} }
void TCPClientMain(const std::string& IP, int Port) { void TCPClientMain(const std::string& IP, int Port) {
LastIP = IP; LastIP = IP;
LastPort = Port; LastPort = Port;
WSADATA wsaData;
SOCKADDR_IN ServerAddr; SOCKADDR_IN ServerAddr;
int RetCode; int RetCode;
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(514, &wsaData); // 2.2 WSAStartup(514, &wsaData); // 2.2
#endif
TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); TCPSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPSock == -1) { if (TCPSock == -1) {
@ -127,6 +139,7 @@ void TCPClientMain(const std::string& IP,int Port){
WSACleanup(); WSACleanup();
return; return;
} }
ServerAddr.sin_family = AF_INET; ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port); ServerAddr.sin_port = htons(Port);
inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr); inet_pton(AF_INET, IP.c_str(), &ServerAddr.sin_addr);
@ -152,6 +165,8 @@ void TCPClientMain(const std::string& IP,int Port){
if (KillSocket(TCPSock) != 0) if (KillSocket(TCPSock) != 0)
debug("(TCP) Cannot close socket. Error code: " + std::to_string(WSAGetLastError())); debug("(TCP) Cannot close socket. Error code: " + std::to_string(WSAGetLastError()));
#ifdef _WIN32
if (WSACleanup() != 0) if (WSACleanup() != 0)
debug("(TCP) Client: WSACleanup() failed!..."); debug("(TCP) Client: WSACleanup() failed!...");
#endif
} }

View File

@ -7,7 +7,14 @@
/// ///
#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>
@ -22,8 +29,7 @@ std::string GameDir;
void lowExit(int code) { void lowExit(int code) {
TraceBack = 0; TraceBack = 0;
std::string msg = std::string msg = "Failed to find the game please launch it. Report this if the issue persists code ";
"Failed to find the game please launch it. Report this if the issue persists code ";
error(msg + std::to_string(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);
@ -46,8 +52,13 @@ void SteamExit(int code){
}*/ }*/
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);
} }
@ -110,18 +121,30 @@ std::string QueryKey(HKEY hKey,int ID){
std::string key = achValue; std::string key = achValue;
switch (ID) { switch (ID) {
case 1: if(key == "SteamExe"){ case 1:
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;
} }
} }
} }
@ -129,6 +152,8 @@ std::string QueryKey(HKEY hKey,int ID){
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) {
@ -166,8 +191,10 @@ 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)c = char(tolower(c)); for (char& c : Name)
if(Name == "steam.exe")s = false; c = char(tolower(c));
if (Name == "steam.exe")
s = false;
if (Name.find("greenluma") != -1) { if (Name.find("greenluma") != -1) {
error("Found malicious file/folder \"" + Name + "\""); error("Found malicious file/folder \"" + Name + "\"");
return true; return true;
@ -189,10 +216,12 @@ 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)S = true; if (!S)
S = true;
else { else {
for (char& c : t) { for (char& c : t) {
if(isdigit(c))r += c; if (isdigit(c))
r += c;
} }
break; break;
} }
@ -208,7 +237,8 @@ std::vector<std::string> GetID(const std::string& log){
} }
for (char& c : t) { for (char& c : t) {
if (c == '"') { if (c == '"') {
if(!S)S = true; if (!S)
S = true;
else { else {
if (r.length() > 10) { if (r.length() > 10) {
Ret.emplace_back(r); Ret.emplace_back(r);
@ -218,7 +248,8 @@ std::vector<std::string> GetID(const std::string& log){
continue; continue;
} }
} }
if(isdigit(c))r += c; if (isdigit(c))
r += c;
} }
} }
vec.clear(); vec.clear();
@ -239,7 +270,8 @@ std::string GetManifest(const std::string& Man){
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 return ""; } else
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;
@ -249,10 +281,12 @@ bool IDCheck(std::string Man, std::string steam){
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))b = false; if (ID == GetManifest(Man))
b = false;
} }
// if(b)Exit(6); // if(b)Exit(6);
}else a = true; } else
a = true;
return a; return a;
} }
void LegitimacyCheck() { void LegitimacyCheck() {
@ -286,24 +320,45 @@ void LegitimacyCheck(){
}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())lowExit(3); if (Result.empty())
lowExit(3);
// if(IDCheck(Result,T))lowExit(5); // if(IDCheck(Result,T))lowExit(5);
GameDir = Result; GameDir = Result;
// TraceBack++; // TraceBack++;
}else lowExit(4); } else
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);
@ -312,7 +367,8 @@ std::string CheckVer(const std::string &dir){
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 == '.')temp+=a; if (isdigit(a) || a == '.')
temp += a;
} }
return temp; return temp;
} }

View File

@ -6,12 +6,11 @@
/// Created by Anonymous275 on 11/26/2020 /// Created by Anonymous275 on 11/26/2020
/// ///
#include <nlohmann/json.hpp>
#include "Http.h" #include "Http.h"
#include <filesystem>
#include "Logger.h" #include "Logger.h"
#include <filesystem>
#include <fstream> #include <fstream>
#include <nlohmann/json.hpp>
namespace fs = std::filesystem; namespace fs = std::filesystem;
std::string PublicKey; std::string PublicKey;
@ -27,7 +26,8 @@ void UpdateKey(const char* newKey){
if (Key.is_open()) { if (Key.is_open()) {
Key << newKey; Key << newKey;
Key.close(); Key.close();
}else 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");
} }
@ -81,7 +81,8 @@ std::string Login(const std::string& fields){
PublicKey = d["public_key"].get<std::string>(); PublicKey = d["public_key"].get<std::string>();
} }
info("Authentication successful!"); info("Authentication successful!");
}else info("Authentication failed!"); } else
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");
@ -137,5 +138,6 @@ void CheckLocalKey(){
warn("Could not open saved key!"); warn("Could not open saved key!");
UpdateKey(nullptr); UpdateKey(nullptr);
} }
}else UpdateKey(nullptr); } else
UpdateKey(nullptr);
} }

View File

@ -6,20 +6,24 @@
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include <nlohmann/json.hpp>
#include <httplib.h>
#include "zip_file.h" #include "zip_file.h"
#include <httplib.h>
#include <nlohmann/json.hpp>
#include <string>
#if defined(_WIN32)
#include <windows.h> #include <windows.h>
#include "Network/network.h" #elif defined(__linux__)
#include <unistd.h>
#endif
#include "Http.h"
#include "Logger.h"
#include "Network/network.hpp"
#include "Security/Init.h" #include "Security/Init.h"
#include <filesystem>
#include "Startup.h" #include "Startup.h"
#include "hashpp.h" #include "hashpp.h"
#include "Logger.h" #include <filesystem>
#include <fstream> #include <fstream>
#include <thread> #include <thread>
#include "Http.h"
extern int TraceBack; extern int TraceBack;
bool Dev = false; bool Dev = false;
@ -40,23 +44,33 @@ std::strong_ordering VersionParser::operator<=>(
const VersionParser& rhs) const noexcept { const VersionParser& rhs) const noexcept {
size_t const fields = std::min(data.size(), rhs.data.size()); size_t const fields = std::min(data.size(), rhs.data.size());
for (size_t i = 0; i != fields; ++i) { for (size_t i = 0; i != fields; ++i) {
if (data[i] == rhs.data[i]) continue; if (data[i] == rhs.data[i])
else if (data[i] < rhs.data[i]) return std::strong_ordering::less; continue;
else return std::strong_ordering::greater; else if (data[i] < rhs.data[i])
return std::strong_ordering::less;
else
return std::strong_ordering::greater;
} }
if (data.size() == rhs.data.size()) return std::strong_ordering::equal; if (data.size() == rhs.data.size())
else if (data.size() > rhs.data.size()) return std::strong_ordering::greater; return std::strong_ordering::equal;
else return std::strong_ordering::less; else if (data.size() > rhs.data.size())
return std::strong_ordering::greater;
else
return std::strong_ordering::less;
} }
bool VersionParser::operator==(const VersionParser& rhs) const noexcept { bool VersionParser::operator==(const VersionParser& rhs) const noexcept {
return std::is_eq(*this <=> rhs); return std::is_eq(*this <=> rhs);
} }
std::string GetEN() { std::string GetEN() {
#if defined(_WIN32)
return "BeamMP-Launcher.exe"; return "BeamMP-Launcher.exe";
#elif defined(__linux__)
return "BeamMP-Launcher";
#endif
} }
std::string GetVer() { std::string GetVer() {
return "2.0"; return "2.0";
} }
@ -71,6 +85,7 @@ std::string GetEP(char*P){
}(); }();
return Ret; return Ret;
} }
#if defined(_WIN32)
void ReLaunch(int argc, char* args[]) { void ReLaunch(int argc, char* args[]) {
std::string Arg; std::string Arg;
for (int c = 2; c <= argc; c++) { for (int c = 2; c <= argc; c++) {
@ -94,11 +109,41 @@ void URelaunch(int argc,char* args[]){
std::this_thread::sleep_for(std::chrono::seconds(1)); std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1); exit(1);
} }
#elif defined(__linux__)
void ReLaunch(int argc, char* args[]) {
std::string Arg;
for (int c = 2; c <= argc; c++) {
Arg += " ";
Arg += args[c - 1];
}
system("clear");
execl((GetEP() + GetEN()).c_str(), Arg.c_str(), NULL);
std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1);
}
void URelaunch(int argc, char* args[]) {
std::string Arg;
for (int c = 2; c <= argc; c++) {
Arg += " ";
Arg += args[c - 1];
}
execl((GetEP() + GetEN()).c_str(), Arg.c_str(), NULL);
std::this_thread::sleep_for(std::chrono::seconds(1));
exit(1);
}
#endif
void CheckName(int argc, char* args[]) { void CheckName(int argc, char* args[]) {
#if defined(_WIN32)
std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('\\') + 1); std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('\\') + 1);
#elif defined(__linux__)
std::string DN = GetEN(), CDir = args[0], FN = CDir.substr(CDir.find_last_of('/') + 1);
#endif
if (FN != DN) { if (FN != DN) {
if(fs::exists(DN))remove(DN.c_str()); if (fs::exists(DN))
if(fs::exists(DN))ReLaunch(argc,args); remove(DN.c_str());
if (fs::exists(DN))
ReLaunch(argc, args);
std::rename(FN.c_str(), DN.c_str()); std::rename(FN.c_str(), DN.c_str());
URelaunch(argc, args); URelaunch(argc, args);
} }
@ -113,19 +158,28 @@ void CheckForUpdates(int argc, char* args[], const std::string& CV) {
std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back"); std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back");
std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, EP); std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, EP);
#if defined(_WIN32)
#elif defined(__linux__)
system("clear");
#endif
if (FileHash != LatestHash && VersionParser(LatestVersion) > VersionParser(GetVer() + GetPatch())) { if (FileHash != LatestHash && VersionParser(LatestVersion) > VersionParser(GetVer() + GetPatch())) {
info("Launcher update found!"); info("Launcher update found!");
#if defined(__linux__)
error("Auto update is NOT implemented for the Linux version. Please update manually ASAP as updates contain security patches.");
#else
fs::remove(Back); fs::remove(Back);
fs::rename(EP, Back); fs::rename(EP, Back);
info("Downloading Launcher update " + LatestHash); info("Downloading Launcher update " + LatestHash);
HTTP::Download( HTTP::Download(
"https://backend.beammp.com/builds/launcher?download=true" "https://backend.beammp.com/builds/launcher?download=true"
"&pk=" + "&pk="
PublicKey + "&branch=" + Branch, + PublicKey + "&branch=" + Branch,
EP); EP);
URelaunch(argc, args); URelaunch(argc, args);
} else info("Launcher version is up to date"); #endif
} else
info("Launcher version is up to date");
TraceBack++; TraceBack++;
} }
@ -138,14 +192,17 @@ void CustomPort(int argc, char* argv[]){
warn("Running on custom port : " + std::to_string(DEFAULT_PORT)); warn("Running on custom port : " + std::to_string(DEFAULT_PORT));
} }
} }
if(argc > 2)Dev = true; if (argc > 2)
Dev = true;
} }
} }
#ifdef _WIN32
void LinuxPatch() { void LinuxPatch() {
HKEY hKey = nullptr; HKEY hKey = nullptr;
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey); LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, R"(Software\Wine)", 0, KEY_READ, &hKey);
if (result != ERROR_SUCCESS || getenv("USER") == nullptr)return; if (result != ERROR_SUCCESS || getenv("USER") == nullptr)
return;
RegCloseKey(hKey); RegCloseKey(hKey);
info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit"); info("Wine/Proton Detected! If you are on windows delete HKEY_CURRENT_USER\\Software\\Wine in regedit");
info("Applying patches..."); info("Applying patches...");
@ -167,7 +224,9 @@ void LinuxPatch(){
info("Patched!"); info("Patched!");
} }
#endif
#if defined(_WIN32)
void InitLauncher(int argc, char* argv[]) { void InitLauncher(int argc, char* argv[]) {
system("cls"); system("cls");
SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str()); SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str());
@ -179,33 +238,48 @@ void InitLauncher(int argc, char* argv[]) {
CustomPort(argc, argv); CustomPort(argc, argv);
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch()); CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
} }
#elif defined(__linux__)
void InitLauncher(int argc, char* argv[]) {
system("clear");
InitLog();
CheckName(argc, argv);
CheckLocalKey();
ConfigInit();
CustomPort(argc, argv);
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
}
#endif
size_t DirCount(const std::filesystem::path& path) { size_t DirCount(const std::filesystem::path& path) {
return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {}); return (size_t)std::distance(std::filesystem::directory_iterator { path }, std::filesystem::directory_iterator {});
} }
void CheckMP(const std::string& Path) { void CheckMP(const std::string& Path) {
if (!fs::exists(Path))return; if (!fs::exists(Path))
return;
size_t c = DirCount(fs::path(Path)); size_t c = DirCount(fs::path(Path));
try { try {
for (auto& p : fs::directory_iterator(Path)) { for (auto& p : fs::directory_iterator(Path)) {
if (p.exists() && !p.is_directory()) { if (p.exists() && !p.is_directory()) {
std::string Name = p.path().filename().string(); std::string Name = p.path().filename().string();
for(char&Ch : Name)Ch = char(tolower(Ch)); for (char& Ch : Name)
if(Name != "beammp.zip")fs::remove(p.path()); Ch = char(tolower(Ch));
if (Name != "beammp.zip")
fs::remove(p.path());
} }
} }
} catch (...) { } catch (...) {
fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?"); fatal("We were unable to clean the multiplayer mods folder! Is the game still running or do you have something open in that folder?");
} }
} }
void EnableMP() { void EnableMP() {
std::string File(GetGamePath() + "mods/db.json"); std::string File(GetGamePath() + "mods/db.json");
if(!fs::exists(File))return; if (!fs::exists(File))
return;
auto Size = fs::file_size(File); auto Size = fs::file_size(File);
if(Size < 2)return; if (Size < 2)
return;
std::ifstream db(File); std::ifstream db(File);
if (db.is_open()) { if (db.is_open()) {
std::string Data(Size, 0); std::string Data(Size, 0);
@ -239,7 +313,8 @@ void PreGame(const std::string& GamePath){
std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey); std::string LatestHash = HTTP::Get("https://backend.beammp.com/sha/mod?branch=" + Branch + "&pk=" + PublicKey);
transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower); transform(LatestHash.begin(), LatestHash.end(), LatestHash.begin(), ::tolower);
LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(), LatestHash.erase(std::remove_if(LatestHash.begin(), LatestHash.end(),
[](auto const& c ) -> bool { return !std::isalnum(c); } ), LatestHash.end()); [](auto const& c) -> bool { return !std::isalnum(c); }),
LatestHash.end());
try { try {
if (!fs::exists(GetGamePath() + "mods/multiplayer")) { if (!fs::exists(GetGamePath() + "mods/multiplayer")) {
@ -249,15 +324,21 @@ void PreGame(const std::string& GamePath){
} catch (std::exception& e) { } catch (std::exception& e) {
fatal(e.what()); fatal(e.what());
} }
#if defined(_WIN32)
std::string ZipPath(GetGamePath() + R"(mods\multiplayer\BeamMP.zip)"); 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); std::string FileHash = hashpp::get::getFileHash(hashpp::ALGORITHMS::SHA2_256, ZipPath);
if (FileHash != LatestHash) { if (FileHash != LatestHash) {
info("Downloading BeamMP Update " + LatestHash); info("Downloading BeamMP Update " + LatestHash);
HTTP::Download("https://backend.beammp.com/builds/client?download=true" HTTP::Download("https://backend.beammp.com/builds/client?download=true"
"&pk=" + PublicKey + "&branch=" + Branch, ZipPath); "&pk="
+ PublicKey + "&branch=" + Branch,
ZipPath);
} }
std::string Target(GetGamePath() + "mods/unpacked/beammp"); std::string Target(GetGamePath() + "mods/unpacked/beammp");
@ -309,7 +390,8 @@ void StartProxy() {
headers.emplace("X-API-Version", req.get_header_value("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, if (auto cli_res = cli.Post(req.path, headers, req.body,
req.get_header_value("Content-Type")); cli_res) { req.get_header_value("Content-Type"));
cli_res) {
res.set_content(cli_res->body, cli_res->get_header_value("Content-Type")); res.set_content(cli_res->body, cli_res->get_header_value("Content-Type"));
} else { } else {
res.set_content(to_string(cli_res.error()), "text/plain"); res.set_content(to_string(cli_res.error()), "text/plain");

View File

@ -5,13 +5,13 @@
/// ///
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include "Network/network.h" #include "Http.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) {