Separate generic libLicenseClient from CCEngine application
This commit is contained in:
parent
e49998d867
commit
ef8276fe83
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
/.vs/
|
||||
*.vcxproj.user
|
||||
*.Build.CppClean.log
|
||||
/CCEngine/Debug/
|
||||
/CCEngine/Release/
|
||||
/Debug/
|
||||
/libModuleManagerTest/Debug/
|
||||
/Release/
|
||||
25
CCEngine.sln
25
CCEngine.sln
@ -5,12 +5,14 @@ VisualStudioVersion = 15.0.27130.2036
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CCEngine", "CCEngine\CCEngine.vcxproj", "{51637EB3-9942-43AE-9272-9DD85412EFC7}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libModuleManagerTest", "libModuleManagerTest\libModuleManagerTest.vcxproj", "{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CCEngineLoader", "CCEngineLoader\CCEngineLoader.vcxproj", "{450E76A9-E271-4349-9C06-3C0540F9B00F}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLicenseClient", "..\libLicenseClient\libLicenseClient.vcxproj", "{51345E59-83E5-4389-93A9-0131B40522B7}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLicenseClientTest", "..\libLicenseClient\test\libLicenseClientTest.vcxproj", "{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{44063F88-E25A-4C9D-AC11-9868D4CDD704}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
@ -27,14 +29,6 @@ Global
|
||||
{51637EB3-9942-43AE-9272-9DD85412EFC7}.Release|x64.Build.0 = Release|x64
|
||||
{51637EB3-9942-43AE-9272-9DD85412EFC7}.Release|x86.ActiveCfg = Release|Win32
|
||||
{51637EB3-9942-43AE-9272-9DD85412EFC7}.Release|x86.Build.0 = Release|Win32
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Debug|x64.Build.0 = Debug|x64
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Debug|x86.Build.0 = Debug|Win32
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Release|x64.ActiveCfg = Release|x64
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Release|x64.Build.0 = Release|x64
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Release|x86.ActiveCfg = Release|Win32
|
||||
{45ECA063-033A-47D0-B8A8-5F7B504C4CE9}.Release|x86.Build.0 = Release|Win32
|
||||
{450E76A9-E271-4349-9C06-3C0540F9B00F}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{450E76A9-E271-4349-9C06-3C0540F9B00F}.Debug|x64.Build.0 = Debug|x64
|
||||
{450E76A9-E271-4349-9C06-3C0540F9B00F}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
@ -51,10 +45,21 @@ Global
|
||||
{51345E59-83E5-4389-93A9-0131B40522B7}.Release|x64.Build.0 = Release|x64
|
||||
{51345E59-83E5-4389-93A9-0131B40522B7}.Release|x86.ActiveCfg = Release|Win32
|
||||
{51345E59-83E5-4389-93A9-0131B40522B7}.Release|x86.Build.0 = Release|Win32
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Debug|x64.Build.0 = Debug|x64
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Debug|x86.Build.0 = Debug|Win32
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Release|x64.ActiveCfg = Release|x64
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Release|x64.Build.0 = Release|x64
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Release|x86.ActiveCfg = Release|Win32
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73}.Release|x86.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73} = {44063F88-E25A-4C9D-AC11-9868D4CDD704}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4CBA44D0-8074-48F8-A6DD-5914FE3F0026}
|
||||
EndGlobalSection
|
||||
|
||||
@ -18,6 +18,18 @@
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="src\CCEngine.cpp" />
|
||||
<ClCompile Include="src\CCServer.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="src\CCServer.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\libLicenseClient\libLicenseClient.vcxproj">
|
||||
<Project>{51345e59-83e5-4389-93a9-0131b40522b7}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>15.0</VCProjectVersion>
|
||||
<ProjectGuid>{51637EB3-9942-43AE-9272-9DD85412EFC7}</ProjectGuid>
|
||||
@ -100,7 +112,7 @@
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_WIN32_WINNT=0x0501;WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\openssl\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\libLicenseClient\api;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
@ -117,7 +129,7 @@
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_WIN32_WINNT=0x0501;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\openssl\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\libLicenseClient\api;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
@ -135,7 +147,7 @@
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_WIN32_WINNT=0x0501;WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions);BOOST_EXCEPTION_DISABLE</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\openssl\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\libLicenseClient\api;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
<CreateHotpatchableImage>false</CreateHotpatchableImage>
|
||||
<RuntimeTypeInfo>false</RuntimeTypeInfo>
|
||||
@ -162,7 +174,7 @@
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_WIN32_WINNT=0x0501;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\..\openssl\include\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>$(ProjectDir)..\..\libLicenseClient\api;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
@ -172,36 +184,6 @@
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="CCEngine.cpp" />
|
||||
<ClCompile Include="CCServer.cpp" />
|
||||
<ClCompile Include="HashUtils.cpp" />
|
||||
<ClCompile Include="HTTPClient.cpp" />
|
||||
<ClCompile Include="JSONModuleDatabase.cpp" />
|
||||
<ClCompile Include="JSONSerialization.cpp" />
|
||||
<ClCompile Include="LicenseClient.cpp" />
|
||||
<ClCompile Include="ModuleManager.cpp" />
|
||||
<ClCompile Include="ModuleUpdate.cpp" />
|
||||
<ClCompile Include="SystemParams.cpp" />
|
||||
<ClCompile Include="SystemParamsProvider_win.cpp" />
|
||||
<ClCompile Include="updclient\CCUpdClient.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="CCServer.h" />
|
||||
<ClInclude Include="HashUtils.h" />
|
||||
<ClInclude Include="HTTPClient.h" />
|
||||
<ClInclude Include="IModuleDatabase.h" />
|
||||
<ClInclude Include="JSONModuleDatabase.h" />
|
||||
<ClInclude Include="JSONSerialization.h" />
|
||||
<ClInclude Include="LicenseClient.h" />
|
||||
<ClInclude Include="ModuleManager.h" />
|
||||
<ClInclude Include="ModuleUpdate.h" />
|
||||
<ClInclude Include="ModuleVersion.h" />
|
||||
<ClInclude Include="SystemParamsProvider.h" />
|
||||
<ClInclude Include="SystemParamsProvider_win.h" />
|
||||
<ClInclude Include="SystemParams.h" />
|
||||
<ClInclude Include="updclient\CCUpdClient.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@ -9,84 +9,18 @@
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="src\updclient">
|
||||
<UniqueIdentifier>{62810fe9-1f5f-41c9-a552-642d73dbcfcb}</UniqueIdentifier>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="updclient\CCUpdClient.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="JSONSerialization.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ModuleManager.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="JSONModuleDatabase.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="HTTPClient.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="SystemParamsProvider_win.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="SystemParams.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="LicenseClient.cpp">
|
||||
<ClCompile Include="src\CCEngine.cpp">
|
||||
<Filter>src</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="HashUtils.cpp">
|
||||
<ClCompile Include="src\CCServer.cpp">
|
||||
<Filter>src</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="CCServer.cpp">
|
||||
<Filter>src</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="ModuleUpdate.cpp">
|
||||
<Filter>src</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="CCEngine.cpp">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="updclient\CCUpdClient.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ModuleManager.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="JSONSerialization.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="JSONModuleDatabase.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="IModuleDatabase.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="HTTPClient.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="SystemParams.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="SystemParamsProvider_win.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="LicenseClient.h" />
|
||||
<ClInclude Include="SystemParamsProvider.h">
|
||||
<ClInclude Include="src\CCServer.h">
|
||||
<Filter>src</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ModuleUpdate.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="ModuleVersion.h">
|
||||
<Filter>src\updclient</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="HashUtils.h" />
|
||||
<ClInclude Include="CCServer.h" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@ -1,312 +0,0 @@
|
||||
#include "HTTPClient.h"
|
||||
|
||||
#include <curl/curl.h>
|
||||
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
static
|
||||
void dump(const char *text,
|
||||
FILE *stream, unsigned char *ptr, size_t size)
|
||||
{
|
||||
size_t i;
|
||||
size_t c;
|
||||
unsigned int width = 0x10;
|
||||
|
||||
fprintf(stream, "%s, %10.10ld bytes (0x%8.8lx)\n",
|
||||
text, (long)size, (long)size);
|
||||
|
||||
fwrite(ptr, 1, size, stream);
|
||||
fputc('\n', stream); // newline
|
||||
/* for (i = 0; i<size; i += width) {
|
||||
fprintf(stream, "%4.4lx: ", (long)i);
|
||||
|
||||
// show hex to the left
|
||||
for (c = 0; c < width; c++) {
|
||||
if (i + c < size)
|
||||
fprintf(stream, "%02x ", ptr[i + c]);
|
||||
else
|
||||
fputs(" ", stream);
|
||||
}
|
||||
|
||||
// show data on the right
|
||||
for (c = 0; (c < width) && (i + c < size); c++) {
|
||||
char x = (ptr[i + c] >= 0x20 && ptr[i + c] < 0x80) ? ptr[i + c] : '.';
|
||||
fputc(x, stream);
|
||||
}
|
||||
|
||||
fputc('\n', stream); // newline
|
||||
} */
|
||||
}
|
||||
|
||||
static
|
||||
int my_trace(CURL *handle, curl_infotype type,
|
||||
char *data, size_t size,
|
||||
void *userp)
|
||||
{
|
||||
const char *text;
|
||||
(void)handle; /* prevent compiler warning */
|
||||
(void)userp;
|
||||
|
||||
switch (type) {
|
||||
case CURLINFO_TEXT:
|
||||
fprintf(stderr, "== Info: %s", data);
|
||||
default: /* in case a new one is introduced to shock us */
|
||||
return 0;
|
||||
|
||||
case CURLINFO_HEADER_OUT:
|
||||
text = "=> Send header";
|
||||
break;
|
||||
case CURLINFO_DATA_OUT:
|
||||
text = "=> Send data";
|
||||
break;
|
||||
case CURLINFO_SSL_DATA_OUT:
|
||||
text = "=> Send SSL data";
|
||||
break;
|
||||
case CURLINFO_HEADER_IN:
|
||||
text = "<= Recv header";
|
||||
break;
|
||||
case CURLINFO_DATA_IN:
|
||||
text = "<= Recv data";
|
||||
break;
|
||||
case CURLINFO_SSL_DATA_IN:
|
||||
text = "<= Recv SSL data";
|
||||
break;
|
||||
}
|
||||
|
||||
dump(text, stderr, (unsigned char *)data, size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static size_t reader(char *ptr, size_t size, size_t nmemb, std::istream *is)
|
||||
{
|
||||
std::streamsize totalRead = 0;
|
||||
if (*is)
|
||||
{
|
||||
is->read(&ptr[totalRead], size * nmemb - totalRead);
|
||||
// is->read(&ptr[totalRead], 1);
|
||||
totalRead = is->gcount();
|
||||
}
|
||||
|
||||
return totalRead;
|
||||
}
|
||||
|
||||
static int writer(char *data, size_t size, size_t nmemb, std::ostream *os)
|
||||
{
|
||||
if (os == NULL)
|
||||
return 0;
|
||||
|
||||
os->write(data, size*nmemb);
|
||||
|
||||
return size * nmemb;
|
||||
}
|
||||
|
||||
struct CURLDeleter
|
||||
{
|
||||
void operator() (CURL* ptr)
|
||||
{
|
||||
if (ptr)
|
||||
{
|
||||
curl_easy_cleanup(ptr);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct curl_slist_deleter
|
||||
{
|
||||
void operator() (curl_slist* ptr)
|
||||
{
|
||||
if (ptr)
|
||||
{
|
||||
curl_slist_free_all(ptr);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct DownloadSession
|
||||
{
|
||||
char errorBuffer[CURL_ERROR_SIZE] = { 0 };
|
||||
std::unique_ptr<CURL, CURLDeleter> conn;
|
||||
std::unique_ptr<curl_slist, curl_slist_deleter> extraHeaders;
|
||||
};
|
||||
|
||||
DownloadSession initCurlRequest(const std::string& url, std::ostream &os)
|
||||
{
|
||||
DownloadSession result;
|
||||
CURLcode code;
|
||||
|
||||
std::unique_ptr<CURL, CURLDeleter> conn(curl_easy_init());
|
||||
|
||||
if (!conn)
|
||||
{
|
||||
throw std::runtime_error("Failed to create CURL connection");
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_ERRORBUFFER, result.errorBuffer);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set error buffer [" << code << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
const char* errorBuffer = result.errorBuffer;
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_URL, url.c_str());
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set URL [" << errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_FOLLOWLOCATION, 1L);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set redirect option [" << errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_MAXREDIRS, 5L);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set maximum number of redirects [" << errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_WRITEFUNCTION, writer);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set write function [" << errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_WRITEDATA, &os);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set write data [" << errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
// DEBUG:
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_DEBUGFUNCTION, my_trace);
|
||||
code = curl_easy_setopt(conn.get(), CURLOPT_VERBOSE, 1);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set verbose mode";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
result.conn = std::move(conn);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
DownloadSession initCurlPostJsonRequest(const std::string& url, std::istream& is, size_t length, std::ostream &os)
|
||||
{
|
||||
DownloadSession result = initCurlRequest(url, os);
|
||||
CURLcode code;
|
||||
|
||||
auto contentLengthHeader = std::string("Content-Length: ") + std::to_string(length);
|
||||
|
||||
struct curl_slist *headers = NULL;
|
||||
headers = curl_slist_append(headers, "Accept: application/json");
|
||||
headers = curl_slist_append(headers, "Content-Type: application/json");
|
||||
headers = curl_slist_append(headers, contentLengthHeader.c_str());
|
||||
headers = curl_slist_append(headers, "Charsets: utf-8");
|
||||
result.extraHeaders.reset(headers);
|
||||
|
||||
code = curl_easy_setopt(result.conn.get(), CURLOPT_POST, 1L);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set post option [" << result.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(result.conn.get(), CURLOPT_HTTPHEADER, result.extraHeaders.get());
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set http headers [" << result.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(result.conn.get(), CURLOPT_READFUNCTION, reader);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set read function [" << result.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
code = curl_easy_setopt(result.conn.get(), CURLOPT_READDATA, &is);
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to set read data [" << result.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
HTTPClient::HTTPClient()
|
||||
{
|
||||
curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
}
|
||||
|
||||
void HTTPClient::get(const std::string& url, std::ostream& dstStream)
|
||||
{
|
||||
auto session = initCurlRequest(url, dstStream);
|
||||
|
||||
auto code = curl_easy_perform(session.conn.get());
|
||||
session.conn.release();
|
||||
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
if (code == CURLE_COULDNT_CONNECT)
|
||||
{
|
||||
throw CouldNotConnectException();
|
||||
}
|
||||
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to get '" << url << "' [" << session.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPClient::postJson(const std::string& url, std::istream& json, size_t length, std::ostream& dstStream)
|
||||
{
|
||||
auto session = initCurlPostJsonRequest(url, json, length, dstStream);
|
||||
|
||||
auto code = curl_easy_perform(session.conn.get());
|
||||
session.conn.release();
|
||||
|
||||
if (code != CURLE_OK)
|
||||
{
|
||||
if (code == CURLE_COULDNT_CONNECT)
|
||||
{
|
||||
throw CouldNotConnectException();
|
||||
}
|
||||
std::ostringstream oss;
|
||||
oss << "Failed to post '" << url << "' [" << session.errorBuffer << "]";
|
||||
throw std::runtime_error(oss.str());
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPClient::postJson(const std::string& url, const std::string& json, std::ostream& dstStream)
|
||||
{
|
||||
std::istringstream is(json);
|
||||
return postJson(url, is, json.size(), dstStream);
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <ostream>
|
||||
|
||||
class CouldNotConnectException : public std::exception
|
||||
{
|
||||
public:
|
||||
CouldNotConnectException()
|
||||
{}
|
||||
|
||||
virtual ~CouldNotConnectException() throw () {}
|
||||
};
|
||||
|
||||
class HTTPClient
|
||||
{
|
||||
public:
|
||||
HTTPClient();
|
||||
|
||||
public:
|
||||
void get(const std::string& url, std::ostream& dstStream) throw (CouldNotConnectException);
|
||||
void postJson(const std::string& url, std::istream& json, size_t length, std::ostream& dstStream) throw (CouldNotConnectException);
|
||||
void postJson(const std::string& url, const std::string& json, std::ostream& dstStream) throw (CouldNotConnectException);
|
||||
};
|
||||
@ -1,22 +0,0 @@
|
||||
#include "HashUtils.h"
|
||||
|
||||
#include <cryptopp/sha.h>
|
||||
#include <cryptopp/files.h>
|
||||
#include <cryptopp/hex.h>
|
||||
|
||||
using CryptoPP::SHA256;
|
||||
using CryptoPP::FileSource;
|
||||
using CryptoPP::HashFilter;
|
||||
using CryptoPP::HexEncoder;
|
||||
using CryptoPP::StringSink;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
std::string calcSHA256(const fs::path& file)
|
||||
{
|
||||
SHA256 hash;
|
||||
std::string digest;
|
||||
|
||||
FileSource f(file.native().c_str(), true, new HashFilter(hash, new HexEncoder(new StringSink(digest))));
|
||||
|
||||
return digest;
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <string>
|
||||
|
||||
std::string calcSHA256(const boost::filesystem::path& file);
|
||||
@ -1,27 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ModuleVersion.h"
|
||||
|
||||
#include <boost/optional.hpp>
|
||||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
struct Module
|
||||
{
|
||||
std::string moduleId;
|
||||
ModuleVersion version;
|
||||
std::set<std::string> filePaths;
|
||||
};
|
||||
|
||||
class IModuleDatabase
|
||||
{
|
||||
public:
|
||||
virtual std::map<std::string, ModuleVersion> listModules() = 0;
|
||||
virtual boost::optional<Module> findModule(const std::string& moduleId) = 0;
|
||||
virtual void storeModule(const Module& module) = 0;
|
||||
|
||||
protected:
|
||||
~IModuleDatabase() {}
|
||||
};
|
||||
@ -1,117 +0,0 @@
|
||||
#include "JSONModuleDatabase.h"
|
||||
|
||||
#include "JSONSerialization.h"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/property_tree/ptree.hpp>
|
||||
#include <boost/property_tree/json_parser.hpp>
|
||||
|
||||
namespace pt = boost::property_tree;
|
||||
|
||||
void serialize(std::ostream& os, const Module& m)
|
||||
{
|
||||
os << "{";
|
||||
os << "moduleId:";
|
||||
serialize(os, m.moduleId);
|
||||
os << ",version:";
|
||||
serialize(os, m.version);
|
||||
os << ",filePaths:";
|
||||
serialize(os, m.filePaths);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree& tree, Module& m)
|
||||
{
|
||||
deserialize(tree.get_child("moduleId"), m.moduleId);
|
||||
deserialize(tree.get_child("version"), m.version);
|
||||
deserialize(tree.get_child("filePaths"), m.filePaths);
|
||||
}
|
||||
|
||||
JSONModuleDatabase::JSONModuleDatabase(const std::string & baseDir)
|
||||
: m_baseDir(baseDir)
|
||||
{
|
||||
if (!boost::filesystem::exists(baseDir))
|
||||
{
|
||||
boost::filesystem::create_directories(baseDir);
|
||||
}
|
||||
|
||||
if (!boost::filesystem::is_directory(baseDir))
|
||||
{
|
||||
throw std::runtime_error(".inst folder is not directory");
|
||||
}
|
||||
}
|
||||
|
||||
std::map<std::string, ModuleVersion> JSONModuleDatabase::listModules()
|
||||
{
|
||||
std::map<std::string, ModuleVersion> result;
|
||||
|
||||
boost::filesystem::path path(m_baseDir);
|
||||
path /= ".modules.json";
|
||||
if (boost::filesystem::is_regular_file(path))
|
||||
{
|
||||
pt::ptree root;
|
||||
pt::read_json(path.string(), root);
|
||||
|
||||
deserialize(root, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
boost::optional<Module> JSONModuleDatabase::findModule(const std::string & moduleId)
|
||||
{
|
||||
boost::filesystem::path path(m_baseDir);
|
||||
|
||||
if (!boost::filesystem::portable_file_name(moduleId))
|
||||
{
|
||||
throw std::runtime_error("Invalid module name");
|
||||
}
|
||||
|
||||
path /= moduleId;
|
||||
path /= ".json";
|
||||
if (boost::filesystem::is_regular_file(path))
|
||||
{
|
||||
pt::ptree root;
|
||||
pt::read_json(path.string(), root);
|
||||
|
||||
Module m;
|
||||
deserialize(root, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
void JSONModuleDatabase::storeModule(const Module & module)
|
||||
{
|
||||
boost::filesystem::path path(m_baseDir);
|
||||
|
||||
if (!boost::filesystem::portable_file_name(module.moduleId))
|
||||
{
|
||||
throw std::runtime_error("Invalid module name");
|
||||
}
|
||||
|
||||
path /= module.moduleId + ".json";
|
||||
{
|
||||
std::ofstream os(path.string(), std::ostream::out);
|
||||
serialize(os, module);
|
||||
}
|
||||
|
||||
updateModuleList(module.moduleId, module.version);
|
||||
}
|
||||
|
||||
void JSONModuleDatabase::storeModuleList(const std::map<std::string, ModuleVersion>& moduleList)
|
||||
{
|
||||
boost::filesystem::path path(m_baseDir);
|
||||
path /= ".modules.json";
|
||||
|
||||
std::ofstream os(path.string(), std::ostream::out);
|
||||
serialize(os, moduleList);
|
||||
}
|
||||
|
||||
void JSONModuleDatabase::updateModuleList(const std::string & moduleId, const ModuleVersion & version)
|
||||
{
|
||||
auto list = listModules();
|
||||
list[moduleId] = version;
|
||||
storeModuleList(list);
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "IModuleDatabase.h"
|
||||
|
||||
class JSONModuleDatabase final : public IModuleDatabase
|
||||
{
|
||||
public:
|
||||
JSONModuleDatabase(const std::string& baseDir);
|
||||
JSONModuleDatabase(const JSONModuleDatabase&) = delete;
|
||||
JSONModuleDatabase& operator=(const JSONModuleDatabase&) = delete;
|
||||
|
||||
public:
|
||||
std::map<std::string, ModuleVersion> listModules() override;
|
||||
boost::optional<Module> findModule(const std::string& moduleId) override;
|
||||
void storeModule(const Module& module) override;
|
||||
|
||||
private:
|
||||
void storeModuleList(const std::map<std::string, ModuleVersion>& moduleList);
|
||||
void updateModuleList(const std::string& moduleId, const ModuleVersion& version);
|
||||
|
||||
private:
|
||||
std::string m_baseDir;
|
||||
};
|
||||
@ -1,15 +0,0 @@
|
||||
#include "JSONSerialization.h"
|
||||
|
||||
namespace pt = boost::property_tree;
|
||||
|
||||
void serialize(std::ostream & os, const std::string & str)
|
||||
{
|
||||
os << '"'
|
||||
<< str
|
||||
<< '"';
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree & tree, std::string & stringVal)
|
||||
{
|
||||
stringVal = tree.get_value<std::string>();
|
||||
}
|
||||
@ -1,118 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/property_tree/ptree.hpp>
|
||||
|
||||
#include <map>
|
||||
#include <ostream>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
void serialize(std::ostream& os, const std::string& str);
|
||||
|
||||
template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
|
||||
void serialize(std::ostream& os, T intVal)
|
||||
{
|
||||
os << intVal;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void serialize(std::ostream& os, const std::vector<T>& vec)
|
||||
{
|
||||
os << "[";
|
||||
if (vec.size() > 0)
|
||||
{
|
||||
serialize(os, vec[0]);
|
||||
std::for_each(std::begin(vec) + 1, std::end(vec), [&os](const auto& el)
|
||||
{
|
||||
os << ',';
|
||||
serialize(os, el);
|
||||
});
|
||||
}
|
||||
os << "]";
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void serialize(std::ostream& os, const std::set<T>& setVal)
|
||||
{
|
||||
bool first = true;
|
||||
os << "[";
|
||||
std::for_each(std::begin(setVal), std::end(setVal), [&os, &first](const auto& el)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
os << ',';
|
||||
}
|
||||
serialize(os, el);
|
||||
first = false;
|
||||
});
|
||||
os << "]";
|
||||
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void serialize(std::ostream& os, const std::map<std::string, T>& m)
|
||||
{
|
||||
bool first = true;
|
||||
os << "{";
|
||||
std::for_each(std::begin(m), std::end(m), [&os, &first](const auto& pair)
|
||||
{
|
||||
if (!first)
|
||||
{
|
||||
os << ',';
|
||||
}
|
||||
serialize(os, pair.first);
|
||||
os << ':';
|
||||
serialize(os, pair.second);
|
||||
first = false;
|
||||
});
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const boost::property_tree::ptree& tree, std::string& stringVal);
|
||||
|
||||
template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
|
||||
void deserialize(const boost::property_tree::ptree & tree, T& intVal)
|
||||
{
|
||||
intVal = tree.get_value<T>();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void deserialize(const boost::property_tree::ptree& tree, std::vector<T>& vec)
|
||||
{
|
||||
vec.clear();
|
||||
for (const boost::property_tree::ptree::value_type &el : tree)
|
||||
{
|
||||
// el.first contain the string "" if it was JSON array
|
||||
T val;
|
||||
deserialize(el.second, val);
|
||||
vec.push_back(std::move(val));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void deserialize(const boost::property_tree::ptree& tree, std::set<T>& setVal)
|
||||
{
|
||||
setVal.clear();
|
||||
for (const boost::property_tree::ptree::value_type &el : tree)
|
||||
{
|
||||
// el.first contain the string "" if it was JSON array
|
||||
T val;
|
||||
deserialize(el.second, val);
|
||||
setVal.insert(std::move(val));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void deserialize(const boost::property_tree::ptree& tree, std::map<std::string, T>& mapVal)
|
||||
{
|
||||
mapVal.clear();
|
||||
for (const boost::property_tree::ptree::value_type &el : tree)
|
||||
{
|
||||
std::string key;
|
||||
T val;
|
||||
key = el.first;
|
||||
deserialize(el.second, val);
|
||||
mapVal.insert(std::make_pair(std::move(key), std::move(val)));
|
||||
}
|
||||
}
|
||||
@ -1,667 +0,0 @@
|
||||
#include "LicenseClient.h"
|
||||
|
||||
#include "JSONSerialization.h"
|
||||
|
||||
#include <cryptopp/cryptlib.h>
|
||||
#include <cryptopp/aes.h>
|
||||
#include <cryptopp/gcm.h>
|
||||
#include <cryptopp/osrng.h>
|
||||
#include <cryptopp/eccrypto.h>
|
||||
#include <cryptopp/oids.h>
|
||||
#include <cryptopp/files.h>
|
||||
#include <cryptopp/hex.h>
|
||||
#include <cryptopp/base64.h>
|
||||
#include <cryptopp/base32.h>
|
||||
#include <cryptopp/dsa.h>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/iostreams/device/array.hpp>
|
||||
#include <boost/iostreams/filtering_stream.hpp>
|
||||
#include <boost/iostreams/filter/zlib.hpp>
|
||||
#include <boost/property_tree/json_parser.hpp>
|
||||
#include <boost/property_tree/ptree.hpp>
|
||||
|
||||
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <streambuf>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace pt = boost::property_tree;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
using CryptoPP::AES;
|
||||
using CryptoPP::GCM;
|
||||
using CryptoPP::byte;
|
||||
using CryptoPP::SecByteBlock;
|
||||
using CryptoPP::AutoSeededRandomPool;
|
||||
using CryptoPP::AuthenticatedDecryptionFilter;
|
||||
using CryptoPP::StringSink;
|
||||
using CryptoPP::StringSource;
|
||||
using CryptoPP::Redirector;
|
||||
using CryptoPP::ECDSA;
|
||||
using CryptoPP::EC2N;
|
||||
using CryptoPP::SHA256;
|
||||
using CryptoPP::HexDecoder;
|
||||
using CryptoPP::Base64Decoder;
|
||||
using CryptoPP::Base32Decoder;
|
||||
using CryptoPP::Base32Encoder;
|
||||
namespace ASN1 = CryptoPP::ASN1;
|
||||
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
static const std::string appId = "coc";
|
||||
|
||||
static const uint32_t initializationVectorSize = AES::BLOCKSIZE;
|
||||
static const uint32_t macTagSize = 16;
|
||||
static const uint32_t ecdsaSignatureSize = 72;
|
||||
|
||||
template< typename T >
|
||||
std::string intToHex(T i)
|
||||
{
|
||||
std::stringstream stream;
|
||||
stream
|
||||
<< std::setfill('0') << std::setw(sizeof(T) * 2)
|
||||
<< std::hex << i;
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
uint64_t fletcher64(uint32_t *data, int count)
|
||||
{
|
||||
uint64_t sum1 = 0;
|
||||
uint64_t sum2 = 0;
|
||||
int index;
|
||||
|
||||
for (index = 0; index < count; ++index)
|
||||
{
|
||||
sum1 = (sum1 + data[index]) % std::numeric_limits<uint32_t>::max();
|
||||
sum2 = (sum2 + sum1) % std::numeric_limits<uint32_t>::max();
|
||||
}
|
||||
|
||||
return (sum2 << std::numeric_limits<uint32_t>::digits) | sum1;
|
||||
}
|
||||
|
||||
typedef std::string ParamHash;
|
||||
ParamHash fletcher64(const std::string& input)
|
||||
{
|
||||
std::vector<uint32_t> buf((input.size() + sizeof(uint32_t) - 1) / sizeof(uint32_t), 0);
|
||||
std::copy_n(std::begin(input), input.size(), stdext::make_checked_array_iterator((std::string::pointer)buf.data(), buf.size() * sizeof(uint32_t)));
|
||||
auto resInt = fletcher64(buf.data(), buf.size());
|
||||
return intToHex(resInt);
|
||||
}
|
||||
|
||||
SystemParams skipEmptyParams(const SystemParams& systemParams)
|
||||
{
|
||||
SystemParams result;
|
||||
for (const auto& entry : systemParams)
|
||||
{
|
||||
if (!entry.second.empty())
|
||||
{
|
||||
result[entry.first] = entry.second;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
SystemParams hashParams(const SystemParams& systemParams)
|
||||
{
|
||||
SystemParams result;
|
||||
for (const auto& entry : systemParams)
|
||||
{
|
||||
result[entry.first] = fletcher64(entry.second);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string base64Decode(const std::string& encoded)
|
||||
{
|
||||
std::string decoded;
|
||||
|
||||
StringSource ss(encoded, true,
|
||||
new Base64Decoder(
|
||||
new StringSink(decoded)
|
||||
)
|
||||
);
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
std::string base32Decode(const std::string& encoded)
|
||||
{
|
||||
// Decoder
|
||||
int lookup[256] = {0};
|
||||
const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
Base64Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 32, true);
|
||||
|
||||
Base32Decoder decoder;
|
||||
CryptoPP::AlgorithmParameters params = CryptoPP::MakeParameters(CryptoPP::Name::DecodingLookupArray(), (const int *)lookup);
|
||||
decoder.IsolatedInitialize(params);
|
||||
std::string decoded;
|
||||
|
||||
decoder.Attach(new StringSink(decoded));
|
||||
decoder.Put((const byte*)encoded.data(), encoded.size());
|
||||
decoder.MessageEnd();
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
std::string base32Encode(const std::string& data)
|
||||
{
|
||||
// Encoder
|
||||
Base32Encoder encoder;
|
||||
const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
CryptoPP::AlgorithmParameters params = CryptoPP::MakeParameters(CryptoPP::Name::EncodingLookupArray(), (const byte *)ALPHABET);
|
||||
encoder.IsolatedInitialize(params);
|
||||
|
||||
std::string encoded;
|
||||
|
||||
encoder.Attach(new StringSink(encoded));
|
||||
encoder.Put((const byte*)data.data(), data.size());
|
||||
encoder.MessageEnd();
|
||||
|
||||
return encoded;
|
||||
}
|
||||
|
||||
typedef std::string Signature;
|
||||
|
||||
struct SignedData
|
||||
{
|
||||
std::string data;
|
||||
std::string signature;
|
||||
};
|
||||
|
||||
std::string readBinaryFile(const std::string& filename)
|
||||
{
|
||||
std::ifstream t(filename, std::istream::binary);
|
||||
std::string str;
|
||||
|
||||
t.seekg(0, std::ios::end);
|
||||
str.reserve(static_cast<size_t>(t.tellg()));
|
||||
t.seekg(0, std::ios::beg);
|
||||
|
||||
str.assign((std::istreambuf_iterator<char>(t)),
|
||||
std::istreambuf_iterator<char>());
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
struct PreactivationRequest
|
||||
{
|
||||
std::string appId = appId;
|
||||
SystemParams systemParams;
|
||||
};
|
||||
|
||||
struct ActivationRequest
|
||||
{
|
||||
std::string appId = appId;
|
||||
SystemParams systemParams;
|
||||
std::string licenseNumber;
|
||||
};
|
||||
|
||||
struct ActivationResponse
|
||||
{
|
||||
bool success;
|
||||
std::optional<std::string> licenseFile;
|
||||
};
|
||||
|
||||
struct CheckUpdatesRequest
|
||||
{
|
||||
SystemParams systemParams;
|
||||
std::string activationId;
|
||||
std::map<std::string, ModuleVersion> moduleVersions;
|
||||
};
|
||||
|
||||
struct CheckUpdatesResponse
|
||||
{
|
||||
bool success;
|
||||
std::optional<std::string> licenseFile;
|
||||
std::vector<ModuleUpdate> moduleUpdates;
|
||||
};
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void serialize(std::ostream& os, const ActivationData& a)
|
||||
{
|
||||
os << "{";
|
||||
os << "\"activationId\":";
|
||||
serialize(os, a.activationId);
|
||||
os << "\"appId\":";
|
||||
serialize(os, a.appId);
|
||||
os << ",\"systemParams\":";
|
||||
serialize(os, a.systemParams);
|
||||
os << ",\"licensedModules\":";
|
||||
serialize(os, a.licensedModules);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree& tree, ActivationData& a)
|
||||
{
|
||||
deserialize(tree.get_child("activationId"), a.activationId);
|
||||
deserialize(tree.get_child("appId"), a.appId);
|
||||
deserialize(tree.get_child("systemParams"), a.systemParams);
|
||||
deserialize(tree.get_child("licensedModules"), a.licensedModules);
|
||||
}
|
||||
|
||||
void serialize(std::ostream& os, const SignedData& d)
|
||||
{
|
||||
os << "{";
|
||||
os << "\"data\":";
|
||||
serialize(os, d.data);
|
||||
os << ",\"signature\":";
|
||||
serialize(os, d.signature);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree& tree, SignedData& d)
|
||||
{
|
||||
deserialize(tree.get_child("data"), d.data);
|
||||
deserialize(tree.get_child("signature"), d.signature);
|
||||
}
|
||||
|
||||
void serialize(std::ostream& os, const PreactivationRequest& a)
|
||||
{
|
||||
os << "{";
|
||||
os << "\"appId\":";
|
||||
::serialize(os, a.appId);
|
||||
os << "\"systemParams\":";
|
||||
::serialize(os, a.systemParams);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void serialize(std::ostream& os, const ActivationRequest& a)
|
||||
{
|
||||
os << "{";
|
||||
os << "\"appId\":";
|
||||
::serialize(os, a.appId);
|
||||
os << "\"systemParams\":";
|
||||
::serialize(os, a.systemParams);
|
||||
os << ",\"licenseNumber\":";
|
||||
::serialize(os, a.licenseNumber);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree& tree, ActivationResponse& a)
|
||||
{
|
||||
deserialize(tree.get_child("success"), a.success);
|
||||
auto licenseFileOpt = tree.get_child_optional("licenseFile");
|
||||
if (licenseFileOpt)
|
||||
{
|
||||
std::string res;
|
||||
deserialize(licenseFileOpt.value(), res);
|
||||
a.licenseFile = base64Decode(res);
|
||||
}
|
||||
else
|
||||
{
|
||||
a.licenseFile = {};
|
||||
}
|
||||
}
|
||||
|
||||
void serialize(std::ostream& os, const CheckUpdatesRequest& r)
|
||||
{
|
||||
os << "{";
|
||||
os << "\"systemParams\":";
|
||||
::serialize(os, r.systemParams);
|
||||
os << ",\"activationId\":";
|
||||
::serialize(os, r.activationId);
|
||||
os << ",\"moduleVersions\":";
|
||||
::serialize(os, r.moduleVersions);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const pt::ptree& tree, CheckUpdatesResponse& r)
|
||||
{
|
||||
deserialize(tree.get_child("success"), r.success);
|
||||
auto licenseFileOpt = tree.get_child_optional("licenseFile");
|
||||
if (licenseFileOpt)
|
||||
{
|
||||
std::string res;
|
||||
deserialize(licenseFileOpt.value(), res);
|
||||
r.licenseFile = base64Decode(res);
|
||||
}
|
||||
else
|
||||
{
|
||||
r.licenseFile = {};
|
||||
}
|
||||
deserialize(tree.get_child("moduleUpdates"), r.moduleUpdates);
|
||||
}
|
||||
|
||||
|
||||
std::optional<std::string> validateLicenseKey(const std::string& licenseKey)
|
||||
{
|
||||
auto result = base32Decode(licenseKey);
|
||||
if (result.size() != 15)
|
||||
return {};
|
||||
return base32Encode(result);
|
||||
}
|
||||
|
||||
LicenseClient::LicenseClient(SystemParamsProvider& systemParamsProvider, const std::string& licenseFile)
|
||||
: m_systemParamsProvider(systemParamsProvider)
|
||||
, m_licenseFile(licenseFile)
|
||||
{
|
||||
}
|
||||
|
||||
LicenseClient::~LicenseClient()
|
||||
{
|
||||
}
|
||||
|
||||
void LicenseClient::init()
|
||||
{
|
||||
m_systemParams = hashParams(skipEmptyParams(m_systemParamsProvider.retrieveSystemParams()));
|
||||
|
||||
loadActivationData();
|
||||
}
|
||||
|
||||
bool LicenseClient::tryPreactivate(HTTPClient &httpClient)
|
||||
{
|
||||
PreactivationRequest req{ appId, m_systemParams };
|
||||
|
||||
std::string jsonReq;
|
||||
{
|
||||
std::ostringstream ss1;
|
||||
serialize(ss1, req);
|
||||
jsonReq = ss1.str();
|
||||
}
|
||||
|
||||
std::string jsonRes;
|
||||
{
|
||||
std::ostringstream ss2;
|
||||
httpClient.postJson("http://localhost:3000/activate0", jsonReq, ss2);
|
||||
jsonRes = ss2.str();
|
||||
}
|
||||
|
||||
ActivationResponse activationResponse;
|
||||
pt::ptree root;
|
||||
std::istringstream ss2(jsonRes);
|
||||
pt::read_json(ss2, root);
|
||||
deserialize(root, activationResponse);
|
||||
if (activationResponse.success)
|
||||
{
|
||||
{
|
||||
const auto& licenseData = activationResponse.licenseFile.value();
|
||||
std::ofstream os(m_licenseFile, std::ofstream::binary);
|
||||
os.write(licenseData.data(), licenseData.size());
|
||||
}
|
||||
return loadActivationData();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool LicenseClient::activate(HTTPClient &httpClient, const std::string & licenseNumber)
|
||||
{
|
||||
std::string jsonReq;
|
||||
|
||||
std::ostringstream ss1;
|
||||
|
||||
ActivationRequest req{ appId, m_systemParams, licenseNumber };
|
||||
serialize(ss1, req);
|
||||
|
||||
std::stringstream ss2;
|
||||
httpClient.postJson("http://localhost:3000/activate", ss1.str() , ss2);
|
||||
|
||||
ActivationResponse activationResponse;
|
||||
pt::ptree root;
|
||||
pt::read_json(ss2, root);
|
||||
deserialize(root, activationResponse);
|
||||
if (activationResponse.success)
|
||||
{
|
||||
{
|
||||
const auto& licenseData = activationResponse.licenseFile.value();
|
||||
std::ofstream os(m_licenseFile, std::ofstream::binary);
|
||||
os.write(licenseData.data(), licenseData.size());
|
||||
}
|
||||
return loadActivationData();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<ModuleUpdate> LicenseClient::checkForUpdates(HTTPClient & httpClient, const std::map<std::string, ModuleVersion>& currentVersions)
|
||||
{
|
||||
if (!isActivated()) { throw std::runtime_error("Not active"); }
|
||||
|
||||
CheckUpdatesRequest req{ m_systemParams, m_activationData->activationId, currentVersions };
|
||||
|
||||
std::ostringstream ss1;
|
||||
serialize(ss1, req);
|
||||
|
||||
std::stringstream ss2;
|
||||
httpClient.postJson("http://localhost:3000/check", ss1.str(), ss2);
|
||||
|
||||
CheckUpdatesResponse checkUpdatesResponse;
|
||||
pt::ptree root;
|
||||
pt::read_json(ss2, root);
|
||||
deserialize(root, checkUpdatesResponse);
|
||||
|
||||
if (!checkUpdatesResponse.success)
|
||||
{
|
||||
throw std::exception("Could not check for updates");
|
||||
}
|
||||
|
||||
if (checkUpdatesResponse.licenseFile)
|
||||
{
|
||||
// Something changes - Server sent us updated licenseFile
|
||||
{
|
||||
const auto& licenseData = checkUpdatesResponse.licenseFile.value();
|
||||
std::ofstream os(m_licenseFile);
|
||||
os.write(licenseData.data(), licenseData.size());
|
||||
}
|
||||
loadActivationData();
|
||||
}
|
||||
|
||||
return checkUpdatesResponse.moduleUpdates;
|
||||
}
|
||||
|
||||
bool LicenseClient::loadActivationData()
|
||||
{
|
||||
if (fs::is_regular_file(m_licenseFile))
|
||||
{
|
||||
// Encrypt in nodejs
|
||||
/*
|
||||
let activationData = {
|
||||
activationId: '1234567890',
|
||||
systemParams: {
|
||||
biosSerialNum: '1234567797980980',
|
||||
diskSerialNum: '1234567857845764'
|
||||
},
|
||||
licensedModules: ['ccengine', 'cc-data-usd', 'cc-data-rub']
|
||||
};
|
||||
|
||||
let algorithm = 'aes-256-gcm';
|
||||
let password = Buffer.from('e73db572349005f1c41979baf8166a0900745119fa096b9c3efbcee11ddd8b88', 'hex');
|
||||
let privateKey = '-----BEGIN EC PRIVATE KEY-----' + "\n" +
|
||||
'MIGAAgEBBCQBPIZnOt/mEsgtH3S9XZMGRuHkB5hYbMJ/BxcGmAc/pZLdxDWgBwYF' + "\n" +
|
||||
'K4EEABGhTANKAAQHyyrnJFywb+B0pcaVRHIOcEao3OtSMSJJZiluIMme1aE+20UA' + "\n" +
|
||||
'0c0+2u+M6bMi072XrXLf8KudcAxihG/aqCqbVVZS6i10SSM=' + "\n" +
|
||||
'-----END EC PRIVATE KEY-----';
|
||||
crypto.randomBytes(16, (err, nonce) => {
|
||||
activationData.nonce = nonce.toString('base64');
|
||||
let data = JSON.stringify(activationData);
|
||||
let sign = crypto.createSign('SHA256');
|
||||
sign.write(data);
|
||||
sign.end();
|
||||
let signature = sign.sign(privateKey, 'hex');
|
||||
data = JSON.stringify({ data, signature });
|
||||
crypto.randomBytes(16, (err, iv) => {
|
||||
zlib.deflateRaw(data, (err, compressed) => {
|
||||
let cipher = crypto.createCipheriv(algorithm, password, iv);
|
||||
let encrypted = cipher.update(compressed);
|
||||
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
||||
let tag = cipher.getAuthTag();
|
||||
let output = Buffer.concat([iv, tag, encrypted]);
|
||||
console.log(output.toString('hex'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
*/
|
||||
|
||||
/*unsigned char publicKey[] = {
|
||||
0x04, 0x07, 0xcb, 0x2a, 0xe7, 0x24, 0x5c, 0xb0, 0x6f, 0xe0, 0x74, 0xa5, 0xc6, 0x95, 0x44, 0x72,
|
||||
0x0e, 0x70, 0x46, 0xa8, 0xdc, 0xeb, 0x52, 0x31, 0x22, 0x49, 0x66, 0x29, 0x6e, 0x20, 0xc9, 0x9e,
|
||||
0xd5, 0xa1, 0x3e, 0xdb, 0x45, 0x00, 0xd1, 0xcd, 0x3e, 0xda, 0xef, 0x8c, 0xe9, 0xb3, 0x22, 0xd3,
|
||||
0xbd, 0x97, 0xad, 0x72, 0xdf, 0xf0, 0xab, 0x9d, 0x70, 0x0c, 0x62, 0x84, 0x6f, 0xda, 0xa8, 0x2a,
|
||||
0x9b, 0x55, 0x56, 0x52, 0xea, 0x2d, 0x74, 0x49, 0x23 }; */
|
||||
|
||||
unsigned char publicKey[] = {
|
||||
0x30, 0x5e, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b,
|
||||
0x81, 0x04, 0x00, 0x11, 0x03, 0x4a, 0x00, 0x04, 0x07, 0xcb, 0x2a, 0xe7, 0x24, 0x5c, 0xb0, 0x6f,
|
||||
0xe0, 0x74, 0xa5, 0xc6, 0x95, 0x44, 0x72, 0x0e, 0x70, 0x46, 0xa8, 0xdc, 0xeb, 0x52, 0x31, 0x22,
|
||||
0x49, 0x66, 0x29, 0x6e, 0x20, 0xc9, 0x9e, 0xd5, 0xa1, 0x3e, 0xdb, 0x45, 0x00, 0xd1, 0xcd, 0x3e,
|
||||
0xda, 0xef, 0x8c, 0xe9, 0xb3, 0x22, 0xd3, 0xbd, 0x97, 0xad, 0x72, 0xdf, 0xf0, 0xab, 0x9d, 0x70,
|
||||
0x0c, 0x62, 0x84, 0x6f, 0xda, 0xa8, 0x2a, 0x9b, 0x55, 0x56, 0x52, 0xea, 0x2d, 0x74, 0x49, 0x23 };
|
||||
|
||||
unsigned char password[] = {
|
||||
0xe7, 0x3d, 0xb5, 0x72, 0x34, 0x90, 0x05, 0xf1, 0xc4, 0x19, 0x79, 0xba, 0xf8, 0x16, 0x6a, 0x09,
|
||||
0x00, 0x74, 0x51, 0x19, 0xfa, 0x09, 0x6b, 0x9c, 0x3e, 0xfb, 0xce, 0xe1, 0x1d, 0xdd, 0x8b, 0x88 };
|
||||
/* unsigned char encrypted[] = {
|
||||
0x5d, 0xc1, 0x4e, 0xaf, 0x95, 0xf0, 0x1d, 0x84, 0x09, 0x71, 0x66, 0x0f, 0x87, 0x19, 0x7a, 0xa1,
|
||||
0x6a, 0x77, 0x39, 0x1e, 0x0a, 0xde, 0x93, 0x0c, 0xda, 0xa8, 0x62, 0x76, 0x53, 0xcb, 0xa7, 0x9f,
|
||||
0x8d, 0x36, 0x2a, 0x74, 0xcd, 0x5d, 0x78, 0x6e, 0x83, 0x14, 0xa4, 0x21, 0x3c }; */
|
||||
/* {
|
||||
unsigned char encrypted[] = {
|
||||
0x88, 0x5d, 0x38, 0xfe, 0xfc, 0x51, 0x7d, 0x3c, 0xb5, 0x95, 0x49, 0xae, 0xa4, 0x6a, 0xa4, 0x7e,
|
||||
0xda, 0x5d, 0x29, 0x84, 0xc2, 0x85, 0xb6, 0x18, 0x6b, 0xd6, 0x40, 0x77, 0x28, 0xc3, 0xa4, 0x0c,
|
||||
0xd1, 0x47, 0x78, 0xf9, 0xce, 0xe4, 0x22, 0xec, 0x68, 0x3f, 0x34, 0xe3, 0xa0, 0x23, 0x42, 0xcc,
|
||||
0x35, 0x50, 0x2a, 0x34, 0xa5, 0xc3, 0x0b, 0x77, 0xa6, 0xb1, 0x00, 0x53, 0xf7, 0x86, 0x08, 0x94,
|
||||
0x72, 0x99, 0x88, 0xc6, 0x07, 0x18, 0x2b, 0xb0, 0xd9, 0xd2, 0x1d, 0xea, 0x5c, 0x96, 0x14, 0x25,
|
||||
0x70, 0xd8, 0x02, 0xb6, 0xc7, 0xa2, 0xae, 0x9e, 0x89, 0x87, 0xb9, 0x9f, 0xad, 0xd6, 0xc6, 0x8a,
|
||||
0xb2, 0x53, 0x8f, 0xfb, 0x3d, 0x4b, 0x21, 0xd3, 0xa1, 0x43, 0x88, 0xef, 0x16, 0x20, 0x19, 0xa2,
|
||||
0x6c, 0x36, 0xc4, 0xfd, 0x17, 0x0c, 0xad, 0x30, 0xef, 0xfc, 0x6c, 0xe8, 0x2c, 0x3a, 0x55, 0x18,
|
||||
0x00, 0x8a, 0x15, 0x46, 0xd6, 0x36, 0x03, 0xb6, 0x8f, 0xb9, 0x86, 0x29, 0x1f, 0x9e, 0xc2, 0x89,
|
||||
0xa2, 0x71, 0x49, 0x64, 0xc7, 0xa6, 0x70, 0x80, 0x00, 0x4c, 0x5d, 0x7c, 0x22, 0x6b, 0xdd, 0x0e,
|
||||
0x2d, 0x17, 0xab, 0xe6, 0xf8, 0x75, 0x8b, 0xd2, 0x5d, 0x2d, 0x40, 0xd6, 0xea, 0x1b, 0x4f, 0xca,
|
||||
0x02, 0x2e, 0x98, 0x16, 0x99, 0xdb, 0x14, 0x67, 0x90, 0xd6, 0x8f, 0xbf, 0xc6, 0x4d, 0xd2, 0x92,
|
||||
0xd2, 0x7b, 0x37, 0x5c, 0x60, 0x7b, 0x78, 0x90, 0x47, 0x73, 0x0a, 0xda, 0x4d, 0xa5, 0x31, 0x51,
|
||||
0x0c, 0xb6, 0x88, 0x93, 0x37, 0x4e, 0x39, 0x5c, 0x06, 0x90, 0x49, 0xd7, 0x48, 0x67, 0x60, 0xfc,
|
||||
0x9f, 0x40, 0xaf, 0x50, 0x67, 0xc0, 0xf5, 0xb4, 0xab, 0xac, 0xa1, 0x1c, 0x95, 0xd8, 0x57, 0x15,
|
||||
0x7d, 0xe8, 0xa7, 0x7f, 0x1a, 0xad, 0x64, 0x7d, 0xa9, 0x3d, 0x38, 0xa6, 0x06, 0xc2, 0x5a, 0x46,
|
||||
0xae, 0x07, 0x53, 0x97, 0x68, 0x6c, 0xc5, 0xf8, 0x2a, 0xb4, 0x86, 0x8e, 0x9a, 0x7b, 0x48, 0x51,
|
||||
0xb4, 0x76, 0x8d, 0x9e, 0x6d, 0x47, 0xa8, 0x55, 0x39, 0x73, 0x1d, 0x35, 0x7c, 0xd2, 0xc1, 0x6a,
|
||||
0x22, 0x91, 0x59, 0x4d, 0xaa, 0x69, 0x11, 0xdf, 0xf3, 0x4f, 0x41, 0x04, 0xff, 0xb4, 0x5d, 0x42,
|
||||
0x42, 0x73, 0x07, 0xc4, 0xfc, 0xac, 0xa4, 0x98, 0x40, 0x24, 0x1f, 0x0a, 0x86, 0xda, 0x06 };
|
||||
|
||||
|
||||
std::ofstream ofs("license.dat", std::ofstream::binary);
|
||||
ofs.write((const char*)encrypted, sizeof(encrypted));
|
||||
} */
|
||||
|
||||
SecByteBlock key(sizeof(password));
|
||||
key.Assign(password, sizeof(password));
|
||||
|
||||
std::string encrypted = readBinaryFile(m_licenseFile);
|
||||
if (std::size(encrypted) < initializationVectorSize)
|
||||
{
|
||||
throw std::runtime_error("Invalid license file");
|
||||
}
|
||||
|
||||
std::string recoveredData;
|
||||
|
||||
GCM<AES>::Decryption d;
|
||||
d.SetKeyWithIV(key, key.size(), (const CryptoPP::byte*)encrypted.data(), initializationVectorSize);
|
||||
|
||||
AuthenticatedDecryptionFilter df(d,
|
||||
new StringSink(recoveredData),
|
||||
AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
|
||||
AuthenticatedDecryptionFilter::THROW_EXCEPTION, macTagSize
|
||||
); // AuthenticatedDecryptionFilter
|
||||
|
||||
// The StringSource dtor will be called immediately
|
||||
// after construction below. This will cause the
|
||||
// destruction of objects it owns. To stop the
|
||||
// behavior so we can get the decoding result from
|
||||
// the DecryptionFilter, we must use a redirector
|
||||
// or manually Put(...) into the filter without
|
||||
// using a StringSource.
|
||||
StringSource ss2((const CryptoPP::byte*)encrypted.data() + initializationVectorSize, encrypted.size() - initializationVectorSize, true,
|
||||
new Redirector(df /*, PASS_EVERYTHING */)
|
||||
); // StringSource
|
||||
|
||||
if (!df.GetLastResult())
|
||||
{
|
||||
throw std::runtime_error("Unable to decrypt data");
|
||||
}
|
||||
|
||||
boost::iostreams::array_source src{ recoveredData.data(), recoveredData.size() };
|
||||
boost::iostreams::filtering_istream is;
|
||||
boost::iostreams::zlib_params zlibParams;
|
||||
zlibParams.noheader = true;
|
||||
is.push(boost::iostreams::zlib_decompressor{zlibParams});
|
||||
is.push(src);
|
||||
|
||||
SignedData signedData;
|
||||
{
|
||||
pt::ptree root;
|
||||
pt::read_json(is, root);
|
||||
deserialize(root, signedData);
|
||||
}
|
||||
|
||||
ECDSA<EC2N, SHA256>::PublicKey pubKey;
|
||||
//CryptoPP::FileSource fs("c:\\work\\ccengine\\openssl\\bin\\ccengine-pub.der", true /*binary*/);
|
||||
CryptoPP::ArraySource arraySource(static_cast<const CryptoPP::byte*>(publicKey), sizeof(publicKey), true);
|
||||
pubKey.Load(arraySource);
|
||||
ECDSA<EC2N, SHA256>::Verifier verifier(pubKey);
|
||||
|
||||
std::string signatureDer;
|
||||
StringSource ss(signedData.signature, true,
|
||||
new HexDecoder(
|
||||
new StringSink(signatureDer)
|
||||
) // HexDecoder
|
||||
); // StringSource
|
||||
|
||||
byte signature[ecdsaSignatureSize] = { 0 };
|
||||
size_t signLength = CryptoPP::DSAConvertSignatureFormat(signature, sizeof(signature), CryptoPP::DSA_P1363,
|
||||
(const CryptoPP::byte*)signatureDer.data(), signatureDer.size(), CryptoPP::DSA_DER);
|
||||
|
||||
bool result = verifier.VerifyMessage((const byte*)signedData.data.data(), signedData.data.size(), signature, signLength);
|
||||
if (!result)
|
||||
{
|
||||
throw std::runtime_error("Signature could not be verified");
|
||||
}
|
||||
|
||||
ActivationData activationData;
|
||||
std::istringstream iss(signedData.data);
|
||||
{
|
||||
pt::ptree root;
|
||||
pt::read_json(iss, root);
|
||||
deserialize(root, activationData);
|
||||
}
|
||||
|
||||
if (!validateActivationData(activationData))
|
||||
{
|
||||
throw std::runtime_error("You system is not genuine. Please contact support!");
|
||||
}
|
||||
|
||||
m_activationData = std::move(activationData);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool LicenseClient::validateActivationData(const ActivationData & activationData)
|
||||
{
|
||||
if (activationData.systemParams.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (activationData.appId != appId)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// activation parameters must match system parameters
|
||||
for (const auto& entry : activationData.systemParams)
|
||||
{
|
||||
auto it = m_systemParams.find(entry.first);
|
||||
if (it == m_systemParams.end() || it->second != entry.second)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@ -1,44 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "HTTPClient.h"
|
||||
#include "ModuleUpdate.h"
|
||||
#include "SystemParamsProvider.h"
|
||||
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
struct ActivationData
|
||||
{
|
||||
std::string activationId;
|
||||
std::string appId;
|
||||
SystemParams systemParams;
|
||||
std::set<std::string> licensedModules;
|
||||
};
|
||||
|
||||
std::optional<std::string> validateLicenseKey(const std::string& licenseKey);
|
||||
|
||||
class LicenseClient
|
||||
{
|
||||
public:
|
||||
explicit LicenseClient(SystemParamsProvider& systemParamsProvider, const std::string& licenseFile);
|
||||
virtual ~LicenseClient();
|
||||
|
||||
public:
|
||||
void init();
|
||||
bool isActivated() const { return m_activationData.has_value(); }
|
||||
bool tryPreactivate(HTTPClient &httpClient);
|
||||
bool activate(HTTPClient &httpClient, const std::string& licenseNumber );
|
||||
auto licensedModules() { if (!isActivated()) { throw std::runtime_error("Not active"); } return m_activationData->licensedModules; }
|
||||
std::vector<ModuleUpdate> checkForUpdates(HTTPClient &httpClient, const std::map<std::string, ModuleVersion>& currentVersions);
|
||||
|
||||
private:
|
||||
bool loadActivationData();
|
||||
bool validateActivationData(const ActivationData& activationData);
|
||||
|
||||
private:
|
||||
SystemParamsProvider& m_systemParamsProvider;
|
||||
SystemParams m_systemParams;
|
||||
std::string m_licenseFile;
|
||||
std::optional<ActivationData> m_activationData;
|
||||
};
|
||||
@ -1,153 +0,0 @@
|
||||
#include "ModuleManager.h"
|
||||
|
||||
#include "HashUtils.h"
|
||||
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
|
||||
void ModuleManager::applyUpdate(const std::string & moduleId, const ModuleUpdate & update)
|
||||
{
|
||||
auto module = m_db.findModule(moduleId).value_or(Module{ moduleId, -1 , {} });
|
||||
|
||||
applyUpdate(module, update);
|
||||
|
||||
m_db.storeModule(module);
|
||||
}
|
||||
|
||||
void ModuleManager::applyUpdate(Module & module, const ModuleUpdate & update)
|
||||
{
|
||||
const auto updatePath = retrieveUpdate(update.updateUri);
|
||||
|
||||
auto hash = calcSHA256(updatePath);
|
||||
if (hash != boost::algorithm::to_upper_copy(update.checksum))
|
||||
{
|
||||
throw std::runtime_error("Integrity check of the update has failed");
|
||||
}
|
||||
|
||||
if (!(update.flag & static_cast<uint32_t>(ModuleUpdateFlags::incremental)))
|
||||
{
|
||||
// We should remove old files first before extracting new ones
|
||||
boost::filesystem::path basePath(m_appBaseDir);
|
||||
std::for_each(module.filePaths.begin(), module.filePaths.end(), [&basePath](const auto& filePath)
|
||||
{
|
||||
boost::filesystem::remove(basePath / filePath);
|
||||
});
|
||||
module.filePaths.clear();
|
||||
}
|
||||
|
||||
auto filePaths = extractUpdate(updatePath, update.instPath);
|
||||
|
||||
module.version = update.version;
|
||||
|
||||
module.filePaths.insert(filePaths.begin(), filePaths.end());
|
||||
}
|
||||
|
||||
boost::filesystem::path ModuleManager::retrieveUpdate(const std::string & updateUrl)
|
||||
{
|
||||
auto tmpFile = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
|
||||
std::ofstream os(tmpFile.string(), std::ofstream::binary);
|
||||
m_httpClient.get(updateUrl, os);
|
||||
return tmpFile;
|
||||
}
|
||||
|
||||
#include <zip.h>
|
||||
#include <stdio.h>
|
||||
|
||||
std::string zipErrorToStr(int err)
|
||||
{
|
||||
static const int bufsize = 100;
|
||||
char buf[bufsize] = { 0 };
|
||||
zip_error_to_str(buf, bufsize, err, errno);
|
||||
return buf;
|
||||
}
|
||||
|
||||
inline std::set<std::string> ModuleManager::extractUpdate(const boost::filesystem::path& archivePath, const std::string & targetPath)
|
||||
{
|
||||
struct zip_file *zf = nullptr;
|
||||
struct zip_stat sb;
|
||||
int err;
|
||||
boost::filesystem::path basePath(m_appBaseDir);
|
||||
basePath /= targetPath;
|
||||
boost::filesystem::path basePathRel(targetPath);
|
||||
|
||||
if (!boost::filesystem::exists(basePath))
|
||||
{
|
||||
boost::filesystem::create_directories(basePath);
|
||||
}
|
||||
|
||||
if (!boost::filesystem::is_directory(basePath))
|
||||
{
|
||||
throw std::runtime_error("Target path is not a directory");
|
||||
}
|
||||
|
||||
std::set<std::string> extractedFiles;
|
||||
|
||||
struct zip *za = zip_open(archivePath.string().c_str(), 0, &err);
|
||||
if (za == NULL)
|
||||
{
|
||||
throw std::runtime_error(zipErrorToStr(err));
|
||||
}
|
||||
|
||||
char buf[1024] = { 0 };
|
||||
const int numZipEntries = zip_get_num_entries(za, 0);
|
||||
for (int i = 0; i < numZipEntries; ++i)
|
||||
{
|
||||
if (zip_stat_index(za, i, 0, &sb) == 0)
|
||||
{
|
||||
printf("==================\n");
|
||||
auto len = strlen(sb.name);
|
||||
printf("Name: [%s], ", sb.name);
|
||||
printf("Size: [%llu], ", sb.size);
|
||||
printf("mtime: [%u]\n", (unsigned int)sb.mtime);
|
||||
auto outPath = basePath / sb.name;
|
||||
auto outPathRel = basePathRel / sb.name;
|
||||
if (sb.name[len - 1] == '/')
|
||||
{
|
||||
if (!boost::filesystem::is_directory(outPath) && !boost::filesystem::create_directory(outPath))
|
||||
{
|
||||
throw std::runtime_error("Directory can't be extracted");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
zf = zip_fopen_index(za, i, 0);
|
||||
if (!zf)
|
||||
{
|
||||
throw std::runtime_error("Can't open file from the archive");
|
||||
}
|
||||
|
||||
{
|
||||
std::ofstream os(outPath.string(), std::ofstream::binary);
|
||||
|
||||
uint64_t sum = 0;
|
||||
while (sum != sb.size) {
|
||||
auto len = zip_fread(zf, buf, sizeof(buf));
|
||||
if (len < 0) {
|
||||
throw std::runtime_error("Can't read file from the archive");
|
||||
}
|
||||
|
||||
os.write(buf, len);
|
||||
sum += len;
|
||||
}
|
||||
}
|
||||
boost::filesystem::last_write_time(outPath, sb.mtime);
|
||||
extractedFiles.insert(outPathRel.string());
|
||||
|
||||
zip_fclose(zf);
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw std::runtime_error("Could not get file information from archive");
|
||||
}
|
||||
}
|
||||
|
||||
if (zip_close(za) == -1)
|
||||
{
|
||||
throw std::runtime_error("Can't close the zip archive");
|
||||
}
|
||||
|
||||
return extractedFiles;
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "JSONSerialization.h"
|
||||
#include "IModuleDatabase.h"
|
||||
#include "ModuleUpdate.h"
|
||||
#include "HTTPClient.h"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
|
||||
class ModuleManager
|
||||
{
|
||||
public:
|
||||
ModuleManager(const std::string& appBaseDir, IModuleDatabase& db, HTTPClient& httpClient)
|
||||
: m_appBaseDir(appBaseDir)
|
||||
, m_db(db)
|
||||
, m_httpClient(httpClient)
|
||||
{}
|
||||
|
||||
public:
|
||||
void applyUpdate(const std::string& moduleId, const ModuleUpdate& update);
|
||||
|
||||
private:
|
||||
void applyUpdate(Module& module, const ModuleUpdate& update);
|
||||
|
||||
boost::filesystem::path retrieveUpdate(const std::string& updateUrl);
|
||||
|
||||
std::set<std::string> extractUpdate(const boost::filesystem::path& archivePath, const std::string& targetPath);
|
||||
|
||||
private:
|
||||
std::string m_appBaseDir;
|
||||
IModuleDatabase & m_db;
|
||||
HTTPClient& m_httpClient;
|
||||
};
|
||||
@ -1,31 +0,0 @@
|
||||
#include "ModuleUpdate.h"
|
||||
|
||||
#include "JSONSerialization.h"
|
||||
|
||||
void serialize(std::ostream& os, const ModuleUpdate& u)
|
||||
{
|
||||
os << "{";
|
||||
os << "moduleId:";
|
||||
::serialize(os, u.moduleId);
|
||||
os << ",updatePath:";
|
||||
::serialize(os, u.updateUri);
|
||||
os << ",instPath:";
|
||||
::serialize(os, u.instPath);
|
||||
os << ",version:";
|
||||
::serialize(os, u.version);
|
||||
os << ",checksum:";
|
||||
::serialize(os, u.checksum);
|
||||
os << ",flag:";
|
||||
::serialize(os, u.flag);
|
||||
os << "}";
|
||||
}
|
||||
|
||||
void deserialize(const boost::property_tree::ptree& tree, ModuleUpdate& u)
|
||||
{
|
||||
::deserialize(tree.get_child("moduleId"), u.moduleId);
|
||||
::deserialize(tree.get_child("updateUri"), u.updateUri);
|
||||
::deserialize(tree.get_child("instPath"), u.instPath);
|
||||
::deserialize(tree.get_child("version"), u.version);
|
||||
::deserialize(tree.get_child("checksum"), u.checksum);
|
||||
::deserialize(tree.get_child("flag"), u.flag);
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ModuleVersion.h"
|
||||
|
||||
#include <boost/property_tree/ptree.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <ostream>
|
||||
|
||||
enum class ModuleUpdateFlags : uint32_t
|
||||
{
|
||||
defaultValue = 0,
|
||||
incremental = 1,
|
||||
restartRequired = 2
|
||||
};
|
||||
|
||||
struct ModuleUpdate
|
||||
{
|
||||
std::string moduleId;
|
||||
std::string updateUri;
|
||||
std::string instPath;
|
||||
ModuleVersion version;
|
||||
std::string checksum;
|
||||
int flag;
|
||||
};
|
||||
|
||||
void serialize(std::ostream& os, const ModuleUpdate& a);
|
||||
void deserialize(const boost::property_tree::ptree& tree, ModuleUpdate& a);
|
||||
@ -1,3 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
typedef int ModuleVersion;
|
||||
@ -1,7 +0,0 @@
|
||||
#include "SystemParams.h"
|
||||
|
||||
const std::string SystemParamTypes::biosSerialNum{ "biosSerialNum" };
|
||||
const std::string SystemParamTypes::computerUUID{ "computerUUID" };
|
||||
const std::string SystemParamTypes::diskSerialNum{ "diskSerialNum" };
|
||||
const std::string SystemParamTypes::osId{ "osId" };
|
||||
const std::string SystemParamTypes::nicMac{ "nicMac" };
|
||||
@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
struct SystemParamTypes
|
||||
{
|
||||
static const std::string biosSerialNum;
|
||||
static const std::string computerUUID;
|
||||
static const std::string diskSerialNum;
|
||||
static const std::string osId;
|
||||
static const std::string nicMac;
|
||||
};
|
||||
|
||||
typedef std::map<std::string, std::string> SystemParams;
|
||||
@ -1,8 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef WIN32
|
||||
|
||||
#include "SystemParamsProvider_win.h"
|
||||
typedef SystemParamsProvider_win SystemParamsProvider;
|
||||
|
||||
#endif // WIN32
|
||||
@ -1,382 +0,0 @@
|
||||
#include "SystemParamsProvider_win.h"
|
||||
|
||||
#define _WIN32_DCOM
|
||||
#include <comdef.h>
|
||||
#include <Wbemidl.h>
|
||||
|
||||
#include <boost/algorithm/string/join.hpp>
|
||||
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
#pragma comment(lib, "wbemuuid.lib")
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string convertWCSToMBS(const wchar_t* pstr, long wslen)
|
||||
{
|
||||
int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);
|
||||
|
||||
std::string dblstr(len, '\0');
|
||||
len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
|
||||
pstr, wslen /* not necessary NULL-terminated */,
|
||||
&dblstr[0], len,
|
||||
NULL, NULL /* no default char */);
|
||||
|
||||
return dblstr;
|
||||
}
|
||||
|
||||
std::string convertBSTRToMBS(BSTR bstr)
|
||||
{
|
||||
int wslen = ::SysStringLen(bstr);
|
||||
return convertWCSToMBS((wchar_t*)bstr, wslen);
|
||||
}
|
||||
|
||||
BSTR convertMBSToBSTR(const std::string& str)
|
||||
{
|
||||
int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
|
||||
str.data(), str.length(),
|
||||
NULL, 0);
|
||||
|
||||
BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
|
||||
::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
|
||||
str.data(), str.length(),
|
||||
wsdata, wslen);
|
||||
return wsdata;
|
||||
}
|
||||
|
||||
class QuerySink final : public IWbemObjectSink
|
||||
{
|
||||
public:
|
||||
typedef std::vector<std::string> Fields_type;
|
||||
typedef std::vector<std::vector<std::string>> Result_type;
|
||||
|
||||
public:
|
||||
QuerySink(const std::string& wmiClass, const Fields_type& fields)
|
||||
: m_wmiClass(wmiClass)
|
||||
, m_fields(fields)
|
||||
{
|
||||
m_lRef = 0;
|
||||
m_bDone = false;
|
||||
InitializeCriticalSection(&m_threadLock);
|
||||
}
|
||||
~QuerySink() {
|
||||
m_bDone = true;
|
||||
DeleteCriticalSection(&m_threadLock);
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
virtual ULONG STDMETHODCALLTYPE AddRef() override
|
||||
{
|
||||
return InterlockedIncrement(&m_lRef);
|
||||
}
|
||||
|
||||
virtual ULONG STDMETHODCALLTYPE Release() override
|
||||
{
|
||||
LONG lRef = InterlockedDecrement(&m_lRef);
|
||||
if (lRef == 0)
|
||||
delete this;
|
||||
return lRef;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override
|
||||
{
|
||||
if (riid == IID_IUnknown || riid == IID_IWbemObjectSink)
|
||||
{
|
||||
*ppv = (IWbemObjectSink *)this;
|
||||
AddRef();
|
||||
return WBEM_S_NO_ERROR;
|
||||
}
|
||||
else return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE Indicate(
|
||||
LONG lObjectCount,
|
||||
IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
|
||||
) override
|
||||
{
|
||||
std::vector<std::vector<std::string>> result;
|
||||
|
||||
for (int i = 0; i < lObjectCount; i++)
|
||||
{
|
||||
std::vector<std::string> lineResult;
|
||||
lineResult.reserve(m_fields.size());
|
||||
for (const auto& field : m_fields)
|
||||
{
|
||||
HRESULT hres = S_OK;
|
||||
VARIANT varName;
|
||||
hres = apObjArray[i]->Get(convertMBSToBSTR(field),
|
||||
0, &varName, 0, 0);
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
std::ostringstream ostr;
|
||||
ostr << "Failed to get the data from the query. Error code = 0x"
|
||||
<< std::hex << hres;
|
||||
std::cerr << ostr.str() << std::endl;
|
||||
return WBEM_E_FAILED; // Program has failed.
|
||||
}
|
||||
|
||||
lineResult.push_back(convertBSTRToMBS(V_BSTR(&varName)));
|
||||
}
|
||||
|
||||
result.push_back(lineResult);
|
||||
}
|
||||
|
||||
m_resultPromise.set_value(std::move(result));
|
||||
|
||||
return WBEM_S_NO_ERROR;
|
||||
}
|
||||
|
||||
virtual HRESULT STDMETHODCALLTYPE SetStatus(
|
||||
/* [in] */ LONG lFlags,
|
||||
/* [in] */ HRESULT hResult,
|
||||
/* [in] */ BSTR strParam,
|
||||
/* [in] */ IWbemClassObject __RPC_FAR *pObjParam
|
||||
) override
|
||||
{
|
||||
if (lFlags == WBEM_STATUS_COMPLETE)
|
||||
{
|
||||
// Call complete
|
||||
EnterCriticalSection(&m_threadLock);
|
||||
m_bDone = true;
|
||||
LeaveCriticalSection(&m_threadLock);
|
||||
}
|
||||
else if (lFlags == WBEM_STATUS_PROGRESS)
|
||||
{
|
||||
// Call in progress...
|
||||
}
|
||||
|
||||
return WBEM_S_NO_ERROR;
|
||||
}
|
||||
|
||||
std::future<Result_type> getFuture()
|
||||
{
|
||||
return m_resultPromise.get_future();
|
||||
}
|
||||
|
||||
bool IsDone() const
|
||||
{
|
||||
bool done = true;
|
||||
|
||||
EnterCriticalSection(&m_threadLock);
|
||||
done = m_bDone;
|
||||
LeaveCriticalSection(&m_threadLock);
|
||||
|
||||
return done;
|
||||
}
|
||||
|
||||
private:
|
||||
LONG m_lRef;
|
||||
bool m_bDone;
|
||||
mutable CRITICAL_SECTION m_threadLock; // for thread safety
|
||||
const std::string m_wmiClass;
|
||||
const Fields_type m_fields;
|
||||
std::promise<Result_type> m_resultPromise;
|
||||
};
|
||||
}
|
||||
|
||||
namespace detail
|
||||
{
|
||||
class SystemParamsProvider_winImpl final
|
||||
{
|
||||
public:
|
||||
SystemParamsProvider_winImpl()
|
||||
{
|
||||
HRESULT hres = 0;
|
||||
|
||||
// Initialize COM. ------------------------------------------
|
||||
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
|
||||
if (FAILED(hres))
|
||||
{
|
||||
std::ostringstream ostr;
|
||||
ostr << "Failed to initialize COM library. Error code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
// Set general COM security levels --------------------------
|
||||
hres = CoInitializeSecurity(NULL,
|
||||
-1, // COM authentication
|
||||
NULL, // Authentication services
|
||||
NULL, // Reserved
|
||||
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
|
||||
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
|
||||
NULL, // Authentication info
|
||||
EOAC_NONE, // Additional capabilities
|
||||
NULL); // Reserved
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
CoUninitialize();
|
||||
std::ostringstream ostr;
|
||||
ostr << "Failed to initialize security. Error code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
// Obtain the initial locator to WMI -------------------------
|
||||
hres = CoCreateInstance(
|
||||
CLSID_WbemLocator,
|
||||
0,
|
||||
CLSCTX_INPROC_SERVER,
|
||||
IID_IWbemLocator, (LPVOID *)&m_pLoc);
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
CoUninitialize();
|
||||
std::ostringstream ostr;
|
||||
ostr << "Failed to create IWbemLocator object. Err code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
// Connect to WMI through the IWbemLocator::ConnectServer method
|
||||
// Connect to the local root\cimv2 namespace
|
||||
// and obtain pointer pSvc to make IWbemServices calls.
|
||||
hres = m_pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"),
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
&m_pSvc);
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
m_pLoc->Release();
|
||||
CoUninitialize();
|
||||
std::ostringstream ostr;
|
||||
ostr << "Could not connect. Error code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
// Set security levels on the proxy -------------------------
|
||||
hres = CoSetProxyBlanket(m_pSvc, // Indicates the proxy to set
|
||||
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
|
||||
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
|
||||
NULL, // Server principal name
|
||||
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
|
||||
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
|
||||
NULL, // client identity
|
||||
EOAC_NONE); // proxy capabilities
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
m_pSvc->Release();
|
||||
m_pLoc->Release();
|
||||
CoUninitialize();
|
||||
std::ostringstream ostr;
|
||||
ostr << "Could not set proxy blanket. Error code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
~SystemParamsProvider_winImpl()
|
||||
{
|
||||
m_pSvc->Release();
|
||||
m_pLoc->Release();
|
||||
CoUninitialize();
|
||||
}
|
||||
|
||||
public:
|
||||
SystemParams retrieveSystemParams()
|
||||
{
|
||||
auto biosFuture = queryWmiInfo("Win32_BIOS", { "SerialNumber" });
|
||||
auto computerSystemProductFuture = queryWmiInfo("Win32_ComputerSystemProduct", { "UUID" });
|
||||
auto diskDriveFuture = queryWmiInfo("Win32_DiskDrive", { "SerialNumber" });
|
||||
auto osFuture = queryWmiInfo("Win32_OperatingSystem", { "SerialNumber" });
|
||||
auto nicFuture = queryWmiInfo("Win32_NetworkAdapter", { "MACAddress" }, "PhysicalAdapter = TRUE");
|
||||
|
||||
SystemParams result;
|
||||
result[SystemParamTypes::biosSerialNum] = processBiosData(biosFuture.get());
|
||||
result[SystemParamTypes::computerUUID] = processComputerSystemProductData(computerSystemProductFuture.get());
|
||||
result[SystemParamTypes::diskSerialNum] = processDiskDrive(diskDriveFuture.get());
|
||||
result[SystemParamTypes::osId] = processOs(osFuture.get());
|
||||
result[SystemParamTypes::nicMac] = processNic(nicFuture.get());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
typedef std::vector<std::vector<std::string>> QueryResult_type;
|
||||
|
||||
private:
|
||||
std::future<QueryResult_type> queryWmiInfo(const std::string& wmiClass, const std::vector<std::string>& fieldNames, const std::string& condition = "")
|
||||
{
|
||||
HRESULT hres = 0;
|
||||
|
||||
std::ostringstream queryStr;
|
||||
queryStr << "SELECT " << boost::algorithm::join(fieldNames, ",") << " FROM " << wmiClass;
|
||||
|
||||
if (!condition.empty())
|
||||
{
|
||||
queryStr << " WHERE " << condition;
|
||||
}
|
||||
|
||||
// Use the IWbemServices pointer to make requests of WMI ----
|
||||
QuerySink* pResponseSink = new QuerySink(wmiClass, fieldNames);
|
||||
pResponseSink->AddRef();
|
||||
auto resultFuture = pResponseSink->getFuture();
|
||||
hres = m_pSvc->ExecQueryAsync(bstr_t("WQL"),
|
||||
convertMBSToBSTR(queryStr.str()),
|
||||
WBEM_FLAG_BIDIRECTIONAL,
|
||||
NULL,
|
||||
pResponseSink);
|
||||
|
||||
if (FAILED(hres))
|
||||
{
|
||||
pResponseSink->Release();
|
||||
std::ostringstream ostr;
|
||||
ostr << "Query for " << boost::algorithm::join(fieldNames, ", ") << " failed. Error code = 0x" << std::hex << hres;
|
||||
throw std::runtime_error(ostr.str());
|
||||
}
|
||||
|
||||
return resultFuture;
|
||||
}
|
||||
|
||||
static std::string processBiosData(const QueryResult_type& biosInfo)
|
||||
{
|
||||
return biosInfo[0][0];
|
||||
}
|
||||
|
||||
static std::string processComputerSystemProductData(const QueryResult_type& csInfo)
|
||||
{
|
||||
return csInfo[0][0];
|
||||
}
|
||||
|
||||
static std::string processDiskDrive(const QueryResult_type& csInfo)
|
||||
{
|
||||
return csInfo[0][0];
|
||||
}
|
||||
|
||||
static std::string processOs(const QueryResult_type& csInfo)
|
||||
{
|
||||
return csInfo[0][0];
|
||||
}
|
||||
|
||||
static std::string processNic(const QueryResult_type& csInfo)
|
||||
{
|
||||
return csInfo[0][0];
|
||||
}
|
||||
|
||||
private:
|
||||
IWbemLocator* m_pLoc = nullptr;
|
||||
IWbemServices *m_pSvc = nullptr;
|
||||
};
|
||||
}
|
||||
|
||||
SystemParamsProvider_win::SystemParamsProvider_win()
|
||||
: m_impl(std::make_unique<detail::SystemParamsProvider_winImpl>())
|
||||
{
|
||||
}
|
||||
|
||||
SystemParamsProvider_win::~SystemParamsProvider_win()
|
||||
{
|
||||
}
|
||||
|
||||
SystemParams SystemParamsProvider_win::retrieveSystemParams()
|
||||
{
|
||||
return m_impl->retrieveSystemParams();
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "SystemParams.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace detail
|
||||
{
|
||||
class SystemParamsProvider_winImpl;
|
||||
}
|
||||
|
||||
class SystemParamsProvider_win final
|
||||
{
|
||||
public:
|
||||
SystemParamsProvider_win();
|
||||
~SystemParamsProvider_win();
|
||||
|
||||
public:
|
||||
SystemParams retrieveSystemParams();
|
||||
private:
|
||||
std::unique_ptr<detail::SystemParamsProvider_winImpl> m_impl;
|
||||
};
|
||||
BIN
CCEngineLoader/CCEngineLoader.cpp
Normal file
BIN
CCEngineLoader/CCEngineLoader.cpp
Normal file
Binary file not shown.
175
CCEngineLoader/CCEngineLoader.vcxproj
Normal file
175
CCEngineLoader/CCEngineLoader.vcxproj
Normal file
@ -0,0 +1,175 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="15.0" 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>15.0</VCProjectVersion>
|
||||
<ProjectGuid>{450E76A9-E271-4349-9C06-3C0540F9B00F}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<RootNamespace>CCEngineLoader</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>10.0.16299.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>v141</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v141</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v141</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v141</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" />
|
||||
<Import Project="..\..\thirdparty\boost-1.66.0\boost.props" />
|
||||
<Import Project="..\..\thirdparty\cryptopp-6.1.0\cryptopp-static.props" />
|
||||
<Import Project="..\..\thirdparty\curl-7.58.0\curl-static.props" />
|
||||
<Import Project="..\..\thirdparty\libzip-1.4.0\libzip-static.props" />
|
||||
<Import Project="..\..\thirdparty\zlib-1.2.11\zlib-static.props" />
|
||||
</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" />
|
||||
<Import Project="..\..\thirdparty\boost-1.66.0\boost.props" />
|
||||
<Import Project="..\..\thirdparty\cryptopp-6.1.0\cryptopp-static.props" />
|
||||
<Import Project="..\..\thirdparty\curl-7.58.0\curl-static.props" />
|
||||
<Import Project="..\..\thirdparty\libzip-1.4.0\libzip-static.props" />
|
||||
<Import Project="..\..\thirdparty\zlib-1.2.11\zlib-static.props" />
|
||||
</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" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>Use</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<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)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>Use</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>Use</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<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)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>Use</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<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>
|
||||
<ClInclude Include="stdafx.h" />
|
||||
<ClInclude Include="targetver.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="CCEngineLoader.cpp" />
|
||||
<ClCompile Include="stdafx.cpp">
|
||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
|
||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
|
||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
|
||||
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
33
CCEngineLoader/CCEngineLoader.vcxproj.filters
Normal file
33
CCEngineLoader/CCEngineLoader.vcxproj.filters
Normal file
@ -0,0 +1,33 @@
|
||||
<?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;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;hm;inl;inc;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>
|
||||
<ClInclude Include="stdafx.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="targetver.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="stdafx.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="CCEngineLoader.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Loading…
Reference in New Issue
Block a user