commit d142df63664efdf401d4677f17cc467b858b2525 Author: Peter Sykora Date: Tue Mar 27 23:03:06 2018 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ead8b4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/Debug/ +/Release/ +*.vcxproj.user +/test/Debug/ +/test/Release/ diff --git a/api/CachedDownloader.h b/api/CachedDownloader.h new file mode 100644 index 0000000..de5bb99 --- /dev/null +++ b/api/CachedDownloader.h @@ -0,0 +1,26 @@ +#pragma once + +#include "HTTPClient.h" +#include "IDownloader.h" + +#include +#include +#include +#include +#include +#include + +class CachedDownloader : public IDownloader +{ +public: + CachedDownloader(const boost::filesystem::path& cacheDir, HTTPClient& httpClient); + +public: + boost::filesystem::path download(const std::string& url) override; + void clearCache(); + +private: + boost::filesystem::path m_cacheDir; + std::map m_cache; + HTTPClient& m_httpClient; +}; diff --git a/api/CryptoUtils.h b/api/CryptoUtils.h new file mode 100644 index 0000000..6407260 --- /dev/null +++ b/api/CryptoUtils.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include + +std::string base64Decode(const std::string& encoded); +std::string base64Encode(const std::string& source); +std::unique_ptr base64Encode(const uint8_t * source, size_t sourceSize); +std::string base32Decode(const std::string& encoded); +std::string base32Encode(const std::string& data); diff --git a/api/HTTPClient.h b/api/HTTPClient.h new file mode 100644 index 0000000..7d78bba --- /dev/null +++ b/api/HTTPClient.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +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); +}; diff --git a/api/IDownloader.h b/api/IDownloader.h new file mode 100644 index 0000000..a81dc02 --- /dev/null +++ b/api/IDownloader.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include + +class IDownloader +{ +public: + virtual boost::filesystem::path download(const std::string& url) = 0; + +protected: + ~IDownloader() {} +}; diff --git a/api/IModuleDatabase.h b/api/IModuleDatabase.h new file mode 100644 index 0000000..5b234a2 --- /dev/null +++ b/api/IModuleDatabase.h @@ -0,0 +1,27 @@ +#pragma once + +#include "ModuleVersion.h" + +#include + +#include +#include +#include + +struct Module +{ + std::string moduleId; + ModuleVersion version; + std::set filePaths; +}; + +class IModuleDatabase +{ +public: + virtual std::map listModules() = 0; + virtual boost::optional findModule(const std::string& moduleId) = 0; + virtual void storeModule(const Module& module) = 0; + +protected: + ~IModuleDatabase() {} +}; diff --git a/api/JSONModuleDatabase.h b/api/JSONModuleDatabase.h new file mode 100644 index 0000000..a589ae2 --- /dev/null +++ b/api/JSONModuleDatabase.h @@ -0,0 +1,23 @@ +#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 listModules() override; + boost::optional findModule(const std::string& moduleId) override; + void storeModule(const Module& module) override; + +private: + void storeModuleList(const std::map& moduleList); + void updateModuleList(const std::string& moduleId, const ModuleVersion& version); + +private: + std::string m_baseDir; +}; diff --git a/api/JSONSerialization.h b/api/JSONSerialization.h new file mode 100644 index 0000000..2c88c59 --- /dev/null +++ b/api/JSONSerialization.h @@ -0,0 +1,118 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +void serialize(std::ostream& os, const std::string& str); + +template::value, int>::type = 0> +void serialize(std::ostream& os, T intVal) +{ + os << intVal; +} + +template +void serialize(std::ostream& os, const std::vector& 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 +void serialize(std::ostream& os, const std::set& 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 +void serialize(std::ostream& os, const std::map& 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::value, int>::type = 0> +void deserialize(const boost::property_tree::ptree & tree, T& intVal) +{ + intVal = tree.get_value(); +} + +template +void deserialize(const boost::property_tree::ptree& tree, std::vector& 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 +void deserialize(const boost::property_tree::ptree& tree, std::set& 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 +void deserialize(const boost::property_tree::ptree& tree, std::map& 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))); + } +} diff --git a/api/LicenseClient.h b/api/LicenseClient.h new file mode 100644 index 0000000..cfcd5a3 --- /dev/null +++ b/api/LicenseClient.h @@ -0,0 +1,44 @@ +#pragma once + +#include "HTTPClient.h" +#include "ModuleUpdate.h" +#include "SystemParamsProvider.h" + +#include +#include +#include + +struct ActivationData +{ + std::string activationId; + std::string appId; + SystemParams systemParams; + std::set licensedModules; +}; + +std::optional 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 checkForUpdates(HTTPClient &httpClient, const std::map& currentVersions); + +private: + bool loadActivationData(); + bool validateActivationData(const ActivationData& activationData); + +private: + SystemParamsProvider& m_systemParamsProvider; + SystemParams m_systemParams; + std::string m_licenseFile; + std::optional m_activationData; +}; diff --git a/api/ModuleManager.h b/api/ModuleManager.h new file mode 100644 index 0000000..b45e3e6 --- /dev/null +++ b/api/ModuleManager.h @@ -0,0 +1,38 @@ +#pragma once + +#include "IDownloader.h" +#include "IModuleDatabase.h" +#include "JSONSerialization.h" +#include "ModuleUpdate.h" + +#include +#include +#include +#include +#include +#include + +class ModuleManager +{ +public: + ModuleManager(const std::string& appBaseDir, IModuleDatabase& db, IDownloader& downloader) + : m_appBaseDir(appBaseDir) + , m_db(db) + , m_downloader(downloader) + {} + +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 extractUpdate(const boost::filesystem::path& archivePath, const std::string& targetPath); + +private: + std::string m_appBaseDir; + IModuleDatabase & m_db; + IDownloader& m_downloader; +}; diff --git a/api/ModuleUpdate.h b/api/ModuleUpdate.h new file mode 100644 index 0000000..4c53687 --- /dev/null +++ b/api/ModuleUpdate.h @@ -0,0 +1,29 @@ +#pragma once + +#include "ModuleVersion.h" + +#include + +#include +#include + +enum class ModuleUpdateFlags : uint32_t +{ + defaultValue = 0, + incremental = 1, + restartRequired = 2, + computerRebootRequired = 4 +}; + +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); diff --git a/api/ModuleVersion.h b/api/ModuleVersion.h new file mode 100644 index 0000000..3da5b6d --- /dev/null +++ b/api/ModuleVersion.h @@ -0,0 +1,3 @@ +#pragma once + +typedef int ModuleVersion; \ No newline at end of file diff --git a/api/SystemParams.h b/api/SystemParams.h new file mode 100644 index 0000000..56c13cc --- /dev/null +++ b/api/SystemParams.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +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 SystemParams; diff --git a/api/SystemParamsProvider.h b/api/SystemParamsProvider.h new file mode 100644 index 0000000..9533ccc --- /dev/null +++ b/api/SystemParamsProvider.h @@ -0,0 +1,8 @@ +#pragma once + +#ifdef WIN32 + +#include "SystemParamsProvider_win.h" +typedef SystemParamsProvider_win SystemParamsProvider; + +#endif // WIN32 diff --git a/api/SystemParamsProvider_win.h b/api/SystemParamsProvider_win.h new file mode 100644 index 0000000..62ecfae --- /dev/null +++ b/api/SystemParamsProvider_win.h @@ -0,0 +1,23 @@ +#pragma once + +#include "SystemParams.h" + +#include +#include + +namespace detail +{ + class SystemParamsProvider_winImpl; +} + +class SystemParamsProvider_win final +{ +public: + SystemParamsProvider_win(); + ~SystemParamsProvider_win(); + +public: + SystemParams retrieveSystemParams(); +private: + std::unique_ptr m_impl; +}; diff --git a/libLicenseClient.vcxproj b/libLicenseClient.vcxproj new file mode 100644 index 0000000..b7921bd --- /dev/null +++ b/libLicenseClient.vcxproj @@ -0,0 +1,197 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {51345E59-83E5-4389-93A9-0131B40522B7} + Win32Proj + libLicenseClient + 10.0.16299.0 + + + + StaticLibrary + true + v141 + MultiByte + + + StaticLibrary + false + v141 + true + MultiByte + + + StaticLibrary + true + v141 + MultiByte + + + StaticLibrary + false + v141 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + NotUsing + Level3 + Disabled + true + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + stdcpplatest + + + Windows + true + + + + + NotUsing + Level3 + Disabled + true + _DEBUG;_LIB;%(PreprocessorDefinitions) + true + stdcpplatest + + + Windows + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + stdcpplatest + false + false + None + + + Windows + true + true + false + YES + false + + false + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + NDEBUG;_LIB;%(PreprocessorDefinitions) + true + stdcpplatest + + + Windows + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libLicenseClient.vcxproj.filters b/libLicenseClient.vcxproj.filters new file mode 100644 index 0000000..18bc2d3 --- /dev/null +++ b/libLicenseClient.vcxproj.filters @@ -0,0 +1,99 @@ + + + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + api + + + api + + + api + + + api + + + api + + + api + + + api + + + api + + + api + + + api + + + api + + + src + + + api + + + api + + + api + + + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + \ No newline at end of file diff --git a/project-common.props b/project-common.props new file mode 100644 index 0000000..99026f2 --- /dev/null +++ b/project-common.props @@ -0,0 +1,24 @@ + + + + + + + + + + + + + $(ProjectDir)api;%(AdditionalIncludeDirectories) + BOOST_EXCEPTION_DISABLE;%(PreprocessorDefinitions) + %(AdditionalOptions) + + + %(AdditionalLibraryDirectories) + %(AdditionalDependencies) + %(AdditionalOptions) + + + + \ No newline at end of file diff --git a/src/CachedDownloader.cpp b/src/CachedDownloader.cpp new file mode 100644 index 0000000..bfc4cdd --- /dev/null +++ b/src/CachedDownloader.cpp @@ -0,0 +1,89 @@ +#include "CachedDownloader.h" + +namespace +{ + static const std::string cacheListFilename = ".downloadCache"; + + std::map loadCache(const boost::filesystem::path& cacheList) + { + std::map result; + + if (boost::filesystem::is_regular_file(cacheList)) + { + std::ifstream infile(cacheList.native()); + std::string line; + while (std::getline(infile, line)) + { + auto pos = line.find_last_of('|'); + if (pos != std::string::npos) + { + auto url = line.substr(0, pos); + auto localFile = line.substr(pos + 1, std::string::npos); + result[url] = localFile; + } + } + } + + return result; + } + + void addToCache(const boost::filesystem::path& cacheList, const std::string& url, const std::string& file) + { + std::ofstream outfile(cacheList.native(), std::ofstream::app); + outfile << url << "|" << file << std::endl; + } + + void clearCache(const boost::filesystem::path& cacheList) + { + auto cache = loadCache(cacheList); + std::ofstream of(cacheList.native()); + std::for_each(cache.begin(), cache.end(), [](const auto& elm) + { + boost::filesystem::remove(elm.second); + }); + } +} + +CachedDownloader::CachedDownloader(const boost::filesystem::path & cacheDir, HTTPClient & httpClient) + : m_cacheDir(cacheDir) + , m_httpClient(httpClient) +{ + if (!boost::filesystem::exists(m_cacheDir)) + { + boost::filesystem::create_directories(m_cacheDir); + } + + if (!boost::filesystem::is_directory(m_cacheDir)) + { + throw std::runtime_error(".upd folder is not directory"); + } + + m_cache = loadCache(m_cacheDir / cacheListFilename); +} + +boost::filesystem::path CachedDownloader::download(const std::string & url) +{ + auto it = m_cache.find(url); + if (it != m_cache.end()) + { + return m_cacheDir / it->second; + } + else + { + auto fileName = boost::filesystem::unique_path(); + auto tmpFile = m_cacheDir / fileName; + { + std::ofstream os(tmpFile.string(), std::ofstream::binary); + m_httpClient.get(url, os); + } + m_cache[url] = fileName.string(); + addToCache(m_cacheDir / cacheListFilename, url, fileName.string()); + return tmpFile; + } +} + +void CachedDownloader::clearCache() +{ + ::clearCache(m_cacheDir / cacheListFilename); + m_cache.clear(); +} diff --git a/src/CryptoUtils.cpp b/src/CryptoUtils.cpp new file mode 100644 index 0000000..9cb2027 --- /dev/null +++ b/src/CryptoUtils.cpp @@ -0,0 +1,92 @@ +#include "CryptoUtils.h" + +#include +#include + +using CryptoPP::Base64Decoder; +using CryptoPP::Base64Encoder; +using CryptoPP::Base32Decoder; +using CryptoPP::Base32Encoder; +using CryptoPP::StringSource; +using CryptoPP::StringSink; +using CryptoPP::byte; + +namespace +{ + static const byte base32Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +} + +std::string base64Decode(const std::string& encoded) +{ + std::string decoded; + + StringSource ss(encoded, true, + new Base64Decoder( + new StringSink(decoded) + ) + ); + + return decoded; +} + +std::string base64Encode(const std::string& source) +{ + std::string encoded; + + StringSource ss(source, true, + new Base64Encoder( + new StringSink(encoded), + false /* no line breaks */ + ) + ); + + return encoded; +} + +std::unique_ptr base64Encode(const uint8_t* source, size_t sourceSize) +{ + auto encoded = std::make_unique((sourceSize*4/3 + 3) & ~3); + + CryptoPP::ArraySource ss(source, sourceSize, true, + new Base64Encoder( + new CryptoPP::ArraySink(encoded.get(), sourceSize * 4 / 3), + false /* no line breaks */ + ) + ); + + return encoded; +} + +std::string base32Decode(const std::string& encoded) +{ + // Decoder + int lookup[256] = { 0 }; + Base64Decoder::InitializeDecodingLookupArray(lookup, base32Alphabet, 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; + CryptoPP::AlgorithmParameters params = CryptoPP::MakeParameters(CryptoPP::Name::EncodingLookupArray(), (const byte *)base32Alphabet); + encoder.IsolatedInitialize(params); + + std::string encoded; + + encoder.Attach(new StringSink(encoded)); + encoder.Put((const byte*)data.data(), data.size()); + encoder.MessageEnd(); + + return encoded; +} diff --git a/src/HTTPClient.cpp b/src/HTTPClient.cpp new file mode 100644 index 0000000..3eee61c --- /dev/null +++ b/src/HTTPClient.cpp @@ -0,0 +1,312 @@ +#include "HTTPClient.h" + +#include + +#include +#include +#include + +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= 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 conn; + std::unique_ptr extraHeaders; +}; + +DownloadSession initCurlRequest(const std::string& url, std::ostream &os) +{ + DownloadSession result; + CURLcode code; + + std::unique_ptr 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); +} diff --git a/src/HashUtils.cpp b/src/HashUtils.cpp new file mode 100644 index 0000000..0c04388 --- /dev/null +++ b/src/HashUtils.cpp @@ -0,0 +1,44 @@ +#include "HashUtils.h" + +#include +#include +#include + +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; +} + +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::max(); + sum2 = (sum2 + sum1) % std::numeric_limits::max(); + } + + return (sum2 << std::numeric_limits::digits) | sum1; +} diff --git a/src/HashUtils.h b/src/HashUtils.h new file mode 100644 index 0000000..4db241b --- /dev/null +++ b/src/HashUtils.h @@ -0,0 +1,7 @@ +#pragma once + +#include +#include + +std::string calcSHA256(const boost::filesystem::path& file); +uint64_t fletcher64(uint32_t * data, int count); diff --git a/src/JSONModuleDatabase.cpp b/src/JSONModuleDatabase.cpp new file mode 100644 index 0000000..3765d57 --- /dev/null +++ b/src/JSONModuleDatabase.cpp @@ -0,0 +1,117 @@ +#include "JSONModuleDatabase.h" + +#include "JSONSerialization.h" + +#include +#include +#include + +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 JSONModuleDatabase::listModules() +{ + std::map 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 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& 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); +} diff --git a/src/JSONSerialization.cpp b/src/JSONSerialization.cpp new file mode 100644 index 0000000..b74647e --- /dev/null +++ b/src/JSONSerialization.cpp @@ -0,0 +1,15 @@ +#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(); +} diff --git a/src/LicenseClient.cpp b/src/LicenseClient.cpp new file mode 100644 index 0000000..5666c2b --- /dev/null +++ b/src/LicenseClient.cpp @@ -0,0 +1,600 @@ +#include "LicenseClient.h" + +#include "CryptoUtils.h" +#include "HashUtils.h" +#include "JSONSerialization.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include + +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; +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(); +} + +typedef std::string ParamHash; +ParamHash fletcher64(const std::string& input) +{ + std::vector 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; +} + +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(t.tellg())); + t.seekg(0, std::ios::beg); + + str.assign((std::istreambuf_iterator(t)), + std::istreambuf_iterator()); + + 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 licenseFile; +}; + +struct CheckUpdatesRequest +{ + SystemParams systemParams; + std::string activationId; + std::map moduleVersions; +}; + +struct CheckUpdatesResponse +{ + bool success; + std::optional licenseFile; + std::vector 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 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 LicenseClient::checkForUpdates(HTTPClient & httpClient, const std::map& 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::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::PublicKey pubKey; + //CryptoPP::FileSource fs("c:\\work\\ccengine\\openssl\\bin\\ccengine-pub.der", true /*binary*/); + CryptoPP::ArraySource arraySource(static_cast(publicKey), sizeof(publicKey), true); + pubKey.Load(arraySource); + ECDSA::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; +} diff --git a/src/ModuleManager.cpp b/src/ModuleManager.cpp new file mode 100644 index 0000000..a6a7f00 --- /dev/null +++ b/src/ModuleManager.cpp @@ -0,0 +1,150 @@ +#include "ModuleManager.h" + +#include "HashUtils.h" + +#include +#include + +#include +#include + +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(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) +{ + return m_downloader.download(updateUrl); +} + +#include +#include + +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 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 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 auto 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; +} diff --git a/src/ModuleUpdate.cpp b/src/ModuleUpdate.cpp new file mode 100644 index 0000000..9875005 --- /dev/null +++ b/src/ModuleUpdate.cpp @@ -0,0 +1,31 @@ +#include "ModuleUpdate.h" + +#include "JSONSerialization.h" + +void serialize(std::ostream& os, const ModuleUpdate& u) +{ + os << "{"; + os << "\"moduleId\":"; + ::serialize(os, u.moduleId); + os << ",\"updateUri\":"; + ::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); +} diff --git a/src/SystemParams.cpp b/src/SystemParams.cpp new file mode 100644 index 0000000..ebdf1a7 --- /dev/null +++ b/src/SystemParams.cpp @@ -0,0 +1,7 @@ +#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" }; diff --git a/src/SystemParamsProvider_win.cpp b/src/SystemParamsProvider_win.cpp new file mode 100644 index 0000000..d5b6663 --- /dev/null +++ b/src/SystemParamsProvider_win.cpp @@ -0,0 +1,382 @@ +#include "SystemParamsProvider_win.h" + +#define _WIN32_DCOM +#include +#include + +#include + +#include +#include +#include + +#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 Fields_type; + typedef std::vector> 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> result; + + for (int i = 0; i < lObjectCount; i++) + { + std::vector 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 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 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> QueryResult_type; + + private: + std::future queryWmiInfo(const std::string& wmiClass, const std::vector& 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()) +{ +} + +SystemParamsProvider_win::~SystemParamsProvider_win() +{ +} + +SystemParams SystemParamsProvider_win::retrieveSystemParams() +{ + return m_impl->retrieveSystemParams(); +} diff --git a/test/libLicenseClientTest.cpp b/test/libLicenseClientTest.cpp new file mode 100644 index 0000000..7cbb469 Binary files /dev/null and b/test/libLicenseClientTest.cpp differ diff --git a/test/libLicenseClientTest.vcxproj b/test/libLicenseClientTest.vcxproj new file mode 100644 index 0000000..1c4c6bd --- /dev/null +++ b/test/libLicenseClientTest.vcxproj @@ -0,0 +1,172 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 15.0 + {E781AE2E-4A02-4D63-9CAC-1AEBACD9CD73} + Win32Proj + libLicenseClientTest + 10.0.16299.0 + + + + Application + true + v141 + MultiByte + + + Application + false + v141 + true + MultiByte + + + Application + true + v141 + MultiByte + + + Application + false + v141 + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + NotUsing + Level3 + Disabled + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + $(ProjectDir)..\api;%(AdditionalIncludeDirectories) + + + + Console + true + + + + + NotUsing + Level3 + Disabled + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + $(ProjectDir)..\api;%(AdditionalIncludeDirectories) + + + + Console + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + $(ProjectDir)..\api;%(AdditionalIncludeDirectories) + + + + Console + true + true + true + + + + + NotUsing + Level3 + MaxSpeed + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + $(ProjectDir)..\api;%(AdditionalIncludeDirectories) + + + + Console + true + true + true + + + + + + + + + {51345e59-83e5-4389-93a9-0131b40522b7} + + + + + + \ No newline at end of file diff --git a/test/libLicenseClientTest.vcxproj.filters b/test/libLicenseClientTest.vcxproj.filters new file mode 100644 index 0000000..c7e8896 --- /dev/null +++ b/test/libLicenseClientTest.vcxproj.filters @@ -0,0 +1,25 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + src + + + src + + + \ No newline at end of file diff --git a/test/src/JSONSerializationTest.cpp b/test/src/JSONSerializationTest.cpp new file mode 100644 index 0000000..ec12f50 --- /dev/null +++ b/test/src/JSONSerializationTest.cpp @@ -0,0 +1,69 @@ +#include + +#include + +#include "JSONSerialization.h" + +namespace pt = boost::property_tree; + +TEST(JSONSerializationTest, testSerializeInt) +{ + std::ostringstream os; + serialize(os, -4556); + EXPECT_EQ("-4556", os.str()); +} + +TEST(JSONSerializationTest, testSerializeString) +{ + std::ostringstream os; + serialize(os, "testString"); + EXPECT_EQ("\"testString\"", os.str()); +} + +TEST(JSONSerializationTest, testSerializeEmptyVector) +{ + std::ostringstream os; + serialize(os, std::vector{}); + EXPECT_EQ("[]", os.str()); +} + +TEST(JSONSerializationTest, testSerializeVector) +{ + std::ostringstream os; + serialize(os, std::vector{1, 2, 3, 4, 5}); + EXPECT_EQ("[1,2,3,4,5]", os.str()); +} + +TEST(JSONSerializationTest, testSerializeSet) +{ + std::ostringstream os; + serialize(os, std::set{1, 2, 3, 4, 5, 1, 3}); + EXPECT_EQ("[1,2,3,4,5]", os.str()); +} + + +TEST(JSONSerializationTest, testDeserializeInt) +{ + std::istringstream is("3"); + pt::ptree root; + pt::read_json(is, root); + int intVal = 0; + deserialize(root, intVal); + EXPECT_EQ(3, intVal); +} + +TEST(JSONSerializationTest, testDeserializeIntVector) +{ + std::istringstream is("[1,2,3,-4,5,6]"); + pt::ptree root; + pt::read_json(is, root); + std::vector intArr; + deserialize(root, intArr); + EXPECT_EQ(6, intArr.size()); + EXPECT_EQ(1, intArr[0]); + EXPECT_EQ(2, intArr[1]); + EXPECT_EQ(3, intArr[2]); + EXPECT_EQ(-4, intArr[3]); + EXPECT_EQ(5, intArr[4]); + EXPECT_EQ(6, intArr[5]); +}