diff --git a/CrownClient/CrownClient.cpp b/CrownClient/CrownClient.cpp
index 2448088..6cd6322 100644
--- a/CrownClient/CrownClient.cpp
+++ b/CrownClient/CrownClient.cpp
@@ -195,7 +195,8 @@ CrownClient::CrownClient(QWidget *parent)
});
// 显示账号和到期时间
- ui.endtimeLabel->setText("
软件登录账号: " + g_verify->Username() + QString(" 软件到期时间: ") + g_verify->GetDueTime().toString("yyyy-MM-dd hh:MM:ss") + "
");
+ // 到期文案由 Verify 统一拼:永久授权 / 剩余点数 / 到期日期,三种计费各显示各的
+ ui.endtimeLabel->setText("软件登录账号: " + g_verify->Username() + QString(" 软件到期时间: ") + g_verify->DueTimeText() + "
");
@@ -2808,8 +2809,9 @@ void CrownClient::heartbeat()
qDebug() << "心跳失败:" << result;
}
- // 检查授权到期时间
- if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) {
+ // 检查授权到期时间;永久授权和点数计费没有到期日,GetDueTime 是占位日期,不会走到这里
+ QDateTime dueTime = g_verify->GetDueTime();
+ if (dueTime.isValid() && dueTime.msecsTo(QDateTime::currentDateTime()) >= 0) {
QMessageBox::critical(nullptr, "错误", "授权已到期!");
QApplication::quit();
}
diff --git a/CrownClient/CrownClient.vcxproj b/CrownClient/CrownClient.vcxproj
index b2fe081..3eba667 100644
--- a/CrownClient/CrownClient.vcxproj
+++ b/CrownClient/CrownClient.vcxproj
@@ -21,16 +21,16 @@
{C339197A-FFBA-4AE7-81FA-325702162EC1}
QtVS_v304
- 10.0.17763.0
+ 10.0.19041.0
10.0
- 10.0.17763.0
+ 10.0.19041.0
10.0
$(MSBuildProjectDirectory)\QtMsBuild
Application
- v141
+ v142
false
@@ -39,7 +39,7 @@
Application
- v141
+ v142
Application
@@ -105,10 +105,10 @@
/utf-8 %(AdditionalOptions)
- D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories)
+ D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories)
- D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories)
+ D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories)
@@ -119,10 +119,10 @@
/utf-8 %(AdditionalOptions)
- D:\开发工具\VMProtect\Include\C;%(AdditionalIncludeDirectories)
+ D:\reverse\vmprotect33\Include\C;%(AdditionalIncludeDirectories)
- D:\开发工具\VMProtect\Lib\Windows;%(AdditionalLibraryDirectories)
+ D:\reverse\vmprotect33\Lib\Windows;%(AdditionalLibraryDirectories)
diff --git a/CrownClient/Verify.cpp b/CrownClient/Verify.cpp
index 3fbabeb..cc55597 100644
--- a/CrownClient/Verify.cpp
+++ b/CrownClient/Verify.cpp
@@ -1,14 +1,24 @@
#include "Verify.h"
#include "Global.h"
+#pragma comment(lib, "bcrypt.lib")
+
+#include
+#include
+#include
+#include
+#include
+
+// 一次网络请求最多等多久,超时就放弃,别把心跳线程卡死
+#define VERIFY_REQUEST_TIMEOUT 15000
///
/// 构造函数
///
-///
-///
-///
-///
+/// verify 站点地址,如 https://gendan.xyz
+/// 后台「应用 -> AppKey」
+/// 后台「应用 -> EncryptKey」
+/// 客户端版本
Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison)
{
VMProtectBegin("Verify_Init");
@@ -18,13 +28,17 @@ Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison)
m_appId = this->ParamEncrypt(AppId);
m_commKey = this->ParamEncrypt(CommKey);
- m_webApi = this->ParamEncrypt(Url + "/api_new.php?");
+ m_webApi = this->ParamEncrypt(Url);
m_machineCode = this->GetCPUID();
m_version = Verison;
+ // 同一台机器多开时用实例ID区分,服务端拿它做会话粒度
+ m_instanceId = QUuid::createUuid().toString(QUuid::WithoutBraces);
+
+ m_permanent = false;
+ m_balance = 0;
//qDebug() << "验证网址:" << Url;
- //qDebug() << "软件ID:" << AppId;
- //qDebug() << "通信密钥:" << CommKey;
+ //qDebug() << "应用AppKey:" << AppId;
//qDebug() << "软件版本:" << Verison;
//qDebug() << "机器码:" << this->GetCPUID();
VMProtectEnd();
@@ -329,223 +343,440 @@ QString Verify::ParamDecrypt(QString Param)
VMProtectEnd();
}
-
-QString ByteArrayToHexString(QByteArray data) {
- QString ret(data.toHex().toUpper());
- int len = ret.length() / 2;
- //qDebug() << len;
- for (int i = 1; i < len; i++)
+// 后端 crypto.padKey 的等价实现:不足 32 字节循环补齐,超过 32 字节直接截断
+static QByteArray PadAesKey(const QByteArray& Secret)
+{
+ QByteArray key(32, '\0');
+ if (Secret.isEmpty())
{
- //qDebug() << i;
- ret.insert(2 * i + i - 1, " ");
+ return key;
}
-
- return ret;
+ // 后端只有 16/24/32 三种长度会原样使用,这里统一补到 32,跟它 padKey(32) 的结果一致
+ if (Secret.size() != 16 && Secret.size() != 24 && Secret.size() != 32)
+ {
+ for (int i = 0; i < key.size(); ++i)
+ {
+ key[i] = Secret[i % Secret.size()];
+ }
+ return key;
+ }
+ return Secret;
}
-// 发送网络请求
-bool Verify::Send(QString Option, QString Data, QString& Result,bool async)
+// 打开一个 GCM 模式的 AES 算法句柄
+static BCRYPT_ALG_HANDLE OpenAesGcm()
+{
+ BCRYPT_ALG_HANDLE alg = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0)))
+ {
+ return nullptr;
+ }
+ ULONG modeLength = (ULONG)((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t));
+ if (!BCRYPT_SUCCESS(BCryptSetProperty(alg, BCRYPT_CHAINING_MODE,
+ (PUCHAR)BCRYPT_CHAIN_MODE_GCM, modeLength, 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ return nullptr;
+ }
+ return alg;
+}
+
+// AES-256-GCM,输出 nonce(12) || 密文 || tag(16)
+QByteArray Verify::AesGcmEncrypt(const QByteArray& Plain, bool& Ok)
+{
+ VMProtectBegin("Verify_AesEnc");
+ Ok = false;
+
+ QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8());
+ BCRYPT_ALG_HANDLE alg = OpenAesGcm();
+ if (alg == nullptr)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ BCRYPT_KEY_HANDLE keyHandle = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0,
+ (PUCHAR)key.data(), (ULONG)key.size(), 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ const int nonceSize = 12;
+ const int tagSize = 16;
+ QByteArray nonce(nonceSize, '\0');
+ BCryptGenRandom(nullptr, (PUCHAR)nonce.data(), (ULONG)nonce.size(), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
+
+ QByteArray cipher(Plain.size(), '\0');
+ QByteArray tag(tagSize, '\0');
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
+ BCRYPT_INIT_AUTH_MODE_INFO(info);
+ info.pbNonce = (PUCHAR)nonce.data();
+ info.cbNonce = (ULONG)nonce.size();
+ info.pbTag = (PUCHAR)tag.data();
+ info.cbTag = (ULONG)tag.size();
+
+ ULONG written = 0;
+ NTSTATUS status = BCryptEncrypt(keyHandle,
+ (PUCHAR)Plain.data(), (ULONG)Plain.size(),
+ &info, nullptr, 0,
+ (PUCHAR)cipher.data(), (ULONG)cipher.size(), &written, 0);
+
+ BCryptDestroyKey(keyHandle);
+ BCryptCloseAlgorithmProvider(alg, 0);
+
+ if (!BCRYPT_SUCCESS(status) || (int)written != Plain.size())
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ Ok = true;
+ VMProtectEnd();
+ return nonce + cipher + tag;
+}
+
+// AES-256-GCM,输入 nonce(12) || 密文 || tag(16),tag 校验不过直接失败
+QByteArray Verify::AesGcmDecrypt(const QByteArray& Cipher, bool& Ok)
+{
+ VMProtectBegin("Verify_AesDec");
+ Ok = false;
+
+ const int nonceSize = 12;
+ const int tagSize = 16;
+ if (Cipher.size() < nonceSize + tagSize)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8());
+ BCRYPT_ALG_HANDLE alg = OpenAesGcm();
+ if (alg == nullptr)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ BCRYPT_KEY_HANDLE keyHandle = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0,
+ (PUCHAR)key.data(), (ULONG)key.size(), 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ QByteArray nonce = Cipher.left(nonceSize);
+ QByteArray tag = Cipher.right(tagSize);
+ QByteArray body = Cipher.mid(nonceSize, Cipher.size() - nonceSize - tagSize);
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
+ BCRYPT_INIT_AUTH_MODE_INFO(info);
+ info.pbNonce = (PUCHAR)nonce.data();
+ info.cbNonce = (ULONG)nonce.size();
+ info.pbTag = (PUCHAR)tag.data();
+ info.cbTag = (ULONG)tag.size();
+
+ QByteArray plain(body.size(), '\0');
+ ULONG written = 0;
+ NTSTATUS status = BCryptDecrypt(keyHandle,
+ (PUCHAR)body.data(), (ULONG)body.size(),
+ &info, nullptr, 0,
+ (PUCHAR)plain.data(), (ULONG)plain.size(), &written, 0);
+
+ BCryptDestroyKey(keyHandle);
+ BCryptCloseAlgorithmProvider(alg, 0);
+
+ if (!BCRYPT_SUCCESS(status))
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ Ok = true;
+ VMProtectEnd();
+ return plain;
+}
+
+QString Verify::EncryptBody(const QString& Plain, bool& Ok)
+{
+ Ok = true;
+#if VERIFY_ENCRYPT_TYPE == 2
+ QByteArray cipher = AesGcmEncrypt(Plain.toUtf8(), Ok);
+ return Ok ? QString::fromLatin1(cipher.toBase64()) : QString();
+#elif VERIFY_ENCRYPT_TYPE == 1
+ return QString::fromLatin1(RC4(Plain.toUtf8(), ParamDecrypt(m_commKey)).toBase64());
+#else
+ return Plain;
+#endif
+}
+
+QString Verify::DecryptBody(const QString& Cipher, bool& Ok)
+{
+ Ok = true;
+#if VERIFY_ENCRYPT_TYPE == 2
+ QByteArray plain = AesGcmDecrypt(QByteArray::fromBase64(Cipher.toLatin1()), Ok);
+ return Ok ? QString::fromUtf8(plain) : QString();
+#elif VERIFY_ENCRYPT_TYPE == 1
+ return QString::fromUtf8(RC4(QByteArray::fromBase64(Cipher.toLatin1()), ParamDecrypt(m_commKey)));
+#else
+ return Cipher;
+#endif
+}
+
+// 发一个 /api/v1/app/{appKey} 请求
+// 请求体加密后放进 {"data": "..."},响应是 {"data": "..."},解密出来才是 {code,message,data}
+bool Verify::Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data,
+ QString& Result, bool WithToken, const QString& Method)
{
VMProtectBegin("Verify_Send");
- QNetworkAccessManager networkAccessManager;
- // 获取当前时间戳
- QDateTime timeDate = QDateTime::currentDateTime();
- QString timestamp = QString::number(timeDate.toSecsSinceEpoch());
- //qDebug() << "解密:" << ParamDecrypt(m_commKey);
- // 获取签名
- // 转为十六进制文本
- QString PostData;
- PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex());
-
- //qDebug() << "RC4的结果:" << PostData;
- QByteArray PostByte = PostData.toUtf8();
- //qDebug() << "RC4结果:" << PostByte.toHex();
- QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8();
- // 转换为十六进制字符串
-
- QString md5 = this->Md5(SignData);
- // a98d0872e603bc63f04767a14617df64
- //qDebug() << "md5:" << md5;
- QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp;
- //qDebug() << "访问地址:" << strUrl;
- // 网络请求
- QNetworkRequest request;
- // 设置请求地址
- request.setUrl(strUrl);
- // 设置请求头
- // request.setRawHeader("Content-Type", "charset='utf-8'");
- request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'"
- //request.setRawHeader("Content-Type", "application/json");
- // 网络应答
-
- QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8());
- QByteArray responseData;
-
- if (!async)
+ if (WithToken && m_token.isEmpty())
{
- // 事件循环
- QEventLoop eventLoop;
- // 连接信号和槽
- connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
- // 开始循环
- eventLoop.exec();
+ Result = "未登录";
+ VMProtectEnd();
+ return false;
}
+ bool ok = false;
+ QString encrypted = EncryptBody(QString::fromUtf8(QJsonDocument(Body).toJson(QJsonDocument::Compact)), ok);
+ if (!ok)
+ {
+ Result = "请求加密失败";
+ VMProtectEnd();
+ return false;
+ }
+
+ QJsonObject envelope;
+ envelope.insert("data", encrypted);
+
+ QNetworkAccessManager networkAccessManager;
+ QNetworkRequest request;
+ request.setUrl(QUrl(ParamDecrypt(m_webApi) + "/api/v1/app/" + ParamDecrypt(m_appId) + Path));
+ // 服务端只在 Content-Type 非空时才解密请求体,这个头不能省
+ request.setRawHeader("Content-Type", "application/json");
+ if (WithToken)
+ {
+ request.setRawHeader("Authorization", ("Bearer " + m_token).toUtf8());
+ }
+
+ QNetworkReply* reply = (Method == "GET")
+ ? networkAccessManager.get(request)
+ : networkAccessManager.post(request, QJsonDocument(envelope).toJson(QJsonDocument::Compact));
+
+ QTimer timer;
+ timer.setSingleShot(true);
+ QEventLoop eventLoop;
+ connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
+ connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
+ timer.start(VERIFY_REQUEST_TIMEOUT);
+ eventLoop.exec();
+
+ if (!reply->isFinished())
+ {
+ reply->abort();
+ reply->deleteLater();
+ Result = "请求超时";
+ VMProtectEnd();
+ return false;
+ }
- //错误处理
if (reply->error() != QNetworkReply::NoError)
{
- qDebug() << "Request protobufHttp handle errors here";
- QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
- // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档
- qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
- qDebug(qPrintable(reply->errorString()));
+ Result = "网络错误: " + reply->errorString();
reply->deleteLater();
- return "";
+ VMProtectEnd();
+ return false;
}
- //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey));
- //QString strReply = reply->readAll();
- QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey));
- //qDebug() << "访问结果:" << result.toStdString().c_str();
+ QByteArray responseData = reply->readAll();
reply->deleteLater();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+ QJsonDocument wrapped = QJsonDocument::fromJson(responseData);
+ if (!wrapped.isObject())
{
- qDebug() << "String NULL";;
+ Result = "服务器返回格式错误";
+ VMProtectEnd();
+ return false;
}
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt());
- QString jsonMsg = jsonObject["msg"].toVariant().toString();
- QString jsonData = jsonObject["data"].toVariant().toString();
- QString jsonSign = jsonObject["sign"].toVariant().toString();
- QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString();
- Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey));
- if (!jsonSign.isEmpty())
+ // 应用不存在 / 应用被禁用这类错误在加密中间件之前就返回了,没有 data 信封,是明文
+ QJsonValue payload = wrapped.object().value("data");
+ QString plain;
+ if (payload.isString())
{
- QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8());
- if (verifySign != jsonSign)
+ plain = DecryptBody(payload.toString(), ok);
+ if (!ok)
{
- Result = "数据校验失败";
+ Result = "响应解密失败";
+ VMProtectEnd();
return false;
}
}
- //qDebug() << "解密结果" << jsonObject["msg"].toVariant().toString();;
-
- if (jsonCode == "1")
+ else
{
- return true;
+ plain = QString::fromUtf8(responseData);
}
- Result = jsonObject["msg"].toVariant().toString();
- return false;
+ QJsonDocument response = QJsonDocument::fromJson(plain.toUtf8());
+ if (!response.isObject())
+ {
+ Result = "响应解密失败";
+ VMProtectEnd();
+ return false;
+ }
+
+ QJsonObject jsonObject = response.object();
+ int code = jsonObject.value("code").toVariant().toInt();
+ Result = jsonObject.value("message").toVariant().toString();
+ if (code != 200)
+ {
+ if (Result.isEmpty())
+ {
+ Result = QString("请求失败(%1)").arg(code);
+ }
+ VMProtectEnd();
+ return false;
+ }
+
+ Data = jsonObject.value("data");
VMProtectEnd();
+ return true;
}
+// 登录和心跳返回同一套计费字段:
+// Balance == -1 -> is_permanent
+// billing_type 订阅 -> expiry_at + expiry_timestamp
+// 其他非免费计费 -> balance
+void Verify::ParseBilling(const QJsonObject& Data)
+{
+ m_permanent = false;
+ m_balance = 0;
+
+ if (Data.value("is_permanent").toVariant().toBool())
+ {
+ m_billingMode = "permanent";
+ m_permanent = true;
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+ return;
+ }
+
+ if (Data.contains("expiry_at") || Data.contains("expiry_timestamp"))
+ {
+ m_billingMode = "subscription";
+ // 必须用 expiry_timestamp。服务器按 UTC 格式化 expiry_at,直接拿这个字符串当本地时间
+ // 解析会早 8 个小时,用户会被提前踢下线。expiry_at 只在拿不到时间戳时才兜底
+ qint64 stamp = Data.value("expiry_timestamp").toVariant().toLongLong();
+ if (stamp > 0)
+ {
+ m_dueTime = QDateTime::fromSecsSinceEpoch(stamp);
+ }
+ else
+ {
+ m_dueTime = QDateTime::fromString(Data.value("expiry_at").toVariant().toString(), "yyyy-MM-dd HH:mm:ss");
+ }
+ return;
+ }
+
+ if (Data.contains("balance"))
+ {
+ m_billingMode = "balance";
+ m_balance = Data.value("balance").toVariant().toDouble();
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+ return;
+ }
+
+ // 免费应用没有计费字段,同样不存在到期一说
+ m_billingMode = "free";
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+}
bool Verify::Login(QString Username, QString Password, QString& result)
{
VMProtectBegin("Verify_Login");
+
QJsonObject JsonObject;
JsonObject.insert("username", Username);
JsonObject.insert("password", Password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("login", post_data, result))
+ // 后台把 device_id 当必填项,用机器码顶上,和旧协议的 hardwareCode 一个作用
+ JsonObject.insert("device_id", m_machineCode);
+ JsonObject.insert("device_name", QSysInfo::machineHostName());
+ JsonObject.insert("device_type", "windows");
+ JsonObject.insert("instance_id", m_instanceId);
+
+ QJsonValue data;
+ if (!Request("/login", JsonObject, data, result, false))
{
- //qDebug() << "登录失败:" << result.toStdString().c_str();
- //result = "登录失败";
+ VMProtectEnd();
return false;
}
- //qDebug() << "登录成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+
+ QJsonObject object = data.toObject();
+ m_token = object.value("token").toVariant().toString();
+ if (m_token.isEmpty())
{
- //qDebug() << "String NULL";;
- //result = "登录失败";
+ result = "登录失败:服务端没有返回令牌";
+ VMProtectEnd();
return false;
}
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonTime = jsonObject["expireTime"].toVariant().toString();
- m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss");
+
m_username = Username;
m_password = Password;
- return true;
+ ParseBilling(object);
+
VMProtectEnd();
+ return true;
}
bool Verify::Heartbeat(QString& result)
{
VMProtectBegin("Verify_Heartbeat");
- QJsonObject JsonObject;
- JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("heartbeat", post_data, result))
- {
- //qDebug() << "登录失败:" << result.toStdString().c_str();
- return false;
- }
- //qDebug() << "登录成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
- {
- //qDebug() << "String NULL";;
- return false;
- }
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonTime = jsonObject["expireTime"].toVariant().toString();
- m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss");
- return true;
+ QJsonObject JsonObject;
+ // 心跳的身份信息全在 JWT 里,请求体只需要实例ID
+ JsonObject.insert("instance_id", m_instanceId);
+
+ QJsonValue data;
+ if (!Request("/heartbeat", JsonObject, data, result, true))
+ {
+ VMProtectEnd();
+ return false;
+ }
+
+ ParseBilling(data.toObject());
+
VMProtectEnd();
+ return true;
}
bool Verify::checkUpdate()
{
VMProtectBegin("Verify_Check");
+
QString result;
- QJsonObject JsonObject;
- JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("version", post_data, result))
+ QJsonValue data;
+ if (!Request("/check-update?version=" + QUrl::toPercentEncoding(m_version),
+ QJsonObject(), data, result, false, "GET"))
{
- //qDebug() << "获取版本失败:" << result.toStdString().c_str();
- return false;
+ // 拿不到更新信息就当是最新,别拦着主程序启动
+ VMProtectEnd();
+ return true;
}
- //qDebug() << "获取版本成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+
+ QJsonObject object = data.toObject();
+ QString latest = object.value("latest_version").toVariant().toString();
+ if (!latest.isEmpty())
{
- //qDebug() << "String NULL";;
- return false;
- }
- QJsonObject jsonObject = jsonDocument.object();
- QString version = jsonObject["version"].toVariant().toString();
- //qDebug() << "最新版本:" << version;
- if (m_version == version)
- {
- //qDebug() << "验证结果: 真";
- }
- else
- {
- //qDebug() << "验证结果: 假";
+ VMProtectEnd();
+ return latest == m_version;
}
- return version == m_version;
VMProtectEnd();
+ return !object.value("has_update").toVariant().toBool();
}
QString Verify::Username()
@@ -558,52 +789,114 @@ QDateTime Verify::GetDueTime()
return m_dueTime;
}
+bool Verify::IsPermanent()
+{
+ return m_permanent;
+}
+
+double Verify::Balance()
+{
+ return m_balance;
+}
+
+QString Verify::BillingMode()
+{
+ return m_billingMode;
+}
+
+QString Verify::DueTimeText()
+{
+ if (m_billingMode.isEmpty())
+ {
+ return "未获取";
+ }
+ if (m_billingMode == "permanent")
+ {
+ return "永久授权";
+ }
+ if (m_billingMode == "balance")
+ {
+ return QString("剩余点数: %1").arg(m_balance, 0, 'g', 10);
+ }
+ if (m_billingMode == "free")
+ {
+ return "无到期限制";
+ }
+ return m_dueTime.toString("yyyy-MM-dd HH:mm:ss");
+}
+
+bool Verify::ChangePassword(QString OldPassword, QString NewPassword, QString& result)
+{
+ VMProtectBegin("Verify_ChangePwd");
+
+ QJsonObject JsonObject;
+ JsonObject.insert("username", m_username);
+ JsonObject.insert("old_password", OldPassword);
+ JsonObject.insert("new_password", NewPassword);
+
+ QJsonValue data;
+ bool ok = Request("/change-password", JsonObject, data, result, false);
+ if (ok)
+ {
+ m_password = NewPassword;
+ }
+
+ VMProtectEnd();
+ return ok;
+}
+
+bool Verify::Devices(QJsonArray& list, QString& result)
+{
+ VMProtectBegin("Verify_Devices");
+
+ QJsonValue data;
+ if (!Request("/devices", QJsonObject(), data, result, true, "GET"))
+ {
+ VMProtectEnd();
+ return false;
+ }
+
+ list = data.toArray();
+
+ VMProtectEnd();
+ return true;
+}
+
+bool Verify::UnbindDevice(QString DeviceId, QString& result)
+{
+ VMProtectBegin("Verify_Unbind");
+
+ QJsonObject JsonObject;
+ JsonObject.insert("device_id", DeviceId);
+
+ QJsonValue data;
+ bool ok = Request("/unbind-device", JsonObject, data, result, true);
+
+ VMProtectEnd();
+ return ok;
+}
+
bool Verify::push_msg(QString type, QString app, QString account, QMap order)
{
VMProtectBegin("Verify_Push");
- QString result;
+
QJsonObject JsonObject;
- JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("account", m_machineCode);
JsonObject.insert("type", type);
JsonObject.insert("app", app);
JsonObject.insert("account", account);
+ JsonObject.insert("time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
- // 修复:直接将 QMap 转换为 QJsonObject
QJsonObject orderJson;
for (auto it = order.begin(); it != order.end(); ++it) {
orderJson.insert(it.key(), it.value());
}
JsonObject.insert("order", orderJson);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("push", post_data, result, false))
- {
- //qDebug() << "推送消息失败:" << result.toStdString().c_str();
- return false;
- }
- //qDebug() << "推送成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
- {
- //qDebug() << "String NULL";;
- return false;
- }
- QJsonObject jsonObject = jsonDocument.object();
- QString version = jsonObject["version"].toVariant().toString();
- //qDebug() << "最新版本:" << version;
- if (m_version == version)
- {
- //qDebug() << "验证结果: 真";
- }
- else
- {
- //qDebug() << "验证结果: 假";
- }
+ // 后台没有专门的推送接口,写进云端变量记录:POST /variables/{key}/records
+ QString result;
+ QJsonValue data;
+ bool ok = Request("/variables/" VERIFY_PUSH_VARIABLE_KEY "/records", JsonObject, data, result, true);
- return false;
VMProtectEnd();
+ return ok;
}
diff --git a/CrownClient/Verify.h b/CrownClient/Verify.h
index 8579790..e038199 100644
--- a/CrownClient/Verify.h
+++ b/CrownClient/Verify.h
@@ -2,12 +2,29 @@
#include
#include
#include
+#include
#include
+#include
#include
#include
#include
#include
+#include
+#include
#include
+#include
+
+// 服务端「应用 -> 加密方式」,改后台配置时这里要跟着改
+// 0 = 不加密 1 = RC4 2 = AES-256-GCM
+#define VERIFY_ENCRYPT_TYPE 2
+
+// 订单推送写进哪个云端变量。后台要先建一个 var_type=stream、
+// 写权限包含 app_user 的变量,key 填这里
+#define VERIFY_PUSH_VARIABLE_KEY "order_push"
+
+// 永久授权 / 点数计费拿不到真实到期日,用这个占位,保证主程序的到期判断永远不触发
+#define VERIFY_NO_EXPIRY_DATE QDate(2999, 12, 31)
+
class Verify :public QObject
{
Q_OBJECT
@@ -26,17 +43,42 @@ private:
private:
QString ParamEncrypt(QString Param);
QString ParamDecrypt(QString Param);
- bool Send(QString Option, QString Data, QString& Result, bool async = false);
+ // AES-256-GCM,布局与后端 crypto.encryptAES 一致:nonce(12) || 密文 || tag(16)
+ QByteArray AesGcmEncrypt(const QByteArray& Plain, bool& Ok);
+ QByteArray AesGcmDecrypt(const QByteArray& Cipher, bool& Ok);
+ // 按后台配置的加密方式处理请求体 / 响应体,输入输出都是 base64
+ QString EncryptBody(const QString& Plain, bool& Ok);
+ QString DecryptBody(const QString& Cipher, bool& Ok);
+ // 发一个 /api/v1/app/{appKey} 请求,成功时 Data 是业务 data(可能是对象也可能是数组)
+ bool Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, QString& Result,
+ bool WithToken = true, const QString& Method = "POST");
+ // 登录和心跳返回同一套计费字段,统一解析
+ void ParseBilling(const QJsonObject& Data);
public:
// 登录
bool Login(QString Username, QString Password, QString& result);
// 心跳
bool Heartbeat(QString& result);
- // 检查更新
+ // 检查更新(主程序的更新已交给 Update.exe,这里只在需要时做补充判断)
bool checkUpdate();
// 软件登录账号
QString Username();
+ // 到期时间;永久授权和点数计费没有到期日,返回 2999-12-31
QDateTime GetDueTime();
+ // 是否永久授权
+ bool IsPermanent();
+ // 剩余点数,非点数计费时无意义
+ double Balance();
+ // 计费模式:permanent / subscription / balance / free,未登录时为空
+ QString BillingMode();
+ // 界面上的到期文案,把三种计费模式合并成一句话
+ QString DueTimeText();
+ // 修改密码
+ bool ChangePassword(QString OldPassword, QString NewPassword, QString& result);
+ // 已绑定的设备列表
+ bool Devices(QJsonArray& list, QString& result);
+ // 解绑设备
+ bool UnbindDevice(QString DeviceId, QString& result);
public slots:
// 推送消息
bool push_msg(QString type, QString app, QString account, QMap order);
@@ -44,11 +86,11 @@ public slots:
private:
// 随机密码字符串 非十六进制
QString m_randomeKey;
- // 应用密钥
+ // 应用密钥(verify 后台的 AppKey)
QString m_appId;
- // 通信密钥
+ // 通信密钥(verify 后台的 EncryptKey)
QString m_commKey;
- // 网络接口
+ // 服务地址
QString m_webApi;
// 机器码
QString m_machineCode;
@@ -58,11 +100,18 @@ private:
QString m_username;
// 密码
QString m_password;
-
+ // 登录拿到的 JWT,心跳和云端接口都要带
+ QString m_token;
+ // 实例ID,同一台机器多开时区分进程
+ QString m_instanceId;
private:
// 到期时间
QDateTime m_dueTime;
-
-
-};
\ No newline at end of file
+ // 是否永久授权
+ bool m_permanent;
+ // 剩余点数
+ double m_balance;
+ // 计费模式
+ QString m_billingMode;
+};
diff --git a/CrownClient/main.cpp b/CrownClient/main.cpp
index 7687438..2fba00d 100644
--- a/CrownClient/main.cpp
+++ b/CrownClient/main.cpp
@@ -4,16 +4,65 @@
#include "Login.h"
#include
#include
+#include
+#include
#include "AppInstanceManager.h"
#include "Utils.h"
-#pragma comment(lib,"D:\\开发工具\\VMProtect\\Lib\\Windows\\VMProtectSDK64.lib")
+#pragma comment(lib,"D:\\reverse\\vmprotect33\\Lib\\Windows\\VMProtectSDK64.lib")
#include "StyleLoader.h"
#include "MessageHandle.h"
+namespace {
+// 更新服务应用 AppKey,取自 verify 后台 -> 应用 -> AppKey
+const char* kUpdaterAppKey = "abab3280114bfe824acfdbc6255538fb";
+
+// Update.exe --check-only 的退出码
+const int kUpdaterNoUpdate = 0; // 已是最新版本
+const int kUpdaterHasUpdate = 1; // 有更新
+const int kUpdaterFailed = 2; // 检查失败(网络/解密/解析异常)
+const int kUpdaterBadVersion = 3; // 服务端版本表里没有当前版本,只能整包重装
+
+// 静默检查更新。返回 true 表示主程序可以继续往下走(进入登录),
+// false 表示已经把更新交给 Update.exe,主程序应当退出
+bool CheckAndRunUpdater()
+{
+ const QString appDir = QCoreApplication::applicationDirPath();
+ const QString updater = appDir + "/Update.exe";
+ if (!QFileInfo::exists(updater)) {
+ return true; // 没有更新器就保持原有行为
+ }
+
+ const QString exeName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
+ const int code = QProcess::execute(updater, QStringList()
+ << "--check-only"
+ << "--app-key" << kUpdaterAppKey
+ << "--version" << VERSION);
+
+ if (code == kUpdaterNoUpdate || code == kUpdaterFailed) {
+ // 已经是最新,或者服务器/网络有问题——后者放行,避免把用户挡在门外
+ return true;
+ }
+
+ QStringList args;
+ if (code == kUpdaterBadVersion) {
+ // 服务端不认识当前版本,补丁包无从生成,直接整包覆盖安装到程序所在目录
+ args << "--app-key" << kUpdaterAppKey << "--dir" << appDir;
+ } else {
+ // 常规补丁包更新
+ args << "--app-key" << kUpdaterAppKey << "--version" << VERSION
+ << "--dir" << appDir;
+ }
+ args << "--launch" << exeName;
+
+ QProcess::startDetached(updater, args, appDir);
+ return false;
+}
+
+}
int main(int argc, char *argv[])
@@ -76,23 +125,19 @@ int main(int argc, char *argv[])
// 初始化配置类
g_config = new Config();
- // 初始化验证类
- g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION);
+ // 初始化验证类(AppKey 和 EncryptKey 都取自 verify 后台的应用配置)
+ g_verify = new Verify("https://gendan.xyz", "abab3280114bfe824acfdbc6255538fb",
+ "07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14", VERSION);
- // 检测更新
- if (g_verify->checkUpdate())
+ // 检测更新(由 Update.exe 走 verify 新版接口静默检查)
+ if (CheckAndRunUpdater())
{
Login w;
w.show();
return app.exec();
}
- else
- {
- QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe");
- QApplication::quit();
- }
return 0;
}
diff --git a/CrownServer/CrownServer.cpp b/CrownServer/CrownServer.cpp
index 0591566..8784408 100644
--- a/CrownServer/CrownServer.cpp
+++ b/CrownServer/CrownServer.cpp
@@ -154,7 +154,7 @@ CrownServer::CrownServer(QWidget* parent)
ui.endtimeLabel->setText(
QString("软件登录账号: %1 软件到期时间: %2
")
.arg(g_verify->Username())
- .arg(g_verify->GetDueTime().toString("yyyy-MM-dd hh:mm:ss"))
+ .arg(g_verify->DueTimeText())
);
/////////////////////////////////////////////////////
@@ -1984,8 +1984,9 @@ void CrownServer::heartbeat()
qDebug() << "心跳失败:" << result;
}
- // 检查授权到期时间
- if (g_verify->GetDueTime().msecsTo(QDateTime::currentDateTime()) >= 0) {
+ // 检查授权到期时间;永久授权和点数计费没有到期日,GetDueTime 是占位日期,不会走到这里
+ QDateTime dueTime = g_verify->GetDueTime();
+ if (dueTime.isValid() && dueTime.msecsTo(QDateTime::currentDateTime()) >= 0) {
QMessageBox::critical(nullptr, "错误", "授权已到期!");
QApplication::quit();
}
diff --git a/CrownServer/Verify.cpp b/CrownServer/Verify.cpp
index dc5ab78..cc55597 100644
--- a/CrownServer/Verify.cpp
+++ b/CrownServer/Verify.cpp
@@ -1,30 +1,44 @@
#include "Verify.h"
#include "Global.h"
+
+#pragma comment(lib, "bcrypt.lib")
+
+#include
+#include
+#include
+#include
+#include
+
+// 一次网络请求最多等多久,超时就放弃,别把心跳线程卡死
+#define VERIFY_REQUEST_TIMEOUT 15000
+
///
/// 构造函数
///
-///
-///
-///
-///
+/// verify 站点地址,如 https://gendan.xyz
+/// 后台「应用 -> AppKey」
+/// 后台「应用 -> EncryptKey」
+/// 客户端版本
Verify::Verify(QString Url, QString AppId, QString CommKey, QString Verison)
{
VMProtectBegin("Verify_Init");
- // 初始化网络权限管理类
-
// 获取随机Key
this->m_randomeKey = this->GetRandom(32);
-
+
m_appId = this->ParamEncrypt(AppId);
m_commKey = this->ParamEncrypt(CommKey);
- m_webApi = this->ParamEncrypt(Url + "/api_new.php?");
+ m_webApi = this->ParamEncrypt(Url);
m_machineCode = this->GetCPUID();
m_version = Verison;
+ // 同一台机器多开时用实例ID区分,服务端拿它做会话粒度
+ m_instanceId = QUuid::createUuid().toString(QUuid::WithoutBraces);
+
+ m_permanent = false;
+ m_balance = 0;
//qDebug() << "验证网址:" << Url;
- //qDebug() << "软件ID:" << AppId;
- //qDebug() << "通信密钥:" << CommKey;
+ //qDebug() << "应用AppKey:" << AppId;
//qDebug() << "软件版本:" << Verison;
//qDebug() << "机器码:" << this->GetCPUID();
VMProtectEnd();
@@ -158,7 +172,7 @@ QByteArray Verify::RC4(QByteArray Data, QString Key)
m[j] = temp;
result[x] = Data[x] ^ m[(m[i] + m[j]) & 255];
}
- // qDebug() << "RC4:" << result.toHex();
+ //qDebug() << "RC4:" << result.toHex();
return result;
}
@@ -241,7 +255,7 @@ QString Verify::ParamEncrypt(QString Param)
return paramByteArray.toHex();
VMProtectEnd();
-
+
}
QString Verify::ParamDecrypt(QString Param)
@@ -329,219 +343,440 @@ QString Verify::ParamDecrypt(QString Param)
VMProtectEnd();
}
-
-QString ByteArrayToHexString(QByteArray data) {
- QString ret(data.toHex().toUpper());
- int len = ret.length() / 2;
- for (int i = 1; i < len; i++)
+// 后端 crypto.padKey 的等价实现:不足 32 字节循环补齐,超过 32 字节直接截断
+static QByteArray PadAesKey(const QByteArray& Secret)
+{
+ QByteArray key(32, '\0');
+ if (Secret.isEmpty())
{
- ret.insert(2 * i + i - 1, " ");
+ return key;
}
-
- return ret;
+ // 后端只有 16/24/32 三种长度会原样使用,这里统一补到 32,跟它 padKey(32) 的结果一致
+ if (Secret.size() != 16 && Secret.size() != 24 && Secret.size() != 32)
+ {
+ for (int i = 0; i < key.size(); ++i)
+ {
+ key[i] = Secret[i % Secret.size()];
+ }
+ return key;
+ }
+ return Secret;
}
-// 发送网络请求
-bool Verify::Send(QString Option, QString Data, QString& Result, bool async)
+// 打开一个 GCM 模式的 AES 算法句柄
+static BCRYPT_ALG_HANDLE OpenAesGcm()
+{
+ BCRYPT_ALG_HANDLE alg = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0)))
+ {
+ return nullptr;
+ }
+ ULONG modeLength = (ULONG)((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t));
+ if (!BCRYPT_SUCCESS(BCryptSetProperty(alg, BCRYPT_CHAINING_MODE,
+ (PUCHAR)BCRYPT_CHAIN_MODE_GCM, modeLength, 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ return nullptr;
+ }
+ return alg;
+}
+
+// AES-256-GCM,输出 nonce(12) || 密文 || tag(16)
+QByteArray Verify::AesGcmEncrypt(const QByteArray& Plain, bool& Ok)
+{
+ VMProtectBegin("Verify_AesEnc");
+ Ok = false;
+
+ QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8());
+ BCRYPT_ALG_HANDLE alg = OpenAesGcm();
+ if (alg == nullptr)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ BCRYPT_KEY_HANDLE keyHandle = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0,
+ (PUCHAR)key.data(), (ULONG)key.size(), 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ const int nonceSize = 12;
+ const int tagSize = 16;
+ QByteArray nonce(nonceSize, '\0');
+ BCryptGenRandom(nullptr, (PUCHAR)nonce.data(), (ULONG)nonce.size(), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
+
+ QByteArray cipher(Plain.size(), '\0');
+ QByteArray tag(tagSize, '\0');
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
+ BCRYPT_INIT_AUTH_MODE_INFO(info);
+ info.pbNonce = (PUCHAR)nonce.data();
+ info.cbNonce = (ULONG)nonce.size();
+ info.pbTag = (PUCHAR)tag.data();
+ info.cbTag = (ULONG)tag.size();
+
+ ULONG written = 0;
+ NTSTATUS status = BCryptEncrypt(keyHandle,
+ (PUCHAR)Plain.data(), (ULONG)Plain.size(),
+ &info, nullptr, 0,
+ (PUCHAR)cipher.data(), (ULONG)cipher.size(), &written, 0);
+
+ BCryptDestroyKey(keyHandle);
+ BCryptCloseAlgorithmProvider(alg, 0);
+
+ if (!BCRYPT_SUCCESS(status) || (int)written != Plain.size())
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ Ok = true;
+ VMProtectEnd();
+ return nonce + cipher + tag;
+}
+
+// AES-256-GCM,输入 nonce(12) || 密文 || tag(16),tag 校验不过直接失败
+QByteArray Verify::AesGcmDecrypt(const QByteArray& Cipher, bool& Ok)
+{
+ VMProtectBegin("Verify_AesDec");
+ Ok = false;
+
+ const int nonceSize = 12;
+ const int tagSize = 16;
+ if (Cipher.size() < nonceSize + tagSize)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ QByteArray key = PadAesKey(ParamDecrypt(m_commKey).toUtf8());
+ BCRYPT_ALG_HANDLE alg = OpenAesGcm();
+ if (alg == nullptr)
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ BCRYPT_KEY_HANDLE keyHandle = nullptr;
+ if (!BCRYPT_SUCCESS(BCryptGenerateSymmetricKey(alg, &keyHandle, nullptr, 0,
+ (PUCHAR)key.data(), (ULONG)key.size(), 0)))
+ {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ QByteArray nonce = Cipher.left(nonceSize);
+ QByteArray tag = Cipher.right(tagSize);
+ QByteArray body = Cipher.mid(nonceSize, Cipher.size() - nonceSize - tagSize);
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
+ BCRYPT_INIT_AUTH_MODE_INFO(info);
+ info.pbNonce = (PUCHAR)nonce.data();
+ info.cbNonce = (ULONG)nonce.size();
+ info.pbTag = (PUCHAR)tag.data();
+ info.cbTag = (ULONG)tag.size();
+
+ QByteArray plain(body.size(), '\0');
+ ULONG written = 0;
+ NTSTATUS status = BCryptDecrypt(keyHandle,
+ (PUCHAR)body.data(), (ULONG)body.size(),
+ &info, nullptr, 0,
+ (PUCHAR)plain.data(), (ULONG)plain.size(), &written, 0);
+
+ BCryptDestroyKey(keyHandle);
+ BCryptCloseAlgorithmProvider(alg, 0);
+
+ if (!BCRYPT_SUCCESS(status))
+ {
+ VMProtectEnd();
+ return QByteArray();
+ }
+
+ Ok = true;
+ VMProtectEnd();
+ return plain;
+}
+
+QString Verify::EncryptBody(const QString& Plain, bool& Ok)
+{
+ Ok = true;
+#if VERIFY_ENCRYPT_TYPE == 2
+ QByteArray cipher = AesGcmEncrypt(Plain.toUtf8(), Ok);
+ return Ok ? QString::fromLatin1(cipher.toBase64()) : QString();
+#elif VERIFY_ENCRYPT_TYPE == 1
+ return QString::fromLatin1(RC4(Plain.toUtf8(), ParamDecrypt(m_commKey)).toBase64());
+#else
+ return Plain;
+#endif
+}
+
+QString Verify::DecryptBody(const QString& Cipher, bool& Ok)
+{
+ Ok = true;
+#if VERIFY_ENCRYPT_TYPE == 2
+ QByteArray plain = AesGcmDecrypt(QByteArray::fromBase64(Cipher.toLatin1()), Ok);
+ return Ok ? QString::fromUtf8(plain) : QString();
+#elif VERIFY_ENCRYPT_TYPE == 1
+ return QString::fromUtf8(RC4(QByteArray::fromBase64(Cipher.toLatin1()), ParamDecrypt(m_commKey)));
+#else
+ return Cipher;
+#endif
+}
+
+// 发一个 /api/v1/app/{appKey} 请求
+// 请求体加密后放进 {"data": "..."},响应是 {"data": "..."},解密出来才是 {code,message,data}
+bool Verify::Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data,
+ QString& Result, bool WithToken, const QString& Method)
{
VMProtectBegin("Verify_Send");
- QNetworkAccessManager networkAccessManager;
- // 获取当前时间戳
- QDateTime timeDate = QDateTime::currentDateTime();
- QString timestamp = QString::number(timeDate.toSecsSinceEpoch());
- //qDebug() << "解密:" << ParamDecrypt(m_commKey);
- // 获取签名
-
- // 转为十六进制文本
- QString PostData;
- PostData.append(RC4(Data.toUtf8(), ParamDecrypt(m_commKey)).toHex());
-
- //qDebug() << "RC4的结果:" << PostData;
- QByteArray PostByte = PostData.toUtf8();
- //qDebug() << "RC4结果:" << PostByte.toHex();
- QByteArray SignData = PostByte + timestamp.toUtf8() + ParamDecrypt(m_commKey).toUtf8();
- // 转换为十六进制字符串
-
- QString md5 = this->Md5(SignData);
- // a98d0872e603bc63f04767a14617df64
- //qDebug() << "md5:" << md5;
- QUrl strUrl = ParamDecrypt(m_webApi) + "&mod=" + Option + "&appId=" + this->ParamDecrypt(m_appId) + "&sign=" + md5 + "×tamp=" + timestamp;
- //qDebug() << "访问地址:" << strUrl;
- // 网络请求
- QNetworkRequest request;
- // 设置请求地址
- request.setUrl(strUrl);
- // 设置请求头
- // request.setRawHeader("Content-Type", "charset='utf-8'");
- request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");// "charset='utf-8'"
- //request.setRawHeader("Content-Type", "application/json");
- // 网络应答
-
- QNetworkReply* reply = networkAccessManager.post(request, PostData.toUtf8());
- QByteArray responseData;
- // 事件循环
- if (async)
+ if (WithToken && m_token.isEmpty())
{
-
+ Result = "未登录";
+ VMProtectEnd();
+ return false;
}
+
+ bool ok = false;
+ QString encrypted = EncryptBody(QString::fromUtf8(QJsonDocument(Body).toJson(QJsonDocument::Compact)), ok);
+ if (!ok)
+ {
+ Result = "请求加密失败";
+ VMProtectEnd();
+ return false;
+ }
+
+ QJsonObject envelope;
+ envelope.insert("data", encrypted);
+
+ QNetworkAccessManager networkAccessManager;
+ QNetworkRequest request;
+ request.setUrl(QUrl(ParamDecrypt(m_webApi) + "/api/v1/app/" + ParamDecrypt(m_appId) + Path));
+ // 服务端只在 Content-Type 非空时才解密请求体,这个头不能省
+ request.setRawHeader("Content-Type", "application/json");
+ if (WithToken)
+ {
+ request.setRawHeader("Authorization", ("Bearer " + m_token).toUtf8());
+ }
+
+ QNetworkReply* reply = (Method == "GET")
+ ? networkAccessManager.get(request)
+ : networkAccessManager.post(request, QJsonDocument(envelope).toJson(QJsonDocument::Compact));
+
+ QTimer timer;
+ timer.setSingleShot(true);
QEventLoop eventLoop;
- // 连接信号和槽
+ connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
- // 开始循环
+ timer.start(VERIFY_REQUEST_TIMEOUT);
eventLoop.exec();
- //错误处理
+ if (!reply->isFinished())
+ {
+ reply->abort();
+ reply->deleteLater();
+ Result = "请求超时";
+ VMProtectEnd();
+ return false;
+ }
+
if (reply->error() != QNetworkReply::NoError)
{
- qDebug() << "Request protobufHttp handle errors here";
- QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
- // statusCodeV是HTTP服务器的相应码,reply->error()是Qt定义的错误码,可以参考QT的文档
- qDebug("request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
- qDebug(qPrintable(reply->errorString()));
+ Result = "网络错误: " + reply->errorString();
reply->deleteLater();
- return "";
+ VMProtectEnd();
+ return false;
}
- //RC4(QByteArray::fromHex(数据.toUtf8()), ParamDecrypt(m_commKey));
- //QString strReply = reply->readAll();
- QString result = reply->readAll();//RC4(QByteArray::fromHex(reply->readAll()),ParamDecrypt(m_commKey));
- //qDebug() << "访问结果:" << result.toStdString().c_str();
+ QByteArray responseData = reply->readAll();
reply->deleteLater();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+ QJsonDocument wrapped = QJsonDocument::fromJson(responseData);
+ if (!wrapped.isObject())
{
- //qDebug() << "String NULL";;
+ Result = "服务器返回格式错误";
+ VMProtectEnd();
+ return false;
}
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonCode = jsonObject["code"].toVariant().toString();//QString::number(jsonObject["code"].toInt());
- QString jsonMsg = jsonObject["msg"].toVariant().toString();
- QString jsonData = jsonObject["data"].toVariant().toString();
- QString jsonSign = jsonObject["sign"].toVariant().toString();
- QString jsonTampstamp = jsonObject["timestamp"].toVariant().toString();
- Result = RC4(QByteArray::fromHex(jsonData.toUtf8()), ParamDecrypt(m_commKey));
- if (!jsonSign.isEmpty())
+ // 应用不存在 / 应用被禁用这类错误在加密中间件之前就返回了,没有 data 信封,是明文
+ QJsonValue payload = wrapped.object().value("data");
+ QString plain;
+ if (payload.isString())
{
- QString verifySign = this->Md5(jsonCode.toUtf8() + jsonMsg.toUtf8() + jsonData.toUtf8());
- if (verifySign != jsonSign)
+ plain = DecryptBody(payload.toString(), ok);
+ if (!ok)
{
- Result = "数据校验失败";
+ Result = "响应解密失败";
+ VMProtectEnd();
return false;
}
}
-
- if (jsonCode == "1")
+ else
{
- return true;
+ plain = QString::fromUtf8(responseData);
}
- Result = jsonMsg;
- return false;
+
+ QJsonDocument response = QJsonDocument::fromJson(plain.toUtf8());
+ if (!response.isObject())
+ {
+ Result = "响应解密失败";
+ VMProtectEnd();
+ return false;
+ }
+
+ QJsonObject jsonObject = response.object();
+ int code = jsonObject.value("code").toVariant().toInt();
+ Result = jsonObject.value("message").toVariant().toString();
+ if (code != 200)
+ {
+ if (Result.isEmpty())
+ {
+ Result = QString("请求失败(%1)").arg(code);
+ }
+ VMProtectEnd();
+ return false;
+ }
+
+ Data = jsonObject.value("data");
VMProtectEnd();
+ return true;
}
+// 登录和心跳返回同一套计费字段:
+// Balance == -1 -> is_permanent
+// billing_type 订阅 -> expiry_at + expiry_timestamp
+// 其他非免费计费 -> balance
+void Verify::ParseBilling(const QJsonObject& Data)
+{
+ m_permanent = false;
+ m_balance = 0;
+
+ if (Data.value("is_permanent").toVariant().toBool())
+ {
+ m_billingMode = "permanent";
+ m_permanent = true;
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+ return;
+ }
+
+ if (Data.contains("expiry_at") || Data.contains("expiry_timestamp"))
+ {
+ m_billingMode = "subscription";
+ // 必须用 expiry_timestamp。服务器按 UTC 格式化 expiry_at,直接拿这个字符串当本地时间
+ // 解析会早 8 个小时,用户会被提前踢下线。expiry_at 只在拿不到时间戳时才兜底
+ qint64 stamp = Data.value("expiry_timestamp").toVariant().toLongLong();
+ if (stamp > 0)
+ {
+ m_dueTime = QDateTime::fromSecsSinceEpoch(stamp);
+ }
+ else
+ {
+ m_dueTime = QDateTime::fromString(Data.value("expiry_at").toVariant().toString(), "yyyy-MM-dd HH:mm:ss");
+ }
+ return;
+ }
+
+ if (Data.contains("balance"))
+ {
+ m_billingMode = "balance";
+ m_balance = Data.value("balance").toVariant().toDouble();
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+ return;
+ }
+
+ // 免费应用没有计费字段,同样不存在到期一说
+ m_billingMode = "free";
+ m_dueTime = QDateTime(VERIFY_NO_EXPIRY_DATE, QTime(23, 59, 59));
+}
bool Verify::Login(QString Username, QString Password, QString& result)
{
VMProtectBegin("Verify_Login");
+
QJsonObject JsonObject;
JsonObject.insert("username", Username);
JsonObject.insert("password", Password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("login", post_data, result))
+ // 后台把 device_id 当必填项,用机器码顶上,和旧协议的 hardwareCode 一个作用
+ JsonObject.insert("device_id", m_machineCode);
+ JsonObject.insert("device_name", QSysInfo::machineHostName());
+ JsonObject.insert("device_type", "windows");
+ JsonObject.insert("instance_id", m_instanceId);
+
+ QJsonValue data;
+ if (!Request("/login", JsonObject, data, result, false))
{
- //qDebug() << "登录失败:" << result.toStdString().c_str();
- //result = "登录失败";
+ VMProtectEnd();
return false;
}
- //qDebug() << "登录成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+
+ QJsonObject object = data.toObject();
+ m_token = object.value("token").toVariant().toString();
+ if (m_token.isEmpty())
{
- //qDebug() << "String NULL";;
- result = "登录失败";
+ result = "登录失败:服务端没有返回令牌";
+ VMProtectEnd();
return false;
}
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonTime = jsonObject["expireTime"].toVariant().toString();
- m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss");
+
m_username = Username;
m_password = Password;
- return true;
+ ParseBilling(object);
+
VMProtectEnd();
+ return true;
}
bool Verify::Heartbeat(QString& result)
{
VMProtectBegin("Verify_Heartbeat");
- QJsonObject JsonObject;
- JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("heartbeat", post_data, result))
- {
- //qDebug() << "心跳失败:" << result.toStdString().c_str();
- return false;
- }
- //qDebug() << "登录成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
- {
- //qDebug() << "String NULL";;
- return false;
- }
- QJsonObject jsonObject = jsonDocument.object();
- QString jsonTime = jsonObject["expireTime"].toVariant().toString();
- m_dueTime = QDateTime::fromString(jsonTime, "yyyy-MM-dd hh:mm:ss");
- return true;
+ QJsonObject JsonObject;
+ // 心跳的身份信息全在 JWT 里,请求体只需要实例ID
+ JsonObject.insert("instance_id", m_instanceId);
+
+ QJsonValue data;
+ if (!Request("/heartbeat", JsonObject, data, result, true))
+ {
+ VMProtectEnd();
+ return false;
+ }
+
+ ParseBilling(data.toObject());
+
VMProtectEnd();
+ return true;
}
bool Verify::checkUpdate()
{
VMProtectBegin("Verify_Check");
+
QString result;
- QJsonObject JsonObject;
- JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("hardwareCode", m_machineCode);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("version", post_data, result))
+ QJsonValue data;
+ if (!Request("/check-update?version=" + QUrl::toPercentEncoding(m_version),
+ QJsonObject(), data, result, false, "GET"))
{
- //qDebug() << "获取版本失败:" << result.toStdString().c_str();
- return false;
+ // 拿不到更新信息就当是最新,别拦着主程序启动
+ VMProtectEnd();
+ return true;
}
- //qDebug() << "获取版本成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
+
+ QJsonObject object = data.toObject();
+ QString latest = object.value("latest_version").toVariant().toString();
+ if (!latest.isEmpty())
{
- //qDebug() << "String NULL";;
- return false;
+ VMProtectEnd();
+ return latest == m_version;
}
- QJsonObject jsonObject = jsonDocument.object();
- QString version = jsonObject["version"].toVariant().toString();
- //qDebug() << "最新版本:" << version;
- if (m_version == version)
- {
- //qDebug() << "验证结果: 真";
- }
- else
- {
- //qDebug() << "验证结果: 假";
- }
-
- return version == m_version;
+
VMProtectEnd();
+ return !object.value("has_update").toVariant().toBool();
}
QString Verify::Username()
@@ -554,61 +789,114 @@ QDateTime Verify::GetDueTime()
return m_dueTime;
}
-bool Verify::push_msg(QString type,QString app,QString account,QMap order)
+bool Verify::IsPermanent()
{
- VMProtectBegin("Verify_Push");
- QString result;
+ return m_permanent;
+}
+
+double Verify::Balance()
+{
+ return m_balance;
+}
+
+QString Verify::BillingMode()
+{
+ return m_billingMode;
+}
+
+QString Verify::DueTimeText()
+{
+ if (m_billingMode.isEmpty())
+ {
+ return "未获取";
+ }
+ if (m_billingMode == "permanent")
+ {
+ return "永久授权";
+ }
+ if (m_billingMode == "balance")
+ {
+ return QString("剩余点数: %1").arg(m_balance, 0, 'g', 10);
+ }
+ if (m_billingMode == "free")
+ {
+ return "无到期限制";
+ }
+ return m_dueTime.toString("yyyy-MM-dd HH:mm:ss");
+}
+
+bool Verify::ChangePassword(QString OldPassword, QString NewPassword, QString& result)
+{
+ VMProtectBegin("Verify_ChangePwd");
+
QJsonObject JsonObject;
JsonObject.insert("username", m_username);
- JsonObject.insert("password", m_password);
- JsonObject.insert("account", m_machineCode);
+ JsonObject.insert("old_password", OldPassword);
+ JsonObject.insert("new_password", NewPassword);
+
+ QJsonValue data;
+ bool ok = Request("/change-password", JsonObject, data, result, false);
+ if (ok)
+ {
+ m_password = NewPassword;
+ }
+
+ VMProtectEnd();
+ return ok;
+}
+
+bool Verify::Devices(QJsonArray& list, QString& result)
+{
+ VMProtectBegin("Verify_Devices");
+
+ QJsonValue data;
+ if (!Request("/devices", QJsonObject(), data, result, true, "GET"))
+ {
+ VMProtectEnd();
+ return false;
+ }
+
+ list = data.toArray();
+
+ VMProtectEnd();
+ return true;
+}
+
+bool Verify::UnbindDevice(QString DeviceId, QString& result)
+{
+ VMProtectBegin("Verify_Unbind");
+
+ QJsonObject JsonObject;
+ JsonObject.insert("device_id", DeviceId);
+
+ QJsonValue data;
+ bool ok = Request("/unbind-device", JsonObject, data, result, true);
+
+ VMProtectEnd();
+ return ok;
+}
+
+bool Verify::push_msg(QString type, QString app, QString account, QMap order)
+{
+ VMProtectBegin("Verify_Push");
+
+ QJsonObject JsonObject;
JsonObject.insert("type", type);
JsonObject.insert("app", app);
JsonObject.insert("account", account);
+ JsonObject.insert("time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
- // 修复:直接将 QMap 转换为 QJsonObject
QJsonObject orderJson;
for (auto it = order.begin(); it != order.end(); ++it) {
- if (it.key() == "TEAM_H")
- {
- //qDebug() << "队伍H:" << it.value();
- }
- if (it.key() == "TEAM_C")
- {
- //qDebug() << "队伍C:" << it.value();
- }
orderJson.insert(it.key(), it.value());
}
- //qDebug() << orderJson;
JsonObject.insert("order", orderJson);
- QJsonDocument jsonDoc = QJsonDocument(JsonObject);
- QString post_data = jsonDoc.toJson(QJsonDocument::Compact);
- //qDebug() << "参数:" << post_data.toStdString().c_str();
- if (!Send("push", post_data, result))
- {
- //qDebug() << "推送消息失败:" << result.toStdString().c_str();
- return false;
- }
- //qDebug() << "推送成功:" << result.toStdString().c_str();
- QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toLocal8Bit().data());
- if (jsonDocument.isNull())
- {
- //qDebug() << "String NULL";;
- return false;
- }
- QJsonObject jsonObject = jsonDocument.object();
- QString version = jsonObject["version"].toVariant().toString();
- //qDebug() << "最新版本:" << version;
- if (m_version == version)
- {
- //qDebug() << "验证结果: 真";
- }
- else
- {
- //qDebug() << "验证结果: 假";
- }
+ // 后台没有专门的推送接口,写进云端变量记录:POST /variables/{key}/records
+ QString result;
+ QJsonValue data;
+ bool ok = Request("/variables/" VERIFY_PUSH_VARIABLE_KEY "/records", JsonObject, data, result, true);
- return false;
VMProtectEnd();
+ return ok;
}
diff --git a/CrownServer/Verify.h b/CrownServer/Verify.h
index f5d9c05..e038199 100644
--- a/CrownServer/Verify.h
+++ b/CrownServer/Verify.h
@@ -2,16 +2,33 @@
#include
#include
#include
+#include
#include
+#include
#include
#include
#include
#include
+#include
+#include
#include
+#include
+
+// 服务端「应用 -> 加密方式」,改后台配置时这里要跟着改
+// 0 = 不加密 1 = RC4 2 = AES-256-GCM
+#define VERIFY_ENCRYPT_TYPE 2
+
+// 订单推送写进哪个云端变量。后台要先建一个 var_type=stream、
+// 写权限包含 app_user 的变量,key 填这里
+#define VERIFY_PUSH_VARIABLE_KEY "order_push"
+
+// 永久授权 / 点数计费拿不到真实到期日,用这个占位,保证主程序的到期判断永远不触发
+#define VERIFY_NO_EXPIRY_DATE QDate(2999, 12, 31)
+
class Verify :public QObject
{
Q_OBJECT
-
+
public:
Verify(QString Url, QString AppKey, QString CommKey, QString Verison);
~Verify();
@@ -26,29 +43,54 @@ private:
private:
QString ParamEncrypt(QString Param);
QString ParamDecrypt(QString Param);
- bool Send(QString Option, QString Data, QString& Result, bool async = false);
+ // AES-256-GCM,布局与后端 crypto.encryptAES 一致:nonce(12) || 密文 || tag(16)
+ QByteArray AesGcmEncrypt(const QByteArray& Plain, bool& Ok);
+ QByteArray AesGcmDecrypt(const QByteArray& Cipher, bool& Ok);
+ // 按后台配置的加密方式处理请求体 / 响应体,输入输出都是 base64
+ QString EncryptBody(const QString& Plain, bool& Ok);
+ QString DecryptBody(const QString& Cipher, bool& Ok);
+ // 发一个 /api/v1/app/{appKey} 请求,成功时 Data 是业务 data(可能是对象也可能是数组)
+ bool Request(const QString& Path, const QJsonObject& Body, QJsonValue& Data, QString& Result,
+ bool WithToken = true, const QString& Method = "POST");
+ // 登录和心跳返回同一套计费字段,统一解析
+ void ParseBilling(const QJsonObject& Data);
public:
// 登录
bool Login(QString Username, QString Password, QString& result);
// 心跳
bool Heartbeat(QString& result);
- // 检查更新
+ // 检查更新(主程序的更新已交给 Update.exe,这里只在需要时做补充判断)
bool checkUpdate();
// 软件登录账号
QString Username();
+ // 到期时间;永久授权和点数计费没有到期日,返回 2999-12-31
QDateTime GetDueTime();
+ // 是否永久授权
+ bool IsPermanent();
+ // 剩余点数,非点数计费时无意义
+ double Balance();
+ // 计费模式:permanent / subscription / balance / free,未登录时为空
+ QString BillingMode();
+ // 界面上的到期文案,把三种计费模式合并成一句话
+ QString DueTimeText();
+ // 修改密码
+ bool ChangePassword(QString OldPassword, QString NewPassword, QString& result);
+ // 已绑定的设备列表
+ bool Devices(QJsonArray& list, QString& result);
+ // 解绑设备
+ bool UnbindDevice(QString DeviceId, QString& result);
public slots:
// 推送消息
- bool push_msg(QString type,QString app, QString account, QMap order);
+ bool push_msg(QString type, QString app, QString account, QMap order);
private:
// 随机密码字符串 非十六进制
QString m_randomeKey;
- // 应用密钥
+ // 应用密钥(verify 后台的 AppKey)
QString m_appId;
- // 通信密钥
+ // 通信密钥(verify 后台的 EncryptKey)
QString m_commKey;
- // 网络接口
+ // 服务地址
QString m_webApi;
// 机器码
QString m_machineCode;
@@ -58,13 +100,18 @@ private:
QString m_username;
// 密码
QString m_password;
-
+ // 登录拿到的 JWT,心跳和云端接口都要带
+ QString m_token;
+ // 实例ID,同一台机器多开时区分进程
+ QString m_instanceId;
private:
// 到期时间
QDateTime m_dueTime;
-
-private:
-
-
-};
\ No newline at end of file
+ // 是否永久授权
+ bool m_permanent;
+ // 剩余点数
+ double m_balance;
+ // 计费模式
+ QString m_billingMode;
+};
diff --git a/CrownServer/main.cpp b/CrownServer/main.cpp
index a04f476..5e7cbd4 100644
--- a/CrownServer/main.cpp
+++ b/CrownServer/main.cpp
@@ -7,6 +7,7 @@
#include "Login.h"
#include "Global.h"
#include
+#include
#include
#include
@@ -18,6 +19,56 @@
#include "Utils.h"
#include "StyleLoader.h"
#include "MessageHandle.h"
+
+namespace {
+
+// 更新服务应用 AppKey,取自 verify 后台 -> 应用 -> AppKey
+const char* kUpdaterAppKey = "abab3280114bfe824acfdbc6255538fb";
+
+// Update.exe --check-only 的退出码
+const int kUpdaterNoUpdate = 0; // 已是最新版本
+const int kUpdaterHasUpdate = 1; // 有更新
+const int kUpdaterFailed = 2; // 检查失败(网络/解密/解析异常)
+const int kUpdaterBadVersion = 3; // 服务端版本表里没有当前版本,只能整包重装
+
+// 静默检查更新。返回 true 表示主程序可以继续往下走(进入登录),
+// false 表示已经把更新交给 Update.exe,主程序应当退出
+bool CheckAndRunUpdater()
+{
+ const QString appDir = QCoreApplication::applicationDirPath();
+ const QString updater = appDir + "/Update.exe";
+ if (!QFileInfo::exists(updater)) {
+ return true; // 没有更新器就保持原有行为
+ }
+
+ const QString exeName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
+ const int code = QProcess::execute(updater, QStringList()
+ << "--check-only"
+ << "--app-key" << kUpdaterAppKey
+ << "--version" << VERSION);
+
+ if (code == kUpdaterNoUpdate || code == kUpdaterFailed) {
+ // 已经是最新,或者服务器/网络有问题——后者放行,避免把用户挡在门外
+ return true;
+ }
+
+ QStringList args;
+ if (code == kUpdaterBadVersion) {
+ // 服务端不认识当前版本,补丁包无从生成,直接整包覆盖安装到程序所在目录
+ args << "--app-key" << kUpdaterAppKey << "--dir" << appDir;
+ } else {
+ // 常规补丁包更新
+ args << "--app-key" << kUpdaterAppKey << "--version" << VERSION
+ << "--dir" << appDir;
+ }
+ args << "--launch" << exeName;
+
+ QProcess::startDetached(updater, args, appDir);
+ return false;
+}
+
+}
+
int main(int argc, char* argv[])
{
// 禁用GPU加速(如果黑屏)
@@ -68,23 +119,19 @@ int main(int argc, char* argv[])
// 初始化配置
g_config = new Config();
- // 初始化验证
- g_verify = new Verify("https://gendan.xyz", "72", "NAO87ZGQXTXR1HLFHGL3NSLXD", VERSION);
+ // 初始化验证(AppKey 和 EncryptKey 都取自 verify 后台的应用配置)
+ g_verify = new Verify("https://gendan.xyz", "abab3280114bfe824acfdbc6255538fb",
+ "07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14", VERSION);
- // 检测版本更新
- if (g_verify->checkUpdate())
+ // 检测版本更新(由 Update.exe 走 verify 新版接口静默检查)
+ if (CheckAndRunUpdater())
{
Login w;
w.show();
return a.exec();
}
- else
- {
- QProcess::execute(QCoreApplication::applicationDirPath() + "/Update.exe");
- QApplication::quit();
- }
-
+
return 0;
}
diff --git a/Update/Api.cpp b/Update/Api.cpp
new file mode 100644
index 0000000..9ee8cc3
--- /dev/null
+++ b/Update/Api.cpp
@@ -0,0 +1,171 @@
+#include "Api.h"
+
+#include "Config.h"
+#include "Crypto.h"
+#include "Http.h"
+#include "Json.h"
+#include "Utils.h"
+
+namespace updater {
+
+namespace {
+
+void ParseStringList(const Json& value, std::vector& out) {
+ out.clear();
+ if (value.isArray()) {
+ for (size_t i = 0; i < value.arraySize(); ++i) {
+ std::wstring item = Utils::Utf8ToWide(value[static_cast(i)].stringValue());
+ item = Utils::Trim(item);
+ if (!item.empty()) out.push_back(item);
+ }
+ return;
+ }
+ if (value.isString()) {
+ // 后台把 JSON 数组存成了 text 字段,这里再解析一次
+ std::string raw = value.stringValue();
+ Json parsed;
+ std::string err;
+ if (!raw.empty() && Json::Parse(raw, parsed, err) && parsed.isArray()) {
+ ParseStringList(parsed, out);
+ return;
+ }
+ std::wstring item = Utils::Trim(Utils::Utf8ToWide(raw));
+ if (!item.empty()) out.push_back(item);
+ }
+}
+
+std::wstring ReadString(const Json& obj, const char* key) {
+ if (!obj.isObject()) return std::wstring();
+ return Utils::Utf8ToWide(obj[key].stringValue());
+}
+
+unsigned long long ReadUInt64(const Json& obj, const char* key) {
+ if (!obj.isObject()) return 0;
+ return static_cast(obj[key].intValue(0));
+}
+
+}
+
+std::wstring Api::BuildCheckUpdateUrl(const std::wstring& appKey,
+ const std::wstring& clientVersion) {
+ std::wstring url = std::wstring(UPDATER_SERVER_URL) + L"/api/v1/app/" +
+ Utils::UrlEncode(appKey) + L"/check-update";
+ if (!clientVersion.empty()) {
+ url += L"?version=" + Utils::UrlEncode(clientVersion);
+ }
+ return url;
+}
+
+std::wstring Api::ResolveUrl(const std::wstring& url) {
+ std::wstring trimmed = Utils::Trim(url);
+ if (trimmed.empty()) return std::wstring();
+ if (Utils::IsAbsoluteUrl(trimmed)) return trimmed;
+
+ std::wstring base = UPDATER_SERVER_URL;
+ while (!base.empty() && (base.back() == L'/' || base.back() == L'\\')) base.pop_back();
+ if (trimmed.front() != L'/') trimmed.insert(trimmed.begin(), L'/');
+ return base + trimmed;
+}
+
+Api::Result Api::CheckUpdate(const std::wstring& appKey, const std::wstring& clientVersion) {
+ Result result;
+
+ Http::SetTimeoutSec(UPDATER_TIMEOUT_SEC);
+
+ std::wstring url = BuildCheckUpdateUrl(appKey, clientVersion);
+ HttpResult http;
+ std::wstring err;
+ if (!Http::Get(url, http, err)) {
+ result.error = L"连接服务器失败:" + err;
+ return result;
+ }
+
+ Json root;
+ std::string parseErr;
+ if (!Json::Parse(http.body, root, parseErr)) {
+ result.error = L"服务器返回内容无法解析";
+ return result;
+ }
+
+ // 服务端开启通信加密时,data 是一整段 base64 密文,解密后才是真正的响应
+#if UPDATER_ENCRYPT_TYPE != 0
+ if (root.isObject() && root["data"].isString()) {
+ std::string plain;
+ std::string cryptoErr;
+ std::string key = Utils::WideToUtf8(UPDATER_ENCRYPT_KEY);
+ if (!Crypto::Decrypt(static_cast(UPDATER_ENCRYPT_TYPE), key,
+ root["data"].stringValue(), plain, cryptoErr)) {
+ result.error = L"响应解密失败:" + Utils::Utf8ToWide(cryptoErr);
+ return result;
+ }
+ if (!Json::Parse(plain, root, parseErr)) {
+ result.error = L"服务器返回内容无法解析";
+ return result;
+ }
+ }
+#endif
+
+ result.httpStatus = http.status;
+ result.code = static_cast(root["code"].intValue(0));
+ result.message = Utils::Utf8ToWide(root["message"].stringValue());
+
+ // 业务层失败(如 404 应用不存在、400 版本号参数错误)
+ if (result.code != 200 && result.code != 0) {
+ result.error = result.message.empty() ? L"请求失败" : result.message;
+ return result;
+ }
+
+ // 正常响应字段在 data 里,兼容后台直接把字段放在根上的情况
+ const Json& data = root["data"].isObject() ? root["data"] : root;
+ if (!data.isObject()) {
+ result.error = L"服务器返回内容无法解析";
+ return result;
+ }
+
+ UpdateInfo& info = result.info;
+ info.hasUpdate = data["has_update"].boolValue(false);
+ info.appName = ReadString(data, "app_name");
+ info.currentVersion = ReadString(data, "current_version");
+ info.latestVersion = ReadString(data, "latest_version");
+
+ info.downloadUrl = ResolveUrl(ReadString(data, "download_url"));
+ info.downloadSize = ReadUInt64(data, "file_size");
+ info.downloadHash = ReadString(data, "file_hash");
+
+ info.entryFile = ReadString(data, "entry_file");
+ ParseStringList(data["entry_files"], info.entryFiles);
+ ParseStringList(data["desktop_shortcut_files"], info.desktopShortcutFiles);
+
+ info.updateNotes = ReadString(data, "update_notes");
+ info.changelog = ReadString(data, "changelog");
+ info.updateStrategy = ReadString(data, "update_strategy");
+ info.updateType = ReadString(data, "update_type");
+ info.updateMethod = ReadString(data, "update_method");
+
+ info.isPatch = data["is_patch"].boolValue(false);
+ info.patchUrl = ResolveUrl(ReadString(data, "patch_url"));
+ info.patchSize = ReadUInt64(data, "patch_size");
+ info.patchHash = ReadString(data, "patch_hash");
+
+ info.fullPackageUrl = ResolveUrl(ReadString(data, "full_package_url"));
+ info.fullPackageSize = ReadUInt64(data, "full_package_size");
+ info.fullPackageHash = ReadString(data, "full_package_hash");
+
+ // 补丁包信息缺失时用主下载地址兜底
+ if (info.isPatch && info.patchUrl.empty()) {
+ info.patchUrl = info.downloadUrl;
+ info.patchSize = info.downloadSize;
+ info.patchHash = info.downloadHash;
+ }
+ // 完整包信息缺失时用主下载地址兜底
+ if (info.fullPackageUrl.empty() && !info.isPatch) {
+ info.fullPackageUrl = info.downloadUrl;
+ info.fullPackageSize = info.downloadSize;
+ info.fullPackageHash = info.downloadHash;
+ }
+
+ result.ok = true;
+ return result;
+}
+
+}
diff --git a/Update/Api.h b/Update/Api.h
new file mode 100644
index 0000000..490b031
--- /dev/null
+++ b/Update/Api.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include
+#include
+
+namespace updater {
+
+// check-update 返回的版本信息
+struct UpdateInfo {
+ bool hasUpdate = false;
+
+ std::wstring appName;
+ std::wstring currentVersion;
+ std::wstring latestVersion;
+
+ // 主下载地址:补丁模式下为补丁包,全量模式下为完整包
+ std::wstring downloadUrl;
+ unsigned long long downloadSize = 0;
+ std::wstring downloadHash;
+
+ std::wstring entryFile;
+ std::vector entryFiles;
+ std::vector desktopShortcutFiles;
+
+ std::wstring updateNotes; // Description,简短说明
+ std::wstring changelog; // 详细变更记录
+ std::wstring updateStrategy; // optional / forced
+ std::wstring updateType; // full / patch
+ std::wstring updateMethod; // auto / manual / silent
+
+ bool isPatch = false;
+ std::wstring patchUrl;
+ unsigned long long patchSize = 0;
+ std::wstring patchHash;
+
+ std::wstring fullPackageUrl;
+ unsigned long long fullPackageSize = 0;
+ std::wstring fullPackageHash;
+};
+
+class Api {
+public:
+ struct Result {
+ bool ok = false;
+ std::wstring error; // 失败原因(已本地化)
+ long httpStatus = 0; // HTTP 状态码
+ int code = 0; // 业务 code
+ std::wstring message; // 服务端 message
+ UpdateInfo info;
+ };
+
+ // clientVersion 为空时按“安装器模式”请求,服务端优先返回全量包
+ static Result CheckUpdate(const std::wstring& appKey,
+ const std::wstring& clientVersion);
+
+ static std::wstring BuildCheckUpdateUrl(const std::wstring& appKey,
+ const std::wstring& clientVersion);
+
+ // 把服务端返回的相对路径补全为绝对地址
+ static std::wstring ResolveUrl(const std::wstring& url);
+};
+
+}
diff --git a/Update/Config.h b/Update/Config.h
new file mode 100644
index 0000000..0d8115b
--- /dev/null
+++ b/Update/Config.h
@@ -0,0 +1,81 @@
+#pragma once
+
+// 编译期配置:按实际情况修改下面几个宏后重新编译
+
+// 服务端地址(末尾不要带斜杠)
+#ifndef UPDATER_SERVER_URL
+#define UPDATER_SERVER_URL L"https://gendan.xyz"
+#endif
+
+// 应用 AppKey,取自 verify 后台 -> 应用 -> AppKey
+#ifndef UPDATER_APP_KEY
+#define UPDATER_APP_KEY L"abab3280114bfe824acfdbc6255538fb"
+#endif
+
+// 通信加密方式:0 = 不加密,1 = RC4,2 = AES-256-GCM
+// 取自 verify 后台 -> 应用 -> 安全设置 -> 加密方式
+#ifndef UPDATER_ENCRYPT_TYPE
+#define UPDATER_ENCRYPT_TYPE 2
+#endif
+
+// 通信密钥,取自 verify 后台 -> 应用 -> 安全设置 -> 加密密钥
+// 服务端用 AES-GCM 加密整个响应体,密钥不对会直接解密失败
+#ifndef UPDATER_ENCRYPT_KEY
+#define UPDATER_ENCRYPT_KEY L"07dab7c3c772a8a8f2dad3f45e2e397806d92f560ac954532ee7562a03c1df14"
+#endif
+
+// 窗口标题
+#ifndef UPDATER_TITLE
+#define UPDATER_TITLE L"自动更新"
+#endif
+
+// 更新完成后拉起的程序(相对更新目录),留空则不拉起
+#ifndef UPDATER_LAUNCH_EXE
+#define UPDATER_LAUNCH_EXE L"金运来客户端2.exe"
+#endif
+
+// 应用名称,显示在安装目录选择界面上
+#ifndef UPDATER_APP_NAME
+#define UPDATER_APP_NAME L"金运来皇冠跟单软件"
+#endif
+
+// 完整包安装时建议的默认目录,留空则用更新器自身所在目录
+// (更新器由主程序从自身目录启动,所以默认就是主程序所在目录)
+#ifndef UPDATER_DEFAULT_INSTALL_DIR
+#define UPDATER_DEFAULT_INSTALL_DIR L""
+#endif
+
+// 更新目标目录,留空表示更新器自身所在目录(完整包模式下会先让用户选择)
+#ifndef UPDATER_TARGET_DIR
+#define UPDATER_TARGET_DIR L""
+#endif
+
+// 是否校验下载包的 SHA256(与服务端返回的 file_hash 比对)
+#ifndef UPDATER_VERIFY_HASH
+#define UPDATER_VERIFY_HASH 1
+#endif
+
+// 下载时是否允许使用系统代理
+#ifndef UPDATER_USE_PROXY
+#define UPDATER_USE_PROXY 1
+#endif
+
+// 更新前等待主程序退出的秒数(0 表示不等待)
+#ifndef UPDATER_WAIT_EXIT_SEC
+#define UPDATER_WAIT_EXIT_SEC 10
+#endif
+
+// 网络超时(秒)
+#define UPDATER_TIMEOUT_SEC 30
+
+// 窗口尺寸
+#define UPDATER_WINDOW_WIDTH 860
+#define UPDATER_WINDOW_HEIGHT 480
+
+// 静默检查(--check-only)的退出码,主程序据此决定继续启动还是交给更新器
+#define UPDATER_EXIT_NO_UPDATE 0 // 已是最新,主程序正常往下走
+#define UPDATER_EXIT_HAS_UPDATE 1 // 有更新,主程序拉起更新器后退出
+#define UPDATER_EXIT_FAILED 2 // 检查失败(网络异常/解密失败/解析失败)
+#define UPDATER_EXIT_BAD_VERSION 3 // 服务端不认识这个版本(HTTP 400 版本号参数错误),只能整包重装
+
+// 主程序收到“检查失败”时是否放行由主程序决定(默认放行,避免断网把用户挡在门外)
diff --git a/Update/Crypto.cpp b/Update/Crypto.cpp
new file mode 100644
index 0000000..60be640
--- /dev/null
+++ b/Update/Crypto.cpp
@@ -0,0 +1,209 @@
+#include "Crypto.h"
+
+#define NOMINMAX
+#include
+
+#include
+
+#include
+#include
+
+#pragma comment(lib, "bcrypt.lib")
+
+namespace updater {
+
+std::vector Crypto::PadKey(const std::vector& key, size_t target) {
+ if (key.size() >= target) {
+ return std::vector(key.begin(), key.begin() + target);
+ }
+ std::vector padded(target, 0);
+ for (size_t i = 0; i < target; ++i) padded[i] = key[i % key.size()];
+ return padded;
+}
+
+bool Crypto::Base64Decode(const std::string& input, std::vector& out) {
+ static const int table[256] = {
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
+ 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
+ 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
+ -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
+ 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1
+ };
+
+ out.clear();
+ unsigned int buffer = 0;
+ int bits = 0;
+ for (unsigned char c : input) {
+ int value = table[c];
+ if (value < 0) {
+ if (c == '=' || c == '\r' || c == '\n' || c == ' ' || c == '\t') continue;
+ return false;
+ }
+ buffer = (buffer << 6) | static_cast(value);
+ bits += 6;
+ if (bits >= 8) {
+ bits -= 8;
+ out.push_back(static_cast((buffer >> bits) & 0xFF));
+ }
+ }
+ return true;
+}
+
+std::string Crypto::Base64Encode(const std::vector& input) {
+ static const char* chars =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ std::string out;
+ out.reserve(((input.size() + 2) / 3) * 4);
+ for (size_t i = 0; i < input.size(); i += 3) {
+ unsigned int n = static_cast(input[i]) << 16;
+ if (i + 1 < input.size()) n |= static_cast(input[i + 1]) << 8;
+ if (i + 2 < input.size()) n |= static_cast(input[i + 2]);
+
+ out.push_back(chars[(n >> 18) & 0x3F]);
+ out.push_back(chars[(n >> 12) & 0x3F]);
+ out.push_back((i + 1 < input.size()) ? chars[(n >> 6) & 0x3F] : '=');
+ out.push_back((i + 2 < input.size()) ? chars[n & 0x3F] : '=');
+ }
+ return out;
+}
+
+bool Crypto::DecryptAes(const std::string& key, const std::string& ciphertext, std::string& out,
+ std::string& err) {
+ std::vector data;
+ if (!Base64Decode(ciphertext, data)) {
+ err = "密文 base64 解码失败";
+ return false;
+ }
+ const size_t kNonceSize = 12;
+ const size_t kTagSize = 16;
+ if (data.size() < kNonceSize + kTagSize) {
+ err = "密文长度不足";
+ return false;
+ }
+
+ std::vector keyBytes =
+ PadKey(std::vector(key.begin(), key.end()), 32);
+
+ BCRYPT_ALG_HANDLE alg = nullptr;
+ NTSTATUS status = BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0);
+ if (status < 0) {
+ err = "无法初始化 AES";
+ return false;
+ }
+
+ status = BCryptSetProperty(alg, BCRYPT_CHAINING_MODE,
+ reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)),
+ static_cast((wcslen(BCRYPT_CHAIN_MODE_GCM) + 1) * sizeof(wchar_t)),
+ 0);
+ if (status < 0) {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ err = "无法设置 GCM 模式";
+ return false;
+ }
+
+ // BCRYPT_KEY_DATA_BLOB:magic(4) + version(4) + cbKeyData(4) + key bytes
+ const ULONG kHeaderSize = 12;
+ std::vector blob(kHeaderSize + keyBytes.size(), 0);
+ ULONG magic = 0x4D42444B; // 'KDBM'
+ ULONG version = 1;
+ ULONG keyLen = static_cast(keyBytes.size());
+ memcpy(blob.data(), &magic, sizeof(magic));
+ memcpy(blob.data() + 4, &version, sizeof(version));
+ memcpy(blob.data() + 8, &keyLen, sizeof(keyLen));
+ memcpy(blob.data() + kHeaderSize, keyBytes.data(), keyBytes.size());
+
+ BCRYPT_KEY_HANDLE keyHandle = nullptr;
+ status = BCryptImportKey(alg, nullptr, BCRYPT_KEY_DATA_BLOB, &keyHandle, nullptr, 0,
+ blob.data(), static_cast(blob.size()), 0);
+ if (status < 0) {
+ BCryptCloseAlgorithmProvider(alg, 0);
+ err = "密钥导入失败";
+ return false;
+ }
+
+ // 密文布局:nonce || ciphertext || tag,tag 单独传给 bcrypt,不能算进密文长度
+ size_t cipherLen = data.size() - kNonceSize - kTagSize;
+ std::vector nonce(data.begin(), data.begin() + kNonceSize);
+ std::vector tag(data.end() - kTagSize, data.end());
+ std::vector plain(cipherLen, 0);
+
+ BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
+ BCRYPT_INIT_AUTH_MODE_INFO(info);
+ info.pbNonce = nonce.data();
+ info.cbNonce = static_cast(nonce.size());
+ info.pbTag = tag.data();
+ info.cbTag = static_cast(tag.size());
+
+ ULONG plainLen = 0;
+ status = BCryptDecrypt(keyHandle, data.data() + kNonceSize, static_cast(cipherLen),
+ &info, nullptr, 0, plain.data(), static_cast(plain.size()),
+ &plainLen, 0);
+
+ BCryptDestroyKey(keyHandle);
+ BCryptCloseAlgorithmProvider(alg, 0);
+
+ if (status < 0) {
+ err = "解密失败(密钥不正确或数据被篡改)";
+ return false;
+ }
+
+ out.assign(reinterpret_cast(plain.data()), plainLen);
+ return true;
+}
+
+bool Crypto::DecryptRc4(const std::string& key, const std::string& ciphertext, std::string& out,
+ std::string& err) {
+ std::vector data;
+ if (!Base64Decode(ciphertext, data)) {
+ err = "密文 base64 解码失败";
+ return false;
+ }
+ if (key.empty()) {
+ err = "RC4 密钥为空";
+ return false;
+ }
+
+ unsigned char sbox[256];
+ for (int i = 0; i < 256; ++i) sbox[i] = static_cast(i);
+
+ unsigned char j = 0;
+ for (int i = 0; i < 256; ++i) {
+ j = static_cast(j + sbox[i] + key[i % key.size()]);
+ unsigned char tmp = sbox[i];
+ sbox[i] = sbox[j];
+ sbox[j] = tmp;
+ }
+
+ unsigned char i = 0;
+ j = 0;
+ out.clear();
+ out.reserve(data.size());
+ for (unsigned char c : data) {
+ i = static_cast(i + 1);
+ j = static_cast(j + sbox[i]);
+ unsigned char tmp = sbox[i];
+ sbox[i] = sbox[j];
+ sbox[j] = tmp;
+ out.push_back(static_cast(c ^ sbox[(sbox[i] + sbox[j]) & 0xFF]));
+ }
+ return true;
+}
+
+bool Crypto::Decrypt(EncryptType type, const std::string& key, const std::string& ciphertext,
+ std::string& out, std::string& err) {
+ if (type == EncryptType::None) {
+ out = ciphertext;
+ return true;
+ }
+ if (key.empty()) {
+ err = "未配置通信密钥";
+ return false;
+ }
+ if (type == EncryptType::AES) return DecryptAes(key, ciphertext, out, err);
+ return DecryptRc4(key, ciphertext, out, err);
+}
+
+}
diff --git a/Update/Crypto.h b/Update/Crypto.h
new file mode 100644
index 0000000..976294c
--- /dev/null
+++ b/Update/Crypto.h
@@ -0,0 +1,33 @@
+#pragma once
+
+#include
+#include
+
+namespace updater {
+
+enum class EncryptType {
+ None = 0,
+ RC4 = 1,
+ AES = 2, // AES-256-GCM:12 字节 nonce 前置 + 16 字节 tag
+};
+
+class Crypto {
+public:
+ // 与 Go 端 crypto.padKey 保持一致:不足 target 时循环补齐,超出则截断
+ static std::vector PadKey(const std::vector& key, size_t target);
+
+ static bool Base64Decode(const std::string& input, std::vector& out);
+ static std::string Base64Encode(const std::vector& input);
+
+ // ciphertext 为 base64 字符串,out 为解密后的明文
+ static bool Decrypt(EncryptType type, const std::string& key, const std::string& ciphertext,
+ std::string& out, std::string& err);
+
+private:
+ static bool DecryptAes(const std::string& key, const std::string& ciphertext, std::string& out,
+ std::string& err);
+ static bool DecryptRc4(const std::string& key, const std::string& ciphertext, std::string& out,
+ std::string& err);
+};
+
+}
diff --git a/Update/FileInfo.cpp b/Update/FileInfo.cpp
deleted file mode 100644
index 575a914..0000000
--- a/Update/FileInfo.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-#include "FileInfo.h"
-
-
-bool FileInfo::QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr)
-{
- bool bSuccess = FALSE;
- BYTE *lpVersionData = NULL;
- DWORD dwLangCharset = 0;
- TCHAR *pStr = NULL;
-
- do
- {
- if (wsValueName.empty() || wsModuleName.empty())
- break;
-
- DWORD dwHandle;
- // 判断系统能否检索到指定文件的版本信息
- DWORD dwDataSize = ::GetFileVersionInfoSize((LPCWSTR)wsModuleName.c_str(), &dwHandle);
- if (dwDataSize == 0)
- break;
-
- lpVersionData = new (std::nothrow) BYTE[dwDataSize];// 分配缓冲区
- if (NULL == lpVersionData)
- break;
-
- // 检索信息
- if (!::GetFileVersionInfo((LPCWSTR)wsModuleName.c_str(), dwHandle, dwDataSize, (void*)lpVersionData))
- break;
-
- UINT nQuerySize;
- DWORD *pTransTable;
- // 设置语言
- if (!::VerQueryValue(lpVersionData, L"\\VarFileInfo\\Translation", (void **)&pTransTable, &nQuerySize))
- break;
-
- dwLangCharset = MAKELONG(HIWORD(pTransTable[0]), LOWORD(pTransTable[0]));
- if (lpVersionData == NULL)
- break;
-
- pStr = new (std::nothrow) TCHAR[128];// 分配缓冲区
- if (NULL == pStr)
- break;
-
- //wchar_t str2[MAX_PATH];
- //wcscpy_s(str2, MAX_PATH, wsValueName.c_str());
- swprintf_s(pStr, 128, L"\\StringFileInfo\\%08lx\\%s", dwLangCharset, wsValueName.c_str());
-
- LPVOID lpData;
-
- // 调用此函数查询前需要先依次调用函数GetFileVersionInfoSize和GetFileVersionInfo
- if (::VerQueryValue((void *)lpVersionData, pStr, &lpData, &nQuerySize))
- wsRetStr = (TCHAR *)lpData;
-
- bSuccess = TRUE;
-
- } while (FALSE);
-
- // 销毁缓冲区
- if (lpVersionData)
- {
- delete[] lpVersionData;
- lpVersionData = NULL;
- }
- if (pStr)
- {
- delete[] pStr;
- pStr = NULL;
- }
-
- return bSuccess;
-}
diff --git a/Update/FileInfo.h b/Update/FileInfo.h
deleted file mode 100644
index 3e9d8ad..0000000
--- a/Update/FileInfo.h
+++ /dev/null
@@ -1,21 +0,0 @@
-#pragma once
-#include
-#include
-
-#pragma comment(lib,"Version.lib")
-
-class FileInfo
-{
-public:
- static bool GetFileDescription(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileDescription", szModuleName, RetStr); }
- static bool GetFileVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"FileVersion", szModuleName, RetStr); }
- static bool GetInternalName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"InternalName", szModuleName, RetStr); }
- static bool GetCompanyName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"CompanyName", szModuleName, RetStr); }
- static bool GetLegalCopyright(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"LegalCopyright", szModuleName, RetStr); }
- static bool GetOriginalFilename(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"OriginalFilename", szModuleName, RetStr); }
- static bool GetProductName(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductName", szModuleName, RetStr); }
- static bool GetProductVersion(const std::wstring& szModuleName, std::wstring& RetStr) { return QueryValue(L"ProductVersion", szModuleName, RetStr); }
-
-private:
- static bool QueryValue(const std::wstring wsValueName, const std::wstring wsModuleName, std::wstring &wsRetStr);
-};
diff --git a/Update/Http.cpp b/Update/Http.cpp
new file mode 100644
index 0000000..da092e9
--- /dev/null
+++ b/Update/Http.cpp
@@ -0,0 +1,253 @@
+#include "Http.h"
+
+#include
+
+#include
+#include
+
+#pragma comment(lib, "winhttp.lib")
+
+namespace updater {
+
+int Http::timeoutSec_ = 30;
+
+namespace {
+
+struct UrlParts {
+ std::wstring host;
+ std::wstring path;
+ INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT;
+ bool https = false;
+};
+
+bool CrackUrl(const std::wstring& url, UrlParts& out) {
+ URL_COMPONENTS uc;
+ ZeroMemory(&uc, sizeof(uc));
+ uc.dwStructSize = sizeof(uc);
+ uc.dwSchemeLength = static_cast(-1);
+ uc.dwHostNameLength = static_cast(-1);
+ uc.dwUrlPathLength = static_cast(-1);
+ uc.dwExtraInfoLength = static_cast(-1);
+ if (!WinHttpCrackUrl(url.c_str(), static_cast(url.size()), 0, &uc)) return false;
+
+ out.host.assign(uc.lpszHostName, uc.dwHostNameLength);
+ out.path.assign(uc.lpszUrlPath, uc.dwUrlPathLength);
+ if (uc.dwExtraInfoLength > 0 && uc.lpszExtraInfo) {
+ out.path.append(uc.lpszExtraInfo, uc.dwExtraInfoLength);
+ }
+ if (out.path.empty()) out.path = L"/";
+ out.port = uc.nPort;
+ out.https = uc.nScheme == INTERNET_SCHEME_HTTPS;
+ return true;
+}
+
+std::wstring ResolveUrl(const std::wstring& base, const std::wstring& location) {
+ if (location.empty()) return std::wstring();
+ if (_wcsnicmp(location.c_str(), L"http://", 7) == 0 ||
+ _wcsnicmp(location.c_str(), L"https://", 8) == 0) {
+ return location;
+ }
+ UrlParts parts;
+ if (!CrackUrl(base, parts)) return location;
+ std::wstring scheme = parts.https ? L"https://" : L"http://";
+ std::wstring hostPort = parts.host;
+ if ((parts.https && parts.port != INTERNET_DEFAULT_HTTPS_PORT) ||
+ (!parts.https && parts.port != INTERNET_DEFAULT_HTTP_PORT)) {
+ hostPort += L":" + std::to_wstring(parts.port);
+ }
+ if (location[0] == L'/') return scheme + hostPort + location;
+
+ std::wstring dir = parts.path;
+ size_t pos = dir.find_last_of(L'/');
+ if (pos == std::wstring::npos) dir = L"/";
+ else dir = dir.substr(0, pos + 1);
+ return scheme + hostPort + dir + location;
+}
+
+class Session {
+public:
+ Session() {
+ DWORD access = WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY;
+ hSession_ = WinHttpOpen(L"Updater/1.0", access, WINHTTP_NO_PROXY_NAME,
+ WINHTTP_NO_PROXY_BYPASS, 0);
+ }
+ ~Session() {
+ if (hSession_) WinHttpCloseHandle(hSession_);
+ }
+ bool valid() const { return hSession_ != nullptr; }
+ HINTERNET get() const { return hSession_; }
+
+private:
+ HINTERNET hSession_ = nullptr;
+};
+
+class Request {
+public:
+ Request(HINTERNET session, const std::wstring& url, bool download) {
+ if (!CrackUrl(url, parts_)) return;
+ hConnect_ = WinHttpConnect(session, parts_.host.c_str(), parts_.port, 0);
+ if (!hConnect_) return;
+ DWORD flags = parts_.https ? WINHTTP_FLAG_SECURE : 0;
+ hRequest_ = WinHttpOpenRequest(hConnect_, L"GET", parts_.path.c_str(), nullptr,
+ WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags);
+ if (!hRequest_) return;
+ WinHttpSetTimeouts(hRequest_, Http::TimeoutMs(), Http::TimeoutMs(),
+ Http::TimeoutMs(), Http::TimeoutMs());
+ if (!download) {
+ DWORD disable = WINHTTP_DISABLE_COOKIES;
+ WinHttpSetOption(hRequest_, WINHTTP_OPTION_DISABLE_FEATURE, &disable,
+ sizeof(disable));
+ }
+ opened_ = true;
+ }
+ ~Request() {
+ if (hRequest_) WinHttpCloseHandle(hRequest_);
+ if (hConnect_) WinHttpCloseHandle(hConnect_);
+ }
+ bool opened() const { return opened_; }
+ bool Send() {
+ return WinHttpSendRequest(hRequest_, WINHTTP_NO_REQUEST_DATA, 0,
+ WINHTTP_NO_REQUEST_DATA, 0, 0, 0) != FALSE &&
+ WinHttpReceiveResponse(hRequest_, nullptr) != FALSE;
+ }
+ long Status() {
+ DWORD code = 0;
+ DWORD size = sizeof(code);
+ if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_HEADER_NAME_BY_INDEX, &code, &size,
+ WINHTTP_NO_HEADER_INDEX)) {
+ return static_cast(code);
+ }
+ return 0;
+ }
+ std::wstring Location() {
+ wchar_t buf[4096] = {0};
+ DWORD size = sizeof(buf);
+ if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX,
+ buf, &size, WINHTTP_NO_HEADER_INDEX)) {
+ return std::wstring(buf);
+ }
+ return std::wstring();
+ }
+ unsigned long long ContentLength() {
+ wchar_t buf[64] = {0};
+ DWORD size = sizeof(buf);
+ if (WinHttpQueryHeaders(hRequest_, WINHTTP_QUERY_CONTENT_LENGTH,
+ WINHTTP_HEADER_NAME_BY_INDEX, buf, &size,
+ WINHTTP_NO_HEADER_INDEX)) {
+ return _wcstoui64(buf, nullptr, 10);
+ }
+ return 0;
+ }
+ bool ReadAll(std::string& out) {
+ DWORD available = 0;
+ std::vector chunk(64 * 1024);
+ for (;;) {
+ if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false;
+ if (available == 0) break;
+ if (available > chunk.size()) chunk.resize(available);
+ DWORD read = 0;
+ if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false;
+ if (read == 0) break;
+ out.append(chunk.data(), read);
+ }
+ return true;
+ }
+ bool ReadToFile(HANDLE hFile, Http::ProgressFunc progress, unsigned long long total,
+ unsigned long long& written) {
+ DWORD available = 0;
+ std::vector chunk(64 * 1024);
+ for (;;) {
+ if (!WinHttpQueryDataAvailable(hRequest_, &available)) return false;
+ if (available == 0) break;
+ if (available > chunk.size()) chunk.resize(available);
+ DWORD read = 0;
+ if (!WinHttpReadData(hRequest_, chunk.data(), available, &read)) return false;
+ if (read == 0) break;
+ DWORD done = 0;
+ while (done < read) {
+ DWORD step = 0;
+ if (!WriteFile(hFile, chunk.data() + done, read - done, &step, nullptr)) return false;
+ done += step;
+ }
+ written += read;
+ if (progress && !progress(written, total)) return false;
+ }
+ return true;
+ }
+
+private:
+ UrlParts parts_;
+ HINTERNET hConnect_ = nullptr;
+ HINTERNET hRequest_ = nullptr;
+ bool opened_ = false;
+};
+
+}
+
+static const int kMaxRedirect = 6;
+
+bool Http::Get(const std::wstring& url, HttpResult& out, std::wstring& err) {
+ std::wstring current = url;
+ for (int i = 0; i < kMaxRedirect; ++i) {
+ Session session;
+ if (!session.valid()) { err = L"无法初始化网络"; return false; }
+ Request request(session.get(), current, false);
+ if (!request.opened()) { err = L"无法创建请求: " + current; return false; }
+ if (!request.Send()) { err = L"请求失败: " + current; return false; }
+ long status = request.Status();
+ if (status >= 300 && status < 400) {
+ std::wstring loc = request.Location();
+ std::wstring next = ResolveUrl(current, loc);
+ if (next.empty()) { err = L"重定向地址无效"; return false; }
+ current = next;
+ continue;
+ }
+ out.status = status;
+ if (!request.ReadAll(out.body)) { err = L"读取响应失败"; return false; }
+ return true;
+ }
+ err = L"重定向次数过多";
+ return false;
+}
+
+bool Http::Download(const std::wstring& url, const std::wstring& savePath,
+ ProgressFunc progress, std::wstring& err) {
+ std::wstring current = url;
+ for (int i = 0; i < kMaxRedirect; ++i) {
+ Session session;
+ if (!session.valid()) { err = L"无法初始化网络"; return false; }
+ Request request(session.get(), current, true);
+ if (!request.opened()) { err = L"无法创建请求: " + current; return false; }
+ if (!request.Send()) { err = L"请求失败: " + current; return false; }
+ long status = request.Status();
+ if (status >= 300 && status < 400) {
+ std::wstring loc = request.Location();
+ std::wstring next = ResolveUrl(current, loc);
+ if (next.empty()) { err = L"重定向地址无效"; return false; }
+ current = next;
+ continue;
+ }
+ if (status != 200) {
+ err = L"下载失败,HTTP " + std::to_wstring(status);
+ return false;
+ }
+ HANDLE hFile = CreateFileW(savePath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL, nullptr);
+ if (hFile == INVALID_HANDLE_VALUE) { err = L"无法创建临时文件"; return false; }
+ unsigned long long written = 0;
+ bool ok = request.ReadToFile(hFile, progress, request.ContentLength(), written);
+ FlushFileBuffers(hFile);
+ CloseHandle(hFile);
+ if (!ok) {
+ DeleteFileW(savePath.c_str());
+ err = L"下载中断";
+ return false;
+ }
+ return true;
+ }
+ err = L"重定向次数过多";
+ return false;
+}
+
+}
diff --git a/Update/Http.h b/Update/Http.h
new file mode 100644
index 0000000..6b9929a
--- /dev/null
+++ b/Update/Http.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include
+
+#include
+#include
+
+namespace updater {
+
+struct HttpResult {
+ long status = 0;
+ std::string body;
+};
+
+class Http {
+public:
+ using ProgressFunc = std::function;
+
+ static bool Get(const std::wstring& url, HttpResult& out, std::wstring& err);
+
+ static bool Download(const std::wstring& url,
+ const std::wstring& savePath,
+ ProgressFunc progress,
+ std::wstring& err);
+
+ static void SetTimeoutSec(int sec) { timeoutSec_ = sec; }
+
+ static int TimeoutMs() { return timeoutSec_ * 1000; }
+
+private:
+ static int timeoutSec_;
+};
+
+}
diff --git a/Update/Json.cpp b/Update/Json.cpp
new file mode 100644
index 0000000..3c78e06
--- /dev/null
+++ b/Update/Json.cpp
@@ -0,0 +1,277 @@
+#include "Json.h"
+
+#include
+
+namespace updater {
+
+struct Json::Impl {
+ bool boolVal = false;
+ double numVal = 0.0;
+ std::string strVal;
+ std::vector arrVal;
+ std::map objVal;
+};
+
+struct JsonAccess {
+ static Json::Impl& impl(Json& j) { return *j.impl_; }
+ static void setType(Json& j, Json::Type t) { j.type_ = t; }
+};
+
+Json::Json() : impl_(std::make_shared()), type_(Null) {}
+Json::Json(Type type) : impl_(std::make_shared()), type_(type) {}
+
+bool Json::boolValue(bool def) const {
+ if (type_ == Bool) return impl_->boolVal;
+ if (type_ == Number) return impl_->numVal != 0.0;
+ return def;
+}
+
+double Json::numberValue(double def) const {
+ if (type_ == Number) return impl_->numVal;
+ return def;
+}
+
+long long Json::intValue(long long def) const {
+ if (type_ == Number) return static_cast(impl_->numVal);
+ return def;
+}
+
+std::string Json::stringValue(const std::string& def) const {
+ if (type_ == String) return impl_->strVal;
+ return def;
+}
+
+const Json& Json::operator[](const char* key) const {
+ static const Json nullValue;
+ if (type_ != Object) return nullValue;
+ auto it = impl_->objVal.find(key);
+ if (it == impl_->objVal.end()) return nullValue;
+ return it->second;
+}
+
+const Json& Json::operator[](const std::string& key) const {
+ return (*this)[key.c_str()];
+}
+
+const Json& Json::operator[](size_t index) const {
+ static const Json nullValue;
+ if (type_ != Array || index >= impl_->arrVal.size()) return nullValue;
+ return impl_->arrVal[index];
+}
+
+bool Json::contains(const char* key) const {
+ return type_ == Object && impl_->objVal.find(key) != impl_->objVal.end();
+}
+
+size_t Json::arraySize() const {
+ return type_ == Array ? impl_->arrVal.size() : 0;
+}
+
+namespace {
+
+void AppendUtf8(std::string& out, unsigned int cp) {
+ if (cp < 0x80) {
+ out += static_cast(cp);
+ } else if (cp < 0x800) {
+ out += static_cast(0xC0 | (cp >> 6));
+ out += static_cast(0x80 | (cp & 0x3F));
+ } else if (cp < 0x10000) {
+ out += static_cast(0xE0 | (cp >> 12));
+ out += static_cast(0x80 | ((cp >> 6) & 0x3F));
+ out += static_cast(0x80 | (cp & 0x3F));
+ } else {
+ out += static_cast(0xF0 | (cp >> 18));
+ out += static_cast(0x80 | ((cp >> 12) & 0x3F));
+ out += static_cast(0x80 | ((cp >> 6) & 0x3F));
+ out += static_cast(0x80 | (cp & 0x3F));
+ }
+}
+
+bool Hex4(const std::string& s, size_t pos, unsigned int& out) {
+ if (pos + 4 > s.size()) return false;
+ unsigned int v = 0;
+ for (size_t i = 0; i < 4; ++i) {
+ char c = s[pos + i];
+ v <<= 4;
+ if (c >= '0' && c <= '9') v |= static_cast(c - '0');
+ else if (c >= 'a' && c <= 'f') v |= static_cast(c - 'a' + 10);
+ else if (c >= 'A' && c <= 'F') v |= static_cast(c - 'A' + 10);
+ else return false;
+ }
+ out = v;
+ return true;
+}
+
+class Parser {
+public:
+ explicit Parser(const std::string& text) : s_(text) {}
+
+ bool ParseValue(Json& out, std::string& err) {
+ SkipSpace();
+ if (pos_ >= s_.size()) { err = "unexpected end"; return false; }
+ char c = s_[pos_];
+ if (c == '{') return ParseObject(out, err);
+ if (c == '[') return ParseArray(out, err);
+ if (c == '"') {
+ std::string str;
+ if (!ParseString(str, err)) return false;
+ JsonAccess::setType(out, Json::String);
+ JsonAccess::impl(out).strVal = str;
+ return true;
+ }
+ if (s_.compare(pos_, 4, "true") == 0) {
+ pos_ += 4;
+ JsonAccess::setType(out, Json::Bool);
+ JsonAccess::impl(out).boolVal = true;
+ return true;
+ }
+ if (s_.compare(pos_, 5, "false") == 0) {
+ pos_ += 5;
+ JsonAccess::setType(out, Json::Bool);
+ JsonAccess::impl(out).boolVal = false;
+ return true;
+ }
+ if (s_.compare(pos_, 4, "null") == 0) {
+ pos_ += 4;
+ JsonAccess::setType(out, Json::Null);
+ return true;
+ }
+ return ParseNumber(out, err);
+ }
+
+private:
+ void SkipSpace() {
+ while (pos_ < s_.size()) {
+ char c = s_[pos_];
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++pos_;
+ else break;
+ }
+ }
+
+ bool ParseString(std::string& out, std::string& err) {
+ if (pos_ >= s_.size() || s_[pos_] != '"') { err = "expected string"; return false; }
+ ++pos_;
+ out.clear();
+ while (pos_ < s_.size()) {
+ char c = s_[pos_];
+ if (c == '"') { ++pos_; return true; }
+ if (c == '\\') {
+ ++pos_;
+ if (pos_ >= s_.size()) break;
+ char e = s_[pos_++];
+ switch (e) {
+ case '"': out += '"'; break;
+ case '\\': out += '\\'; break;
+ case '/': out += '/'; break;
+ case 'b': out += '\b'; break;
+ case 'f': out += '\f'; break;
+ case 'n': out += '\n'; break;
+ case 'r': out += '\r'; break;
+ case 't': out += '\t'; break;
+ case 'u': {
+ unsigned int cp = 0;
+ if (!Hex4(s_, pos_, cp)) { err = "bad unicode escape"; return false; }
+ pos_ += 4;
+ if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 1 < s_.size() &&
+ s_[pos_] == '\\' && s_[pos_ + 1] == 'u') {
+ unsigned int lo = 0;
+ if (Hex4(s_, pos_ + 2, lo) && lo >= 0xDC00 && lo <= 0xDFFF) {
+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
+ pos_ += 6;
+ }
+ }
+ AppendUtf8(out, cp);
+ break;
+ }
+ default: out += e; break;
+ }
+ } else {
+ out += c;
+ ++pos_;
+ }
+ }
+ err = "unterminated string";
+ return false;
+ }
+
+ bool ParseNumber(Json& out, std::string& err) {
+ size_t start = pos_;
+ if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) ++pos_;
+ bool hasDigit = false;
+ while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') { ++pos_; hasDigit = true; }
+ if (pos_ < s_.size() && s_[pos_] == '.') {
+ ++pos_;
+ while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') { ++pos_; hasDigit = true; }
+ }
+ if (hasDigit && pos_ < s_.size() && (s_[pos_] == 'e' || s_[pos_] == 'E')) {
+ ++pos_;
+ if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) ++pos_;
+ while (pos_ < s_.size() && s_[pos_] >= '0' && s_[pos_] <= '9') ++pos_;
+ }
+ if (!hasDigit) { err = "invalid number"; return false; }
+ std::string num = s_.substr(start, pos_ - start);
+ JsonAccess::setType(out, Json::Number);
+ JsonAccess::impl(out).numVal = strtod(num.c_str(), nullptr);
+ return true;
+ }
+
+ bool ParseArray(Json& out, std::string& err) {
+ ++pos_;
+ JsonAccess::setType(out, Json::Array);
+ SkipSpace();
+ if (pos_ < s_.size() && s_[pos_] == ']') { ++pos_; return true; }
+ while (pos_ < s_.size()) {
+ Json item;
+ if (!ParseValue(item, err)) return false;
+ JsonAccess::impl(out).arrVal.push_back(item);
+ SkipSpace();
+ if (pos_ < s_.size() && s_[pos_] == ',') { ++pos_; continue; }
+ if (pos_ < s_.size() && s_[pos_] == ']') { ++pos_; return true; }
+ err = "expected , or ]";
+ return false;
+ }
+ err = "unterminated array";
+ return false;
+ }
+
+ bool ParseObject(Json& out, std::string& err) {
+ ++pos_;
+ JsonAccess::setType(out, Json::Object);
+ SkipSpace();
+ if (pos_ < s_.size() && s_[pos_] == '}') { ++pos_; return true; }
+ while (pos_ < s_.size()) {
+ SkipSpace();
+ std::string key;
+ if (!ParseString(key, err)) return false;
+ SkipSpace();
+ if (pos_ >= s_.size() || s_[pos_] != ':') { err = "expected :"; return false; }
+ ++pos_;
+ Json value;
+ if (!ParseValue(value, err)) return false;
+ JsonAccess::impl(out).objVal[key] = value;
+ SkipSpace();
+ if (pos_ < s_.size() && s_[pos_] == ',') { ++pos_; continue; }
+ if (pos_ < s_.size() && s_[pos_] == '}') { ++pos_; return true; }
+ err = "expected , or }";
+ return false;
+ }
+ err = "unterminated object";
+ return false;
+ }
+
+ const std::string& s_;
+ size_t pos_ = 0;
+};
+
+}
+
+bool Json::Parse(const std::string& text, Json& out, std::string& err) {
+ Parser parser(text);
+ Json value;
+ if (!parser.ParseValue(value, err)) return false;
+ JsonAccess::setType(out, value.type());
+ JsonAccess::impl(out) = JsonAccess::impl(value);
+ return true;
+}
+
+}
diff --git a/Update/Json.h b/Update/Json.h
new file mode 100644
index 0000000..9079bf2
--- /dev/null
+++ b/Update/Json.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include
+#include
+#include