initial commit

This commit is contained in:
C
2022-07-16 15:39:16 +05:00
parent 1ccb57df4d
commit 497a441e0d
10 changed files with 707 additions and 0 deletions
+363
View File
@@ -0,0 +1,363 @@
// websocket
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <iostream>
#include <string>
#include <thread>
#include <functional>
// json
#include <nlohmann/json.hpp>
// windows child process
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
// windows terminate process
#include <tlhelp32.h>
//hash
#include <boost/functional/hash.hpp>
// time
#include <chrono>
#include <ctime>
// fixed int
#include <cstdint>
// user
#include "user.h"
#include <vector>
// session
#include "sessionManager.h"
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
void EndProc(DWORD procId)
{
PROCESSENTRY32 pe;
memset(&pe, 0, sizeof(PROCESSENTRY32));
pe.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (::Process32First(hSnap, &pe))
{
BOOL bContinue = TRUE;
// kill child processes
while (bContinue)
{
// only kill child processes
if (pe.th32ParentProcessID == procId)
{
HANDLE hChildProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
if (hChildProc)
{
::TerminateProcess(hChildProc, 1);
::CloseHandle(hChildProc);
}
}
bContinue = ::Process32Next(hSnap, &pe);
}
// kill the main process
HANDLE hProc = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, procId);
if (hProc)
{
::TerminateProcess(hProc, 1);
::CloseHandle(hProc);
}
}
}
template <typename T>
uint32_t hash6(T arg)
{
boost::hash<T> h;
return h(arg) % 1000000;
}
LRESULT CALLBACK GLWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_DESTROY) PostQuitMessage(0);
return DefWindowProc(hWnd, msg, wParam, lParam);
}
int main(int argc, char* argv[])
{
// disable console input
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
DWORD prev_mode;
GetConsoleMode(hInput, &prev_mode);
SetConsoleMode(hInput, ENABLE_EXTENDED_FLAGS |
(prev_mode & ~ENABLE_QUICK_EDIT_MODE));
// ip and socket init
std::string ip("192.168.1.115");
uint16_t sess_port = 13001;
auto const address = net::ip::make_address(ip);
auto const port = static_cast<unsigned short>(std::atoi("8083"));
net::io_context ioc{ 1 };
tcp::acceptor acceptor{ ioc, {address, port} };
// sessions
sessionManager sessManager;
sessManager.setlimit(10);
// stats count
uint64_t user_n = 0;
while (true)
{
tcp::socket socket(ioc);
acceptor.accept(socket);
std::thread([sock = std::move(socket), &sessManager, &ip, &sess_port, &user_n]() mutable
{
std::string user_ip = sock.remote_endpoint().address().to_string();
uint64_t user_id = std::chrono::system_clock::now().time_since_epoch().count();
user_id = hash6(user_ip + std::to_string(user_id));
uint64_t thisUserNum = ++user_n;
std::cout << "user(" << thisUserNum << ") connected (ip: " << user_ip << "), (id: " << user_id << ")" << std::endl;
websocket::stream<tcp::socket> ws(std::move(const_cast<tcp::socket&>(sock)));
ws.accept();
// Set a decorator to change the Server of the
/*ws.set_option(websocket::stream_base::decorator(
[](websocket::response_type& res)
{
res.set(http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-server-sync");
}));*/
//session sessTmp;
session* sessCur = nullptr;
uint32_t sessId = 0;
nlohmann::json jsonData;
std::string message;
std::string content;
while (true)
{
try
{
// This buffer will hold the incoming message
// buffer types https://www.boost.org/doc/libs/1_75_0/libs/beast/doc/html/beast/using_io/buffer_types.html
// check for the best one
// beast::multi_buffer buffer;
beast::flat_buffer buffer;
// Read a message
ws.read(buffer);
// cout buffer to string
//std::cout << beast::buffers_to_string(buffer.data()) << std::endl;
// validate errors
try
{
jsonData = nlohmann::json::parse(beast::buffers_to_string(buffer.data()));
message = jsonData.at("message");
}
catch (nlohmann::json::parse_error& e)
{
std::cout << "Parse error:" << e.what() << std::endl;
}
catch (nlohmann::json::out_of_range& e)
{
std::cout << "Out of range:" << e.what() << std::endl;
}
catch (nlohmann::json::exception& e)
{
std::cout << "JSON exception: " << e.what() << std::endl;
}
catch (std::exception& e)
{
std::cout << "Unknown exception" << e.what() << std::endl;
}
// validate message
if (message == "NEW_USER")
{
buffer.clear();
boost::beast::ostream(buffer) << "connected";
ws.write(buffer.data());
}
else if (message == "NEW_SESS")
{
buffer.clear();
if (sessManager.isLimitReached())
{
boost::beast::ostream(buffer)
<< std::string("{\"message\" : \"SESS_LIMIT\"}").c_str();
ws.write(buffer.data());
continue;
}
if (sessManager.existsOwnerIp(user_ip))
{
boost::beast::ostream(buffer)
<< std::string("{\"message\" : \"PERSON_LIMIT\"}").c_str();
ws.write(buffer.data());
continue;
}
//sessManager
boost::beast::ostream(buffer)
<< std::string("{\"message\" : \"CREATING_SESSION\", \"content\" : \"true\"}").c_str();
ws.write(buffer.data());
std::string path = "D:\\Builds\\Fortis_UnStable_57\\FORTIS_Taktika.exe";
std::wstring path_ws = std::wstring(path.begin(), path.end());
const wchar_t* path_cw = path_ws.c_str();
std::string cmd = "-PixelStreamingIP=localhost -PixelStreamingPort=12005 -RenderOffScreen -PixelStreamingEncoderMaxBitrate=15000000 -ResX 1280 -ResY 720 -PixelStreamingEncoderMinQP=25 -PixelStreamingEncoderMultipass=QUARTER -PixelStreamingWebRTCMaxFps=60";
std::wstring cmd_ws = std::wstring(cmd.begin(), cmd.end());
wchar_t* cmd_w = const_cast<wchar_t*>(cmd_ws.c_str());
// creating process
STARTUPINFO startupInfo = { sizeof(startupInfo) };
PROCESS_INFORMATION processInfo;
if (CreateProcess(path_cw, cmd_w, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo))
{
// bind process close listen
std::thread([processInfo]()
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}).detach();
sessId = hash6(user_id);
// create session
sessManager.add(
session(
GetProcessId(processInfo.hProcess),
sessId,
ip + std::to_string(sess_port),
user_ip
));
std::cout << "user(" << thisUserNum << ") created session (id: " << sessId << ")" << std::endl;
if (sessManager.getById(sessId, &sessCur))
{
sessCur->addUser(user(user_id));
}
buffer.clear();
boost::beast::ostream(buffer)
<< (std::string("{\"message\" : \"NEW_SESS\", \"content\" : \"") + std::to_string(sessId) + "\"}");
ws.write(buffer.data());
}
else
{
std::cout << "CreateProcess failed (" << GetLastError() << ")." << std::endl;
}
}
else if (message == "EXIS_SESS")
{
// read session id
try
{
jsonData = nlohmann::json::parse(beast::buffers_to_string(buffer.data()));
content = jsonData.at("content");
}
catch (nlohmann::json::parse_error& e)
{
std::cout << "Parse error:" << e.what() << std::endl;
}
catch (nlohmann::json::out_of_range& e)
{
std::cout << "Out of range:" << e.what() << std::endl;
}
catch (nlohmann::json::exception& e)
{
std::cout << "JSON exception: " << e.what() << std::endl;
}
catch (std::exception& e)
{
std::cout << "Unknown exception" << e.what() << std::endl;
}
// connect to session
if (sessManager.getById(atoi(content.c_str()), &sessCur))
{
sessCur->addUser(user(user_id));
std::cout << "user(" << thisUserNum << ") connected to session (id: " << sessCur->getId()
<< "), (users: " << sessCur->getUsersCount() << ")" << std::endl;
buffer.clear();
boost::beast::ostream(buffer)
<< (std::string("{\"message\" : \"EXIS_SESS\", \"content\" : \"") + std::to_string(sessCur->getId()) + "\"}");
ws.write(buffer.data());
}
else
{
std::cout << "no session (id: " << content << ")" << std::endl;
}
}
// Echo the message back
// ws.text(ws.got_text());
// boost::beast::ostream(buffer) << "something";
// ws.write(buffer.data());
}
catch (beast::system_error const& se)
{
std::cout << "user(" << thisUserNum << ") disconnected" << std::endl;
if (sessCur)
{
sessCur->removeUserById(user_id);
if (!sessCur->getUsersCount())
{
std::cout << "destroy session (id: " << sessCur->getId() << ")" << std::endl;
EndProc(sessCur->getProcId());
sessManager.remove(sessId);
}
}
break;
/* if (se.code() != websocket::error::closed)
{
std::cerr << "Error: " << se.code().message() << std::endl;
break;
}*/
}
}
}).detach();
}
return 0;
}
+144
View File
@@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{46b65b94-51fc-4b93-9b89-262fd262c49f}</ProjectGuid>
<RootNamespace>ServerPixel</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>C:\Libraries\json-develop\include;C:\Libraries\boost\include\boost_1_79_0;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="ServerPixel.cpp" />
<ClCompile Include="session.cpp" />
<ClCompile Include="sessionManager.cpp" />
<ClCompile Include="user.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="session.h" />
<ClInclude Include="sessionManager.h" />
<ClInclude Include="user.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="ServerPixel.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="user.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="session.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="sessionManager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="user.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="session.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="sessionManager.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
+1
View File
@@ -0,0 +1 @@
#include "session.h"
+40
View File
@@ -0,0 +1,40 @@
#include <windows.h>
#include <cstdint>
#include <vector>
#include "user.h"
#pragma once
class session
{
private:
DWORD procId = 0;
uint32_t sessId = 0;
std::string sessLink;
std::vector<user> users;
std::string ownerIp;
public:
session() {}
session(DWORD procId, uint32_t sessId, std::string sessLink, std::string ownerIp)
{
this->procId = procId;
this->sessId = sessId;
this->sessLink = sessLink;
this->ownerIp = ownerIp;
}
void addUser(user u)
{
users.push_back(u);
}
void removeUserById(uint32_t id)
{
for (int i = 0; i < users.size(); ++i)
if (users[i].getId() == id)
users.erase(users.begin() + i);
}
inline size_t getUsersCount() const { return users.size(); }
inline const uint32_t& getId() const { return sessId; }
inline const DWORD& getProcId() const { return procId; }
inline const std::string& getOwnerIp() const { return ownerIp; }
};
+1
View File
@@ -0,0 +1 @@
#include "sessionManager.h"
+52
View File
@@ -0,0 +1,52 @@
#include "session.h"
#include <vector>
#pragma once
class sessionManager
{
private:
std::vector<session> sessions;
uint32_t limit = 0;
public:
bool add(session s)
{
if (isLimitReached())
return false;
sessions.push_back(s);
return true;
}
void remove(uint32_t id)
{
for (uint32_t i = 0; i < sessions.size(); ++i)
if (sessions[i].getId() == id)
sessions.erase(sessions.begin() + i);
}
bool getById(uint32_t id, session** s)
{
for (int i = 0; i < sessions.size(); ++i)
if (sessions[i].getId() == id)
{
*s = &(*(sessions.begin() + i));
return true;
}
return false;
}
bool existsOwnerIp(std::string ip)
{
for (auto& s : sessions)
if (s.getOwnerIp() == ip)
return true;
return false;
}
size_t getCount() { return sessions.size(); }
void setlimit(uint32_t limit) { this->limit = limit; }
bool isLimitReached()
{
return limit == sessions.size();
}
};
+1
View File
@@ -0,0 +1 @@
#include "user.h"
+32
View File
@@ -0,0 +1,32 @@
#include <string>
#include <cstdint>
//#ifndef FRAMEWORK_H
//# define FRAMEWORK_H
//# include <A.h>
//# include <B.h>
//# include <C.h>
//#endif
#pragma once
class user
{
public:
std::string name = "";
char age = 0;
uint32_t id = 0;
public:
user() {};
user(std::string name, char age)
{
this->name = name;
this->age = age;
}
user(uint32_t id)
{
this->id = id;
}
std::string getName() { return name; }
char getAge() { return age; }
uint32_t getId() { return id; }
};