Replaced cURL with evpp

This commit is contained in:
Anonymous-275 2021-03-29 16:43:17 +03:00
parent 5c1b7b1dbf
commit fff747afca
9 changed files with 172 additions and 164 deletions

13
.gitignore vendored
View File

@ -1,13 +1,4 @@
cmake-build-debug/CMakeFiles/ cmake-build-debug
cmake-build-release/CMakeFiles/ cmake-build-release
cmake-build-debug/BeamNG/
cmake-build-release/BeamNG/
cmake-build-debug/Resources/
cmake-build-release/Resources/
cmake-build-debug/*.*
cmake-build-release/*.*
cmake-build-debug/Makefile
cmake-build-release/Makefile
/.idea/ /.idea/
*.log *.log
cmake-build-release/key

View File

@ -4,12 +4,18 @@ set(CMAKE_CXX_STANDARD 17)
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")
#file(GLOB evpp_src evpp/evpp/*.cc evpp/evpp/*/*.cc evpp/evpp/*.h evpp/evpp/*/*.h)
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")
add_definitions("-DEVPP_HTTP_CLIENT_SUPPORTS_SSL")
add_subdirectory("evpp")
if (WIN32) if (WIN32)
find_package(glog CONFIG REQUIRED)
find_package(Libevent CONFIG REQUIRED)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
find_package(CURL REQUIRED) find_package(CURL REQUIRED)
find_package(OpenSSL REQUIRED)
message(STATUS "MSVC -> forcing use of statically-linked runtime.") message(STATUS "MSVC -> forcing use of statically-linked runtime.")
STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE}) STRING(REPLACE "/MD" "/MT" CMAKE_CXX_FLAGS_RELEASE ${CMAKE_CXX_FLAGS_RELEASE})
STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) STRING(REPLACE "/MDd" "/MTd" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
@ -17,11 +23,13 @@ if (WIN32)
set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}) set(VcpkgRoot ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET})
include_directories(${VcpkgRoot}/include) include_directories(${VcpkgRoot}/include)
link_directories(${VcpkgRoot}/lib) link_directories(${VcpkgRoot}/lib)
target_link_libraries(${PROJECT_NAME} PRIVATE discord-rpc CURL::libcurl ZLIB::ZLIB) target_link_libraries(${PROJECT_NAME} PRIVATE discord-rpc evpp_static
libevent::core libevent::extra glog::glog ZLIB::ZLIB
OpenSSL::SSL OpenSSL::Crypto libevent::openssl)
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} -s -static-libgcc -static-libstdc++ --static") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s -static-libgcc -static-libstdc++ --static")
target_link_libraries(${PROJECT_NAME} discord-rpc.a ssp z ws2_32) target_link_libraries(${PROJECT_NAME} discord-rpc evpp_static glog event pthread ssl crypto event_openssl ws2_32 ssp dbghelp iphlpapi z)
endif(WIN32) endif(WIN32)
target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>) target_include_directories(${PROJECT_NAME} PUBLIC include evpp)

View File

@ -6,7 +6,21 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#pragma once #pragma once
#include <evpp/httpc/response.h>
#include <evpp/httpc/request.h>
#include <string> #include <string>
int Download(const std::string& URL,const std::string& Path,bool close); #include "Logger.h"
std::string PostHTTP(const std::string& IP, const std::string& Fields); class HTTP{
std::string HTTP_REQUEST(const std::string& IP,int port); public:
static void Response(const std::shared_ptr<evpp::httpc::Response>& response, evpp::httpc::Request* request);
static bool Download(const std::string &IP, const std::string &Path);
static std::string Post(const std::string& IP, const std::string& Fields);
static std::string Get(const std::string &IP);
static void Init(char* argv[]){
google::InitGoogleLogging(argv[0]);
google::SetStderrLogging(google::GLOG_ERROR);
evpp::httpc::SET_SSL_VERIFY_MODE(SSL_VERIFY_NONE);
}
private:
static std::string Res_;
};

24
include/winmain-inl.h Normal file
View File

@ -0,0 +1,24 @@
#pragma once
namespace {
struct OnApp {
OnApp() {
#ifdef WIN32
// Initialize Winsock 2.2
WSADATA wsaData;
int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err) {
std::cout << "WSAStartup() failed with error: %d" << err;
}
#endif
}
~OnApp() {
#ifdef WIN32
WSACleanup();
#endif
}
} __s_onexit_pause;
}

View File

@ -8,7 +8,7 @@
#include "Network/network.h" #include "Network/network.h"
#include "Security/Init.h" #include "Security/Init.h"
#include "Curl/http.h" #include "http.h"
#include <winsock2.h> #include <winsock2.h>
#include <ws2tcpip.h> #include <ws2tcpip.h>
#include "Startup.h" #include "Startup.h"
@ -58,7 +58,7 @@ void Parse(std::string Data,SOCKET CSocket){
NetReset(); NetReset();
Terminate = true; Terminate = true;
TCPTerminate = true; TCPTerminate = true;
Data = Code + HTTP_REQUEST("https://beammp.com/servers-info",443); Data = Code + HTTP::Get("https://beammp.com/servers-info");
break; break;
case 'C': case 'C':
ListOfMods.clear(); ListOfMods.clear();

View File

@ -6,139 +6,113 @@
/// Created by Anonymous275 on 7/18/2020 /// Created by Anonymous275 on 7/18/2020
/// ///
#include <curl/curl.h> #include <evpp/event_loop_thread.h>
#include <evpp/httpc/conn_pool.h>
#include <iostream> #include <iostream>
#include <Logger.h> #include <Logger.h>
#include <fstream>
#include "http.h"
#include <mutex> #include <mutex>
#include <cmath> #include <cmath>
class CurlManager{ #include "winmain-inl.h"
public:
CurlManager(){
curl = curl_easy_init();
}
~CurlManager(){
curl_easy_cleanup(curl);
}
inline CURL* Get(){
return curl;
}
private:
CURL *curl;
};
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp){ static bool responded;
((std::string*)userp)->append((char*)contents, size * nmemb); std::string HTTP::Res_{};
return size * nmemb; void HTTP::Response(const std::shared_ptr<evpp::httpc::Response>& response, evpp::httpc::Request* request){
if(response->http_code() == 200){
Res_ = std::move(response->body().ToString());
} else {
std::cout << "\n";
error("Failed request! http code " + std::to_string(response->http_code()));
}
responded = true;
assert(request == response->request());
delete request;
} }
std::string HTTP_REQUEST(const std::string& IP,int port){ std::string HTTP::Get(const std::string &IP) {
static thread_local CurlManager M;
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
CURL *curl = M.Get(); responded = false;
CURLcode res; Res_.clear();
std::string readBuffer; evpp::EventLoopThread t;
if(curl) { t.Start(true);
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); auto* r = new evpp::httpc::GetRequest(t.loop(), IP, evpp::Duration(10.0));
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); r->Execute(Response);
curl_easy_setopt(curl, CURLOPT_PORT, port);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); while (!responded) {
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); usleep(1);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
res = curl_easy_perform(curl);
if(res != CURLE_OK)return "-1";
}
return readBuffer;
} }
int nb_bar; t.Stop(true);
double last_progress, progress_bar_adv; return Res_;
bool Downloaded; }
int progress_bar (void *bar, double t, double d){
if(t > 0 && last_progress != round(d/t*100)){ std::string HTTP::Post(const std::string& IP, const std::string& Fields) {
nb_bar = 25; static std::mutex Lock;
progress_bar_adv = round(d/t*nb_bar); std::scoped_lock Guard(Lock);
responded = false;
Res_.clear();
evpp::EventLoopThread t;
t.Start(true);
auto* r = new evpp::httpc::PostRequest(t.loop(), IP, Fields, evpp::Duration(10.0));
r->AddHeader("Content-Type","application/json");
r->Execute(Response);
while (!responded) {
usleep(1);
}
t.Stop(true);
if(Res_.empty())return "-1";
else return Res_;
}
void ProgressBar(size_t d, size_t t){
static double last_progress, progress_bar_adv;
progress_bar_adv = round(d/double(t)*25);
std::cout << "\r"; std::cout << "\r";
std::cout << "Progress : [ "; std::cout << "Progress : [ ";
std::cout<<round(d/t*100); std::cout << round(d/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++)std::cout<<"#";
for(i = 0; i < nb_bar - progress_bar_adv; i++)std::cout<<"."; for(i = 0; i < 25 - progress_bar_adv; i++)std::cout<<".";
std::cout << "]"; std::cout << "]";
last_progress = round(d/t*100); last_progress = round(d/double(t)*100);
if(round(d/t*100) == 100){
Downloaded = true;
} }
}
return 0; bool HTTP::Download(const std::string &IP, const std::string &Path) {
}
struct File {
const char *filename;
FILE *stream;
};
static size_t my_fwrite(void *buffer,size_t size,size_t nmemb,void *stream){
auto *out = (struct File*)stream;
if(!out->stream) {
fopen_s(&out->stream,out->filename,"wb");
if(!out->stream)return -1;
}
return fwrite(buffer, size, nmemb, out->stream);
}
int Download(const std::string& URL,const std::string& Path,bool close){
static thread_local CurlManager M;
CURL *curl = M.Get();
CURLcode res;
struct File file = {Path.c_str(),nullptr};
Downloaded = false;
if(curl){
curl_easy_setopt(curl, CURLOPT_URL,URL.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &file);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_bar);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
res = curl_easy_perform(curl);
if(res != CURLE_OK){
return res;
}
}
if(file.stream)fclose(file.stream);
if(!Downloaded){
remove(Path.c_str());
fatal("Failed to download please try again later!");
}
std::cout << std::endl;
return -1;
}
std::string PostHTTP(const std::string& IP, const std::string& Fields) {
static auto *header = new curl_slist{(char*)"Content-Type: application/json"};
static thread_local CurlManager M;
static std::mutex Lock; static std::mutex Lock;
std::scoped_lock Guard(Lock); std::scoped_lock Guard(Lock);
CURL* curl = M.Get(); responded = false;
CURLcode res; Res_.clear();
std::string readBuffer; evpp::EventLoopThread t;
t.Start(true);
auto* r = new evpp::httpc::GetRequest(t.loop(), IP, evpp::Duration(10.0));
r->set_progress_callback(ProgressBar);
r->Execute(Response);
while (!responded) {
if (curl) { usleep(1);
curl_easy_setopt(curl, CURLOPT_URL, IP.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, Fields.size());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, Fields.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
//curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
return "-1";
} }
return readBuffer;
t.Stop(true);
if(Res_.empty())return false;
std::ofstream File(Path, std::ios::binary);
if(File.is_open()) {
File << Res_;
File.close();
std::cout << "\n";
}else{
error("Failed to open file directory: " + Path);
return false;
}
return true;
} }

View File

@ -6,7 +6,7 @@
/// Created by Anonymous275 on 11/26/2020 /// Created by Anonymous275 on 11/26/2020
/// ///
#include "Curl/http.h" #include "http.h"
#include <filesystem> #include <filesystem>
#include "Logger.h" #include "Logger.h"
#include <fstream> #include <fstream>
@ -47,7 +47,7 @@ std::string Login(const std::string& fields){
return ""; return "";
} }
info("Attempting to authenticate..."); info("Attempting to authenticate...");
std::string Buffer = PostHTTP("https://auth.beammp.com/userlogin", fields); std::string Buffer = HTTP::Post("https://auth.beammp.com/userlogin", fields);
json::Document d; json::Document d;
d.Parse(Buffer.c_str()); d.Parse(Buffer.c_str());
if(Buffer == "-1"){ if(Buffer == "-1"){
@ -88,7 +88,7 @@ void CheckLocalKey(){
Key.read(&Buffer[0], Size); Key.read(&Buffer[0], Size);
Key.close(); Key.close();
Buffer = PostHTTP("https://auth.beammp.com/userlogin", R"({"pk":")"+Buffer+"\"}"); Buffer = HTTP::Post("https://auth.beammp.com/userlogin", R"({"pk":")" + Buffer + "\"}");
json::Document d; json::Document d;
d.Parse(Buffer.c_str()); d.Parse(Buffer.c_str());

View File

@ -6,16 +6,15 @@
/// Created by Anonymous275 on 7/16/2020 /// Created by Anonymous275 on 7/16/2020
/// ///
#include "Discord/discord_info.h" #include "Discord/discord_info.h"
#include "Network/network.h" #include "Network/network.h"
#include "Security/Init.h" #include "Security/Init.h"
#include "Curl/http.h"
#include <curl/curl.h>
#include <filesystem> #include <filesystem>
#include "Startup.h" #include "Startup.h"
#include <windows.h>
#include "Logger.h" #include "Logger.h"
#include <thread> #include <thread>
#include "http.h"
extern int TraceBack; extern int TraceBack;
bool Dev = false; bool Dev = false;
@ -71,20 +70,19 @@ void CheckName(int argc,char* args[]){
} }
void CheckForUpdates(int argc,char*args[],const std::string& CV){ void CheckForUpdates(int argc,char*args[],const std::string& CV){
std::string link = "https://beammp.com/builds/launcher?version=true"; std::string link;
std::string HTTP = HTTP_REQUEST(link,443); std::string HTTP = HTTP::Get("https://beammp.com/builds/launcher?version=true");
bool fallback = false; bool fallback = false;
if(HTTP.find_first_of("0123456789") == std::string::npos){ if(HTTP.find_first_of("0123456789") == std::string::npos){
link = "https://backup1.beammp.com/builds/launcher?version=true"; HTTP = HTTP::Get("https://backup1.beammp.com/builds/launcher?version=true");
HTTP = HTTP_REQUEST(link,443);
fallback = true; fallback = true;
if(HTTP.find_first_of("0123456789") == std::string::npos) { if(HTTP.find_first_of("0123456789") == std::string::npos) {
fatal("Primary Servers Offline! sorry for the inconvenience!"); fatal("Primary Servers Offline! sorry for the inconvenience!");
} }
} }
if(fallback){ if(fallback){
link = "https://backup1.beammp.com/builds/launcher?download=true"; link = "www.backup1.beammp.com/builds/launcher?download=true";
}else link = "https://beammp.com/builds/launcher?download=true"; }else link = "www.beammp.com/builds/launcher?download=true";
std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back"); std::string EP(GetEP() + GetEN()), Back(GetEP() + "BeamMP-Launcher.back");
@ -95,13 +93,13 @@ void CheckForUpdates(int argc,char*args[],const std::string& CV){
info("Update found!"); info("Update found!");
info("Updating..."); info("Updating...");
if(std::rename(EP.c_str(), Back.c_str()))error("failed creating a backup!"); if(std::rename(EP.c_str(), Back.c_str()))error("failed creating a backup!");
int i = Download(link, EP,true);
if(i != -1){ if(!HTTP::Download(link, EP)){
error("Launcher Update failed! trying again... code : " + std::to_string(i)); error("Launcher Update failed! trying again...");
std::this_thread::sleep_for(std::chrono::seconds(2)); std::this_thread::sleep_for(std::chrono::seconds(2));
int i2 = Download(link, EP,true);
if(i2 != -1){ if(!HTTP::Download(link, EP)){
error("Launcher Update failed! code : " + std::to_string(i2)); error("Launcher Update failed!");
std::this_thread::sleep_for(std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::seconds(5));
ReLaunch(argc,args); ReLaunch(argc,args);
} }
@ -125,7 +123,6 @@ void CustomPort(int argc, char* argv[]){
} }
void InitLauncher(int argc, char* argv[]) { void InitLauncher(int argc, char* argv[]) {
system("cls"); system("cls");
curl_global_init(CURL_GLOBAL_DEFAULT);
SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str()); SetConsoleTitleA(("BeamMP Launcher v" + std::string(GetVer()) + GetPatch()).c_str());
InitLog(); InitLog();
CheckName(argc, argv); CheckName(argc, argv);
@ -134,7 +131,6 @@ void InitLauncher(int argc, char* argv[]) {
CustomPort(argc, argv); CustomPort(argc, argv);
Discord_Main(); Discord_Main();
CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch()); CheckForUpdates(argc, argv, std::string(GetVer()) + GetPatch());
} }
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{});
@ -180,11 +176,11 @@ void PreGame(const std::string& GamePath){
fatal(e.what()); fatal(e.what());
} }
/* Download("https://backend.beammp.com/builds/client?download=true" /* Download("www.backend.beammp.com/builds/client?download=true"
"&pk=" + PublicKey + "&pk=" + PublicKey +
"&branch=" + Branch, GetGamePath() + R"(mods\multiplayer\BeamMP.zip)", true);*/ "&branch=" + Branch, GetGamePath() + R"(mods\multiplayer\BeamMP.zip)", true);*/
Download("https://beammp.com/builds/client", GetGamePath() + R"(mods\multiplayer\BeamMP.zip)", true); HTTP::Download("https://beammp.com/builds/client", GetGamePath() + R"(mods\multiplayer\BeamMP.zip)");
info("Download Complete!"); info("Download Complete!");
} }

View File

@ -11,7 +11,7 @@
#include <iostream> #include <iostream>
#include "Logger.h" #include "Logger.h"
#include <thread> #include <thread>
#include "http.h"
[[noreturn]] void flush(){ [[noreturn]] void flush(){
while(true){ while(true){
@ -20,24 +20,25 @@
} }
} }
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
#ifdef DEBUG #ifdef DEBUG
std::thread th(flush); std::thread th(flush);
th.detach(); th.detach();
#endif #endif
GetEP(argv[0]); GetEP(argv[0]);
HTTP::Init(argv);
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()));
} }
PreGame(GetGameDir()); PreGame(GetGameDir());
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...)
///move to master create branch then make the new config in json
} }